> For the complete documentation index, see [llms.txt](https://kawsing.gitbook.io/opensystem/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kawsing.gitbook.io/opensystem/andoid-shou-ji/termux/zai-termux-shang-de-python-cheng-shi/python-mqtt.md).

# 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接收測試

![](/files/-LrmESmt1Avb9AtGfTGr)

![](/files/-LrmFIAZuxYu4D7Z8WXn)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

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

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
