MENU

ESP8266自动配置HA

• 2024 年 01 月 27 日 • 阅读: 485 • 学习笔记

电路板相同 数据不同 则是一个设备两个实体

如果需要同一个设备 两个实体 则:

主题: homeassistant/sensor/HA/HA-ESP8266-01-01/config

{
  "unique_id": "HA-ESP8266-01-01",
  "name":"温度传感器",
  "icon":"mdi:thermometer",
  "state_topic":"HA-ESP8266-01/01/state",
  "json_attributes_topic":"HA-ESP8266-01/01/attributes",
  "unit_of_measurement":"℃",
  "device":{
    "identifiers":"ESP8266-01",
    "manufacturer":"liuxiaobai",
    "model":"HA",
    "name":"ESO8266-01",
    "sw_version":"1.0"
  }
}

测试数据

主题:HA-ESP8266-01/01/state

22

主题:homeassistant/sensor/HA/HA-ESP8266-01-02/config

{
  "unique_id": "HA-ESP8266-01-02",
  "name":"湿度传感器",
  "icon":"mdi:thermometer",
  "state_topic":"HA-ESP8266-01/02/state",
  "json_attributes_topic":"HA-ESP8266-01/01/attributes",
  "unit_of_measurement":"%RH",
  "device":{
    "identifiers":"ESP8266-01",
    "manufacturer":"liuxiaobai",
    "model":"HA",
    "name":"ESO8266-01",
    "sw_version":"1.0"
  }
}

测试数据

主题:HA-ESP8266-01/02/state

45
测试HA自动配置

如果需要同不同的设备 则:

主题:homeassistant/sensor/HA/HA-ESP8266-02-01/config

{
  "unique_id": "HA-ESP8266-02-01",
  "name":"湿度传感器1",
  "icon":"mdi:thermometer",
  "state_topic":"HA-ESP8266-02/01/state",
  "json_attributes_topic":"HA-ESP8266-02/01/attributes",
  "unit_of_measurement":"%RH",
  "device":{
    "identifiers":"ESP8266-02",
    "manufacturer":"文水县聚策科技有限公司",
    "model":"HA",
    "name":"ESO8266-02",
    "sw_version":"1.0"
  }
}

测试数据

主题:HA-ESP8266-02-01/state

45

python实现

import time
import network
import ujson
from umqtt import MQTTClient

# 这里需要根据自己的情况适当修改配置
homeassistant_device_name = "ESP8266-02"
homeassistant_device_sensor_name = "1"
homeassistant_device_sensor_type = "Temp"
# 下面的内容是固定格式 是需要替换对应数据即可
homeassistant_config_topic = "homeassistant/sensor/HA/HA-%s-%s/config" % (homeassistant_device_name, homeassistant_device_sensor_name)
homeassistant_config_content = {
    "unique_id":"HA-%s-%s" % (homeassistant_device_name, homeassistant_device_sensor_name),
    "name":homeassistant_device_sensor_type,
    "icon":"mdi:thermometer",
    "state_topic":"HA-%s/%s/state" % (homeassistant_device_name, homeassistant_device_sensor_name),
    "json_attributes_topic":"HA-%s/%s/attributes" %(homeassistant_device_name, homeassistant_device_sensor_name),
    # "unit_of_measurement":"℃",
    "device":{
        "identifiers": homeassistant_device_name,
        "manufacturer": "JuceSoft", #不允许中文
        "model": "HA",
        "name": homeassistant_device_name,
        "sw_version": "1.0"
    }
}
homeassistant_state_topic = "HA-%s/%s/state" % (homeassistant_device_name, homeassistant_device_sensor_name)
homeassistant_state_content = 23 # 这里是温湿度传感器的值

# print(homeassistant_config_topic)

SSID = "WIFI"
PASSWORD = "password"
def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect(SSID, PASSWORD)
 
    start = time.ticks_ms() # get millisecond counter
    while not wlan.isconnected():
        time.sleep(1) # sleep for 1 second
        if time.ticks_ms()-start > 20000:
            print("connect timeout!")
            break
 
    if wlan.isconnected():
        print('Connected! network config :', wlan.ifconfig())
  
# 回调函数 HA可以给esp发消息 主题是 my_esp8266
def sub_cb(topic,msg):
    print(topic,msg)

def main():
    do_connect()
  
    c = MQTTClient(homeassistant_device_name, "mqttIP", 1883, "admin", "password", keepalive=60)
    # 根据自己的情况修改mqttip 端口 账号 密码
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"my_esp8266")
  
    time.sleep(0.5)
  
    send_content = ujson.dumps(homeassistant_config_content)
    c.publish(homeassistant_config_topic,send_content)
  
    for i in range(100):
        time.sleep(0.5)
        c.publish(homeassistant_state_topic ,"%d" %i)
        print("esp8266...%d" %i)
        time.sleep(1)
  
if __name__ == "__main__":
    main()

温湿度

