signalk-czone 0.3.0-beta.13 → 0.3.0-beta.15

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,58 @@
1
+ 'use strict'
2
+
3
+ // A Shelly (Gen2 and later: Plus, Pro, PM Mini, 1PM, ...) reached directly on
4
+ // the network, through its local RPC API. No GX needed. Tested on a Shelly PM1
5
+ // on the test bench, 13 Oct 2026:
6
+ //
7
+ // GET http://<host>/rpc/Switch.GetStatus?id=<channel>
8
+ // -> {"id":0,"output":true,"apower":0.0,"voltage":239.1,"current":0.000, ...}
9
+ // GET http://<host>/rpc/Switch.Set?id=<channel>&on=true|false
10
+ //
11
+ // A Shelly with a password set refuses with 401; that is reported, not
12
+ // worked around (digest login is not supported yet).
13
+
14
+ const http = require('http')
15
+
16
+ const TIMEOUT_MS = 3000
17
+
18
+ // host: '192.168.1.204', or 'host:port' (a Shelly always uses 80; the port is
19
+ // for testing and for a Shelly behind a port forward).
20
+ function get (hostAndPort, pathAndQuery, { timeoutMs = TIMEOUT_MS, port = 80 } = {}) {
21
+ const m = /^(.+?)(?::(\d+))?$/.exec(String(hostAndPort))
22
+ const host = m[1]
23
+ if (m[2]) port = Number(m[2])
24
+ return new Promise((resolve, reject) => {
25
+ const req = http.get({ host, port, path: pathAndQuery, timeout: timeoutMs }, res => {
26
+ let body = ''
27
+ res.setEncoding('utf8')
28
+ res.on('data', c => { if (body.length < 65536) body += c })
29
+ res.on('end', () => {
30
+ if (res.statusCode === 401) return reject(new Error('the Shelly has a password set'))
31
+ if (res.statusCode !== 200) return reject(new Error(`HTTP ${res.statusCode}`))
32
+ try { resolve(JSON.parse(body)) } catch (_) { reject(new Error('not a Shelly Gen2 reply')) }
33
+ })
34
+ })
35
+ req.on('timeout', () => req.destroy(new Error('no answer')))
36
+ req.on('error', reject)
37
+ })
38
+ }
39
+
40
+ function createShellyDriver ({ port = 80, timeoutMs = TIMEOUT_MS } = {}) {
41
+ const opts = { port, timeoutMs }
42
+ return {
43
+ describe: entry => `Shelly ${entry.host}${entry.channel ? ` channel ${entry.channel}` : ''}`,
44
+ async status (entry) {
45
+ return get(entry.host, `/rpc/Switch.GetStatus?id=${entry.channel || 0}`, opts)
46
+ },
47
+ async read (entry) {
48
+ const s = await get(entry.host, `/rpc/Switch.GetStatus?id=${entry.channel || 0}`, opts)
49
+ if (typeof s.output !== 'boolean') throw new Error('no switch on that channel')
50
+ return s.output
51
+ },
52
+ async write (entry, on) {
53
+ await get(entry.host, `/rpc/Switch.Set?id=${entry.channel || 0}&on=${on ? 'true' : 'false'}`, opts)
54
+ }
55
+ }
56
+ }
57
+
58
+ module.exports = { createShellyDriver }
@@ -0,0 +1,115 @@
1
+ 'use strict'
2
+
3
+ // A Victron switchable output, on the GX's D-Bus: anything Venus OS lists in
4
+ // its switch pane, whatever kind of service carries it. Tested on the bench,
5
+ // 13 Oct 2026, with a Shelly PM1 added to the Cerbo, which appears as
6
+ //
7
+ // com.victronenergy.acload.shelly_28372F37CD6C_0
8
+ // /CustomName 'Power Board'
9
+ // /SwitchableOutput/0/State 1 (on) / 0 (off), writable
10
+ // /SwitchableOutput/0/Settings/CustomName 'Power Board'
11
+ // /SwitchableOutput/0/Settings/Type 1 (on/off)
12
+ //
13
+ // The service name carries the device's MAC address, so it does not change
14
+ // when the output is renamed; the name is shown, the service is stored.
15
+ //
16
+ // The GX's own relays are switchable outputs of com.victronenergy.system
17
+ // (Compass Rose, Venus OS 3.80, 15 Oct 2026):
18
+ //
19
+ // /SwitchableOutput/0/Name 'GX internal relay 1'
20
+ // /SwitchableOutput/0/Settings/Function 0 (alarm relay)
21
+ // /SwitchableOutput/1/Name 'GX internal relay 2'
22
+ // /SwitchableOutput/1/Settings/Function 2 (manual)
23
+ //
24
+ // A relay the GX uses for something (alarm, generator, tank pump,
25
+ // temperature) must not be switched by anyone else: an output with a function
26
+ // is offered only when that function is Manual, and is never written
27
+ // otherwise, even if it was linked before its function was changed. An I/O
28
+ // extender's relays are expected to carry the same setting.
29
+
30
+ const OWN_SERVICE = 'com.victronenergy.switch.czone_circuits' // this plugin's own switch pane
31
+ const IFACE = 'com.victronenergy.BusItem'
32
+ const MANUAL = 2
33
+ const FUNCTIONS = { 0: 'alarm relay', 1: 'generator start/stop', 3: 'tank pump', 4: 'temperature relay' }
34
+ const ON_OFF = 1 // Settings/Type of an on/off output
35
+ const functionName = f => FUNCTIONS[f] || `function ${f}`
36
+
37
+ function errText (err) {
38
+ return Array.isArray(err) ? err.join(' ') : String((err && err.message) || err)
39
+ }
40
+
41
+ // dbus-native hands a variant over as [[signature], [value]].
42
+ function unwrap (v) {
43
+ if (Array.isArray(v) && v.length === 2 && Array.isArray(v[0]) && Array.isArray(v[1])) return v[1][0]
44
+ return v
45
+ }
46
+
47
+ function createVictronDriver ({ getBus } = {}) {
48
+ function call (msg) {
49
+ const bus = getBus()
50
+ return new Promise((resolve, reject) => {
51
+ bus.invoke(msg, (err, res) => err ? reject(new Error(errText(err))) : resolve(res))
52
+ })
53
+ }
54
+ const getValue = (service, path) => call({ destination: service, path, interface: IFACE, member: 'GetValue' }).then(unwrap)
55
+
56
+ const optional = (service, path) => getValue(service, path).then(v => (v === '' || v === null || v === undefined || Number.isNaN(Number(v)) ? undefined : Number(v)), () => undefined)
57
+ // Why an output may not be linked or switched, or null.
58
+ async function blocked (service, id) {
59
+ const f = await optional(service, `/SwitchableOutput/${id}/Settings/Function`)
60
+ if (f !== undefined && f !== MANUAL) return `used by the GX as ${functionName(f)}`
61
+ const t = await optional(service, `/SwitchableOutput/${id}/Settings/Type`)
62
+ if (t !== undefined && t !== ON_OFF) return 'not an on/off output'
63
+ return null
64
+ }
65
+
66
+ async function read (entry) {
67
+ const v = await getValue(entry.service, `/SwitchableOutput/${entry.output}/State`)
68
+ if (typeof v !== 'number') throw new Error('no switchable output there')
69
+ return v !== 0
70
+ }
71
+
72
+ async function write (entry, on) {
73
+ const why = await blocked(entry.service, entry.output)
74
+ if (why) throw new Error(`not switched: ${why} (set it to Manual on the GX to use it here)`)
75
+ const r = await call({ destination: entry.service, path: `/SwitchableOutput/${entry.output}/State`, interface: IFACE, member: 'SetValue', signature: 'v', body: [['i', on ? 1 : 0]] })
76
+ if (typeof r === 'number' && r !== 0) throw new Error(`the GX refused (${r})`)
77
+ }
78
+
79
+ // Every switchable output on the GX, for the settings page.
80
+ async function list () {
81
+ const names = await call({ destination: 'org.freedesktop.DBus', path: '/org/freedesktop/DBus', interface: 'org.freedesktop.DBus', member: 'ListNames' })
82
+ const services = (names || []).filter(n => /^com\.victronenergy\./.test(n) && n !== OWN_SERVICE && !/^com\.victronenergy\.(settings|logger|platform|modbustcp)$/.test(n))
83
+ const out = []
84
+ for (const service of services) {
85
+ let ids = []
86
+ try {
87
+ const items = await call({ destination: service, path: '/', interface: IFACE, member: 'GetItems' })
88
+ const paths = Array.isArray(items) ? items.map(i => i[0]) : Object.keys(items || {})
89
+ ids = [...new Set(paths.map(p => /^\/SwitchableOutput\/([^/]+)\/State$/.exec(p)).filter(Boolean).map(m => m[1]))]
90
+ } catch (_) {
91
+ // No GetItems: try the usual first channels.
92
+ for (const id of ['0', '1', '2', '3']) {
93
+ try { if (typeof await getValue(service, `/SwitchableOutput/${id}/State`) === 'number') ids.push(id) } catch (_) {}
94
+ }
95
+ }
96
+ for (const id of ids) {
97
+ const text = async p => { try { const v = await getValue(service, p); return typeof v === 'string' && v.trim() ? v.trim() : '' } catch (_) { return '' } }
98
+ const name = (await text(`/SwitchableOutput/${id}/Settings/CustomName`)) || (await text('/CustomName')) ||
99
+ [await text('/ProductName'), await text(`/SwitchableOutput/${id}/Name`)].filter(Boolean).join(' ') || service
100
+ const why = await blocked(service, id)
101
+ out.push({ value: `${service}#${id}`, label: name, service, output: id, available: !why, reason: why || undefined })
102
+ }
103
+ }
104
+ return out.sort((a, b) => a.label.localeCompare(b.label))
105
+ }
106
+
107
+ return {
108
+ describe: entry => (entry.label ? `${entry.label} (GX)` : `${entry.service} output ${entry.output}`),
109
+ read,
110
+ write,
111
+ list
112
+ }
113
+ }
114
+
115
+ module.exports = { createVictronDriver, OWN_SERVICE }
package/lib/inputs.js ADDED
@@ -0,0 +1,94 @@
1
+ 'use strict'
2
+
3
+ // CZone switch inputs: ON / OFF of each switch wired to a CZone module, from
4
+ // the module's own messages. The inputs and their wiring come from the ZCF's
5
+ // signal-input table (signalk-czone-zcf parseSignalInputs).
6
+ //
7
+ // PGN 65284 (0xFF04), module status, about every two seconds and on change:
8
+ // 27 99 <module dipswitch> <module kind> <bitmap, 32 bits, low byte first>
9
+ // PGN 65308 (0xFF1C), input message, sent on change:
10
+ // 27 99 <module dipswitch> <variant> <bitmap, 32 bits, low byte first>
11
+ //
12
+ // Where an input sits depends on the kind of module (its type in the ZCF):
13
+ //
14
+ // Signal Interface (0x0D). Test bench, 6 Oct 2026: module 2, five switches on
15
+ // inputs 0-4 closed one after another gave 02 00, 0A 00, 2A 00, AA 00, AA 02:
16
+ // input n (from 0) is bit 2n+1, in 65284 and in 65308 (variant 00). The
17
+ // message comes on change too, so a tap on a momentary switch is caught.
18
+ //
19
+ // COI (0x1F). SugarShack capture, 27 Sep 2026: a COI's 65284 carries its
20
+ // outputs only; its inputs are in 65308 (variant 03), numbered from 16 in
21
+ // the ZCF, input i at bit 2(i-16)+1. Module 1A input 19 -> 80 00, 1A input
22
+ // 20 -> 00 02, 1C input 17 -> 08 00.
23
+ //
24
+ // Control X PLUS (0x36). Compass Rose, 15 Oct 2026, each input operated twice:
25
+ // its 65284 has the outputs in bits 0-15 and the inputs above, input i (from
26
+ // 16 in the ZCF) at bit i when it switches to positive, bit i+1 when it
27
+ // switches to negative. Anchor Up (input 17, to +) bit 17; Ignition (24, to +)
28
+ // bit 24; High Bilge Water Alarm (18, to -) bit 19. Only one input to
29
+ // negative was seen. Its 65308 messages come in four variants (byte 3: 00,
30
+ // 01, 03, 06) and are not read.
31
+ //
32
+ // Other kinds: not decoded (no state rather than a guess).
33
+
34
+ const STATUS_PGN = 65284
35
+ const INPUT_PGN = 65308
36
+
37
+ const oddBits = first => input => 2 * (input - first) + 1
38
+ const LAYOUT = {
39
+ 0x0d: { name: 'Signal Interface', pgns: [STATUS_PGN, INPUT_PGN], first: 0, bit: oddBits(0) },
40
+ 0x1f: { name: 'COI', pgns: [INPUT_PGN], first: 16, bit: oddBits(16) },
41
+ 0x36: { name: 'Control X PLUS', pgns: [STATUS_PGN], first: 16, bit: (input, wiring) => input + (wiring === 'switchToNeg' ? 1 : 0) }
42
+ }
43
+
44
+ // data: 8 bytes of a 65284 or 65308 frame -> { module, variant, bitmap } or null
45
+ function decodeFrame (data) {
46
+ if (!data || data.length !== 8 || data[0] !== 0x27 || data[1] !== 0x99) return null
47
+ return { module: data[2], variant: data[3], bitmap: data.readUInt32LE(4) }
48
+ }
49
+
50
+ // true / false, or undefined when this kind of module or message does not
51
+ // carry the input.
52
+ function inputState (kind, bitmap, input, pgn, wiring) {
53
+ const layout = LAYOUT[kind]
54
+ if (!layout || !Number.isInteger(input) || !layout.pgns.includes(pgn)) return undefined
55
+ if (input < layout.first) return undefined
56
+ const bit = layout.bit(input, wiring)
57
+ if (bit > 31) return undefined
58
+ return ((bitmap >>> bit) & 1) === 1
59
+ }
60
+
61
+ function slugify (name) {
62
+ const cleaned = String(name || 'Input').trim().replace(/[^A-Za-z0-9]+/g, '_').replace(/^_+|_+$/g, '')
63
+ return cleaned || 'Input'
64
+ }
65
+
66
+ // The switch inputs of a loaded configuration, each with its Signal K path
67
+ // (electrical.czone.inputs.<name>.state) and its module's kind.
68
+ function switchInputs (mapping) {
69
+ const table = mapping && mapping.signalInputs
70
+ if (!table || !Array.isArray(table.inputs)) return []
71
+ const kinds = new Map((mapping.modules || []).filter(m => Number.isInteger(m.module)).map(m => [m.module, m.type]))
72
+ const used = new Map()
73
+ return table.inputs
74
+ .filter(i => i.type === 'switch' && Number.isInteger(i.module) && i.module !== 0)
75
+ .map(i => {
76
+ const base = slugify(i.name)
77
+ const count = (used.get(base) || 0) + 1
78
+ used.set(base, count)
79
+ const slug = count === 1 ? base : `${base}${count}`
80
+ const kind = kinds.get(i.module)
81
+ return {
82
+ name: String(i.name).trim(),
83
+ slug,
84
+ path: `electrical.czone.inputs.${slug}.state`,
85
+ module: i.module,
86
+ input: i.input,
87
+ wiring: i.wiring,
88
+ moduleKind: Number.isInteger(kind) ? kind : null,
89
+ decoded: Boolean(LAYOUT[kind])
90
+ }
91
+ })
92
+ }
93
+
94
+ module.exports = { STATUS_PGN, INPUT_PGN, LAYOUT, decodeFrame, inputState, switchInputs }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "signalk-czone",
3
- "version": "0.3.0-beta.13",
3
+ "version": "0.3.0-beta.15",
4
4
  "description": "BETA: Signal K CZone monitoring and control using dynamically parsed ZCF configuration and NMEA 2000",
