环境:thingsboard,mqtt安装,python3.11

模拟光强,温度,湿度

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

access = "obM6PnLfddjK83XviB4L"  # 访问令牌

broker = "localhost"  # 本机模拟地址

port = 1883  # 端口号


def on_publish(client, userdata, result):
    print("published")


def on_connect(client, userdata, flag, rc):
    print(str(rc))
    print("connected")


test = paho.Client("device1")
test.on_publish = on_publish
test.on_connect = on_connect
test.username_pw_set(access)
test.connect(broker, port, keepalive=60)
test.loop_start()

# 模拟数据范围
# 人体在20-24温度较为舒适
MAXTEMPERATURE = 30  # 最高温度
MINTEMPERATURE = 15  # 最低温度

# 人体在45-65%湿度较为舒适
MAXHUMILITY = 70  # 最高湿度
MINHUMILITY = 40  # 最低湿度

# 人体在400-600光强较为舒适
MAXILLUMINATION = 650  # 最大光强
MINILLUMINATION = 350  # 最小光强


while True:
    data = {
        # 在这里可以增加键值模拟不同的数据
        "temperature": random.randint(MINTEMPERATURE, MAXTEMPERATURE),  # 温度
        "humility": random.randint(MINHUMILITY, MAXHUMILITY),  # 湿度
        "illumination": random.randint(MINILLUMINATION, MAXILLUMINATION),  # 光照
    }
    test.publish("v1/devices/me/telemetry", payload=json.dumps(data), qos=0)
    time.sleep(5)

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