import time
import network
import ujson
from umqtt import MQTTClient
from machine import Pin
from dht import DHT22

# 这里需要根据自己的情况适当修改配置
homeassistant_device_name = "ESP8266-01"
homeassistant_device_sensor_name1 = "01"
homeassistant_device_sensor_name2 = "02"
homeassistant_device_sensor_type1 = "Temp"
homeassistant_device_sensor_type2 = "Humidity"
# 下面的内容是固定格式 是需要替换对应数据即可
homeassistant_config_topic1 = "homeassistant/sensor/HA/HA-%s-%s/config" % (homeassistant_device_name, homeassistant_device_sensor_name1)
homeassistant_config_topic2 = "homeassistant/sensor/HA/HA-%s-%s/config" % (homeassistant_device_name, homeassistant_device_sensor_name2)
homeassistant_config_content1 = {
    "unique_id":"HA-%s-%s" % (homeassistant_device_name, homeassistant_device_sensor_name1),
    "name":homeassistant_device_sensor_type1,
    "icon":"mdi:thermometer",
    "state_topic":"HA-%s/%s/state" % (homeassistant_device_name, homeassistant_device_sensor_name1),
    "json_attributes_topic":"HA-%s/%s/attributes" %(homeassistant_device_name, homeassistant_device_sensor_name1),
    # "unit_of_measurement":"℃",
    "device":{
        "identifiers": [homeassistant_device_name],
        "manufacturer": "JuCeSoft",
        "model": "HA",
        "name": homeassistant_device_name,
        "sw_version": "1.0"
    }
}
homeassistant_config_content2 = {
    "unique_id":"HA-%s-%s" % (homeassistant_device_name, homeassistant_device_sensor_name2),
    "name":homeassistant_device_sensor_type2,
    "icon":"mdi:water-percent",
    "state_topic":"HA-%s/%s/state" % (homeassistant_device_name, homeassistant_device_sensor_name2),
    "json_attributes_topic":"HA-%s/%s/attributes" %(homeassistant_device_name, homeassistant_device_sensor_name2),
    # "unit_of_measurement":"%",
    "device":{
        "identifiers": [homeassistant_device_name],
        "manufacturer": "JuCeSoft",
        "model": "HA",
        "name": homeassistant_device_name,
        "sw_version": "1.0"
    }
}
homeassistant_state_topic1 = "HA-%s/%s/state" % (homeassistant_device_name, homeassistant_device_sensor_name1)
homeassistant_state_topic2 = "HA-%s/%s/state" % (homeassistant_device_name, homeassistant_device_sensor_name2)

# 创建DHT22对象
dht_pin = Pin(0, Pin.IN) #接温湿度传感器的GPIO引脚
dht22 = DHT22(dht_pin)

def read_dht22():
    try:
        # 读取温湿度数据
        dht22.measure()
        temperature = dht22.temperature()
        humidity = dht22.humidity()

        return temperature, humidity

    except OSError as e:
        print("Error reading DHT22 sensor:", e)
        return None, None

def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect("wifi", "password")
 
    start = time.ticks_ms() # get millisecond counter
    while not wlan.isconnected():
        time.sleep(1) # sleep for 1 second
        if time.ticks_ms()-start > 20000:
            print("connect timeout!")
            break
 
    if wlan.isconnected():
        print('Connected! network config :', wlan.ifconfig())
  
# 回调函数 HA可以给esp发消息 主题是 my_esp8266
def sub_cb(topic,msg):
    print(topic,msg)

def main():
    do_connect()
  
  
  
    while True:
        # 读取温湿度数据
        temperature, humidity = read_dht22()
        c = MQTTClient(homeassistant_device_name, "mqttIP", 1883, "admin", "password", keepalive=60)
        # 根据自己的情况修改mqttip 端口 账号 密码
        c.set_callback(sub_cb)
        c.connect()
        c.subscribe(b"my_esp8266")
  
        time.sleep(0.5)
  
        send_content1 = ujson.dumps(homeassistant_config_content1)
        c.publish(homeassistant_config_topic1, send_content1)
  
        send_content2 = ujson.dumps(homeassistant_config_content2)
        c.publish(homeassistant_config_topic2, send_content2)
        # 如果成功读取到数据,则上传至Home Assistant
        if temperature is not None and humidity is not None:
            send_state_content1 = str(temperature)
            c.publish(homeassistant_state_topic1, send_state_content1)

            send_state_content2 = str(humidity)
            c.publish(homeassistant_state_topic2, send_state_content2)

        time.sleep(180) # 每隔3分钟读取一次温湿度数据
  
if __name__ == "__main__":
    main()

image.pngimage.png


本文作者:LiuXiaoBai
文章标题:ESP8266自动配置HA
本文地址:https://www.ounoe.com/archives/416
版权说明:若无注明,本文皆刘小白的小窝原创,转载请保留文章出处。

返回文章列表 文章二维码 打赏
本页链接的二维码
打赏二维码