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()})
ESP32 ESP8266 micropython 连接thingsboard
于 2024-06-02 18:02:07 首次发布