2018年5月6日 星期日

MQTT with python3

with C
#!/usr/bin/python3
import time
import paho.mqtt.client as paho
import ssl
import json

#broker="broker.hivemq.com"
broker = "happy.ai.hinet.net"
port=8888
CA_ROOT_CERT_FILE = "./ROOTeCA_64.crt"
topic_p = "ai/speaker/NerERA/04370927/req"
topic_s = "ai/speaker/NerERA/04370927/rsp"
MQTT_MSG = "{\"Action\": \"RegisterReq\", \"Time\": \"2018-03-14T11:50:00Z\",\"RequestID\": \"xxxxxxx\", \"Version\": \"1.1\"}"
#define callback
def on_message(client, userdata, message):
    #time.sleep(1)
    print("received message =",str(message.payload.decode("utf-8")))

client= paho.Client("client-001") #create client object client1.on_publish = on_publish #assign function to callback client1.connect(broker,port) #establish connection client1.publish("house/bulb1","on")
######Bind function to callback
#client.tls_set(CA_ROOT_CERT_FILE, cert_reqs=ssl.CERT_REQUIRED,
client.tls_set(None, cert_reqs=ssl.CERT_REQUIRED,
            tls_version=ssl.PROTOCOL_TLSv1_2, ciphers=None)

client.username_pw_set("de0236c6ece1dd2dfce194c7c4b8d54", "de0236c6ece1dd2dfce194c7c4b8d54")
client.on_message=on_message
#####
print("connecting to broker ",broker)
client.connect(broker, port)#connect
client.loop_start() #start loop to process received messages
print("subscribing")
client.subscribe(topic_s)#subscribe
#time.sleep(2)
print("publishing ")
client.publish(topic_p, MQTT_MSG)#publish
time.sleep(4)
client.disconnect() #disconnect
client.loop_stop() #stop loop

ref:
Simple Python MQTT Publish and Subscribe -Example
MQTT用戶端入門 - 三、Python 用戶端程式設計

沒有留言:

張貼留言