使用Python连接华为IoTDA并发布数据

前面的博文,我已经简单介绍了华为的物联网云平台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()

程序运行后,就可以在云平台看到时间的定期更新了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神一样的老师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值