在前面的博文,我已经简单介绍了华为的物联网云平台IoTDA的使用,包括如何建立设备、创建物模型,并演示了如何使用MQTTX连接平台发送数据。今天介绍一下如何使用Python程序连接云平台并发布数据。
程序中使用了paho-mqtt库,所以需要先安装该库文件:
pip install paho-mqtt
程序很简单,先连接到华为云服务器,然后周期发布数据,数据包括随机产生的温度、湿度和当前的系统时间。完整的代码如下(其中的用户名、密码等敏感信息已经替换为XXXXXXXXX):
import datetime
import random
import time
from paho.mqtt import client as mqtt_client
broker = 'XXXXXX.st1.iotda-device.cn-north-4.myhuaweicloud.com'
port = 1883
topic = "$oc/devices/XXXXXXXXXX/sys/properties/report"
client_id = 'XXXXXXXXXXXX'
def connect_mqtt():
def on_connect(client, userdata, flags, rc, props):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(mqtt_client.CallbackAPIVersion.VERSION2, client_id)
client.username = 'XXXXXXXXXXX'
client.password = 'XXXXXXXXXXX'
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client):
msg_count = 0
while True:
time.sleep(3)
# 获取当前系统时间,并格式化为"YYYYMMDDTHHMMSSZ"
now = datetime.datetime.now().strftime("%Y%m%dT%H%M%SZ")
# 生成随机温湿度值
random_temperature = random.randint(10, 35)
random_humidity = random.randint(30, 90)
msg = f"""
{{
"services": [
{{
"serviceId": "温湿度",
"properties": {{
"温度": {random_temperature},
"湿度": {random_humidity}
}},
"event_time": "{now}"
}}
]
}}
"""
result = client.publish(topic, msg)
# result: [0, 1]
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
msg_count += 1
def run():
client = connect_mqtt()
client.loop_start()
publish(client)
if __name__ == '__main__':
run()
程序运行后,就可以在云平台看到时间的定期更新了。