개발일지/Python
[Python] MQTT 사용
chi_chi
2020. 4. 7. 10:44
1. mqtt 설치
pip install paho-mqtt
2. python (subscribe.py)
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.username_pw_set("user", "1234") # broker에 password가 설정되어 있다면 추가 없으면 생략
client.subscribe("#") # Topic
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
msg.payload = msg.payload.decode("utf-8")
print("topic: "+msg.topic+" value: "+msg.payload)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("localhost") # broker IP
client.loop_forever() #무한루프