『瀚思彼岸』» 智能家居技术论坛

 找回密码
 立即注册
查看: 547|回复: 1

[插件集成] 使用外部python给homeassistant MQTT推送设备代码示例

[复制链接]

3

主题

60

帖子

326

积分

中级会员

Rank: 3Rank: 3

积分
326
金钱
266
HASS币
0
发表于 2023-6-28 14:35:48 | 显示全部楼层 |阅读模式
这个是纯个人学习,也相当于给一些练手的看看,HA有node-red方式方法是一样的,只是个人喜欢使用python,处理逻辑好用,具体代码可以下载附件
import json
import time

import paho.mqtt.client as mqtt

# 这段是你的MQTT的地址和端口信息
mqtt_server = "192.168.20.6"
mqtt_port = 1883
# ------------------------------------

client = mqtt.Client()
# 这段是你的MQTT的账户名和密码,
client.username_pw_set("homeassistant", "Eugae4phah6aaz9fohpei9duGuh7Yatujei4NoreiNai2eem7oQue1OhKoch7ooj")
client.connect(mqtt_server, mqtt_port, 60)


# 连接MQTT服务器,使用函数方式
def client_mqtt():
    mqtt_server = "192.168.20.6"
    mqtt_port = 1883
    client = mqtt.Client()
    client.username_pw_set("homeassistant", "Eugae4phah6aaz9fohpei9duGuh7Yatujei4NoreiNai2eem7oQue1OhKoch7ooj")
    client.connect(mqtt_server, mqtt_port, 60)


# 如果有批量,可以使用此种方式创建MQTT控件信息,直接调用函数就可以
def configure_device(client, device_type, device_id, name, manufacturer, model, sw_version, unit, icon, payload_on=None,
                     payload_off=None):
    topic_config = f"homeassistant/{device_type}/{device_id}/config"
    topic_state = f"homeassistant/{device_type}/{device_id}/state"

    config_data = {
        "name": name,
        "state_topic": topic_state,
        "unit_of_measurement": unit,
        "device": {
            "identifiers": [device_id],
            "manufacturer": manufacturer,
            "model": model,
            "name": name,
            "sw_version": sw_version
        },
        "icon": icon
    }

    if payload_on is not None and payload_off is not None:
        config_data["payload_on"] = payload_on
        config_data["payload_off"] = payload_off

    client.publish(topic_config, json.dumps(config_data))


# 单控件创建
while True:  # 循环创建,这个是测试环境,正式环境自己调节
    try:
        mqtt_topic_sensor_config = "homeassistant/sensor/test1/config"
        sensor_config = {
            "device_class": "temperature",
            ""
            "name": "test1",
            "state_topic": "homeassistant/sensor/test1/state",
            "unit_of_measurement": "°C",
            # "value_template": 0,
            "unique_id": "test1",
            # device信息,如果是相同的就会归纳到同一个设备,如果不同就是不同的设备
            "device": {
                "identifiers": ["my_sensor"],
                "manufacturer": "测试MQTT",
                "model": "Model 1.0",
                "name": "my_sensor",
                "sw_version": "1.0.0"
            },
            "icon": "mdi:thermometer"
        }
        # 这段代码是创建控件
        client.publish(mqtt_topic_sensor_config, json.dumps(sensor_config))
        # 这段代码是更新控件值信息
        client.publish("homeassistant/sensor/test1/state", '525')
        # 创建第二个控件--------------------------------------------------------
        mqtt_topic_sensor_config = "homeassistant/sensor/test/config"
        sensor_config = {
            "name": "test",
            "text": "",
            "state_topic": "homeassistant/sensor/test/state",
            # "value_template": "0",
            "unique_id": "test",
            # device信息,如果是相同的就会归纳到同一个设备,如果不同就是不同的设备
            "device": {
                "identifiers": ["my_sensor"],
                "manufacturer": "测试MQTT",
                "model": "Model 1.0",
                "name": "my_sensor",
                "sw_version": "1.0.0"
            },
            "icon": "mdi:thermometer"
        }
        # 这段代码是创建控件
        client.publish(mqtt_topic_sensor_config, json.dumps(sensor_config))
        # 这段代码是更新控件值信息
        client.publish("homeassistant/sensor/test/state", '1521')
        # 输出调试信息,正式可以拿掉
        print("OK")
    except Exception as e:
        # 错误,返回错误信息
        print(f"An error occurred: {e}")
        print("Attempting to reconnect...")
        client.reconnect()  # Attempt to reconnect

    # 设置的是每5秒更新一次
    time.sleep(5)  # Wait for 5 seconds


HA 使用外部开发发送MQTT方式进行配置设备信息.zip

1.68 KB, 下载次数: 0

回复

使用道具 举报

7

主题

1072

帖子

3361

积分

论坛元老

Rank: 8Rank: 8

积分
3361
金钱
2289
HASS币
0
发表于 2023-6-28 21:11:20 | 显示全部楼层
真棒,我原来只推送了一个,你这个好。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-4-30 09:07 , Processed in 0.149674 second(s), 26 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表