python mqtt模拟设备连接thingsboard

import time
import paho.mqtt.client as mqtt
import json
import random

class MQTTBase:
    def __init__(self,sub_topic,callback):
        self.token = "0eGsZDsKsf6PN3yRLy8e"
        self.callback=callback
        self.sub_topic=sub_topic
        self.client = mqtt.Client(self.token)
        self.client.username_pw_set(self.token)
        self.client.on_message = self.on_message
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        # 连接到MQTT代理服务器
        self.client.connect('iot.armfun.cn',11883)
        self.client.loop_start()
       
    def on_connect(self, client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT broker")
            for topic in self.sub_topic:
                print("sub topic:"+topic)
                self.client.subscribe(topic)
        else:
            print("Failed to connect, return code: " + str(rc))
    def on_disconnect(self,client, userdata, rc):
        if rc != 0:
            print("Unexpected disconnection. Will reconnect...")
            client.reconnect()
    def on_message(self, client, userdata, msg):
        #print(msg.topic)
        #print("Received message: " + msg.payload.decode())
        self.callback(self.client,msg.topic,msg.payload.decode())

    def publish(self, topic, message):
        print("public msg")
        print(topic)
        if self.client.is_connected:
            print(message)
            self.client.publish(topic, message)
ledsta = False
def message_rev(client,topic,msg):
    global ledsta
    print("rev msg:")
    print(topic)
    print(msg)
    if topic.startswith("v1/devices/me/rpc/request/"):
        reqid = topic[len("v1/devices/me/rpc/request/"):]
        print(reqid)
        data=json.loads(msg)
        if(data["method"]=="setValue"):
            ledsta = data["params"]
            data={"value":True}
            mymqtt.publish("v1/devices/me/rpc/response/"+reqid, json.dumps(data))
        elif (data["method"]=="getValue"):
            data={"value":ledsta}
            mymqtt.publish("v1/devices/me/rpc/response/"+reqid, json.dumps(data))


if __name__ == '__main__':
    temp=1
    mymqtt=MQTTBase(["v1/devices/me/rpc/request/+","v1/devices/me/attributes"],message_rev)
    time.sleep(2) 
    while True:
        temp=temp+1
        data={"ledsta":ledsta,"count":temp}
        mymqtt.publish("v1/devices/me/telemetry", json.dumps(data))
        data={"deviceName":"a device"}
        mymqtt.publish("v1/devices/me/attributes", json.dumps(data))
        time.sleep(1)  # 每隔1秒发送一次消息

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值