Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 182 additions & 1 deletion lib/extension/homeassistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ const BINARY_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
color_sync: {entity_category: "config", icon: "mdi:sync-circle"},
consumer_connected: {device_class: "plug"},
contact: {device_class: "door"},
dhcp_enabled: {enabled_by_default: false, entity_category: "diagnostic", icon: "mdi:check-network-outline"},
garage_door_contact: {device_class: "garage_door", payload_on: false, payload_off: true},
frost_protection: {entity_category: "config", icon: "mdi:snowflake-thermometer"},
heating_stop: {entity_category: "config", icon: "mdi:radiator-off"},
Expand Down Expand Up @@ -186,9 +187,15 @@ const NUMERIC_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
humidity_calibration: {entity_category: "config", icon: "mdi:wrench-clock"},
humidity_max: {entity_category: "config", icon: "mdi:water-percent"},
humidity_min: {entity_category: "config", icon: "mdi:water-percent"},
ip_address: {
device_class: "ip_address",
enabled_by_default: false,
entity_category: "diagnostic",
},
illuminance_calibration: {entity_category: "config", icon: "mdi:wrench-clock"},
illuminance: {device_class: "illuminance", state_class: "measurement"},
illuminance_raw: {state_class: "measurement"},
irrigation_plan_remove_plan_index: {enabled_by_default: false, entity_category: "config", icon: "mdi:calendar-remove"},
internalTemperature: {
device_class: "temperature",
entity_category: "diagnostic",
Expand Down Expand Up @@ -243,6 +250,18 @@ const NUMERIC_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
entity_category: "diagnostic",
icon: "mdi:brightness-5",
},
seasonal_watering_adjustment_april: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_august: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_december: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_february: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_january: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_july: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_june: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_march: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_may: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_november: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_october: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
seasonal_watering_adjustment_september: {enabled_by_default: false, entity_category: "config", icon: "mdi:sprinkler-variant"},
smoke_density: {icon: "mdi:google-circles-communities", state_class: "measurement"},
soil_fertility: {device_class: "conductivity", state_class: "measurement"},
soil_moisture: {device_class: "moisture", state_class: "measurement"},
Expand Down Expand Up @@ -325,6 +344,7 @@ const LIST_DISCOVERY_LOOKUP: {[s: string]: KeyValue} = {
level_config: {entity_category: "diagnostic"},
programming_mode: {icon: "mdi:calendar-clock"},
schedule_settings: {icon: "mdi:calendar-clock"},
wifi_status: {enabled_by_default: false, entity_category: "diagnostic", icon: "mdi:wifi"},
} as const;