5
5
  "main": "index.js",
6
6
  "keywords": [
@@ -42,10 +42,13 @@
42
42
  "icon.png"
43
43
  ],
44
44
  "scripts": {
45
- "test": "node test/zcf.test.js && node test/zcf-fixtures.test.js && node test/circuit-state.test.js && node test/czone.test.js && node test/nmea2000.test.js && node test/control-x-plus.test.js && node test/signalk.test.js && node test/write.test.js && node test/circuit-status.test.js && node test/status-mapping-regression.test.js && node test/state.test.js && node test/config-network.test.js && node test/config-namespace.test.js && node test/monitoring.test.js && node test/confirm-off.test.js && node test/webapp-current.test.js && node test/trends.test.js && node --require ./test/helpers/gx-low-space.cjs test/trends.test.js"
45
+ "test": "node test/zcf.test.js && node test/zcf-fixtures.test.js && node test/circuit-state.test.js && node test/czone.test.js && node test/nmea2000.test.js && node test/control-x-plus.test.js && node test/signalk.test.js && node test/write.test.js && node test/circuit-status.test.js && node test/status-mapping-regression.test.js && node test/state.test.js && node test/config-network.test.js && node test/config-namespace.test.js && node test/monitoring.test.js && node test/confirm-off.test.js && node test/webapp-current.test.js && node test/bridge.test.js && node test/trends.test.js && node test/inputs.test.js && node --require ./test/helpers/gx-low-space.cjs test/trends.test.js"
46
46
  },
47
47
  "dependencies": {
48
- "signalk-czone-zcf": "github:mattsmitchell/signalk-czone-zcf#4991170ac20a3506bfcc1131b2c7dd025c4a983c"
48
+ "signalk-czone-zcf": "0.1.0-beta.2"
49
+ },
50
+ "optionalDependencies": {
51
+ "dbus-native": "^0.4.0"
49
52
  },
50
53
  "repository": {
51
54
  "type": "git",
@@ -4,7 +4,7 @@
4
4
  const root = document.documentElement;
5
5
  const request = root.requestFullscreen || root.webkitRequestFullscreen;
6
6
  const exit = document.exitFullscreen || document.webkitExitFullscreen;
7
- const enabled = document.fullscreenEnabled ?? document.webkitFullscreenEnabled;
7
+ const enabled = document.fullscreenEnabled != null ? document.fullscreenEnabled : document.webkitFullscreenEnabled;
8
8
  if (!button || !request || !exit || enabled === false) return;
9
9
 
10
10
  const current = () => document.fullscreenElement || document.webkitFullscreenElement;