Skip to main content

Thingsboard topic

遥测

数据:v1/devices/me/telemetry 属性:v1/devices/me/attributes

你需要安装paho-mqtt,这是一个MQTT客户端库,用于与MQTT服务器通信

python代码
import paho.mqtt.client as mqtt
import json

# ThingsBoard平台的配置
THINGSBOARD_HOST = 'your_thingsboard_host' # 替换为你的ThingsBoard主机地址
ACCESS_TOKEN = 'your_access_token' # 替换为你的设备访问令牌

# 连接事件的回调函数
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))

# 创建MQTT客户端实例
client = mqtt.Client()
# 设置连接事件的回调函数
client.on_connect = on_connect
# 设定访问令牌为用户名
client.username_pw_set(ACCESS_TOKEN)
# 连接到ThingsBoard服务器
client.connect(THINGSBOARD_HOST, 1883, 60)
# 要发送的数据
data = {"temperature": 25, "humidity": 60}
# 发送数据到ThingsBoard
client.publish('v1/devices/me/telemetry', json.dumps(data), 1)
# 断开连接
client.disconnect()

响应RPC

python代码
import paho.mqtt.client as mqtt
import json

# ThingsBoard平台的配置
THINGSBOARD_HOST = 'your_thingsboard_host' # 替换为你的ThingsBoard主机地址
ACCESS_TOKEN = 'your_access_token' # 替换为你的设备访问令牌

# RPC请求的处理函数
def handle_rpc_request(client, userdata, message):
print("Received RPC request: " + str(message.payload))
request_data = json.loads(message.payload)
request_id = message.topic.split('/')[-1] # 从主题中提取RPC请求的ID

response_data = {}
# 根据RPC请求执行动作,这里仅为示例
if request_data['method'] == 'getValue':
# 这里实现获取某个值的逻辑
response_data = {"value": 42} # 示例响应
# 在响应主题中包含相同的请求ID
if request_data['method'] == 'setValue':
response_data = {"value":"ok"}
print("参数:" + request_data["params"])
# 下面写一些控制相关的业务逻辑
# ....
client.publish(f'v1/devices/me/rpc/response/{request_id}', json.dumps(response_data), 1)

# 连接事件的回调函数
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# 订阅RPC请求主题
client.subscribe('v1/devices/me/rpc/request/+')

# 创建MQTT客户端实例
client = mqtt.Client()
# 设置连接事件的回调函数
client.on_connect = on_connect
# 设置接收消息的回调函数
client.message_callback_add('v1/devices/me/rpc/request/+', handle_rpc_request)
# 设定访问令牌为用户名
client.username_pw_set(ACCESS_TOKEN)
# 连接到ThingsBoard服务器
client.connect(THINGSBOARD_HOST, 1883, 60)
# 开始MQTT循环,以处理进入消息和保持连接
client.loop_forever()

Example banner