node-red-contrib-knx-ultimate 5.0.0 → 5.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,596 @@
1
+ 'use strict'
2
+
3
+ // Native MQTT bridge for the KNX gateway config node.
4
+ //
5
+ // When enabled it:
6
+ // - exposes every imported ETS group address (GA) as a Home Assistant MQTT entity
7
+ // (switch / sensor / binary_sensor / number / text, derived from the DPT),
8
+ // - exposes user-defined composite entities (cover / climate) that aggregate several GAs,
9
+ // - publishes each GA value to a retained state topic as telegrams arrive on the bus,
10
+ // - subscribes to the command topics and writes incoming HA commands back to the KNX bus,
11
+ // - publishes Home Assistant MQTT Discovery so the entities appear automatically in HA,
12
+ // - tracks an availability (online/offline) topic via Last Will,
13
+ // - re-announces discovery on the HA "birth" message (HA restart / integration re-add).
14
+ //
15
+ // Internally everything is reduced to two maps, so simple and composite entities share the
16
+ // same plumbing:
17
+ // - gaPublishers: GA -> [fn(decodedValue)] (KNX bus -> MQTT state topics)
18
+ // - commandHandlers: command topic -> fn(text) -> [{ ga, dpt, value }] (MQTT -> KNX bus)
19
+ //
20
+ // The bridge is best-effort: a broker that is down or misconfigured must never crash the
21
+ // runtime, and stopping/redeploying must never block on a slow broker.
22
+
23
+ const mqtt = require('mqtt')
24
+ const ha = require('./knx-home-assistant.js')
25
+
26
+ function slugify (value, fallback) {
27
+ const s = String(value == null ? '' : value)
28
+ .trim()
29
+ .toLowerCase()
30
+ .replace(/[^a-z0-9_-]+/g, '_')
31
+ .replace(/_+/g, '_')
32
+ .replace(/^_|_$/g, '')
33
+ return s || fallback
34
+ }
35
+
36
+ function sanitizeBaseTopic (value) {
37
+ const s = typeof value === 'string' ? value.trim() : ''
38
+ // Strip wildcards and surrounding slashes; MQTT base topics must be concrete.
39
+ return (s || 'knx-ultimate').replace(/[#+]/g, '').replace(/^\/+|\/+$/g, '') || 'knx-ultimate'
40
+ }
41
+
42
+ // A GA "1/2/3" becomes "1_2_3" for use inside topics and HA object ids.
43
+ function gaToSlug (ga) {
44
+ return String(ga == null ? '' : ga).replace(/[^0-9]+/g, '_').replace(/^_|_$/g, '')
45
+ }
46
+
47
+ function normalizeGa (ga) {
48
+ return typeof ga === 'string' ? ga.trim() : ''
49
+ }
50
+
51
+ function toFiniteNumber (value, fallback) {
52
+ const n = Number(value)
53
+ return Number.isFinite(n) ? n : fallback
54
+ }
55
+
56
+ function clamp (value, min, max) {
57
+ return Math.min(max, Math.max(min, value))
58
+ }
59
+
60
+ function createMqttBridge (options) {
61
+ const opts = options || {}
62
+ const node = opts.node
63
+ const onCommand = typeof opts.onCommand === 'function' ? opts.onCommand : () => {}
64
+ const onStatus = typeof opts.onStatus === 'function' ? opts.onStatus : () => {}
65
+
66
+ const url = typeof opts.url === 'string' ? opts.url.trim() : ''
67
+ const baseTopic = sanitizeBaseTopic(opts.baseTopic)
68
+ const discovery = opts.discovery !== false
69
+ const discoveryPrefix = (typeof opts.discoveryPrefix === 'string' && opts.discoveryPrefix.trim()) || 'homeassistant'
70
+ const username = typeof opts.username === 'string' && opts.username ? opts.username : undefined
71
+ const password = typeof opts.password === 'string' && opts.password ? opts.password : undefined
72
+
73
+ // Source per-GA entities: [{ ga, dpt, devicename }]
74
+ const sourceGAs = Array.isArray(opts.groupAddresses) ? opts.groupAddresses : []
75
+ // User-defined composite entities: [{ type:'cover'|'climate', name, ga... }]
76
+ const customEntities = Array.isArray(opts.customEntities) ? opts.customEntities : []
77
+ // Optional whitelist of GAs to expose as simple entities. null => expose all imported GAs.
78
+ const exposeFilter = Array.isArray(opts.exposedGAs)
79
+ ? new Set(opts.exposedGAs.map((g) => normalizeGa(g)).filter((g) => g !== ''))
80
+ : null
81
+ // GAs the user marked read-only: exposed as read-only HA entities (no command topic).
82
+ const readOnlyFilter = new Set(
83
+ (Array.isArray(opts.readOnlyGAs) ? opts.readOnlyGAs : [])
84
+ .map((g) => normalizeGa(g))
85
+ .filter((g) => g !== '')
86
+ )
87
+
88
+ const gatewayName = (node && node.name) || 'KNX Gateway'
89
+ const gatewaySlug = slugify(node && node.name, '') || slugify(node && node.id, 'knx')
90
+ const deviceId = `knx_${gatewaySlug}`
91
+
92
+ const root = `${baseTopic}/${gatewaySlug}`
93
+ const availabilityTopic = `${root}/availability`
94
+ // Home Assistant birth topic(s): on (re)start HA publishes "online" here and devices must
95
+ // re-announce their discovery. Default homeassistant/status; also cover a custom prefix.
96
+ const birthTopics = Array.from(new Set(['homeassistant/status', `${discoveryPrefix}/status`]))
97
+
98
+ const deviceBlock = {
99
+ identifiers: [deviceId],
100
+ name: gatewayName,
101
+ manufacturer: 'node-red-contrib-knx-ultimate',
102
+ model: 'KNX Ultimate Gateway'
103
+ }
104
+
105
+ // Resolve a GA's DPT from the ETS CSV (used to encode composite-entity writes).
106
+ const dptByGa = new Map()
107
+ sourceGAs.forEach((entry) => {
108
+ if (entry && typeof entry.ga === 'string' && entry.ga.trim() !== '' && entry.dpt) {
109
+ dptByGa.set(entry.ga.trim(), entry.dpt)
110
+ }
111
+ })
112
+ const resolveDpt = (ga, fallback) => dptByGa.get(normalizeGa(ga)) || fallback
113
+
114
+ // Unified plumbing (filled by the builders below).
115
+ const discoveryConfigs = [] // [{ topic, config }]
116
+ const gaPublishers = new Map() // ga -> [fn(decodedValue)]
117
+ const commandHandlers = new Map() // topic -> fn(text) -> [{ ga, dpt, value }]
118
+ const lastByTopic = new Map() // topic -> last published payload (dedupe + re-announce)
119
+
120
+ const usedSlugs = new Set()
121
+ function uniqueSlug (base) {
122
+ let slug = base
123
+ let i = 2
124
+ while (slug === '' || usedSlugs.has(slug)) {
125
+ slug = `${base || 'entity'}_${i}`
126
+ i += 1
127
+ }
128
+ usedSlugs.add(slug)
129
+ return slug
130
+ }
131
+
132
+ function addPublisher (ga, fn) {
133
+ const key = normalizeGa(ga)
134
+ if (key === '') return
135
+ if (!gaPublishers.has(key)) gaPublishers.set(key, [])
136
+ gaPublishers.get(key).push(fn)
137
+ }
138
+
139
+ function addDiscovery (domain, slug, config) {
140
+ discoveryConfigs.push({ topic: `${discoveryPrefix}/${domain}/${deviceId}/${slug}/config`, config })
141
+ }
142
+
143
+ // ---- Composite entities (cover / climate) ----------------------------------------------
144
+ // Track GAs consumed by composite entities so they are NOT also exposed as plain per-GA
145
+ // entities (which would duplicate them in Home Assistant).
146
+ const consumedGAs = new Set()
147
+
148
+ function buildCover (def, index) {
149
+ const name = (typeof def.name === 'string' && def.name.trim()) ? def.name.trim() : `Cover ${index + 1}`
150
+ const slug = uniqueSlug(slugify(name, `cover_${index + 1}`))
151
+ const uniqueId = `${deviceId}_${slug}`
152
+ const invert = def.invertPosition !== false // KNX 0% = open by default
153
+
154
+ const gaUpDown = normalizeGa(def.gaUpDown)
155
+ const gaStop = normalizeGa(def.gaStop)
156
+ const gaPosSet = normalizeGa(def.gaPosSet)
157
+ const gaPosState = normalizeGa(def.gaPosState)
158
+ if (!gaUpDown && !gaPosSet && !gaPosState) return // nothing usable
159
+
160
+ ;[gaUpDown, gaStop, gaPosSet, gaPosState].forEach((g) => { if (g) consumedGAs.add(g) })
161
+
162
+ const commandTopic = `${root}/${slug}/set`
163
+ const positionTopic = `${root}/${slug}/position`
164
+ const setPositionTopic = `${root}/${slug}/position/set`
165
+
166
+ const config = {
167
+ name,
168
+ unique_id: uniqueId,
169
+ object_id: uniqueId,
170
+ device_class: typeof def.deviceClass === 'string' && def.deviceClass ? def.deviceClass : 'blind',
171
+ availability_topic: availabilityTopic,
172
+ payload_available: 'online',
173
+ payload_not_available: 'offline',
174
+ device: deviceBlock
175
+ }
176
+
177
+ if (gaUpDown) {
178
+ config.command_topic = commandTopic
179
+ config.payload_open = 'OPEN'
180
+ config.payload_close = 'CLOSE'
181
+ config.payload_stop = gaStop ? 'STOP' : null
182
+ const dptUpDown = resolveDpt(gaUpDown, ha.COVER_DEFAULT_DPT.upDown)
183
+ const dptStop = resolveDpt(gaStop, ha.COVER_DEFAULT_DPT.stop)
184
+ commandHandlers.set(commandTopic, (text) => {
185
+ const cmd = String(text || '').trim().toUpperCase()
186
+ if (cmd === 'OPEN') return [{ ga: gaUpDown, dpt: dptUpDown, value: false }] // 0 = Up/Open
187
+ if (cmd === 'CLOSE') return [{ ga: gaUpDown, dpt: dptUpDown, value: true }] // 1 = Down/Close
188
+ if (cmd === 'STOP' && gaStop) return [{ ga: gaStop, dpt: dptStop, value: true }]
189
+ return []
190
+ })
191
+ }
192
+
193
+ if (gaPosSet || gaPosState) {
194
+ config.position_topic = positionTopic
195
+ config.position_open = 100
196
+ config.position_closed = 0
197
+ }
198
+ if (gaPosSet) {
199
+ config.set_position_topic = setPositionTopic
200
+ const dptPos = resolveDpt(gaPosSet, ha.COVER_DEFAULT_DPT.position)
201
+ commandHandlers.set(setPositionTopic, (text) => {
202
+ const haPos = toFiniteNumber(text, null)
203
+ if (haPos === null) return []
204
+ const knxPos = clamp(invert ? 100 - haPos : haPos, 0, 100)
205
+ return [{ ga: gaPosSet, dpt: dptPos, value: knxPos }]
206
+ })
207
+ }
208
+ if (gaPosState) {
209
+ addPublisher(gaPosState, (value) => {
210
+ const knxPos = toFiniteNumber(value, null)
211
+ if (knxPos === null) return
212
+ const haPos = clamp(invert ? 100 - knxPos : knxPos, 0, 100)
213
+ pub(positionTopic, String(Math.round(haPos)), true)
214
+ })
215
+ }
216
+
217
+ addDiscovery('cover', slug, config)
218
+ }
219
+
220
+ function buildClimate (def, index) {
221
+ const name = (typeof def.name === 'string' && def.name.trim()) ? def.name.trim() : `Climate ${index + 1}`
222
+ const slug = uniqueSlug(slugify(name, `climate_${index + 1}`))
223
+ const uniqueId = `${deviceId}_${slug}`
224
+
225
+ const gaCurrentTemp = normalizeGa(def.gaCurrentTemp)
226
+ const gaSetpointSet = normalizeGa(def.gaSetpointSet)
227
+ const gaSetpointState = normalizeGa(def.gaSetpointState) || gaSetpointSet
228
+ const gaOnOff = normalizeGa(def.gaOnOff)
229
+ if (!gaCurrentTemp && !gaSetpointSet) return // nothing usable
230
+
231
+ ;[gaCurrentTemp, gaSetpointSet, gaSetpointState, gaOnOff].forEach((g) => { if (g) consumedGAs.add(g) })
232
+
233
+ const currentTempTopic = `${root}/${slug}/current_temp`
234
+ const tempSetTopic = `${root}/${slug}/temp/set`
235
+ const tempStateTopic = `${root}/${slug}/temp/state`
236
+ const modeSetTopic = `${root}/${slug}/mode/set`
237
+ const modeStateTopic = `${root}/${slug}/mode/state`
238
+
239
+ const config = {
240
+ name,
241
+ unique_id: uniqueId,
242
+ object_id: uniqueId,
243
+ availability_topic: availabilityTopic,
244
+ payload_available: 'online',
245
+ payload_not_available: 'offline',
246
+ device: deviceBlock,
247
+ min_temp: toFiniteNumber(def.minTemp, 5),
248
+ max_temp: toFiniteNumber(def.maxTemp, 35),
249
+ temp_step: toFiniteNumber(def.tempStep, 0.5),
250
+ temperature_unit: 'C'
251
+ }
252
+
253
+ if (gaCurrentTemp) {
254
+ config.current_temperature_topic = currentTempTopic
255
+ addPublisher(gaCurrentTemp, (value) => {
256
+ const n = toFiniteNumber(value, null)
257
+ if (n !== null) pub(currentTempTopic, String(n), true)
258
+ })
259
+ }
260
+
261
+ if (gaSetpointSet) {
262
+ config.temperature_command_topic = tempSetTopic
263
+ const dptSet = resolveDpt(gaSetpointSet, ha.CLIMATE_DEFAULT_DPT.setpoint)
264
+ commandHandlers.set(tempSetTopic, (text) => {
265
+ const n = toFiniteNumber(text, null)
266
+ if (n === null) return []
267
+ return [{ ga: gaSetpointSet, dpt: dptSet, value: n }]
268
+ })
269
+ }
270
+ if (gaSetpointState) {
271
+ config.temperature_state_topic = tempStateTopic
272
+ addPublisher(gaSetpointState, (value) => {
273
+ const n = toFiniteNumber(value, null)
274
+ if (n !== null) pub(tempStateTopic, String(n), true)
275
+ })
276
+ }
277
+
278
+ if (gaOnOff) {
279
+ // Minimal HVAC mode support: off / heat, backed by a 1-bit on/off GA.
280
+ config.modes = ['off', 'heat']
281
+ config.mode_command_topic = modeSetTopic
282
+ config.mode_state_topic = modeStateTopic
283
+ const dptOnOff = resolveDpt(gaOnOff, ha.CLIMATE_DEFAULT_DPT.onOff)
284
+ commandHandlers.set(modeSetTopic, (text) => {
285
+ const mode = String(text || '').trim().toLowerCase()
286
+ if (mode === 'off') return [{ ga: gaOnOff, dpt: dptOnOff, value: false }]
287
+ return [{ ga: gaOnOff, dpt: dptOnOff, value: true }] // heat / any other -> on
288
+ })
289
+ addPublisher(gaOnOff, (value) => {
290
+ pub(modeStateTopic, value === true || value === 'true' || value === 1 ? 'heat' : 'off', true)
291
+ })
292
+ } else {
293
+ config.modes = ['heat']
294
+ }
295
+
296
+ addDiscovery('climate', slug, config)
297
+ }
298
+
299
+ customEntities.forEach((def, index) => {
300
+ if (!def || typeof def !== 'object') return
301
+ try {
302
+ if (def.type === 'cover') buildCover(def, index)
303
+ else if (def.type === 'climate') buildClimate(def, index)
304
+ } catch (_err) {
305
+ // A single malformed entity must not break the whole bridge.
306
+ }
307
+ })
308
+
309
+ // ---- Simple per-GA entities ------------------------------------------------------------
310
+ const simpleSeen = new Set()
311
+ sourceGAs.forEach((entry) => {
312
+ if (!entry || typeof entry.ga !== 'string' || entry.ga.trim() === '') return
313
+ const ga = entry.ga.trim()
314
+ if (consumedGAs.has(ga)) return // already part of a cover/climate
315
+ if (exposeFilter && !exposeFilter.has(ga)) return // deselected by the user
316
+ const baseSlug = gaToSlug(ga)
317
+ if (baseSlug === '' || simpleSeen.has(ga)) return
318
+ simpleSeen.add(ga)
319
+ const map = ha.mapDptToHa(entry.dpt)
320
+ // Read-only GAs are downgraded to a state-only domain and never get a command topic,
321
+ // so Home Assistant can display them but can't write back to the KNX bus.
322
+ const isReadOnly = readOnlyFilter.has(ga)
323
+ const domain = isReadOnly
324
+ ? (map.domain === 'switch' ? 'binary_sensor' : (map.domain === 'number' || map.domain === 'text' ? 'sensor' : map.domain))
325
+ : map.domain
326
+ const slug = uniqueSlug(baseSlug)
327
+ const uniqueId = `${deviceId}_${slug}`
328
+ const name = (typeof entry.devicename === 'string' && entry.devicename.trim()) ? entry.devicename.trim() : ga
329
+ const stateTopic = `${root}/${slug}/state`
330
+ const commandTopic = `${root}/${slug}/set`
331
+
332
+ const config = {
333
+ name,
334
+ unique_id: uniqueId,
335
+ object_id: uniqueId,
336
+ state_topic: stateTopic,
337
+ availability_topic: availabilityTopic,
338
+ payload_available: 'online',
339
+ payload_not_available: 'offline',
340
+ device: deviceBlock
341
+ }
342
+ switch (domain) {
343
+ case 'switch':
344
+ config.command_topic = commandTopic
345
+ config.payload_on = 'true'
346
+ config.payload_off = 'false'
347
+ config.state_on = 'true'
348
+ config.state_off = 'false'
349
+ break
350
+ case 'binary_sensor':
351
+ config.payload_on = 'true'
352
+ config.payload_off = 'false'
353
+ if (map.deviceClass) config.device_class = map.deviceClass
354
+ break
355
+ case 'number':
356
+ config.command_topic = commandTopic
357
+ if (typeof map.min === 'number') config.min = map.min
358
+ if (typeof map.max === 'number') config.max = map.max
359
+ if (typeof map.step === 'number') config.step = map.step
360
+ config.mode = 'box'
361
+ if (map.unit) config.unit_of_measurement = map.unit
362
+ break
363
+ case 'text':
364
+ config.command_topic = commandTopic
365
+ break
366
+ case 'sensor':
367
+ default:
368
+ if (map.unit) config.unit_of_measurement = map.unit
369
+ if (map.deviceClass) config.device_class = map.deviceClass
370
+ break
371
+ }
372
+ addDiscovery(domain, slug, config)
373
+
374
+ // KNX -> MQTT: publish the decoded value to the state topic.
375
+ addPublisher(ga, (value) => pub(stateTopic, ha.formatValueForMqtt(value), true))
376
+
377
+ // MQTT -> KNX: writable domains accept commands (unless the GA is read-only).
378
+ if (map.writable === true && !isReadOnly) {
379
+ const dpt = entry.dpt
380
+ commandHandlers.set(commandTopic, (text) => {
381
+ const value = ha.parseCommandFromMqtt(text, dpt)
382
+ if (value === null) return []
383
+ return [{ ga, dpt, value }]
384
+ })
385
+ }
386
+ })
387
+
388
+ const entityCount = discoveryConfigs.length
389
+ const commandTopics = Array.from(commandHandlers.keys())
390
+
391
+ let client = null
392
+ let closed = false
393
+
394
+ function log (msg) {
395
+ if (node && typeof node.log === 'function') node.log(`[mqtt] ${msg}`)
396
+ }
397
+
398
+ function publishRaw (topic, payload, retain) {
399
+ if (!client || closed) return
400
+ try {
401
+ client.publish(topic, payload, { retain: retain === true, qos: 0 })
402
+ } catch (_err) {
403
+ // best-effort
404
+ }
405
+ }
406
+
407
+ // Publish a state value, retained and deduplicated per topic.
408
+ function pub (topic, payload, retain) {
409
+ if (lastByTopic.get(topic) === payload) return
410
+ lastByTopic.set(topic, payload)
411
+ publishRaw(topic, payload, retain)
412
+ }
413
+
414
+ // Called from the config node on every GroupValue_Write/Response, with the value already
415
+ // decoded by KNXUltimate. Routes it to every MQTT topic that depends on this GA.
416
+ function publishState (ga, value) {
417
+ const publishers = gaPublishers.get(normalizeGa(ga))
418
+ if (!publishers) return
419
+ publishers.forEach((fn) => {
420
+ try {
421
+ fn(value)
422
+ } catch (_err) {
423
+ // best-effort
424
+ }
425
+ })
426
+ }
427
+
428
+ function warn (msg) {
429
+ if (node && typeof node.warn === 'function') {
430
+ try { node.warn(msg) } catch (_err) { /* ignore */ }
431
+ }
432
+ }
433
+
434
+ // Never let a callback passed in by the caller throw out of an mqtt event handler.
435
+ function safeStatus (status) {
436
+ try {
437
+ onStatus(status)
438
+ } catch (_err) {
439
+ // ignore
440
+ }
441
+ }
442
+
443
+ // (Re)publish availability + discovery + last known state for every entity. Called on
444
+ // connect and whenever HA comes online, so entities reappear after an HA restart.
445
+ function announce () {
446
+ try {
447
+ publishRaw(availabilityTopic, 'online', true)
448
+ if (discovery) {
449
+ discoveryConfigs.forEach((d) => {
450
+ try {
451
+ publishRaw(d.topic, JSON.stringify(d.config), true)
452
+ } catch (_err) {
453
+ // skip a single malformed config rather than abort the whole announce
454
+ }
455
+ })
456
+ }
457
+ // Re-send cached states so HA doesn't show "unknown" right after (re)announcing.
458
+ lastByTopic.forEach((payload, topic) => publishRaw(topic, payload, true))
459
+ log(`announced discovery (${discovery ? entityCount + ' entit(y/ies)' : 'discovery OFF'})`)
460
+ } catch (err) {
461
+ warn('MQTT announce error: ' + (err && err.message))
462
+ }
463
+ }
464
+
465
+ function handleIncoming (topic, buf) {
466
+ try {
467
+ const text = buf == null ? '' : buf.toString()
468
+
469
+ // Home Assistant birth message: re-announce everything when HA comes online.
470
+ if (birthTopics.includes(topic)) {
471
+ if (text.trim().toLowerCase() === 'online') announce()
472
+ return
473
+ }
474
+
475
+ const handler = commandHandlers.get(topic)
476
+ if (!handler) return
477
+ let writes = []
478
+ try {
479
+ writes = handler(text) || []
480
+ } catch (err) {
481
+ if (node && typeof node.error === 'function') node.error(err)
482
+ return
483
+ }
484
+ writes.forEach((w) => {
485
+ if (!w || !w.ga) return
486
+ try {
487
+ onCommand(w)
488
+ } catch (err) {
489
+ if (node && typeof node.error === 'function') node.error(err)
490
+ }
491
+ })
492
+ } catch (err) {
493
+ warn('MQTT message handling error: ' + (err && err.message))
494
+ }
495
+ }
496
+
497
+ function connect () {
498
+ if (!url) {
499
+ onStatus({ state: 'error', detail: 'missing url' })
500
+ return
501
+ }
502
+ const connectOpts = {
503
+ reconnectPeriod: 5000,
504
+ connectTimeout: 15000,
505
+ will: { topic: availabilityTopic, payload: 'offline', retain: true, qos: 0 }
506
+ }
507
+ if (username) connectOpts.username = username
508
+ if (password) connectOpts.password = password
509
+
510
+ try {
511
+ client = mqtt.connect(url, connectOpts)
512
+ } catch (err) {
513
+ safeStatus({ state: 'error', detail: err && err.message })
514
+ return
515
+ }
516
+
517
+ // Every handler is fully guarded: an exception thrown inside an mqtt event listener would
518
+ // otherwise become an uncaught exception and could take Node-RED down.
519
+ client.on('connect', () => {
520
+ try {
521
+ log(`connected to ${url} (${entityCount} entities)`)
522
+ announce()
523
+ try {
524
+ commandTopics.forEach((t) => client.subscribe(t, { qos: 0 }))
525
+ birthTopics.forEach((t) => client.subscribe(t, { qos: 0 }))
526
+ } catch (_err) {
527
+ // best-effort
528
+ }
529
+ safeStatus({ state: 'connected', detail: String(entityCount) })
530
+ } catch (err) {
531
+ warn('MQTT connect handler error: ' + (err && err.message))
532
+ }
533
+ })
534
+ client.on('message', handleIncoming)
535
+ client.on('reconnect', () => safeStatus({ state: 'reconnect' }))
536
+ client.on('offline', () => safeStatus({ state: 'offline' }))
537
+ client.on('error', (err) => {
538
+ warn(`MQTT error: ${err && err.message}`)
539
+ safeStatus({ state: 'error', detail: err && err.message })
540
+ })
541
+ client.on('close', () => safeStatus({ state: 'offline' }))
542
+ }
543
+
544
+ function close (done) {
545
+ closed = true
546
+ const c = client
547
+ client = null
548
+
549
+ let finished = false
550
+ function finish () {
551
+ if (finished) return
552
+ finished = true
553
+ clearTimeout(guard)
554
+ // Force-close the socket and stop reconnection attempts; never wait on the broker.
555
+ if (c) {
556
+ try {
557
+ c.end(true)
558
+ } catch (_err) {
559
+ // ignore
560
+ }
561
+ }
562
+ if (typeof done === 'function') done()
563
+ }
564
+
565
+ // Hard cap so stopping/redeploying is never blocked when the broker is slow or unreachable.
566
+ const guard = setTimeout(finish, 700)
567
+ if (typeof guard.unref === 'function') guard.unref()
568
+
569
+ if (!c) {
570
+ finish()
571
+ return
572
+ }
573
+
574
+ if (c.connected) {
575
+ // Best-effort retained "offline" before a graceful disconnect (the Last Will only fires
576
+ // on an ungraceful drop). The guard above bounds how long we wait for it.
577
+ try {
578
+ c.publish(availabilityTopic, 'offline', { retain: true, qos: 0 }, () => finish())
579
+ } catch (_err) {
580
+ finish()
581
+ }
582
+ } else {
583
+ finish()
584
+ }
585
+ }
586
+
587
+ return {
588
+ connect,
589
+ close,
590
+ publishState,
591
+ entityCount,
592
+ topics: { root, availabilityTopic, commandTopics }
593
+ }
594
+ }
595
+
596
+ module.exports = { createMqttBridge }
@@ -1,8 +1,32 @@
1
1
  <script type="text/markdown" data-help-name="knxUltimateIoTBridge">
2
- # KNX IoT Bridge
2
+ # MQTT Home Assistant - IoT
3
3
 
4
4
  Erstellen Sie bidirektionale Brücken zwischen KNX-Gruppenadressen und IoT-Kanälen (MQTT-Themen, REST-Endpunkte, Modbus-Register). Jede Zuordnung kann Werte skalieren, Payloads formatieren und Metadaten für nachgelagerte Nodes bereitstellen.
5
5
 
6
+ > **Zwei Modi.** Verwenden Sie den **Modus**-Schalter oben im Node:
7
+ > - **IoT-Bridge** (Standard) — das unten beschriebene klassische Verhalten (Zuordnungsliste, MQTT/REST/Modbus-Ausgabemeldungen).
8
+ > - **MQTT / Home Assistant (nativ)** — der Node verbindet sich direkt mit einem MQTT-Broker und überbrückt KNX ↔ MQTT in beide Richtungen, mit Home-Assistant-MQTT-Discovery, sodass Entitäten automatisch erscheinen.
9
+
10
+ ## Modus MQTT / Home Assistant
11
+
12
+ Eine native MQTT-Bridge mit Home-Assistant-Discovery. Benötigt einen MQTT-Broker, der sowohl von Node-RED als auch von Home Assistant erreichbar ist, mit aktivierter MQTT-Integration in HA. Alle Entitäten erscheinen unter einem einzigen Gerät mit dem Namen dieses Nodes.
13
+
14
+ - **KNX-Bus-Verbindung** — wie der Knoten Telegramme mit KNX austauscht:
15
+ - *Eigenständig* (Standard) — der Knoten kommuniziert direkt mit dem KNX-Gateway und hat keine Ein-/Ausgangs-Pins.
16
+ - *Flow-Nachrichten* — der Knoten zeigt einen Eingangs- und einen Ausgangs-Pin. Verbinden Sie den Ausgang eines KNXUltimate-Knotens im **Universal**-Modus mit dem Eingangs-Pin (KNX-Bus → MQTT) und den Ausgangs-Pin mit dem Eingang eines weiteren KNXUltimate-Knotens im **Universal**-Modus (MQTT → KNX-Bus).
17
+ - **Broker-URL / Benutzername / Passwort** — Verbindung zu Ihrem MQTT-Broker.
18
+ - **Basis-Topic / Discovery-Präfix** — Root-Topic für Status-/Befehls-Topics und das HA-Discovery-Präfix (Standard `homeassistant`).
19
+ - **Bereitzustellende Gruppenadressen** — jede im KNX-Gateway importierte Adresse (ETS-Liste) wird mit einem Kontrollkästchen angezeigt. Angehakte Adressen werden als Home-Assistant-Entitäten veröffentlicht, automatisch nach dem DPT typisiert (switch, sensor, binary_sensor, number, text). Verwenden Sie das Filterfeld und die Schaltflächen *Alle auswählen* / *Keine auswählen*. Standardmäßig sind alle Adressen ausgewählt. Jede Zeile hat zudem eine Option **Nur lesen**: eine schreibgeschützte Adresse wird weiterhin an Home Assistant veröffentlicht (ihr Status bleibt sichtbar), akzeptiert aber nie Befehle zurück auf den KNX-Bus (switch werden zu binary_sensor, number zu sensor). Die Schaltflächen *Nur lesen setzen* / *Nur lesen entfernen* wenden dies auf alle aktuell angezeigten Adressen an.
20
+ - **Rollläden & Thermostate** — fassen mehrere Adressen zu einer Entität zusammen:
21
+ - *Rollladen*: Auf/Ab-GA (1.008), optionale Stopp-GA (1.007), optionale Positions-GA Befehl/Status (5.001). *Position invertieren* bildet die KNX-Konvention (0% = offen) auf Home Assistant (100% = offen) ab.
22
+ - *Thermostat*: GA Ist-Temperatur (9.001), GA Sollwert Befehl/Status (9.001), optionale Ein/Aus-GA (1.001 → off/heat), plus Min-/Max-Temperatur und Schrittweite.
23
+
24
+ KNX-Buswerte werden an MQTT veröffentlicht und beschreibbare Datenpunkte akzeptieren Befehle von Home Assistant. Die Datenpunkttypen stammen aus der importierten ETS-Liste, sofern vorhanden, andernfalls aus KNX-Standardwerten (1.008 Auf/Ab, 1.007 Stopp, 5.001 Position, 9.001 Temperatur, 1.001 Ein/Aus); für zuverlässige Statuswerte sollten die von Rollläden/Thermostaten verwendeten Adressen im ETS-Import enthalten sein.
25
+
26
+ ---
27
+
28
+ Der Rest dieser Hilfe beschreibt den klassischen **IoT-Bridge**-Modus.
29
+
6
30
  ## Eingänge
7
31
 
8
32
  |Eigenschaft|Beschreibung|