// HomeAssistant MQTT 自动发现配置 - 无分割版本
|
// 每个传感器单独发送,避免分割节点问题
|
|
const deviceId = "central_liquid_supply";
|
const deviceName = "新安国际集中供液系统";
|
const baseTopic = "homeassistant";
|
|
// 设备基本信息
|
const device = {
|
identifiers: [deviceId],
|
name: deviceName,
|
manufacturer: "新安国际",
|
model: "集中供液系统",
|
sw_version: "1.0"
|
};
|
|
// 所有传感器配置
|
const allSensors = [
|
{ type: "sensor", name: "温度", entity_id: "temperature", unit: "°C", device_class: "temperature" },
|
{ type: "sensor", name: "PH值", entity_id: "ph_value", unit: "pH" },
|
{ type: "sensor", name: "电导率", entity_id: "conductivity", unit: "μS/cm" },
|
{ type: "sensor", name: "储液当前液位", entity_id: "storage_level", unit: "L" },
|
{ type: "sensor", name: "供液一压力", entity_id: "supply_pressure_1", unit: "kPa", device_class: "pressure" },
|
{ type: "sensor", name: "供液二压力", entity_id: "supply_pressure_2", unit: "kPa", device_class: "pressure" },
|
{ type: "binary_sensor", name: "工作状态", entity_id: "work_status", device_class: "running" },
|
{ type: "binary_sensor", name: "报警状态", entity_id: "alarm_status", device_class: "problem" }
|
];
|
|
node.warn(`开始处理 ${allSensors.length} 个传感器配置`);
|
|
// 逐个发送传感器配置
|
allSensors.forEach((sensor, index) => {
|
const config = {
|
name: sensor.name,
|
unique_id: `${deviceId}_${sensor.entity_id}`,
|
state_topic: `${deviceId}/${sensor.type}/${sensor.entity_id}/state`,
|
device: device
|
};
|
|
// 根据传感器类型添加特定配置
|
if (sensor.type === "sensor") {
|
config.state_class = "measurement";
|
if (sensor.unit) config.unit_of_measurement = sensor.unit;
|
if (sensor.device_class) config.device_class = sensor.device_class;
|
} else if (sensor.type === "binary_sensor") {
|
config.device_class = sensor.device_class;
|
config.payload_on = sensor.entity_id === "work_status" ? "运行" : "报警";
|
config.payload_off = sensor.entity_id === "work_status" ? "停止" : "正常";
|
}
|
|
const mqttTopic = `${baseTopic}/${sensor.type}/${deviceId}_${sensor.entity_id}/config`;
|
const mqttPayload = JSON.stringify(config);
|
|
node.warn(`发送配置 ${index + 1}/${allSensors.length}: ${sensor.name}`);
|
node.warn(` 主题: ${mqttTopic}`);
|
|
// 立即发送MQTT消息
|
node.send({
|
topic: mqttTopic,
|
payload: mqttPayload,
|
retain: true
|
});
|
|
// 添加小延迟,确保消息按顺序发送
|
setTimeout(() => {
|
if (index === allSensors.length - 1) {
|
// 最后发送设备状态
|
node.send({
|
topic: `${deviceId}/status`,
|
payload: "online",
|
retain: true
|
});
|
node.warn("所有自动发现配置已发送完成");
|
}
|
}, index * 100);
|
});
|
|
return null; // 不通过return发送,直接通过node.send发送
|