9/18/2025

ส่งค่าอุณหภูมิจาก Pi ไป Home Assistant แบบ Docker

 ส่งค่าอุณหภูมิจาก Pi ไป Home Assistant แบบ Docker

ต่อจาก
https://intranet.scivalve.com/blog.php?u=281&b=2051

1. ตัว HA ลงแบบ Docker ก็ต้อง Mosquitto ด้วย Docker container
1.1. สร้างโฟลเดอร์เก็บ config/data/log ของ Mosquitto:

  1. mkdir -p /HA/mosquitto/config /HA/mosquitto/data /HA/mosquitto/log

1.2. สร้างไฟล์ config
  1. nano /HA/mosquitto/config/mosquitto.conf

1.3. ใส่ค่า
แบบใช้ได้หมด ไม่ต้องใส่ use password ไม่ปลอดภัย
  1. persistence true
  2. persistence_location /mosquitto/data/
  3. log_dest file /mosquitto/log/mosquitto.log
  4.  
  5. allow_anonymous true
  6. listener 1883

แบบตั้ง user password
  1. persistence true
  2. persistence_location /mosquitto/data/
  3. log_dest file /mosquitto/log/mosquitto.log
  4.  
  5. allow_anonymous false
  6. password_file /mosquitto/config/password.txt
  7. listener 1883


1.4. สร้าง user ด้วยคำสั่ง
docker run --rm -it \
  1.  -v /HA/mosquitto/config:/mosquitto/config \
  2.   eclipse-mosquitto mosquitto_passwd -c /mosquitto/config/password.txt hauserXXXXX

มันจะถาม password ให้คุณใส่ → เก็บไว้ใน /HA/mosquitto/config/password.txt

1.5. รัน container Mosquitto:
  1. docker run -d \
  2.   --name mosquitto \
  3.   -p 1883:1883 \
  4.   -p 9001:9001 \
  5.   -v /HA/mosquitto/config:/mosquitto/config \
  6.   -v /HA/mosquitto/data:/mosquitto/data \
  7.   -v /HA/mosquitto/log:/mosquitto/log \
  8.   eclipse-mosquitto


1.6. Restart Mosquitto
  1. docker restart mosquitto


1.7. ทดสอบ ที่เครื่อง HA Run
  1. mosquitto_sub -h localhost -p 1883 -u "hauser" -P "รหัสผ่าน" -t "#"


1.8. ที่เครื่องเรา ติดตั้ง
  1. apt install mosquitto-clients -y

แล้วลองส่งค่าไป
  1. mosquitto_pub -h 192.168.2.5 -p 1883 -u "xxx" -P "xxxx" -t "test/topic" -m "Hello MQTT"
  1. mosquitto_pub -h 192.168.2.5 -p 1883 -u "xxx" -P "xxxx" -t "hass/sensor/temperature" -m "27"

ที่ Terminal ของ HA จะต้องเห็นข้อความ Hello MQTT

1.9. ที่ เครื่อง HA เพิ่ม ที่ไฟล์ configuration.yaml เป็น Sensor และรอรับค่า MQTT
  1. mqtt:
  2.   sensor:
  3.     - name: "Server Temp."
  4.       state_topic: "hass/sensor/temperature"
  5.       value_template: "{{ value_json.temperature }}"
  6.       unit_of_measurement: "°C"
  7.  
  8.     - name: "Server Hum."
  9.       state_topic: "hass/sensor/temperature"
  10.       value_template: "{{ value_json.humidity }}"
  11.       unit_of_measurement: "%"


1.10. เข้า Setting --> Devices & Services Add integration MQTT เข้าไปด้วย
ใส่ IP User Password

1.11. ที่เครื่อง pi ทดลอง run python Code temp2mqtt.2.5.py
  1. #!/usr/bin/python3
  2. import sys
  3. import Adafruit_DHT
  4.  
  5. import time, json
  6. import RPi.GPIO as GPIO
  7. import paho.mqtt.client as mqtt
  8.  
  9. import requests
  10.  
  11. # Config
  12. MQTT_BROKER = "192.168.2.5"   # IP ของ Home Assistant
  13. MQTT_PORT = 1883
  14. MQTT_USER = "xx"
  15. MQTT_PASSWORD = "xx"
  16. MQTT_TOPIC = "hass/sensor/temperature"
  17.  
  18. SENSOR = Adafruit_DHT.AM2302  # หรือ DHT11 แล้วแต่ที่ใช้
  19. PIN = 4  # GPIO ที่ต่อ sensor
  20.  
  21. # Connect MQTT
  22. client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
  23. client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
  24. client.connect(MQTT_BROKER, MQTT_PORT, 60)
  25.  
  26. # Try to grab a sensor reading.  Use the read_retry method which will retry up
  27. # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
  28. humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
  29.  
  30. # Un-comment the line below to convert the temperature to Fahrenheit.
  31. # temperature = temperature * 9/5.0 + 32
  32.  
  33. from datetime import datetime
  34. if humidity is not None and temperature is not None:
  35.    print('Temp={0:0.1f}*  Humidity={1:0.1f}%  Date={2}'.format(temperature, humidity, datetime.today().strftime('%Y-%m-%d %H:%M:%S')))
  36.    payload = {
  37.         "temperature": round(temperature, 2),
  38.         "humidity": round(humidity, 2)
  39.    }
  40.    #print('{0}'.format(json.dumps(payload)))
  41.    client.publish(MQTT_TOPIC, json.dumps(payload))
  42.  


แก้ Code ให้ส่ง MQTT ไป 2 เครื่อง
  1. #!/usr/bin/python3
  2. import Adafruit_DHT
  3. import time, json
  4. from datetime import datetime
  5. import paho.mqtt.client as mqtt
  6.  
  7. # Config broker 1
  8. MQTT_BROKER1   = "192.168.0.187"
  9. MQTT_PORT1     = 1883
  10. MQTT_USER1     = "xxx"
  11. MQTT_PASSWORD1 = "xxx"
  12. BROKER1_TOPIC  = "hass/sensor/temperature"
  13.  
  14. # Config broker 2
  15. MQTT_BROKER2   = "192.168.2.5"
  16. MQTT_PORT2     = 1883
  17. MQTT_USER2     = "xxx"
  18. MQTT_PASSWORD2 = "xxx"
  19. BROKER2_TOPIC  = "hass/sensor/temperature"
  20.  
  21. SENSOR = Adafruit_DHT.AM2302
  22. PIN = 4
  23.  
  24. # อ่านค่าจาก DHT
  25. humidity, temperature = Adafruit_DHT.read_retry(SENSOR, PIN)
  26.  
  27. if humidity is not None and temperature is not None:
  28.     payload = {
  29.         "temperature": round(temperature, 2),
  30.         "humidity": round(humidity, 2)
  31.     }
  32.  
  33.     print(f"Publish: {payload} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
  34.  
  35.     # ส่งไป broker 1
  36.     client1 = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
  37.     client1.username_pw_set(MQTT_USER1, MQTT_PASSWORD1)
  38.     client1.connect(MQTT_BROKER1, MQTT_PORT1, 60)
  39.     client1.publish(BROKER1_TOPIC, json.dumps(payload))
  40.     client1.disconnect()
  41.  
  42.     # ส่งไป broker 2
  43.     client2 = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)
  44.     client2.username_pw_set(MQTT_USER2, MQTT_PASSWORD2)
  45.     client2.connect(MQTT_BROKER2, MQTT_PORT2, 60)
  46.     client2.publish(BROKER2_TOPIC, json.dumps(payload))
  47.     client2.disconnect()

 

No comments:

Post a Comment