From 5652be5ca3b724b8ad663ce8c5b9ad3ea568f04e Mon Sep 17 00:00:00 2001 From: Aaron Ten Clay Date: Sun, 8 Oct 2023 04:11:10 -0700 Subject: [PATCH] First stab at fixing MQTT topic paths for HA discovery in 2023.8+ HomeAssistant 2023.8 changed the naming requirements for MQTT entities - entity names can no longer contain the device name. This means multiple entities might have the same name if you have multiple instances of the same device type, and they will clobber each other with the existing discovery topic naming scheme. This change inserts the host into the discovery topic name to avoid the clobbering. --- .gitignore | 3 +++ .gitlab-ci.yml | 2 ++ src/home_assistant.ts | 5 +++-- src/util.ts | 4 ++++ 4 files changed, 12 insertions(+), 2 deletions(-) create mode 100644 .gitlab-ci.yml diff --git a/.gitignore b/.gitignore index b079212..9f86038 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,6 @@ dist node_modules config.yml yarn-error.log + +# JetBrains Cruft +/.idea/ diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..16d0625 --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,2 @@ +include: + - template: Docker.gitlab-ci.yml diff --git a/src/home_assistant.ts b/src/home_assistant.ts index cf008f9..c7ef20a 100644 --- a/src/home_assistant.ts +++ b/src/home_assistant.ts @@ -1,6 +1,6 @@ import { Client } from "./mqtt"; import { TargetConfig } from "./types"; -import { md5, slugify } from "./util"; +import {md5, nodify, slugify} from "./util"; export const createHomeAssistantTopics = async ( mqtt: Client, @@ -31,7 +31,8 @@ export const createHomeAssistantTopics = async ( ? "binary_sensor" : "sensor"; const sensorName = slugify(sensor.name); - const topic = `${prefix}/${sensorType}/snmp2mqtt/${sensorName}/config`; + const nodeName = nodify(target.host); + const topic = `${prefix}/${sensorType}/snmp2mqtt-${nodeName}/${sensorName}/config`; const discovery: any = { availability: [ diff --git a/src/util.ts b/src/util.ts index 25364df..fbbf384 100644 --- a/src/util.ts +++ b/src/util.ts @@ -11,4 +11,8 @@ export function slugify(str: string) { ).replace(/^_+|_+$/g, ""); } +export function nodify(str: string) { + return str.replaceAll(/[^a-zA-Z0-9_-]/g, '_') +} + export const md5 = (str: string) => createHash("md5").update(str).digest("hex");