import hmac
from hashlib import sha1
import paho.mqtt.client as mqtt
import json
import time
product_key = "****"
device_name = "****"
device_secret = "****"
#旧版公共实例的host
host = product_key + ".iot-as-mqtt.cn-shanghai.aliyuncs.com"
#新版公共实例的host,控制台查看开发配置中的mqtt接入域名
#instance_id = "***"
#host = instance_id + ".mqtt.iothub.aliyuncs.com"
port = 1883
#以下参数的含义,具体请参考:https://help.aliyun.com/document_detail/73742.html
client_id = "12345"
content = "clientId" + client_id + "deviceName" + device_name + "productKey" + product_key
mqttClientId = client_id + "|securemode=2,signmethod=hmacsha1|"
mqttUsername = device_name + '&' + product_key
mqttPassword = hmac.new(device_secret.encode(), content.encode(), sha1).hexdigest()
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("connect success!")
else:
print("connect failed...")
client = mqtt.Client(mqttClientId)
client.username_pw_set(username=mqttUsername, password=mqttPassword)
client.on_connect = on_connect
client.connect(host, port)
return client
#消息回调
def on_message(client, userdata, msg):
topic = msg.topic
payload = msg.payload.decode()
print("收到消息! topic:" + topic)
print("收到消息! payload:" + payload)
print(" ")
if ("thing/service/property/set" in topic):
on_thing_prop_changed(client, msg.topic, msg.payload)
#属性设置的处理函数
def on_thing_prop_changed(client,topic,payload):
post_topic = topic.replace("service","event")
post_topic = post_topic.replace("set","post")
Msg = json.loads(payload)
params = Msg['params']
post_payload = "{\"params\":" + json.dumps(params) + "}"
print("收到属性设置的指令,需要主动上报属性变化的topic:" + post_topic)
print("收到属性设置的指令,需要主动上报属性变化的payload:" + post_payload)
print(" ")
client.publish(post_topic, post_payload)
client = connect_mqtt()
client.loop_start()
client.on_message = on_message
#订阅topic
#client.subscribe("${topic}")
#发布消息
#client.publish("${topic}", "${payload}")
while True:
time.sleep(1)