From 51b69fe0b874f165b5661934727ba91d54bff406 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Sat, 21 Nov 2026 06:14:08 +0000 Subject: [PATCH 1/5] fix: retry discovery when a tree ends with no body A 343 followed by a 344 and no data cleared the tree session and the stall timer, then returned without scheduling a retry. The network stayed on discovering until restart. An empty body for a known network now fails the request the same way a malformed tree does. A tree that cannot be attributed to a network is still dropped. --- src/haDiscoveryTreeSession.js | 7 +++++++ tests/haDiscovery.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/haDiscoveryTreeSession.js b/src/haDiscoveryTreeSession.js index c83cb77..a142d84 100644 --- a/src/haDiscoveryTreeSession.js +++ b/src/haDiscoveryTreeSession.js @@ -588,6 +588,13 @@ class _HaDiscoveryTreeSession { if (!networkForTree || !treeXmlData) { this.logger.warn(`Received TreeXML end (344) but no buffer or network context was set.`); + // A 343 followed by a 344 with no body has already cleared the + // session and the stall deadline. Leaving it there keeps the + // network on "discovering" with nothing scheduled to retry. + // 'unknown' stays a drop: there is no network id worth retrying. + if (networkForTree && networkForTree !== 'unknown') { + this._handleTreeRequestFailure(networkForTree, 'empty tree response'); + } return null; } diff --git a/tests/haDiscovery.test.js b/tests/haDiscovery.test.js index 876c55a..4bf47d7 100644 --- a/tests/haDiscovery.test.js +++ b/tests/haDiscovery.test.js @@ -770,6 +770,33 @@ describe('HaDiscovery', () => { expect(mockSendCommandFn).toHaveBeenCalledTimes(2); }); + it('retries when a tree ends with no body', () => { + haDiscovery.trigger(); + expect(mockSendCommandFn).toHaveBeenCalledTimes(1); + + // 343 then 344 and nothing in between. The session is real and the + // network was taken off the pending queue at start, so dropping + // the end leaves discovery stuck on "discovering". + haDiscovery.handleTreeStart('343 Begin tree //PROJECT/254'); + haDiscovery.handleTreeEnd('344 End tree'); + + const state = haDiscovery._treeRequestState.get('254'); + expect(state).toBeDefined(); + expect(state.attempts).toBe(1); + expect(haDiscovery.activeTreeSession).toBeNull(); + + jest.advanceTimersByTime(haDiscovery._treeRetryInitialDelayMs); + expect(mockSendCommandFn).toHaveBeenCalledTimes(2); + }); + + it('does not retry a tree end that cannot be attributed to a network', () => { + haDiscovery.handleTreeStart('343 Begin tree'); + haDiscovery.handleTreeEnd('344 End tree'); + + expect(haDiscovery._treeRequestState.has('unknown')).toBe(false); + expect(mockSendCommandFn).not.toHaveBeenCalled(); + }); + it('rejects TreeXML with a DTD before handing it to xml2js', () => { haDiscovery.trigger(); haDiscovery.handleTreeStart('343 Begin tree //PROJECT/254'); From f4c6a524ae91945ad94b68ee0432113e94132a75 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Sat, 21 Nov 2026 06:14:38 +0000 Subject: [PATCH 2/5] fix: rate-limit MQTT gettree, getall, and announce Any client that can publish can ask C-Gate for a whole network as fast as the broker will take it. gettree, getall, and bridge/announce now share the existing sliding-window limiter, with a separate counter per command, and drop further commands once a kind exceeds 30 in a minute. The cap is a standalone setting so it can be raised without an add-on option that invites turning the limit off. --- docs/SETTINGS.md | 3 ++ src/config/schema.js | 27 ++++++++++++ src/mqttCommandRouter.js | 44 ++++++++++++++++++++ tests/defaultSettings.test.js | 4 +- tests/fixtures/defaultSettings.snapshot.json | 3 ++ tests/mqttCommandRouter.test.js | 37 ++++++++++++++++ 6 files changed, 116 insertions(+), 2 deletions(-) diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index 653fc1f..ef858d5 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -427,6 +427,9 @@ Mostly standalone-only knobs. Defaults are chosen for a typical install; change | `topicCacheMaxEntries` | *standalone only* | integer | `5000` | Cap on the computed-topic string cache. Floor of 100. | | `deviceStateMaxEntries` | *standalone only* | integer | `5000` | Cap on `DeviceStateManager`'s per-address level and last-seen maps. Bounds worst-case memory growth from device churn over long uptime. Floor of 100. | | `relativeLevelTimeoutMs` | *standalone only* | integer (ms) | `5000` | How long a relative-level command (increase/decrease) waits for the current level to come back before giving up. | +| `mqttAdminCommandMaxRequests` | *standalone only* | integer | `30` | How many MQTT `gettree`, `getall`, or `bridge/announce` commands of one kind are accepted per window. Each kind has its own counter, so a burst of getall does not block a gettree. Further commands in the window are logged and dropped. | +| `mqttAdminCommandWindowMs` | *standalone only* | integer (ms) | `60000` | Sliding window for `mqttAdminCommandMaxRequests`. | +| `mqttAdminCommandMaxTrackedKeys` | *standalone only* | integer | `16` | Cap on distinct keys the admin-command limiter tracks. | ### State resync diff --git a/src/config/schema.js b/src/config/schema.js index 4ab3b60..20a9e74 100644 --- a/src/config/schema.js +++ b/src/config/schema.js @@ -1393,6 +1393,33 @@ const SETTINGS_SCHEMA = { description: 'Timeout for outbound calls to the HA Supervisor API from the web UI.', reason: TUNING_ONLY_REASON }, + mqttAdminCommandMaxRequests: { + key: 'mqttAdminCommandMaxRequests', + type: 'number', + default: 30, + unit: 'none', + exposure: 'standalone', + description: 'How many MQTT gettree, getall, or bridge/announce commands of one kind are accepted per window. Each kind has its own counter.', + reason: 'These three commands each ask C-Gate for a whole network. A client that republishes one of them in a tight loop keeps the command pool busy and can wedge discovery. 30 a minute is more than a refresh of every network and application, and still stops a flood. Standalone on purpose: raising it from the add-on UI would be the usual response to the warning that exists to say the flood is happening.' + }, + mqttAdminCommandWindowMs: { + key: 'mqttAdminCommandWindowMs', + type: 'number', + default: 60000, + unit: 'ms', + exposure: 'standalone', + description: 'Sliding window for mqttAdminCommandMaxRequests.', + reason: TUNING_ONLY_REASON + }, + mqttAdminCommandMaxTrackedKeys: { + key: 'mqttAdminCommandMaxTrackedKeys', + type: 'number', + default: 16, + unit: 'none', + exposure: 'standalone', + description: 'Cap on distinct command keys tracked by the MQTT admin-command limiter. gettree, getall, and announce are the only keys.', + reason: TUNING_ONLY_REASON + }, relativeLevelTimeoutMs: { key: 'relativeLevelTimeoutMs', type: 'number', diff --git a/src/mqttCommandRouter.js b/src/mqttCommandRouter.js index a0413dc..7d77c66 100644 --- a/src/mqttCommandRouter.js +++ b/src/mqttCommandRouter.js @@ -5,6 +5,7 @@ const CoverRampTracker = require('./coverRampTracker'); const { createLogger } = require('./logger'); const { redactMqttPayload, describeCbusAddressRangeError } = require('./utils'); const { resolveSetting } = require('./config/schema'); +const RateLimiter = require('./web/rateLimiter'); const { MQTT_TOPIC_MANUAL_TRIGGER, MQTT_CMD_TYPE_GETALL, @@ -323,6 +324,7 @@ class MqttCommandRouter extends EventEmitter { */ _handleDiscoveryTrigger() { if (this.haDiscoveryEnabled) { + if (this._adminCommandLimited('announce')) return; this.logger.info('Manual HA Discovery triggered via MQTT'); this.emit('haDiscoveryTrigger'); } else { @@ -336,6 +338,7 @@ class MqttCommandRouter extends EventEmitter { * @private */ _handleGetTree(command) { + if (this._adminCommandLimited('gettree')) return; this.logger.debug(`Requesting device tree for network ${command.getNetwork()}`); // Emit event only; the bridge routes this to HaDiscovery.queueTreeRequest, @@ -356,6 +359,7 @@ class MqttCommandRouter extends EventEmitter { * @private */ _handleGetAll(command) { + if (this._adminCommandLimited('getall')) return; this.logger.debug(`Getting all devices for ${command.getNetwork()}/${command.getApplication()}`); // C-Gate path format: //PROJECT/network/application/* (wildcard gets all groups) @@ -462,6 +466,46 @@ class MqttCommandRouter extends EventEmitter { this.cgateCommandQueue.add(command); } } + + /** + * One sliding window shared by gettree, getall, and bridge/announce, with + * a separate counter per command. Rebuilt when the settings change so a + * test (or a reload) that tightens the cap takes effect on the next command. + * @returns {RateLimiter} + * @private + */ + _getAdminCommandLimiter() { + const maxRequests = resolveSetting(this.settings, 'mqttAdminCommandMaxRequests'); + const windowMs = resolveSetting(this.settings, 'mqttAdminCommandWindowMs'); + const maxTrackedSources = resolveSetting(this.settings, 'mqttAdminCommandMaxTrackedKeys'); + if (!this._adminCommandLimiter + || this._adminCommandLimiter.maxRequests !== maxRequests + || this._adminCommandLimiter.windowMs !== windowMs + || this._adminCommandLimiter.maxTrackedSources !== maxTrackedSources) { + this._adminCommandLimiter = new RateLimiter({ + windowMs, + maxRequests, + maxTrackedSources + }); + } + return this._adminCommandLimiter; + } + + /** + * @param {string} kind - gettree, getall, or announce + * @returns {boolean} true when the command must not be sent + * @private + */ + _adminCommandLimited(kind) { + if (this._getAdminCommandLimiter().isLimitedByKey(kind)) { + const windowSeconds = Math.round(this._adminCommandLimiter.windowMs / 1000); + this.logger.warn( + `Rejected MQTT ${kind}: more than ${this._adminCommandLimiter.maxRequests} in ${windowSeconds}s` + ); + return true; + } + return false; + } } Object.assign(MqttCommandRouter.prototype, require('./mqttCommandRouterSecurity')); diff --git a/tests/defaultSettings.test.js b/tests/defaultSettings.test.js index c6cb9de..f4a5b1d 100644 --- a/tests/defaultSettings.test.js +++ b/tests/defaultSettings.test.js @@ -11,14 +11,14 @@ describe('defaultSettings — frozen baseline', () => { expect(defaultSettings).toStrictEqual(defaultSettingsSnapshot); }); - it('exports the same 156 keys as the baseline', () => { + it('exports the same 159 keys as the baseline', () => { expect(Object.keys(defaultSettings).sort()) .toEqual(Object.keys(defaultSettingsSnapshot).sort()); // Bumping this count is only ever legitimate alongside a genuinely NEW // setting added to the fixture; a changed value for an existing key is // the thing this baseline exists to catch, and must never be "fixed" // in the fixture. - expect(Object.keys(defaultSettings)).toHaveLength(156); + expect(Object.keys(defaultSettings)).toHaveLength(159); }); it('returns a fresh object so consumers cannot mutate the schema defaults', () => { diff --git a/tests/fixtures/defaultSettings.snapshot.json b/tests/fixtures/defaultSettings.snapshot.json index c78538b..a147bd2 100644 --- a/tests/fixtures/defaultSettings.snapshot.json +++ b/tests/fixtures/defaultSettings.snapshot.json @@ -103,6 +103,9 @@ "messageinterval": 200, "messageIntervalMinMs": 10, "mqtt": "localhost:1883", + "mqttAdminCommandMaxRequests": 30, + "mqttAdminCommandMaxTrackedKeys": 16, + "mqttAdminCommandWindowMs": 60000, "mqttCaFile": null, "mqttCertFile": null, "mqttConnectTimeoutMs": 30000, diff --git a/tests/mqttCommandRouter.test.js b/tests/mqttCommandRouter.test.js index e40e563..2534ee6 100644 --- a/tests/mqttCommandRouter.test.js +++ b/tests/mqttCommandRouter.test.js @@ -830,6 +830,43 @@ describe('MqttCommandRouter', () => { }); }); + describe('admin command rate limit', () => { + it('drops gettree, getall, and announce once each kind exceeds its own window', () => { + router.settings.mqttAdminCommandMaxRequests = 1; + const emitSpy = jest.spyOn(router, 'emit'); + const warnSpy = jest.spyOn(router.logger, 'warn'); + + router.routeMessage('cbus/write/254/0/0/gettree', ''); + router.routeMessage('cbus/write/254/0/0/gettree', ''); + expect(emitSpy.mock.calls.filter((call) => call[0] === 'treeRequest')).toHaveLength(1); + + router.routeMessage('cbus/write/254/56/0/getall', ''); + router.routeMessage('cbus/write/254/56/0/getall', ''); + expect(queueSpy.mock.calls.filter((call) => String(call[0]).startsWith('GET'))).toHaveLength(1); + + router.routeMessage('cbus/write/bridge/announce', ''); + router.routeMessage('cbus/write/bridge/announce', ''); + expect(emitSpy.mock.calls.filter((call) => call[0] === 'haDiscoveryTrigger')).toHaveLength(1); + + expect(warnSpy.mock.calls.map((call) => call[0]).join('\n')).toEqual(expect.stringContaining('Rejected MQTT gettree')); + expect(warnSpy.mock.calls.map((call) => call[0]).join('\n')).toEqual(expect.stringContaining('Rejected MQTT getall')); + expect(warnSpy.mock.calls.map((call) => call[0]).join('\n')).toEqual(expect.stringContaining('Rejected MQTT announce')); + }); + + it('does not count an announce while discovery is disabled', () => { + router.haDiscoveryEnabled = false; + router.settings.mqttAdminCommandMaxRequests = 1; + const emitSpy = jest.spyOn(router, 'emit'); + + router.routeMessage('cbus/write/bridge/announce', ''); + router.haDiscoveryEnabled = true; + router.routeMessage('cbus/write/bridge/announce', ''); + + expect(emitSpy).toHaveBeenCalledTimes(1); + expect(emitSpy).toHaveBeenCalledWith('haDiscoveryTrigger'); + }); + }); + describe('Switch Commands', () => { it('should handle ON switch commands', () => { router.routeMessage('cbus/write/254/56/1/switch', 'ON'); From d4cfbc63e510dc9536354d5125b60a6d8c2d6014 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Sat, 21 Nov 2026 06:14:43 +0000 Subject: [PATCH 3/5] fix: start a dim timeout when the level read is sent INCREASE and DECREASE armed their five-second wait as soon as the GET was queued. While the command pool was down that wait expired, Home Assistant was told the old level, and the ramp never went out. The wait now starts when the queue dequeues the read, and a read dropped from a full queue fails the dim immediately so the listener does not stay registered. --- docs/SETTINGS.md | 2 +- src/deviceStateManager.js | 73 ++++++++++++++++++++++++-------- src/mqttCommandRouterLighting.js | 19 +++++++-- src/throttledQueue.js | 64 ++++++++++++++++++++++++++-- tests/mqttCommandRouter.test.js | 63 +++++++++++++++++++++++++-- tests/throttledQueue.test.js | 43 +++++++++++++++++++ 6 files changed, 235 insertions(+), 29 deletions(-) diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index ef858d5..c8484fe 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -426,7 +426,7 @@ Mostly standalone-only knobs. Defaults are chosen for a typical install; change | `eventPublishCoalesce` | *standalone only* | boolean | `false` | Buffer publishes per topic and flush the latest value, instead of publishing every intermediate value. Cuts broker traffic during ramps at the cost of some latency. | | `topicCacheMaxEntries` | *standalone only* | integer | `5000` | Cap on the computed-topic string cache. Floor of 100. | | `deviceStateMaxEntries` | *standalone only* | integer | `5000` | Cap on `DeviceStateManager`'s per-address level and last-seen maps. Bounds worst-case memory growth from device churn over long uptime. Floor of 100. | -| `relativeLevelTimeoutMs` | *standalone only* | integer (ms) | `5000` | How long a relative-level command (increase/decrease) waits for the current level to come back before giving up. | +| `relativeLevelTimeoutMs` | *standalone only* | integer (ms) | `5000` | How long a relative-level command (increase/decrease) waits for the current level to come back before giving up. The wait starts when the level read leaves the command queue, so time spent waiting for a free C-Gate connection does not count. | | `mqttAdminCommandMaxRequests` | *standalone only* | integer | `30` | How many MQTT `gettree`, `getall`, or `bridge/announce` commands of one kind are accepted per window. Each kind has its own counter, so a burst of getall does not block a gettree. Further commands in the window are logged and dropped. | | `mqttAdminCommandWindowMs` | *standalone only* | integer (ms) | `60000` | Sliding window for `mqttAdminCommandMaxRequests`. | | `mqttAdminCommandMaxTrackedKeys` | *standalone only* | integer | `16` | Cap on distinct keys the admin-command limiter tracks. | diff --git a/src/deviceStateManager.js b/src/deviceStateManager.js index e9ebb9a..4e15c8b 100644 --- a/src/deviceStateManager.js +++ b/src/deviceStateManager.js @@ -176,9 +176,11 @@ class DeviceStateManager { * @param {string} address - Device address (network/app/group) * @param {Function} callback - Callback function to handle the level response * @param {number} [timeout] - Timeout in milliseconds (schema default if omitted) - * @returns {string} Operation ID that can be used to cancel the operation + * @param {{ deferTimeout?: boolean }} [options] - deferTimeout waits to arm the + * timer until startRelativeLevelTimeout, so queue time is not part of the wait + * @returns {string|null} Operation ID that can be used to cancel the operation */ - setupRelativeLevelOperation(address, callback, timeout) { + setupRelativeLevelOperation(address, callback, timeout, options = {}) { if (!Number.isFinite(timeout) || timeout <= 0) { timeout = resolveSetting(this.settings, 'relativeLevelTimeoutMs'); } @@ -188,34 +190,71 @@ class DeviceStateManager { } const operationId = `${address}_${Date.now()}`; + const deferTimeout = options.deferTimeout === true; - function cleanup() { - this.internalEventEmitter.removeListener(MQTT_TOPIC_SUFFIX_LEVEL, levelHandler); - clearTimeout(timeoutHandle); + /** @type {{ handler: (...args: any[]) => void, timeoutHandle: NodeJS.Timeout|null, timeout: number, finish: (level: number|null, timedOut: boolean) => void }} */ + const operation = { + handler: () => {}, + timeoutHandle: null, + timeout, + finish: () => {} + }; + + const finish = (level, timedOut) => { + if (!this.activeOperations.has(address)) return; + this.internalEventEmitter.removeListener(MQTT_TOPIC_SUFFIX_LEVEL, operation.handler); + if (operation.timeoutHandle) clearTimeout(operation.timeoutHandle); this.activeOperations.delete(address); - } + if (timedOut) { + this.logger.warn(`Timeout waiting for level response from ${address}`); + } + callback(level); + }; + operation.finish = finish; // Use .on() instead of .once() so non-matching address events don't consume the listener const levelHandler = (responseAddress, currentLevel) => { if (responseAddress === address) { - cleanup.call(this); this.logger.debug(`Received level response for ${address}: ${currentLevel}`); - callback(currentLevel); + finish(currentLevel, false); } }; + operation.handler = levelHandler; - const timeoutHandle = setTimeout(() => { - cleanup.call(this); - this.logger.warn(`Timeout waiting for level response from ${address}`); - callback(null); - }, timeout).unref(); - - this.activeOperations.set(address, { handler: levelHandler, timeoutHandle }); + this.activeOperations.set(address, operation); this.internalEventEmitter.on(MQTT_TOPIC_SUFFIX_LEVEL, levelHandler); - + if (!deferTimeout) this.startRelativeLevelTimeout(address); + return operationId; } + /** + * Arm the wait for a relative-level read. Called when the GET leaves the + * command queue, so a connection outage does not consume the timeout + * before C-Gate has been asked. + * @param {string} address + */ + startRelativeLevelTimeout(address) { + const operation = this.activeOperations.get(address); + if (!operation || operation.timeoutHandle) return; + operation.timeoutHandle = setTimeout(() => { + operation.finish(null, true); + }, operation.timeout).unref(); + } + + /** + * The level read will never be sent (the queue dropped it, or the queue + * was cleared). Fail the operation now so the listener does not stay + * registered until process exit. + * @param {string} address + */ + failRelativeLevelOperation(address) { + const operation = this.activeOperations.get(address); + if (!operation) return; + this.logger.warn(`Relative level read for ${address} left the queue before C-Gate saw it`); + operation.finish(null, false); + } + /** * Cancels an active relative level operation. * @@ -225,7 +264,7 @@ class DeviceStateManager { const operation = this.activeOperations.get(address); if (operation) { this.internalEventEmitter.removeListener(MQTT_TOPIC_SUFFIX_LEVEL, operation.handler); - clearTimeout(operation.timeoutHandle); + if (operation.timeoutHandle) clearTimeout(operation.timeoutHandle); this.activeOperations.delete(address); this.logger.debug(`Cancelled relative level operation for ${address}`); } diff --git a/src/mqttCommandRouterLighting.js b/src/mqttCommandRouterLighting.js index 8e3e4f7..a485309 100644 --- a/src/mqttCommandRouterLighting.js +++ b/src/mqttCommandRouterLighting.js @@ -41,12 +41,19 @@ class _MqttCommandRouterLighting { /** @type {Object} */ settings; - /** @type {{ cancelRelativeLevelOperation: Function, setupRelativeLevelOperation: Function, getLevel: Function }|null} */ + /** @type {{ cancelRelativeLevelOperation: Function, setupRelativeLevelOperation: Function, startRelativeLevelTimeout: Function, failRelativeLevelOperation: Function, getLevel: Function }|null} */ deviceStateManager; /** @type {{ publish: Function }|null} */ mqttClient; + /** + * Command queue (implemented on MqttCommandRouter). The relative-level + * read goes straight here so its onSent/onDrop hooks are not dropped. + * @type {{ add: (command: string, options?: { onSent?: Function, onDrop?: Function, priority?: string }) => void }} + */ + cgateCommandQueue; + /** * Queue a C-Gate command string (implemented on MqttCommandRouter). * @type {(command: string, priority?: *) => void} @@ -211,11 +218,17 @@ class _MqttCommandRouterLighting { state: newLevel > 0 ? MQTT_STATE_ON : MQTT_STATE_OFF, levelPercent: Math.round(newLevel / CGATE_LEVEL_MAX * 100) }); - }, timeoutMs); + }, timeoutMs, { deferTimeout: true }); // Query current level first; the response drives the callback above. + // The wait starts when this GET is dequeued to send. Time spent blocked + // behind an unhealthy command pool is not a missing level response, and + // a drop has to fail the listener or it stays registered forever. const queryCommand = `${CGATE_CMD_GET} ${cbusPath} ${CGATE_PARAM_LEVEL}${NEWLINE}`; - this._queueCommand(queryCommand); + this.cgateCommandQueue.add(queryCommand, { + onSent: () => this.deviceStateManager.startRelativeLevelTimeout(levelAddress), + onDrop: () => this.deviceStateManager.failRelativeLevelOperation(levelAddress) + }); } /** diff --git a/src/throttledQueue.js b/src/throttledQueue.js index 243eb52..3aef2fb 100644 --- a/src/throttledQueue.js +++ b/src/throttledQueue.js @@ -1,5 +1,9 @@ // @ts-check const { createLogger } = require('./logger'); + +// Marks a queue entry that carries send/drop hooks. The process function +// still receives the original item; only this queue sees the wrapper. +const QUEUE_HOOKS = Symbol('cgateQueueHooks'); const { clampSetting, redactCgateLine } = require('./utils'); const { resolveSetting } = require('./config/schema'); @@ -70,7 +74,7 @@ class ThrottledQueue { if (this._maxSize > 0 && this._length >= this._maxSize) { this._dropOneItem(); } - this._queues[priority].push(item); + this._queues[priority].push(this._attachHooks(item, options)); this._length++; if (!this._active) { @@ -98,11 +102,16 @@ class ThrottledQueue { return; } - const item = this._dequeueOneItem(); - if (item === undefined) { + const stored = this._dequeueOneItem(); + if (stored === undefined) { this._clearTimer(); return; } + const { item, onSent } = this._unwrap(stored); + // The command is leaving the queue now, after canProcess has passed. + // Callers that time a response (relative dim) start that wait here, + // not when the command was merely queued. + this._callHook(onSent, 'onSent'); this._isProcessing = true; let result; @@ -207,9 +216,10 @@ class ThrottledQueue { const dropOrder = ['bulk', 'normal', 'interactive', 'critical']; for (const priority of dropOrder) { if (this._queueLength(priority) > 0) { - this._takeFromQueue(priority); + const stored = this._takeFromQueue(priority); this._length--; this._droppedCount++; + this._callHook(this._unwrap(stored).onDrop, 'onDrop'); if (this._droppedCount === 1 || this._droppedCount % 100 === 0) { this._logger.warn(`${this._name} queue full (max ${this._maxSize}), dropping ${priority} items (${this._droppedCount} total dropped)`); this._onDrop?.(this._droppedCount, priority, this._maxSize); @@ -228,6 +238,13 @@ class ThrottledQueue { } clear() { + for (const priority of this._priorityOrder) { + while (this._queueLength(priority) > 0) { + const stored = this._takeFromQueue(priority); + this._length--; + this._callHook(this._unwrap(stored).onDrop, 'onDrop'); + } + } this._queues = { critical: [], interactive: [], normal: [], bulk: [] }; this._queueHeads = { critical: 0, interactive: 0, normal: 0, bulk: 0 }; this._length = 0; @@ -236,6 +253,45 @@ class ThrottledQueue { this._clearTimer(); } + /** + * @param {*} item + * @param {{ onSent?: Function, onDrop?: Function }} options + * @returns {*} + * @private + */ + _attachHooks(item, options) { + const onSent = typeof options.onSent === 'function' ? options.onSent : null; + const onDrop = typeof options.onDrop === 'function' ? options.onDrop : null; + if (!onSent && !onDrop) return item; + return { [QUEUE_HOOKS]: true, item, onSent, onDrop }; + } + + /** + * @param {*} stored + * @returns {{ item: *, onSent: Function|null, onDrop: Function|null }} + * @private + */ + _unwrap(stored) { + if (stored && typeof stored === 'object' && stored[QUEUE_HOOKS] === true) { + return stored; + } + return { item: stored, onSent: null, onDrop: null }; + } + + /** + * @param {Function|null} hook + * @param {string} label + * @private + */ + _callHook(hook, label) { + if (!hook) return; + try { + hook(); + } catch (error) { + this._logger.error(`Error in ${this._name} ${label} hook:`, { error }); + } + } + get length() { return this._length; } diff --git a/tests/mqttCommandRouter.test.js b/tests/mqttCommandRouter.test.js index 2534ee6..8df603c 100644 --- a/tests/mqttCommandRouter.test.js +++ b/tests/mqttCommandRouter.test.js @@ -11,7 +11,12 @@ describe('MqttCommandRouter', () => { beforeEach(() => { mockQueue = { - add: jest.fn() + add: jest.fn((_command, options) => { + // The production queue calls onSent when the command is + // dequeued. This mock sends immediately, which is what every + // test except the "still queued" cases is exercising. + if (options && typeof options.onSent === 'function') options.onSent(); + }) }; // Relative-level operations are owned by DeviceStateManager; the router // delegates to it. Share its event emitter so level responses reach the @@ -970,7 +975,10 @@ describe('MqttCommandRouter', () => { router.routeMessage('cbus/write/254/56/1/ramp', 'INCREASE'); // Should first query current level - expect(queueSpy).toHaveBeenCalledWith('GET //TestProject/254/56/1 level\n'); + expect(queueSpy).toHaveBeenCalledWith('GET //TestProject/254/56/1 level\n', expect.objectContaining({ + onSent: expect.any(Function), + onDrop: expect.any(Function) + })); // Simulate level response mockInternalEmitter.emit('level', '254/56/1', 100); @@ -983,7 +991,10 @@ describe('MqttCommandRouter', () => { router.routeMessage('cbus/write/254/56/1/ramp', 'DECREASE'); // Should first query current level - expect(queueSpy).toHaveBeenCalledWith('GET //TestProject/254/56/1 level\n'); + expect(queueSpy).toHaveBeenCalledWith('GET //TestProject/254/56/1 level\n', expect.objectContaining({ + onSent: expect.any(Function), + onDrop: expect.any(Function) + })); // Simulate level response with higher level mockInternalEmitter.emit('level', '254/56/1', 200); @@ -1043,7 +1054,10 @@ describe('MqttCommandRouter', () => { // Only the GET query should have been queued so far expect(queueSpy).toHaveBeenCalledTimes(1); - expect(queueSpy).toHaveBeenCalledWith('GET //TestProject/254/56/1 level\n'); + expect(queueSpy).toHaveBeenCalledWith('GET //TestProject/254/56/1 level\n', expect.objectContaining({ + onSent: expect.any(Function), + onDrop: expect.any(Function) + })); // Now the matching event arrives mockInternalEmitter.emit('level', '254/56/1', 100); @@ -1106,6 +1120,47 @@ describe('MqttCommandRouter', () => { }); }); + it('does not time out a dim while the level read is still waiting to be sent', () => { + withFakeTimers(() => { + mockQueue.add.mockImplementation(() => {}); + const warnSpy = jest.spyOn(router.logger, 'warn'); + + router.routeMessage('cbus/write/254/56/1/ramp', 'INCREASE'); + expect(mockInternalEmitter.listenerCount('level')).toBe(1); + + jest.advanceTimersByTime(5000); + expect(mockInternalEmitter.listenerCount('level')).toBe(1); + expect(warnSpy).not.toHaveBeenCalledWith(expect.stringContaining('INCREASE aborted')); + + mockQueue.add.mock.calls[0][1].onSent(); + jest.advanceTimersByTime(4999); + expect(mockInternalEmitter.listenerCount('level')).toBe(1); + jest.advanceTimersByTime(1); + expect(mockInternalEmitter.listenerCount('level')).toBe(0); + expect(warnSpy).toHaveBeenCalledWith(expect.stringContaining('INCREASE aborted')); + + warnSpy.mockRestore(); + }); + }); + + it('re-publishes the last known level when the level read is dropped before it is sent', () => { + withFakeTimers(() => { + mockQueue.add.mockImplementation(() => {}); + const publish = jest.fn(); + router.mqttClient = { publish }; + deviceStateManager._deviceLevels.set('254/56/1', 128); + + router.routeMessage('cbus/write/254/56/1/ramp', 'INCREASE'); + mockQueue.add.mock.calls[0][1].onDrop(); + + expect(mockInternalEmitter.listenerCount('level')).toBe(0); + expect(publish).toHaveBeenCalledWith( + 'cbus/read/254/56/1/level', '50', expect.any(Object) + ); + expect(queueSpy.mock.calls.some((c) => String(c[0]).startsWith('RAMP'))).toBe(false); + }); + }); + it('should clear timeout when matching response arrives before timeout', () => { withFakeTimers(() => { router.routeMessage('cbus/write/254/56/1/ramp', 'INCREASE'); diff --git a/tests/throttledQueue.test.js b/tests/throttledQueue.test.js index 4b6318e..60f6677 100644 --- a/tests/throttledQueue.test.js +++ b/tests/throttledQueue.test.js @@ -434,5 +434,48 @@ describe('ThrottledQueue', () => { queue.clear(); }); + + it('calls onSent only once canProcess allows the item out, and still processes the original item', () => { + jest.useFakeTimers(); + let allow = false; + const processed = []; + const sent = []; + const queue = new ThrottledQueue( + (item) => processed.push(item), + 10, + 'Hooks', + { canProcessFn: () => allow, retryWhenBlockedMs: 20 } + ); + + queue.add('GET level', { onSent: () => sent.push('GET level') }); + jest.advanceTimersByTime(100); + expect(processed).toEqual([]); + expect(sent).toEqual([]); + + allow = true; + jest.advanceTimersByTime(20); + expect(sent).toEqual(['GET level']); + expect(processed).toEqual(['GET level']); + + queue.clear(); + jest.useRealTimers(); + }); + + it('calls onDrop with the dropped command when the queue is full, and when it is cleared', () => { + const dropped = []; + const queue = new ThrottledQueue( + () => {}, + 1000, + 'Hooks', + { maxSize: 1, canProcessFn: () => false } + ); + + queue.add('first', { onDrop: () => dropped.push('first') }); + queue.add('second', { onDrop: () => dropped.push('second') }); + expect(dropped).toEqual(['first']); + + queue.clear(); + expect(dropped).toEqual(['first', 'second']); + }); }); }); \ No newline at end of file From 7922868f7045b98dbe204f9b6d5035d21160c268 Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Sat, 21 Nov 2026 06:14:53 +0000 Subject: [PATCH 4/5] fix: keep a newer network auto-discovery run when an older one finishes Each tree //PROJECT pass stored its handler on one field and cleared that field when it finished. A second pass replaced the handler, then the first pass's timeout or error nulled the new handler and could apply the first pass's networks. A generation counter lets only the current pass clear the handler and publish what it found. --- src/bridgeInitializationService.js | 14 ++++++++++++ tests/bridgeInitializationService.test.js | 26 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/bridgeInitializationService.js b/src/bridgeInitializationService.js index 6409a07..27379b4 100644 --- a/src/bridgeInitializationService.js +++ b/src/bridgeInitializationService.js @@ -84,6 +84,9 @@ class BridgeInitializationService { this._startupHolds = new Map(); /** @type {Map} */ this._networkCreatedPolledAt = new Map(); + // Bumped at the start of every auto-discovery run. An older run's + // finish must not clear the handler or networks a newer run owns. + this._networkDiscoveryGeneration = 0; } /** @@ -349,11 +352,18 @@ class BridgeInitializationService { let settled = false; const timeoutRef = { handle: null }; + const generation = ++this._networkDiscoveryGeneration; const finish = () => { if (settled) return; settled = true; clearTimeout(timeoutRef.handle); + // A newer run has replaced this one. Resolve so the caller is + // not left hanging, but leave its handler and its networks alone. + if (generation !== this._networkDiscoveryGeneration) { + resolve(); + return; + } processor.networkDiscoveryHandler = null; // Parse collected lines for network IDs: lines like "//HOME/254" or "//HOME/1" @@ -386,6 +396,10 @@ class BridgeInitializationService { // We collect lines that match //PROJECT/NNN and stop on a 4xx/5xx error or timeout. // Returning true claims the response so the default error logger doesn't also fire. processor.networkDiscoveryHandler = (responseCode, statusData) => { + if (generation !== this._networkDiscoveryGeneration) { + finish(); + return false; + } if (responseCode === '200') { collectedLines.push(statusData); return false; diff --git a/tests/bridgeInitializationService.test.js b/tests/bridgeInitializationService.test.js index f4ebe1a..56d669e 100644 --- a/tests/bridgeInitializationService.test.js +++ b/tests/bridgeInitializationService.test.js @@ -421,6 +421,32 @@ describe('BridgeInitializationService', () => { expect(commandQueueAdd).toHaveBeenCalledWith('tree //HOME\n'); }); + it('does not let an earlier discovery run clear or overwrite a later one', async () => { + const { bridge } = makeBridge({ cbusname: 'HOME' }); + const svc = makeService(bridge); + const processor = bridge.commandResponseProcessor; + + const first = svc._discoverNetworks(); + const firstHandler = processor.networkDiscoveryHandler; + const second = svc._discoverNetworks(); + const secondHandler = processor.networkDiscoveryHandler; + + expect(secondHandler).not.toBe(firstHandler); + + // The first run's responses, including the error that used to + // null the handler, belong to a generation that is no longer current. + firstHandler('200', '//HOME/1'); + firstHandler('400', 'superseded'); + expect(processor.networkDiscoveryHandler).toBe(secondHandler); + + secondHandler('200', '//HOME/254'); + jest.advanceTimersByTime(6000); + await Promise.all([first, second]); + + expect(bridge.discoveredNetworks).toEqual([254]); + expect(processor.networkDiscoveryHandler).toBeNull(); + }); + it('ignores non-network lines in the tree response', async () => { const { bridge } = makeBridge({ cbusname: 'HOME' }); const svc = makeService(bridge); From f1b4f3aeb0e1b49c7cd35ea1b1297a606e6aa10a Mon Sep 17 00:00:00 2001 From: Doug Rathbone Date: Sat, 21 Nov 2026 06:28:04 +0000 Subject: [PATCH 5/5] chore: release v1.40.5 --- homeassistant-addon/CHANGELOG.md | 12 ++++++++++++ homeassistant-addon/config.yaml | 2 +- package-lock.json | 4 ++-- package.json | 2 +- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/homeassistant-addon/CHANGELOG.md b/homeassistant-addon/CHANGELOG.md index a205d71..952a556 100644 --- a/homeassistant-addon/CHANGELOG.md +++ b/homeassistant-addon/CHANGELOG.md @@ -11,6 +11,18 @@ If this add-on saves you time, you can [buy me a coffee](https://buymeacoffee.co Releases before 1.22.0 are in the [changelog archive](https://github.com/dougrathbone/cgateweb/blob/master/homeassistant-addon/CHANGELOG-archive.md). +## [1.40.5](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.5) - 2026-11-21 + +### Fixed + +- **Discovery no longer stays on discovering when C-Gate ends a tree with no body.** The add-on treats that as a failed request and tries again. +- **Dim up and dim down no longer give up while the level read is still waiting to be sent.** The wait starts when the command leaves the queue, and a dropped read restores the last known level. +- **A second network scan no longer cancels the first.** Only the scan that is still running applies the networks it found. + +### Changed + +- **Repeated gettree, getall, and announce commands are limited to 30 of each kind per minute.** Further commands in that minute are ignored so a flood cannot keep C-Gate busy. + ## [1.40.4](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.4) - 2026-11-20 ### Fixed diff --git a/homeassistant-addon/config.yaml b/homeassistant-addon/config.yaml index afb0523..2d866b7 100644 --- a/homeassistant-addon/config.yaml +++ b/homeassistant-addon/config.yaml @@ -1,5 +1,5 @@ name: "C-Gate Web Bridge" -version: "1.40.4" +version: "1.40.5" slug: cgateweb description: "Bridge between Clipsal C-Bus systems and MQTT/Home Assistant" url: "https://github.com/dougrathbone/cgateweb" diff --git a/package-lock.json b/package-lock.json index b05ebd6..71b71fd 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "cgateweb", - "version": "1.40.4", + "version": "1.40.5", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "cgateweb", - "version": "1.40.4", + "version": "1.40.5", "license": "MIT", "dependencies": { "adm-zip": "^0.6.1", diff --git a/package.json b/package.json index 82f5822..ae2f791 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cgateweb", - "version": "1.40.4", + "version": "1.40.5", "description": "Node.js bridge connecting Clipsal C-Bus automation systems to MQTT for Home Assistant integration", "keywords": [ "cbus",