Skip to content
Merged
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
5 changes: 4 additions & 1 deletion docs/SETTINGS.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,10 @@ 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. |

### State resync

Expand Down
12 changes: 12 additions & 0 deletions homeassistant-addon/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion homeassistant-addon/config.yaml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
14 changes: 14 additions & 0 deletions src/bridgeInitializationService.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ class BridgeInitializationService {
this._startupHolds = new Map();
/** @type {Map<string, number>} */
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;
}

/**
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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;
Expand Down
27 changes: 27 additions & 0 deletions src/config/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
73 changes: 56 additions & 17 deletions src/deviceStateManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
Expand All @@ -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.
*
Expand All @@ -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}`);
}
Expand Down
7 changes: 7 additions & 0 deletions src/haDiscoveryTreeSession.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand Down
44 changes: 44 additions & 0 deletions src/mqttCommandRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand All @@ -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)
Expand Down Expand Up @@ -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'));
Expand Down
19 changes: 16 additions & 3 deletions src/mqttCommandRouterLighting.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down Expand Up @@ -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)
});
}

/**
Expand Down
Loading
Loading