python 连接 mqtt broker服务器
安裝 Mosquitto MQTT Broke
sudo apt install -y mosquitto mosquitto-clients
TEST Mosquitto MQTT Broker
建立 Subscriber
mosquitto_sub -h test.mosquitto.org -t Sensor/Temperature/Room1
建立 Publisher
mosquitto_pub -h 54.159.81.55 -t Sensor/Temperature/Room1 -m "hello world"
安裝paho-mqtt套件
pip install paho-mqtt
mosquitto_mqtt.py
import paho.mqtt.client as mqtt
import time
import json
import random
# *********************************************************************
# MQTT Config
dataChnId1 = "Temperature"
MQTT_SERVER = "test.mosquitto.org"
MQTT_PORT = 1883
MQTT_ALIVE = 60
MQTT_TOPIC1 = "Sensor/" + dataChnId1 + "/Room1"
# *********************************************************************
mqtt_client = mqtt.Client()
mqtt_client.connect(MQTT_SERVER, MQTT_PORT, MQTT_ALIVE)
while True:
t0 = random.randint(0,30)
payload = {"dataChnId":dataChnId1,"value":t0}
print(dataChnId1 + " : " + str(t0))
mqtt_client.publish(MQTT_TOPIC1, json.dumps(payload), qos=1)
time.sleep(10)
本文链接地址:https://const.net.cn/680.html