# -*- coding: utf-8 -*-import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json
#这个就是我们在阿里云注册产品和设备时的三元组啦#把我们自己对应的三元组填进去即可
options ={'productKey':'gn1y3ZtF5Ii','deviceName':'ESP8266_test','deviceSecret':'3b7a4b32af967cdfd8ac741cdfd5b66a','regionId':'cn-shanghai'}
HOST = options['productKey']+'.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT =1883
PUB_TOPIC ="/sys/"+ options['productKey']+"/"+ options['deviceName']+"/thing/event/property/post";# The callback for when the client receives a CONNACK response from the server.defon_connect(client, userdata, flags, rc):print("Connected with result code "+str(rc))# client.subscribe("the/topic")# The callback for when a PUBLISH message is received from the server.defon_message(client, userdata, msg):print(msg.topic+" "+str(msg.payload))defhmacsha1(key, msg):return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()defgetAliyunIoTClient():
timestamp =str(int(time.time()))
CLIENT_ID ="paho.py|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|"
CONTENT_STR_FORMAT ="clientIdpaho.pydeviceName"+options['deviceName']+"productKey"+options['productKey']+"timestamp"+timestamp
# set username/password.
USER_NAME = options['deviceName']+"&"+options['productKey']
PWD = hmacsha1(options['deviceSecret'],CONTENT_STR_FORMAT)
client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
client.username_pw_set(USER_NAME, PWD)return client
if __name__ =='__main__':
client = getAliyunIoTClient()
client.on_connect = on_connect
client.on_message = on_message
client.connect(HOST,1883,300)#while True:
payload_json ={'id':int(time.time()),'params':{'temperature': random.randint(20,30),#随机温度'humidity': random.randint(40,50)#随机相对湿度},'method':"thing.event.property.post"}print('send data to iot server: '+str(payload_json))
client.publish(PUB_TOPIC,payload=str(payload_json),qos=1)
client.loop_forever()
双线程代码
# -*- coding: utf-8 -*-import paho.mqtt.client as mqtt
import time
import hashlib
import hmac
import random
import json
import threading # 导入线程模块#这个就是我们在阿里云注册产品和设备时的三元组啦#把我们自己对应的三元组填进去即可
options ={'productKey':'gn1y3ZtF5Ii','deviceName':'ESP8266_test','deviceSecret':'3b7a4b32af967cdfd8ac741cdfd5b66a','regionId':'cn-shanghai'}
HOST = options['productKey']+'.iot-as-mqtt.'+options['regionId']+'.aliyuncs.com'
PORT =1883
PUB_TOPIC ="/sys/"+ options['productKey']+"/"+ options['deviceName']+"/thing/event/property/post";# The callback for when the client receives a CONNACK response from the server.defon_connect(client, userdata, flags, rc):print("Connected with result code "+str(rc))# client.subscribe("the/topic")# The callback for when a PUBLISH message is received from the server.defon_message(client, userdata, msg):print(msg.topic+" "+str(msg.payload))defhmacsha1(key, msg):return hmac.new(key.encode(), msg.encode(), hashlib.sha1).hexdigest()defgetAliyunIoTClient():
timestamp =str(int(time.time()))
CLIENT_ID ="paho.py|securemode=3,signmethod=hmacsha1,timestamp="+timestamp+"|"
CONTENT_STR_FORMAT ="clientIdpaho.pydeviceName"+options['deviceName']+"productKey"+options['productKey']+"timestamp"+timestamp
# set username/password.
USER_NAME = options['deviceName']+"&"+options['productKey']
PWD = hmacsha1(options['deviceSecret'],CONTENT_STR_FORMAT)
client = mqtt.Client(client_id=CLIENT_ID, clean_session=False)
client.username_pw_set(USER_NAME, PWD)return client
# 定义发布消息的函数defpublish_data(client):whileTrue:# 创建一个循环来持续发送数据
payload_json ={'id':int(time.time()),'params':{'temperature': random.randint(20,30),# 随机温度'humidity': random.randint(40,50)# 随机相对湿度},'method':"thing.event.property.post"}print('Sending data to IoT server: '+str(payload_json))
client.publish(PUB_TOPIC, payload=json.dumps(payload_json), qos=1)
time.sleep(5)# 每隔5秒发送一次数据if __name__ =='__main__':
client = getAliyunIoTClient()
client.on_connect = on_connect
client.on_message = on_message
# 连接 MQTT 服务器
client.connect(HOST, PORT,300)# 使用线程来发布消息,不干扰主线程的接收消息循环
publish_thread = threading.Thread(target=publish_data, args=(client,))
publish_thread.start()# 启动线程# 开始 MQTT 客户端的循环,处理接收到的消息和重新连接等
client.loop_forever()