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
33 changes: 19 additions & 14 deletions .github/workflows/hacs-distribution.yml
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,25 @@ jobs:
fi
echo "Rendered distribution config validated at version ${VERSION}."

# Release notes and the source GitHub Release are created before the
# add-on store is updated. Doing it the other way left Supervisor on the
# new version whenever changelog extraction or the source release failed.
# If the store push fails after this point, the source release already
# exists and distribution-drift-check reports the unpublished tag.
- name: Write source-repo release notes from the changelog
env:
VERSION: ${{ steps.version.outputs.version }}
run: node tools/extract-changelog.js "$VERSION" > source-release-notes.md

- name: Create source-repo GitHub Release
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
tag_name: v${{ steps.version.outputs.version }}
name: v${{ steps.version.outputs.version }}
body_path: source-release-notes.md
draft: false
prerelease: false

- name: Checkout or initialize distribution repository
env:
HACS_DEPLOY_TOKEN: ${{ secrets.HACS_DEPLOY_TOKEN }}
Expand Down Expand Up @@ -401,20 +420,6 @@ jobs:
exit 1
fi

- name: Write source-repo release notes from the changelog
env:
VERSION: ${{ steps.version.outputs.version }}
run: node tools/extract-changelog.js "$VERSION" > source-release-notes.md

- name: Create source-repo GitHub Release
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
tag_name: v${{ steps.version.outputs.version }}
name: v${{ steps.version.outputs.version }}
body_path: source-release-notes.md
draft: false
prerelease: false

- name: Create distribution-repo GitHub Release
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3.0.3
with:
Expand Down
1 change: 1 addition & 0 deletions docs/SETTINGS.md
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,7 @@ C-Gate accepts connections on the command port before its networks have loaded,
| `haDiscoveryTreeRetryMaxDelayMs` | *standalone only* | integer (ms) | `60000` | Backoff ceiling. |
| `haDiscoveryTreeRequestTimeoutMs` | *standalone only* | integer (ms) | `8000` | "No response at all" timeout for a tree request. |
| `haDiscoveryTreeStreamStallMs` | *standalone only* | integer (ms) | `8000` | How long a tree stream may go **silent mid-transfer** before counting as stalled. Reset by every data chunk, so it bounds idle time rather than total transfer time. Raise it only if a very large tree on slow hardware still reports "tree stream stalled". |
| `haDiscoveryConfigCacheMaxEntries` | *standalone only* | integer | `20000` | How many discovery configs to remember so a broker restart can replay them. Past this, the oldest are dropped and the next restart re-requests the tree. A normal install never reaches it. |
| `haDiscoveryMaxTreeResyncAttempts` | *standalone only* | integer | `3` | Re-fetches of an accepted tree that still had empty `<Groups>` because C-Gate had not finished syncing group bindings. |
| `haDiscoveryTreeResyncInitialDelayMs` | *standalone only* | integer (ms) | `30000` | Initial delay before the first re-fetch. |
| `haDiscoveryTreeResyncMaxDelayMs` | *standalone only* | integer (ms) | `120000` | Ceiling for re-fetch backoff. |
Expand Down
11 changes: 11 additions & 0 deletions homeassistant-addon/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ 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.4](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.4) - 2026-11-20

### Fixed

- **Home Assistant no longer builds devices from a partial C-Bus tree.** When the tree arrives before discovery is ready and does not fit, the add-on discards it and requests a complete one.
- **A tree fragment with no matching start is ignored.** Discovery no longer assigns that fragment to the wrong network.

### Changed

- **Discovery keeps a bounded set of device configs across a broker restart.** An installation past that bound is rediscovered from C-Gate instead of growing the add-on's memory without a limit.

## [1.40.3](https://github.com/dougrathbone/cgateweb/releases/tag/v1.40.3) - 2026-11-14

