상세한 설치 방법이 아래 Paho 라이브러리 사이트에 나와 있습니다.

 

파이썬 라이브러리 소스코드는 아래 링크에 공개되어 있으니 필요하신 분은 참고하시고…

 

설치는 pip 툴을 이용해서 합니다.

  • pip install paho-mqtt

 

만약 소스를 컴파일해서 설치하고 싶으시다면 아래 방법대로 하세요.

  • git clone https://github.com/eclipse/paho.mqtt.python.git
  • cd org.eclipse.paho.mqtt.python.git
  • sudo python setup.py install

 

라이브러리를 설치했으면 아래처럼 코드를 작성해서 간단히 테스트 할 수 있습니다.

import paho.mqtt.client as mqtt

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, rc):
    print("Connected with result code "+str(rc))
	# Subscribing in on_connect() means that if we lose the connection and
	# reconnect then subscriptions will be renewed.
	client.subscribe("$SYS/#")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
	print(msg.topic+" "+str(msg.payload))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("iot.eclipse.org", 1883, 60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
client.loop_forever()

 

on_connect() 함수와  on_message() 함수를 미리 선언해 둔 뒤 아래 코드를 통해 callback 함수로 등록합니다. 그럼 MQTT에 연결되거나 메시지를 받을 때 자동으로 callback 함수가 호출됩니다.

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

이 외에도 등록할 수 있는 callback 함수가 많습니다. 아래 링크에 있는 예제 파일들을 읽어보시면 금방 사용법을 터득하실 수 있습니다.

예제를 테스트 하기 전 아래 코드에서 MQTT broker URL을 자신의 환경에 맞게 수정해줘야 합니다.

client.connect("iot.eclipse.org", 1883, 60)

 

참고자료