ESP32 ESP8266 micropython 连接thingsboard

from umqtt.simple import MQTTClient
from machine import Pin
import wifi
import time
import _thread
import json
import gc

client = None
con_ok = False
switch = False
def mqtt_publish(topic,msg):
    client.publish(topic,msg)
def sub_callback(topic, msg):
    global switch
    topic = topic.decode()
    msg = msg.decode()
    print((topic, 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"):
            switch = data["params"]
            data={"value":switch}
            mqtt_publish(f"v1/devices/me/rpc/response/{reqid}", json.dumps(data))
        elif (data["method"]=="getValue"):
            data={"value":switch}
            mqtt_publish(f"v1/devices/me/rpc/response/{reqid}", json.dumps(data))
def mqtt_connect():
    global client
    client = MQTTClient("tb_token", "192.168.1.100", 1883,"tb_token","")#修改实际的ip 和token
    client.set_callback(sub_callback)
    client.connect()
    client.subscribe("v1/devices/me/rpc/request/+")
    client.subscribe("v1/devices/me/attributes")
    print("mqtt connected")
# 线程1的任务
def thread1_task():
    global list_topic,list_msg,con_ok
    while True:
        time.sleep(1)
        print("wifi connecting...")
        if wifi.wlan.isconnected():
            mqtt_connect()
            con_ok=True
            while True:
                client.wait_msg()
                
    print("mqtt thread end")                
    _thread.exit()
                
            
_thread.start_new_thread(thread1_task, ())

def tb_send_tele(dic):
    if con_ok :
        msg = json.dumps(dic)
        mqtt_publish("v1/devices/me/telemetry", json.dumps(dic))
    else:
        print("pub tele failed")
def tb_send_attr(dic):
    if con_ok :
        msg = json.dumps(dic)
        mqtt_publish("v1/devices/me/attributes", json.dumps(dic))
    else:
        print("pub attr failed")

led=Pin(2,Pin.OUT)            #初始化
while True:
    wifi.check_connect()
    led.on()                  #灯打开
    time.sleep(1)             #延时一秒
    led.off()                 #灯关闭
    time.sleep(1)#延时一秒
    #print(gc.mem_free())
    tb_send_tele({"voltage":12.1,"current":3.1,
                  "soc":99,"temperature":20})
    tb_send_attr({"memory":gc.mem_free()})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值