### 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.3"
version: "1.40.4"
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.3",
"version": "1.40.4",
"description": "Node.js bridge connecting Clipsal C-Bus automation systems to MQTT for Home Assistant integration",
"keywords": [
"cbus",
Expand Down
25 changes: 22 additions & 3 deletions src/commandResponseProcessor.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ class CommandResponseProcessor {
? pendingCap
: resolveSetting({}, 'commandResponseMaxPendingTreeMessages');
this._pendingTreeOverflowLogged = false;
// Once a tree no longer fits, the rest of that tree is discarded too.
// Keeping the head and dropping the tail is what used to replay a
// truncated TREEXML into discovery.
this._pendingTreeDiscarding = false;
this.onObjectStatus = onObjectStatus;
this.onCommandError = onCommandError || null;
// Called for network-level interface/state responses
Expand Down Expand Up @@ -123,6 +127,7 @@ class CommandResponseProcessor {
this._pendingTreeMessages = [];
}
this._pendingTreeOverflowLogged = false;
this._pendingTreeDiscarding = false;
}

/**
Expand Down Expand Up @@ -520,22 +525,36 @@ class CommandResponseProcessor {
}

/**
* Queue a TREEXML fragment until HA Discovery is constructed. Log once
* when the cap is hit so a truncated tree is visible in the logs.
* Queue a TREEXML fragment until HA Discovery is constructed.
*
* A tree that does not fit is discarded whole. Replaying the fragments
* that happened to fit publishes a partial tree, and discovery then
* treats the missing groups as gone. The following startup request
* fetches a complete one. A later TREE_START begins a new buffer.
* @private
*/
_bufferTreeMessage(code, data) {
if (this._pendingTreeDiscarding) {
if (code === CGATE_RESPONSE_TREE_START) {
this._pendingTreeDiscarding = false;
} else {
if (code === CGATE_RESPONSE_TREE_END) this._pendingTreeDiscarding = false;
return;
}
}
if (this._pendingTreeMessages.length < this._maxPendingTreeMessages) {
if (code === CGATE_RESPONSE_TREE_START) {
this.logger.debug('Buffering tree start (HA Discovery not yet initialized)');
}
this._pendingTreeMessages.push({ code, data });
return;
}
this._pendingTreeMessages = [];
this._pendingTreeDiscarding = code !== CGATE_RESPONSE_TREE_END;
if (this._pendingTreeOverflowLogged) return;
this._pendingTreeOverflowLogged = true;
this.logger.warn(
`Dropping TREEXML fragments: HA Discovery is not ready and the pending-tree buffer is full (${this._maxPendingTreeMessages} messages). Discovery may start with a truncated tree.`
`Discarding incomplete TREEXML: HA Discovery is not ready and the pending-tree buffer is full (${this._maxPendingTreeMessages} messages). Discovery will request a fresh tree once it starts.`
);
}

Expand Down
11 changes: 10 additions & 1 deletion src/config/schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -1440,6 +1440,15 @@ const SETTINGS_SCHEMA = {
description: 'How long a TreeXML request may go without any response at all before it counts as failed.',
reason: TUNING_ONLY_REASON
},
haDiscoveryConfigCacheMaxEntries: {
key: 'haDiscoveryConfigCacheMaxEntries',
type: 'number',
default: 20000,
unit: 'none',
exposure: 'standalone',
description: 'How many Home Assistant discovery configs to remember so they can be replayed after a broker restart. Past this, the oldest are dropped and the next restart re-requests the tree.',
reason: 'Each config is a few hundred bytes and a normal install is well under this. The cap stops a stream of unique topics from growing the cache for the life of the process.'
},
haDiscoveryTreeStreamStallMs: {
key: 'haDiscoveryTreeStreamStallMs',
type: 'number',
Expand Down Expand Up @@ -1502,7 +1511,7 @@ const SETTINGS_SCHEMA = {
default: 500,
unit: 'none',
exposure: 'standalone',
description: 'How many TREEXML fragments to buffer while HA Discovery is still starting. Further fragments are dropped (with one warning) until discovery is ready.',
description: 'How many TREEXML fragments to buffer while HA Discovery is still starting. A tree that does not fit is discarded whole, and discovery requests a fresh one once it starts.',
reason: TUNING_ONLY_REASON
},
commandErrorRepeatWindowMs: {
Expand Down
59 changes: 53 additions & 6 deletions src/haDiscovery.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const path = require('path');
const { createLogger } = require('./logger');
const { findNetworkData, collectUnitGroups, collectUnitTypeData, networkHasUnsyncedUnits } = require('./haDiscoveryTree');
const { parseSecurityZoneLabelKey, securityZoneLabelKey } = require('./securityZoneLabels');
const { resolveSetting } = require('./config/schema');
const { resolveSetting, resolveClampedSetting } = require('./config/schema');
const {
DEFAULT_CBUS_APP_LIGHTING,
MQTT_RETAINED_STATE_OPTIONS,
Expand Down Expand Up @@ -54,14 +54,18 @@ class HaDiscovery {
// after an MQTT broker restart drops them (issue #44). Recorded in the
// _publish wrapper below rather than at each of the ~16 call sites that
// publish a config, so the cache cannot drift out of sync with them.
// Bounded by entity count: a few hundred payloads of roughly 500 bytes.
// Capped so a runaway unique-topic stream cannot grow for the life of
// the process. Updating an existing topic does not count as growth.
// Oldest entries are dropped first; a broker restart then re-requests
// the tree so those devices are announced again.
this._configCacheMaxEntries = resolveClampedSetting(settings || {}, 'haDiscoveryConfigCacheMaxEntries', { min: 1 });
this._configCacheEvicted = false;
this._discoveryNetworks = null;
this._publishedConfigPayloads = new Map();
this._rawPublish = publishFn;
this._publish = (topic, payload, options) => {
if (typeof topic === 'string' && topic.endsWith(CONFIG_TOPIC_SUFFIX)) {
// An empty payload is a retraction — forget it, don't replay it.
if (payload) this._publishedConfigPayloads.set(topic, payload);
else this._publishedConfigPayloads.delete(topic);
this._rememberConfigPayload(topic, payload);
}
return publishFn(topic, payload, options);
};
Expand Down Expand Up @@ -208,9 +212,12 @@ class HaDiscovery {
* A broker restart without retained-message persistence loses the configs,
* and Home Assistant then has no entities at all until the next tree run.
* Replaying the cached payloads restores them exactly, without re-running
* TREEXML and its retry/epoch machinery (issue #44).
* TREEXML and its retry/epoch machinery (issue #44). If the cache had to
* drop configs to stay within its cap, a fresh tree is requested as well
* so those devices are announced again.
*
* @returns {number} configs republished
* @this {HaDiscovery & HaDiscoveryMixinMethods}
*/
republishDiscoveryConfigs() {
let count = 0;
Expand All @@ -220,11 +227,50 @@ class HaDiscovery {
this._rawPublish(topic, payload, MQTT_RETAINED_STATE_OPTIONS);
count++;
}
if (this._configCacheEvicted) {
this.logger.warn(
'Discovery config cache was truncated; requesting a fresh tree so evicted devices are announced again'
);
this.trigger(this._discoveryNetworks);
}
if (count > 0) this.logger.info(`Republished ${count} HA Discovery config(s)`);
this.syncUnlistedGroupDiscovery();
return count;
}

/**
* Remember a discovery config for replay, or forget it when retracted.
* An update of a topic already cached refreshes that entry in place.
* A new topic past the cap evicts the oldest one.
* @param {string} topic
* @param {string} payload
* @private
*/
_rememberConfigPayload(topic, payload) {
if (!payload) {
this._publishedConfigPayloads.delete(topic);
return;
}
if (this._publishedConfigPayloads.has(topic)) {
// Refresh in place and move to the newest end of the eviction order.
this._publishedConfigPayloads.delete(topic);
this._publishedConfigPayloads.set(topic, payload);
return;
}
while (this._publishedConfigPayloads.size >= this._configCacheMaxEntries) {
const oldest = this._publishedConfigPayloads.keys().next().value;
if (oldest === undefined) break;
this._publishedConfigPayloads.delete(oldest);
if (!this._configCacheEvicted) {
this._configCacheEvicted = true;
this.logger.warn(
`HA discovery config cache reached ${this._configCacheMaxEntries} entries; oldest configs will not be replayed from memory. A broker restart re-requests the tree.`
);
}
}
this._publishedConfigPayloads.set(topic, payload);
}

/**
* Replace the label data (used for hot-reload).
* Accepts either a full labelData object or a plain Map for backward compatibility.
Expand Down Expand Up @@ -537,6 +583,7 @@ class HaDiscovery {
}

this.logger.info(`HA Discovery enabled, querying network trees...`);
this._discoveryNetworks = discoveredNetworks;
let networksToDiscover = this.settings.ha_discovery_networks;

// If no networks explicitly configured, fall back to auto-discovered networks
Expand Down
9 changes: 7 additions & 2 deletions src/haDiscoveryTreeSession.js
Original file line number Diff line number Diff line change
Expand Up @@ -511,8 +511,13 @@ class _HaDiscoveryTreeSession {

handleTreeData(statusData) {
if (!this.activeTreeSession) {
this.logger.warn('Received TreeXML data without active tree session; creating fallback session.');
this.handleTreeStart('');
// A data chunk with no TREE_START used to open a fallback session
// and attach the XML to whichever network was next in the queue,
// or to the literal 'unknown'. That corrupts discovery for the
// wrong network. Drop the chunk. The request watchdog still fails
// a tree that never completes.
this.logger.warn('Received TreeXML data without active tree session; ignoring it.');
return;
}
const chunk = typeof statusData === 'string' ? statusData : String(statusData);
// Cap while streaming so a compromised/runaway C-Gate cannot grow
Expand Down
51 changes: 51 additions & 0 deletions tests/cgateWebBridge.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1913,6 +1913,57 @@ describe('CgateWebBridge', () => {
);
expect(publishSpy.mock.calls[0][1]).toContain('No healthy connections');
});

it('warns once for a failed send and still sends the next command', async () => {
jest.useFakeTimers();
try {
mockConnectionPool.isStarted = true;
setPoolHealthyCount(3);
mockConnectionPool.getStats.mockImplementation(() => ({
isStarted: mockConnectionPool.isStarted,
isShuttingDown: false,
healthyConnections: mockConnectionPool.healthyConnections.size,
writableConnections: mockConnectionPool.healthyConnections.size
}));
let attempts = 0;
mockConnectionPool.execute.mockImplementation(async () => {
attempts += 1;
if (attempts === 1) {
throw new Error('No healthy connections available in pool');
}
return true;
});

bridge.settings.messageinterval = 10;
bridge.settings.messageIntervalMinMs = 10;
bridge.settings.commandMinIntervalMs = 10;
bridge.settings.commandMinIntervalFloorMs = 10;
bridge._buildQueues();

const publishSpy = jest.spyOn(bridge.mqttManager, 'publish');
bridge.cgateCommandQueue.add('CMD1\n');
bridge.cgateCommandQueue.add('CMD2\n');

for (let i = 0; i < 10 && mockConnectionPool.execute.mock.calls.length < 2; i++) {
jest.advanceTimersByTime(20);
await Promise.resolve();
await Promise.resolve();
}

expect(mockConnectionPool.execute).toHaveBeenCalledTimes(2);
expect(mockConnectionPool.execute).toHaveBeenNthCalledWith(1, 'CMD1\n');
expect(mockConnectionPool.execute).toHaveBeenNthCalledWith(2, 'CMD2\n');
const warnings = publishSpy.mock.calls.filter((call) => (
call[0] === 'hello/cgateweb/warnings'
&& String(call[1]).includes('C-Gate command send failed')
));
expect(warnings).toHaveLength(1);
expect(bridge.cgateCommandQueue.length).toBe(0);
} finally {
mockConnectionPool.execute.mockImplementation(async () => true);
jest.useRealTimers();
}
});
});

describe('command queue gating', () => {
Expand Down
Loading
Loading