# Python MQTT

## 透過 Python 傳送數據到 Mosquitto MQTT Broker

```
pip3 install paho-mqtt
```

```python
import paho.mqtt.client as mqtt
import time
import json
import random
#變數設定
MQTT_TOPIC = "Sensor/BedRoom/Temperature"  
MQTT_SERVER = "192.168.43.61"  
MQTT_PORT = 1883  
MQTT_ALIVE = 60  

#------------
#mqtt client 物件
mqtt_client=mqtt.Client()
#連線MQTT Server
mqtt_client.connect(MQTT_SERVER, MQTT_PORT, MQTT_ALIVE)

while True:
    temp=random.randint(0,30)
    payload={
        "Topic":MQTT_TOPIC,
        "溫度":temp
    }
    print("目標 topic:"+MQTT_TOPIC+"=>溫度:"+str(temp))
    #送出topic訊息，須加入ensure_ascii=False讓中文正常顯示
    mqtt_client.publish(MQTT_TOPIC, json.dumps(payload, ensure_ascii=False),qos=1)
    time.sleep(10)  
```

MQTT Server端測試

```
mosquitto_sub -t "Sensor/BedRoom/Temperature"
{"Topic": "Sensor/BedRoom/Temperature", "\u6eab\u5ea6": 3}
{"Topic": "Sensor/BedRoom/Temperature", "\u6eab\u5ea6": 24}
{"Topic": "Sensor/BedRoom/Temperature", "\u6eab\u5ea6": 16}

＃加入ensure_ascii=False
{"Topic": "Sensor/BedRoom/Temperature", "溫度": 21}
{"Topic": "Sensor/BedRoom/Temperature", "溫度": 13}

```

### Node-Red mqtt接收測試

![](https://529150212-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lh81JtaIQ84bwQqz_Wh%2F-LrmERgYr0yRxAB3P1sj%2F-LrmESmt1Avb9AtGfTGr%2Fimage.png?alt=media\&token=fceea079-8697-4d90-9051-387b19f4713f)

![](https://529150212-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-Lh81JtaIQ84bwQqz_Wh%2F-LrmERgYr0yRxAB3P1sj%2F-LrmFIAZuxYu4D7Z8WXn%2Fimage.png?alt=media\&token=8bcfce61-30fb-476c-afae-c3035c1ae2cf)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kawsing.gitbook.io/opensystem/andoid-shou-ji/termux/zai-termux-shang-de-python-cheng-shi/python-mqtt.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