const featurePropertyWithoutEndpoint = (feature: zhc.Feature): string => {
Expand All @@ -335,6 +355,39 @@ const featurePropertyWithoutEndpoint = (feature: zhc.Feature): string => {
return feature.property;
};

const isSensitiveCompositeFeature = (feature: zhc.Feature): boolean => {
return /pass(word)?|token|secret|credential|key/i.test(feature.name) || /pass(word)?|token|secret|credential|key/i.test(feature.property);
};

const compositePathValueTemplate = (path: string[], lower = false): string => {
const pathExpression = path.map((part) => `["${part}"]`).join("");
const checks = path.map(
(part, index) =>
`${
index === 0
? "value_json"
: `value_json${path
.slice(0, index)
.map((p) => `["${p}"]`)
.join("")}`
}["${part}"] is defined`,
);
const value = `value_json${pathExpression}`;
const renderedValue = lower ? `${value} | string | lower` : value;

return `{% if ${checks.join(" and ")} %}{{ ${renderedValue} }}{% endif %}`;
};

const compositePathCommandTemplate = (path: string[], valueTemplate: string): string => {
let result = valueTemplate;

for (let i = path.length - 1; i >= 0; i--) {
result = `{"${path[i]}": ${result}}`;
}

return result;
};

/**
* This class handles the bridge entity configuration for Home Assistant Discovery.
*/
Expand Down Expand Up @@ -1300,6 +1353,134 @@ export class HomeAssistant extends Extension {
break;
}

if (firstExposeTyped.type === "composite") {
const firstComposite = firstExposeTyped as zhc.Composite;
const addCompositeFeatureDiscovery = (
feature: zhc.Feature,
path: string[],
labelParts: string[],
inheritedCategory?: "config" | "diagnostic",
): void => {
if (isSensitiveCompositeFeature(feature)) {
return;
}

const featureCategory =
feature.category === "config" || feature.category === "diagnostic" ? feature.category : inheritedCategory;

if (feature.type === "composite") {
for (const child of (feature as zhc.Composite).features) {
addCompositeFeatureDiscovery(child, [...path, child.property], [...labelParts, child.label], featureCategory);
}
return;
}

const allowsState = !!(feature.access & ACCESS_STATE);
const allowsSet = !!(feature.access & ACCESS_SET);
if (!allowsState && !allowsSet) {
return;
}

const objectId = path.join("_");
const name = endpointName ? `${labelParts.join(" ")} ${endpointName}` : labelParts.join(" ");
const writeOnlyConfig = allowsSet && !allowsState;
const advancedConfigGroup = ["wifi_config"].includes(firstComposite.property);
const discoveryPayload: KeyValue = {
name,
state_topic: allowsState,
...(allowsState && {
value_template: compositePathValueTemplate(path, isBinaryExpose(feature) && typeof feature.value_on === "boolean"),
}),
...(allowsSet && {
command_topic: true,
optimistic: !allowsState,
}),
};

if (writeOnlyConfig || advancedConfigGroup) {
discoveryPayload.entity_category = "config";
discoveryPayload.enabled_by_default = false;
}

if (featureCategory) {
discoveryPayload.entity_category ??= featureCategory;
}

if (isNumericExpose(feature)) {
if (allowsSet) discoveryPayload.command_template = compositePathCommandTemplate(path, "{{ value }}");
if (feature.unit) discoveryPayload.unit_of_measurement = feature.unit;
if (feature.value_step) discoveryPayload.step = feature.value_step;
if (feature.value_min != null) discoveryPayload.min = feature.value_min;
if (feature.value_max != null) discoveryPayload.max = feature.value_max;
Object.assign(discoveryPayload, NUMERIC_DISCOVERY_LOOKUP[feature.name]);

if (NUMERIC_DISCOVERY_LOOKUP[feature.name]?.device_class === "temperature") {
discoveryPayload.device_class = NUMERIC_DISCOVERY_LOOKUP[feature.name]?.device_class;
} else {
delete discoveryPayload.device_class;
}

discoveryEntries.push({
type: allowsSet ? "number" : "sensor",
object_id: objectId,
mockProperties: [{property: firstComposite.property, value: null}],
discovery_payload: discoveryPayload,
});
} else if (isEnumExpose(feature)) {
if (allowsSet) {
discoveryPayload.options = feature.values.map((v) => v.toString());
discoveryPayload.command_template = compositePathCommandTemplate(path, "{{ value | tojson }}");
}
Object.assign(discoveryPayload, ENUM_DISCOVERY_LOOKUP[feature.name]);
discoveryEntries.push({
type: allowsSet ? "select" : "sensor",
object_id: objectId,
mockProperties: [{property: firstComposite.property, value: null}],
discovery_payload: discoveryPayload,
});
} else if (isBinaryExpose(feature)) {
discoveryPayload.payload_on = feature.value_on.toString();
discoveryPayload.payload_off = feature.value_off.toString();
if (allowsSet) {
discoveryPayload.command_template = compositePathCommandTemplate(
path,
typeof feature.value_on === "boolean" ? "{{ value }}" : "{{ value | tojson }}",
);
}
Object.assign(discoveryPayload, BINARY_DISCOVERY_LOOKUP[feature.name]);
discoveryEntries.push({
type: allowsSet ? "switch" : "binary_sensor",
object_id: objectId,
mockProperties: [{property: firstComposite.property, value: null}],
discovery_payload: discoveryPayload,
});
} else if (feature.type === "text") {
const textFeature = feature as zhc.Text;
if (allowsSet) discoveryPayload.command_template = compositePathCommandTemplate(path, "{{ value | tojson }}");
Object.assign(discoveryPayload, LIST_DISCOVERY_LOOKUP[textFeature.name]);
discoveryEntries.push({
type: allowsSet ? "text" : "sensor",
object_id: objectId,
mockProperties: [{property: firstComposite.property, value: null}],
discovery_payload: discoveryPayload,
});
}
};

for (const feature of firstComposite.features) {
addCompositeFeatureDiscovery(
feature,
[firstComposite.property, feature.property],
[firstComposite.label, feature.label],
firstComposite.category,
);
}

if (discoveryEntries.length > 0) {
break;
}
}

if (firstExposeTyped.type === "text" && firstExposeTyped.access & ACCESS_SET) {
discoveryEntries.push({
type: "text",
Expand Down Expand Up @@ -1339,7 +1520,7 @@ export class HomeAssistant extends Extension {
// This takes precedence over definitions in this file.
if (firstExpose.category === "config" || firstExpose.category === "diagnostic") {
for (const entry of discoveryEntries) {
entry.discovery_payload.entity_category = firstExpose.category;
entry.discovery_payload.entity_category ??= firstExpose.category;
}
}

Expand Down
Loading
Loading