@rhizomatics/signalk-ble-sensors-plugin 0.0.0-stage → 1.0.1

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,30 @@
1
+ # [1.0.1]
2
+ No code change, re-release only for automated build.
3
+
4
+ # [1.0.0]
5
+
6
+ - Package moved to [Rhizomatics](https://www.rhizomatics.org.uk/sailing/)
7
+ - Choice of outdoor pressure sensors now limited to ones that have pressure (RuuviTags all have pressure in data structure, however the waterproof Pro tags send a placeholder only).
8
+
9
+ # [0.1.4]
10
+
11
+ Improved handling of Switchbot (Woan) thermometers with rolling codes in payload
12
+ Fix missing devices in registration dropdown
13
+
14
+ # [0.1.3]
15
+
16
+ Optionally re-publish a pressure value as `environment.outside.pressure` to cope with IP68 RuuviTag Pro that doesn't capture pressure, and re-use near enough value from an indoor standard RuuviTag.
17
+
18
+ # [0.1.2]
19
+
20
+ Improve RuuviTag support, adding motion sensor and removing humidity/pressure where not supported, e.g. the 3in1 or 2in1 RuuviTag Pro models
21
+ Fix for SwitchBot (Woan) thermometers that publish payloads with MAC address prefixes
22
+ The device RSSI is added to the drop-down list, to help work out which device is which ( e.g. saloon vs deck thermometers ) or even on another boat
23
+
24
+ # [0.1.1]
25
+
26
+ Simplify sensor names, and make sure values published with SignalK units.
27
+
28
+ # [0.1.0]
29
+
30
+ First alpha release
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # signalk-ble-sensors-plugin
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This is a limited replacement for `bt-sensors-plugin-sk` that has SignalK BLE Manager support, with only a few sensors known to work and passive only BLE integration. It may work for other sensors not listed here, and PRs welcome to add or correct support.
4
+
5
+ Passive BLE sensor listening for [SignalK](https://signalk.org/) — reads temperature, humidity and battery data broadcast by cheap, popular BLE sensors and republishes it to SignalK paths, without ever opening a Bluetooth connection to the device. Relies only on _BLE Manager_, so requires SignalK v2.31 or above with v2.34+ recommended.
6
+
7
+ ## How it works
8
+
9
+ Sensors like these broadcast their readings in plain BLE advertisement packets a few times a second. This plugin listens to that broadcast stream through the SignalK server's **BLE Manager API** and decodes it — there's no pairing, no GATT connection, and no battery drain on the sensor from being connected to.
10
+
11
+ Devices the plugin doesn't recognise (anything not in the supported list below — a phone, a fitness tracker, or a sensor type not yet supported) are ignored entirely; only useful advertisements from a recognised sensor type are ever surfaced, so there's noise from unknown devices reporting their Bluetooth signal strength.
12
+
13
+ ### Air Pressure Override
14
+
15
+ For boats that have IP68 RuuviTag Pro outside and RuuviTag inside, it can be handy to republish the inside pressure value as if it were outside, for example when using the _Barometer Trend_ plugin, so there's an option now to pick a device to publish the pressure also to `environment.outside.pressure`.
16
+
17
+ ## Requirements
18
+
19
+ - SignalK server **>= 2.31.0** with the BLE Manager enabled (Server → Bluetooth in the admin UI) and at least one BLE provider available — the server's own local Bluetooth adapter support is enough, or a BLE proxy.
20
+ - No other dependencies. This plugin never talks to Bluetooth hardware directly.
21
+
22
+ ## Supported sensors
23
+
24
+ | Sensor | Notes |
25
+ | ------------------------------------------------ | ------------------------------------------------------ |
26
+ | SwitchBot Meter (WoSensorTH) | Actively used, well tested |
27
+ | SwitchBot Meter Plus | Actively used, well tested |
28
+ | RuuviTag (data format 5) | Actively used, well tested |
29
+ | Xiaomi LYWSD03MMC (pvvx/atc1441 custom firmware) | Best-effort — not actively used, contributions welcome |
30
+ | Govee H5074 / H5075 | Best-effort — not actively used, contributions welcome |
31
+
32
+ Stock Xiaomi firmware (encrypted, not the ATC/pvvx custom firmware above) isn't supported. Sensors that need a GATT connection to read (Victron, Renogy, most BMS chips, etc.) are out of scope for this plugin. Many of these already have plugins, such as [signalk-bluetti-plugin](https://github.com/rhizomatics/signalk-bluetti-plugin) or [signalk-victron-ble](https://github.com/stefanor/signalk-victron-ble).
33
+
34
+ ## Configuring a sensor
35
+
36
+ 1. Install and enable the plugin, then restart (or just start) the SignalK server.
37
+ 2. Make sure the sensor is powered on and within Bluetooth range for a minute or two.
38
+ 3. Open the plugin's configuration page and click **+ Add Item** under "Registered sensors".
39
+ 4. Pick the sensor from the **Device** dropdown — it lists every recognised sensor the plugin has seen, labelled with its advertised name, sensor type, and MAC address. If it's not there yet, close the page, wait a bit longer, and reopen it.
40
+ 5. Fill in a **Zone / location** (e.g. `cabin`, `fridge`, `engine`) — this becomes part of the SignalK path (`environment.<zone>.temperature`, etc.); dots nest into sub-paths, e.g. `inside.mainCabin` becomes `environment.inside.mainCabin.temperature` — and optionally a **Name override**.
41
+ 6. Save. Readings should start appearing within a few seconds.
42
+
43
+ If a sensor measures pressure (currently RuuviTag only), it can optionally also be picked as the **Outside pressure source**
44
+ (a plugin-level setting, above "Registered sensors") to additionally publish its reading to `environment.outside.pressure` —
45
+ the SignalK-standard path other plugins (e.g. barometer trend) expect — alongside its own `environment.<zone>.pressure`. The
46
+ sensor still needs to be added under "Registered sensors" as usual; picking it here doesn't register it on its own.
47
+
48
+ ## Published paths
49
+
50
+ | Value | Path | Unit |
51
+ | ---------------- | --------------------------------- | ----------------------------------- |
52
+ | Temperature | `environment.<zone>.temperature` | K |
53
+ | Humidity | `environment.<zone>.humidity` | ratio (0-1) |
54
+ | Pressure | `environment.<zone>.pressure` | Pa |
55
+ | Battery strength | `sensors.<name>.battery.strength` | ratio (0-1), with low-battery zones |
56
+ | Battery voltage | `sensors.<name>.battery.voltage` | V |
57
+ | Signal strength | `sensors.<name>.RSSI` | dB |
58
+ | Reachable | `sensors.<name>.reachable` | boolean |
59
+ | Motion counter | `sensors.<name>.motionCounter` | count |
60
+
61
+ `<name>` is the sensor's name, lowercased and sanitized — give each registered sensor a distinct name, since
62
+ two sensors with the same name will collide on these paths. Not every sensor publishes every path above — only the values its
63
+ decoder actually supports (e.g. only RuuviTag currently reports pressure and a motion counter).
64
+
65
+ These path and unit conventions are reused from
66
+ [bt-sensors-plugin-sk](https://github.com/naugehyde/bt-sensors-plugin-sk) so this plugin's output lines up with dashboards or alarms already built against that plugin's paths.
67
+
68
+ ## Relationship to bt-sensors-plugin-sk
69
+
70
+ [bt-sensors-plugin-sk](https://github.com/naugehyde/bt-sensors-plugin-sk) is the more complete, actively maintained BLE sensor plugin for SignalK, supporting many more sensors including ones that need a GATT connection. It doesn't yet have support for the BLE Manager, so can suffer the same issues as other dedicated Bluetooth plugins. This plugin exists to cover the gap in the meantime for a narrower set of passive, advertisement-only sensors, and is expected to be retired once that support lands upstream.
71
+
72
+ ### Bluetooth Issues
73
+
74
+ There's a long list of of advice and fixes for Bluetooth Low Energy on SignalK at the [eInk Label Bluetooth](https://signalk-einklabel.rhizomatics.org.uk/bluetooth/#ble-manager-readiness) page that covers Bluetti use too, although Bluetti isn't as tricky to work with as some eInk labels.
@@ -0,0 +1,37 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256">
2
+ <defs>
3
+ <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
4
+ <stop offset="0" stop-color="#0f4c5c"/>
5
+ <stop offset="1" stop-color="#093542"/>
6
+ </linearGradient>
7
+ <linearGradient id="body" x1="0" y1="0" x2="0" y2="1">
8
+ <stop offset="0" stop-color="#f4f6f7"/>
9
+ <stop offset="1" stop-color="#d7dde0"/>
10
+ </linearGradient>
11
+ </defs>
12
+
13
+ <!-- app icon background -->
14
+ <rect x="0" y="0" width="256" height="256" rx="48" fill="url(#bg)"/>
15
+
16
+ <!-- advertisement broadcast waves -->
17
+ <g fill="none" stroke="#f4a340" stroke-width="9" stroke-linecap="round">
18
+ <path d="M182 58 A22 22 0 0 1 204 80"/>
19
+ <path d="M182 38 A42 42 0 0 1 224 80"/>
20
+ </g>
21
+
22
+ <!-- sensor body -->
23
+ <rect x="48" y="80" width="136" height="128" rx="18" fill="url(#body)" stroke="#093542" stroke-width="4"/>
24
+
25
+ <!-- display -->
26
+ <rect x="64" y="96" width="104" height="70" rx="8" fill="#0f4c5c"/>
27
+ <!-- thermometer glyph -->
28
+ <rect x="88" y="106" width="12" height="38" rx="6" fill="none" stroke="#7fd8c4" stroke-width="3"/>
29
+ <rect x="92" y="122" width="4" height="24" fill="#7fd8c4"/>
30
+ <circle cx="94" cy="150" r="8" fill="#7fd8c4"/>
31
+ <!-- humidity droplet glyph -->
32
+ <path d="M138 108 C134 116 126 126 126 136 a12 12 0 0 0 24 0 C150 126 142 116 138 108 z" fill="#7fd8c4"/>
33
+
34
+ <!-- status LED / button -->
35
+ <circle cx="116" cy="187" r="7" fill="none" stroke="#093542" stroke-width="4"/>
36
+ <circle cx="116" cy="187" r="2.5" fill="#093542"/>
37
+ </svg>
package/index.js ADDED
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+
3
+ module.exports = function (app) {
4
+ const plugin = {};
5
+ plugin.id = "signalk-ble-sensors-plugin";
6
+ plugin.name = "BLE Sensors (Passive)";
7
+ plugin.description =
8
+ "Passively listens to BLE advertisements from supported sensors (SwitchBot, RuuviTag, and others) via the SignalK BLE Manager API — no GATT connection required.";
9
+
10
+ // Lazy-required so a dependency load failure surfaces as a plugin error
11
+ // rather than crashing the server (mirrors the sibling signalk-bluetti-plugin).
12
+ let manager = null;
13
+
14
+ plugin.schema = function () {
15
+ const recognized = manager ? manager.getRecognizedDevices() : [];
16
+ const configured = manager ? manager.getConfiguredDevices() : [];
17
+ const outsidePressureSourceMac = manager ? manager.getOutsidePressureSourceMac() : null;
18
+ return buildSchema(recognized, configured, outsidePressureSourceMac);
19
+ };
20
+
21
+ plugin.start = function (options = {}) {
22
+ if (!app.bleApi) {
23
+ const msg =
24
+ "BLE Manager API (app.bleApi) is not available on this SignalK server — requires server >= 2.31.0 with Bluetooth enabled.";
25
+ app.setPluginError(msg);
26
+ return;
27
+ }
28
+
29
+ const SensorManager = require("./lib/sensor-manager");
30
+ manager = new SensorManager(app, plugin.id, (msg) => app.debug(msg));
31
+ manager.configure(options);
32
+
33
+ try {
34
+ manager.start();
35
+ } catch (err) {
36
+ app.setPluginError(err.message);
37
+ manager = null;
38
+ return;
39
+ }
40
+
41
+ const count = (options.sensors || []).filter((s) => s.enabled !== false).length;
42
+ app.setPluginStatus(`Listening for BLE sensor advertisements (${count} sensor${count === 1 ? "" : "s"} registered)`);
43
+ };
44
+
45
+ plugin.stop = function () {
46
+ if (manager) {
47
+ manager.stop();
48
+ manager = null;
49
+ }
50
+ };
51
+
52
+ return plugin;
53
+ };
54
+
55
+ function normalizeMac(mac) {
56
+ return String(mac).toLowerCase();
57
+ }
58
+
59
+ // adv.name is frequently blank for these sensors — SwitchBot and RuuviTag
60
+ // decode entirely from manufacturer/service data and don't depend on the BLE
61
+ // advertised name, which many providers never surface anyway (it's typically
62
+ // only present in a scan response, not the primary advertising packet). Drop
63
+ // the name segment rather than showing a literal placeholder. RSSI is
64
+ // appended as a live disambiguator: with a neighboring boat's identical
65
+ // sensor model also in range, the stronger (less negative) signal is
66
+ // generally the one actually on this boat. sensorTypeName is only known once
67
+ // a device's advertisement has actually been decoded — a registered MAC not
68
+ // yet re-observed since the plugin last started (see mergeKnownWithConfigured
69
+ // below) won't have one.
70
+ function formatDeviceLabel(d) {
71
+ const namePart = d.name ? `${d.name} — ` : "";
72
+ const typePart = d.sensorTypeName || "not seen since restart";
73
+ const rssiPart = d.rssi === undefined || d.rssi === null ? "" : ` · ${d.rssi}dBm`;
74
+ return `${namePart}${typePart} (${d.mac})${rssiPart}`;
75
+ }
76
+
77
+ // _recognized (and therefore getRecognizedDevices()) is runtime-only and
78
+ // resets on every plugin restart, while a MAC already saved in options.sensors
79
+ // persists across restarts. Without this merge, a registered sensor's MAC
80
+ // would vanish from the dropdown's enum until it happened to broadcast again,
81
+ // making an already-saved selection look like it disappeared even though
82
+ // it's still in the config. Merged-in entries carry no sensorTypeName (we
83
+ // only learn that by decoding an actual advertisement) or providesPressure
84
+ // (safe default: false, so they can't wrongly appear in the pressure-source
85
+ // dropdown until re-observed confirms what they are).
86
+ function mergeKnownWithConfigured(recognized, configured) {
87
+ const byMac = new Map(recognized.map((d) => [normalizeMac(d.mac), d]));
88
+ for (const c of configured) {
89
+ if (!c || !c.mac || byMac.has(normalizeMac(c.mac))) continue;
90
+ byMac.set(normalizeMac(c.mac), { mac: c.mac, name: c.name, sensorTypeName: null, providesPressure: false, rssi: undefined });
91
+ }
92
+ return [...byMac.values()];
93
+ }
94
+
95
+ function buildSchema(recognized, configured = [], outsidePressureSourceMac = null) {
96
+ const known = mergeKnownWithConfigured(recognized, configured).sort((a, b) => a.mac.localeCompare(b.mac));
97
+ const hasKnown = known.length > 0;
98
+
99
+ let pressureCapable = known.filter((d) => d.providesPressure);
100
+ // Same rationale as above, for the single outsidePressureSource pick: keep
101
+ // it selectable even if the device hasn't re-confirmed its pressure
102
+ // capability since the last restart.
103
+ if (outsidePressureSourceMac && !pressureCapable.some((d) => normalizeMac(d.mac) === normalizeMac(outsidePressureSourceMac))) {
104
+ pressureCapable = [...pressureCapable, { mac: outsidePressureSourceMac, name: null, sensorTypeName: null, rssi: undefined }].sort(
105
+ (a, b) => a.mac.localeCompare(b.mac),
106
+ );
107
+ }
108
+ const hasPressureCapable = pressureCapable.length > 0;
109
+
110
+ return {
111
+ type: "object",
112
+ properties: {
113
+ outsidePressureSource: {
114
+ type: "string",
115
+ title: "Outside pressure source",
116
+ description:
117
+ "Optional. Also publish this sensor's pressure reading to environment.outside.pressure — the SignalK-standard path other plugins (e.g. barometer trend) expect — in addition to its own environment.<zone>.pressure. Only sensors that have actually reported a pressure reading since the plugin started (e.g. a RuuviTag, but not the pressure-less RuuviTag Pro IP68) are listed here; the device must also be added as a registered sensor below to actually be read.",
118
+ enum: hasPressureCapable ? ["", ...pressureCapable.map((d) => d.mac)] : [""],
119
+ enumNames: hasPressureCapable
120
+ ? ["(none)", ...pressureCapable.map(formatDeviceLabel)]
121
+ : ["No pressure-capable sensors detected yet"],
122
+ },
123
+ sensors: {
124
+ type: "array",
125
+ title: "Registered sensors",
126
+ description:
127
+ "Sensors to publish to SignalK. Only devices already recognised as a supported sensor type appear in the dropdown below — after installing, give the plugin a minute or two to run (with the sensor in Bluetooth range) and then reopen this configuration page.",
128
+ items: {
129
+ type: "object",
130
+ title: "Sensor",
131
+ required: ["mac"],
132
+ properties: {
133
+ mac: {
134
+ type: "string",
135
+ title: "Device",
136
+ enum: hasKnown ? known.map((d) => d.mac) : [""],
137
+ enumNames: hasKnown ? known.map(formatDeviceLabel) : ["No recognised sensors detected yet"],
138
+ },
139
+ name: {
140
+ type: "string",
141
+ title: "Name override",
142
+ description:
143
+ "Used as the SignalK $source and in generated sensor paths. Defaults to the device's advertised name if it has one, otherwise its sensor type (e.g. 'SwitchBot Meter') — worth setting explicitly.",
144
+ },
145
+ zone: {
146
+ type: "string",
147
+ title: "Zone / location",
148
+ description:
149
+ "Used in environment.<zone>.* paths, e.g. 'cabin', 'engine', 'fridge'. Dots nest into sub-paths, e.g. 'inside.mainCabin' becomes environment.inside.mainCabin.*.",
150
+ examples: ["inside", "outside", "galley", "fridge", "cabin", "engine", "deck", "cockpit", "inside.mainCabin"],
151
+ },
152
+ enabled: { type: "boolean", title: "Enabled", default: true },
153
+ },
154
+ },
155
+ },
156
+ },
157
+ };
158
+ }
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+
3
+ // Normalises a raw BLEAdvertisement from the SignalK server's BLE Manager API
4
+ // (app.bleApi.onAdvertisement — see @signalk/server-api's bleapi.d.ts) into the
5
+ // shape our sensor decoders expect. manufacturerData/serviceData arrive as
6
+ // hex-encoded strings keyed by manufacturer ID / service UUID; decoders work
7
+ // against decoded Buffers instead.
8
+ function normalizeAdvertisement(adv) {
9
+ const manufacturerData = new Map();
10
+ if (adv.manufacturerData) {
11
+ for (const [key, hex] of Object.entries(adv.manufacturerData)) {
12
+ manufacturerData.set(Number(key), Buffer.from(hex, "hex"));
13
+ }
14
+ }
15
+
16
+ const serviceData = new Map();
17
+ if (adv.serviceData) {
18
+ for (const [uuid, hex] of Object.entries(adv.serviceData)) {
19
+ serviceData.set(uuid.toLowerCase(), Buffer.from(hex, "hex"));
20
+ }
21
+ }
22
+
23
+ const serviceUuids = (adv.serviceUuids || []).map((u) => u.toLowerCase());
24
+
25
+ return {
26
+ mac: adv.mac,
27
+ name: adv.name || "",
28
+ rssi: adv.rssi,
29
+ manufacturerData,
30
+ serviceData,
31
+ serviceUuids,
32
+ };
33
+ }
34
+
35
+ module.exports = { normalizeAdvertisement };
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+
3
+ // Govee H5074/H5075 thermo-hygrometers advertise manufacturer data under
4
+ // Govee's ID (0xEC88); the two models pack it differently, distinguished by
5
+ // each device's advertised name. No GATT connection needed.
6
+
7
+ const MANUFACTURER_ID = 0xec88;
8
+ const H5075_NAME = /^Govee_H5075_[0-9A-Fa-f]{4}$/;
9
+ const H5074_NAME = /^Govee_H5074_[0-9A-Fa-f]{4}$/;
10
+
11
+ function identify(adv) {
12
+ const md = adv.manufacturerData.get(MANUFACTURER_ID);
13
+ if (!md) return false;
14
+ return (H5075_NAME.test(adv.name) && md.length >= 6) || (H5074_NAME.test(adv.name) && md.length >= 6);
15
+ }
16
+
17
+ function decodeH5075(md) {
18
+ // 3-byte big-endian packed value: sign bit on the top byte, then
19
+ // temp-in-tenths-of-a-degree * 1000 + humidity-in-hundredths-of-a-percent.
20
+ const negative = (md[1] & 0x80) !== 0;
21
+ const packed = (md.readUIntBE(1, 3) & 0xffffff) ^ (negative ? 0x800000 : 0);
22
+ const tempTenths = Math.trunc(packed / 1000) * (negative ? -1 : 1);
23
+ const temp = 273.15 + tempTenths / 10;
24
+ const humidity = (packed % 1000) / 1000;
25
+ const battStrength = md[4] / 100;
26
+ return { temp, humidity, battStrength };
27
+ }
28
+
29
+ function decodeH5074(md) {
30
+ const temp = 273.15 + md.readInt16LE(1) / 100;
31
+ const humidity = md.readUInt16LE(3) / 10000;
32
+ const battStrength = md.readUInt8(5) / 100;
33
+ return { temp, humidity, battStrength };
34
+ }
35
+
36
+ function decode(adv) {
37
+ const md = adv.manufacturerData.get(MANUFACTURER_ID);
38
+ return H5075_NAME.test(adv.name) ? decodeH5075(md) : decodeH5074(md);
39
+ }
40
+
41
+ module.exports = {
42
+ id: "govee",
43
+ name: "Govee H5074/H5075",
44
+ domain: "environmental",
45
+ identify,
46
+ decode,
47
+ };
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+
3
+ // RuuviTag "data format 5" — https://github.com/ruuvi/ruuvi-sensor-protocols/blob/master/dataformat_05.md
4
+ // Manufacturer-specific advertisement data, no GATT connection needed.
5
+
6
+ const MANUFACTURER_ID = 0x0499;
7
+ const DATA_FORMAT_5 = 5;
8
+
9
+ // RuuviTags run on a CR2477 coin cell; 2.0V-3.0V is the commonly used
10
+ // "practical" range for a rough charge estimate (the ADC itself covers
11
+ // 1.6V-3.646V per the spec, but cells are unreliable below ~2.0V).
12
+ const BATT_EMPTY_V = 2.0;
13
+ const BATT_FULL_V = 3.0;
14
+
15
+ function clamp01(v) {
16
+ return Math.max(0, Math.min(1, v));
17
+ }
18
+
19
+ function identify(adv) {
20
+ const data = adv.manufacturerData.get(MANUFACTURER_ID);
21
+ return !!data && data.length >= 24 && data[0] === DATA_FORMAT_5;
22
+ }
23
+
24
+ // Sensor-less variants (e.g. the Pro IP68, which only has temperature and the
25
+ // accelerometer-driven motion counter) fill the fields they can't measure
26
+ // with the format's "not available" sentinel rather than omitting them:
27
+ // largest representable value for unsigned fields, smallest for signed ones.
28
+ // Decoding those as real numbers would publish nonsense (e.g. the invalid
29
+ // humidity sentinel 0xffff decodes to 163.8% if not filtered out here).
30
+ const TEMP_INVALID = -32768; // 0x8000 as int16
31
+ const HUMIDITY_INVALID = 0xffff;
32
+ const PRESSURE_INVALID = 0xffff;
33
+ const BATT_VOLTAGE_11BIT_INVALID = 0x7ff;
34
+ const MOTION_COUNTER_INVALID = 0xff;
35
+
36
+ function decode(adv) {
37
+ const buf = adv.manufacturerData.get(MANUFACTURER_ID);
38
+
39
+ const rawTemp = buf.readInt16BE(1);
40
+ const temp = rawTemp === TEMP_INVALID ? undefined : 273.15 + rawTemp * 0.005;
41
+
42
+ const rawHumidity = buf.readUInt16BE(3);
43
+ const humidity = rawHumidity === HUMIDITY_INVALID ? undefined : (rawHumidity * 0.0025) / 100;
44
+
45
+ const rawPressure = buf.readUInt16BE(5);
46
+ const pressure = rawPressure === PRESSURE_INVALID ? undefined : rawPressure + 50000;
47
+
48
+ const battMillivolts11Bit = buf.readUInt16BE(13) >> 5;
49
+ let battVoltage;
50
+ let battStrength;
51
+ if (battMillivolts11Bit !== BATT_VOLTAGE_11BIT_INVALID) {
52
+ battVoltage = 1.6 + battMillivolts11Bit / 1000;
53
+ battStrength = clamp01((battVoltage - BATT_EMPTY_V) / (BATT_FULL_V - BATT_EMPTY_V));
54
+ }
55
+
56
+ const rawMotionCounter = buf.readUInt8(15);
57
+ const motionCounter = rawMotionCounter === MOTION_COUNTER_INVALID ? undefined : rawMotionCounter;
58
+
59
+ return { temp, humidity, pressure, battVoltage, battStrength, motionCounter };
60
+ }
61
+
62
+ module.exports = {
63
+ id: "ruuvitag",
64
+ name: "RuuviTag",
65
+ domain: "environmental",
66
+ // Sensor-less variants (e.g. the Pro IP68) never emit a pressure value —
67
+ // see the invalid-sentinel handling in decode() above. This flag only says
68
+ // the model family *can* report pressure; sensor-manager additionally
69
+ // requires a device to have actually decoded a pressure value before
70
+ // offering it as an outside-pressure source.
71
+ providesPressure: true,
72
+ identify,
73
+ decode,
74
+ };
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+
3
+ // SwitchBot Meter Plus — a newer sibling of the base Meter (switchbot-th.js)
4
+ // with its own model byte (0x69) and its temp/humidity/battery all packed
5
+ // into the service-data payload instead of manufacturer data. Format per
6
+ // https://github.com/OpenWonderLabs/SwitchBotAPI-BLE (devicetypes/meter.md,
7
+ // "(new) broadcast message"). No GATT connection needed.
8
+
9
+ const MANUFACTURER_ID = 0x0969;
10
+ const MODEL_ID = 0x69;
11
+ const SERVICE_DATA_UUID = "0000fd3d-0000-1000-8000-00805f9b34fb";
12
+
13
+ function identify(adv) {
14
+ const md = adv.manufacturerData.get(MANUFACTURER_ID);
15
+ const sd = adv.serviceData.get(SERVICE_DATA_UUID);
16
+ return !!md && md.length >= 1 && md[0] === MODEL_ID && !!sd && sd.length >= 6;
17
+ }
18
+
19
+ function decode(adv) {
20
+ const sd = adv.serviceData.get(SERVICE_DATA_UUID);
21
+
22
+ // Byte 4 bit 7: sign (1 = positive). Byte 4 bits 0-6: integer part.
23
+ // Byte 3 bits 0-3: fractional decimal digit. Byte 5 bit 7: unit flag
24
+ // (1 = the value above is in Fahrenheit rather than Celsius).
25
+ const sign = (sd[4] & 0x80) !== 0 ? 1 : -1;
26
+ const intPart = sd[4] & 0x7f;
27
+ const frac = (sd[3] & 0x0f) / 10;
28
+ const rawTemp = sign * (intPart + frac);
29
+ const isFahrenheit = (sd[5] & 0x80) !== 0;
30
+ const tempC = isFahrenheit ? (rawTemp - 32) / 1.8 : rawTemp;
31
+
32
+ const humidity = (sd[5] & 0x7f) / 100;
33
+ const battStrength = sd[2] / 100;
34
+
35
+ return { temp: tempC + 273.15, humidity, battStrength };
36
+ }
37
+
38
+ module.exports = {
39
+ id: "switchbot-meter-plus",
40
+ name: "SwitchBot Meter Plus",
41
+ domain: "environmental",
42
+ identify,
43
+ decode,
44
+ };
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+
3
+ // SwitchBot Meter (WoSensorTH) — manufacturer-data + service-data advertisement
4
+ // format documented at https://github.com/OpenWonderLabs/SwitchBotAPI-BLE
5
+ // (devicetypes/meter.md). No GATT connection needed.
6
+
7
+ const MANUFACTURER_ID = 0x0969;
8
+ const MODEL_ID = 0x77; // 'w' — distinguishes the base Meter from Meter Plus (0x69)
9
+ // Some firmware/chip revisions prefix manufacturerData with the device's own
10
+ // MAC address instead of putting the model byte at offset 0. Byte 6 (right
11
+ // after the MAC) was initially assumed to be a stable device-type/mode byte
12
+ // per OpenWonderLabs's device-type table (0x74 't' / 0x54 'T' for WoSensorTH)
13
+ // — but a second capture from the same physical device showed it change
14
+ // (0x74 -> 0x75) between advertisements while the sensor payload after it
15
+ // stayed identical, so it's some kind of rolling counter, not a fixed
16
+ // discriminator. Don't gate on its value. The MAC match alone is already a
17
+ // ~1-in-2^48 signal, so it's sufficient on its own; the payload after it is
18
+ // otherwise the same shape, and since the buffer is still 12 bytes total
19
+ // either way, the temp/humidity offsets below land in the same place
20
+ // regardless of variant.
21
+ const BATTERY_SERVICE_UUID = "0000fd3d-0000-1000-8000-00805f9b34fb";
22
+
23
+ function macBytesMatch(md, mac) {
24
+ if (!mac) return false;
25
+ return md.subarray(0, 6).toString("hex") === String(mac).replace(/:/g, "").toLowerCase();
26
+ }
27
+
28
+ function identify(adv) {
29
+ const md = adv.manufacturerData.get(MANUFACTURER_ID);
30
+ if (!md || md.length !== 12) return false;
31
+ return md[0] === MODEL_ID || macBytesMatch(md, adv.mac);
32
+ }
33
+
34
+ function decode(adv) {
35
+ const md = adv.manufacturerData.get(MANUFACTURER_ID);
36
+
37
+ // Byte 9 bit 7: sign (1 = positive). Byte 9 bits 0-6: integer part (°C).
38
+ // Byte 8 bits 0-3: fractional decimal digit (tenths of a degree).
39
+ const sign = (md[9] & 0x80) !== 0 ? 1 : -1;
40
+ const intPart = md[9] & 0x7f;
41
+ const frac = (md[8] & 0x0f) / 10;
42
+ const temp = 273.15 + sign * (intPart + frac);
43
+
44
+ // Byte 10 bit 7 is an alarm flag, not part of the value.
45
+ const humidity = (md[10] & 0x7f) / 100;
46
+
47
+ const result = { temp, humidity };
48
+
49
+ // Byte 2 bit 7 is an "update UTC" flag, not part of the value — per
50
+ // OpenWonderLabs's Service Data table (Byte 2: "Update UTC Flag Battery",
51
+ // bit[6:0] = remaining battery 0-100%).
52
+ const sd = adv.serviceData.get(BATTERY_SERVICE_UUID);
53
+ if (sd && sd.length >= 3) {
54
+ result.battStrength = (sd[2] & 0x7f) / 100;
55
+ }
56
+
57
+ return result;
58
+ }
59
+
60
+ module.exports = {
61
+ id: "switchbot-th",
62
+ name: "SwitchBot Meter",
63
+ domain: "environmental",
64
+ identify,
65
+ decode,
66
+ };
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+
3
+ // Xiaomi LYWSD03MMC / similar running the pvvx or atc1441 custom firmware
4
+ // (https://github.com/pvvx/ATC_MiThermometer) advertises under its own name
5
+ // (ATC_XXXXXX, where XXXXXX is the last 3 MAC bytes) with a fixed-format
6
+ // service-data payload — no encryption key or GATT connection needed, unlike
7
+ // stock Xiaomi firmware. This decodes the firmware's default little-endian
8
+ // "custom" format: mac[6] temp[i16LE, x0.01 degC] humidity[u16LE, x0.0001]
9
+ // voltage[u16LE, mV] battery[u8, %] counter[u8].
10
+
11
+ const NAME_PATTERN = /^ATC_[A-Fa-f0-9]{6}$/;
12
+ const SERVICE_DATA_UUIDS = ["0000181a-0000-1000-8000-00805f9b34fb", "0000fcd2-0000-1000-8000-00805f9b34fb"];
13
+
14
+ function getServiceData(adv) {
15
+ for (const uuid of SERVICE_DATA_UUIDS) {
16
+ const sd = adv.serviceData.get(uuid);
17
+ if (sd) return sd;
18
+ }
19
+ return null;
20
+ }
21
+
22
+ function identify(adv) {
23
+ if (!NAME_PATTERN.test(adv.name)) return false;
24
+ const sd = getServiceData(adv);
25
+ return !!sd && sd.length >= 13;
26
+ }
27
+
28
+ function decode(adv) {
29
+ const sd = getServiceData(adv);
30
+
31
+ const temp = 273.15 + sd.readInt16LE(6) / 100;
32
+ const humidity = sd.readUInt16LE(8) / 10000;
33
+ const battVoltage = sd.readUInt16LE(10) / 1000;
34
+ const battStrength = sd.readUInt8(12) / 100;
35
+
36
+ return { temp, humidity, battVoltage, battStrength };
37
+ }
38
+
39
+ module.exports = {
40
+ id: "xiaomi-atc",
41
+ name: "Xiaomi (ATC/pvvx custom firmware)",
42
+ domain: "environmental",
43
+ identify,
44
+ decode,
45
+ };
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+
3
+ // SignalK path/unit conventions reused from bt-sensors-plugin-sk's
4
+ // plugin_defaults.json (https://github.com/naugehyde/bt-sensors-plugin-sk) —
5
+ // path templates, units and battery-low zones only; the decoding and
6
+ // templating code here is our own, written for this plugin's BLE-Manager-only,
7
+ // passive-advertisement design.
8
+ const FIELD_PATHS = {
9
+ temp: {
10
+ path: "environment.{zone}.temperature",
11
+ unit: "K",
12
+ description: "Zone's current temperature",
13
+ },
14
+ humidity: {
15
+ path: "environment.{zone}.humidity",
16
+ unit: "ratio",
17
+ description: "Zone's current humidity",
18
+ },
19
+ pressure: {
20
+ path: "environment.{zone}.pressure",
21
+ unit: "Pa",
22
+ description: "Zone's current ambient air pressure",
23
+ },
24
+ battVoltage: {
25
+ path: "sensors.{sensorId}.battery.voltage",
26
+ unit: "V",
27
+ description: "Sensor battery voltage",
28
+ },
29
+ battStrength: {
30
+ path: "sensors.{sensorId}.battery.strength",
31
+ unit: "ratio",
32
+ description: "Sensor battery strength",
33
+ zones: [
34
+ { lower: 0.3, upper: 0.5, state: "alert", message: "Battery low - change soon" },
35
+ { lower: 0, upper: 0.3, state: "warn", message: "Battery very low - change now" },
36
+ ],
37
+ },
38
+ rssi: {
39
+ path: "sensors.{sensorId}.RSSI",
40
+ unit: "dB",
41
+ description: "Sensor signal strength in decibels",
42
+ },
43
+ motionCounter: {
44
+ path: "sensors.{sensorId}.motionCounter",
45
+ description: "Cumulative motion-detection interrupt count from the sensor's accelerometer",
46
+ },
47
+ reachable: {
48
+ path: "sensors.{sensorId}.reachable",
49
+ description: "Whether the sensor is currently in Bluetooth contact",
50
+ },
51
+ };
52
+
53
+ function sanitize(str) {
54
+ return String(str)
55
+ .replace(/[^a-zA-Z0-9_-]/g, "_")
56
+ .replace(/_+/g, "_")
57
+ .replace(/^_|_$/g, "");
58
+ }
59
+
60
+ function sensorId(name) {
61
+ return sanitize(name || "sensor").toLowerCase();
62
+ }
63
+
64
+ // A zone of "inside.mainCabin" nests into environment.inside.mainCabin.* —
65
+ // each dot-separated segment is sanitized independently so a stray invalid
66
+ // character in one segment doesn't merge it into its neighbor.
67
+ function sanitizeZone(zone) {
68
+ const segments = String(zone || "")
69
+ .split(".")
70
+ .map(sanitize)
71
+ .filter(Boolean);
72
+ return segments.length > 0 ? segments.join(".") : "unknown";
73
+ }
74
+
75
+ function resolvePath(template, { zone, name }) {
76
+ return template.replace("{zone}", sanitizeZone(zone)).replace("{sensorId}", sensorId(name));
77
+ }
78
+
79
+ // Builds a SignalK delta from a decoder's { tag: value } output. Unknown
80
+ // tags and null/undefined/NaN values are dropped rather than published —
81
+ // callers don't need to filter decoder output themselves.
82
+ function buildDelta({ name, zone, values, source }) {
83
+ const deltaValues = [];
84
+ for (const [tag, value] of Object.entries(values)) {
85
+ const meta = FIELD_PATHS[tag];
86
+ if (!meta || value === undefined || value === null || (typeof value === "number" && Number.isNaN(value))) continue;
87
+ deltaValues.push({ path: resolvePath(meta.path, { zone, name }), value });
88
+ }
89
+ if (deltaValues.length === 0) return null;
90
+ return {
91
+ updates: [{ $source: source, timestamp: new Date().toISOString(), values: deltaValues }],
92
+ };
93
+ }
94
+
95
+ // Builds the SignalK meta delta (units, description, alarm zones) for the
96
+ // paths a decoder's { tag: value } output maps to. Without this, the server
97
+ // has no unit metadata for plugin-defined paths like environment.<zone>.* or
98
+ // sensors.<sensorId>.* (unlike the fixed paths in the SignalK spec, e.g.
99
+ // environment.outside.temperature), so webapps display raw numbers — e.g. a
100
+ // temperature of 287.04 with no indication it's Kelvin — instead of
101
+ // converting/labelling them.
102
+ function buildMetaDelta({ name, zone, values, source }) {
103
+ const metas = [];
104
+ for (const tag of Object.keys(values)) {
105
+ const meta = FIELD_PATHS[tag];
106
+ if (!meta) continue;
107
+ const metaValue = {};
108
+ if (meta.unit) metaValue.units = meta.unit;
109
+ if (meta.description) metaValue.description = meta.description;
110
+ if (meta.zones) metaValue.zones = meta.zones;
111
+ metas.push({ path: resolvePath(meta.path, { zone, name }), value: metaValue });
112
+ }
113
+ if (metas.length === 0) return null;
114
+ return {
115
+ updates: [{ $source: source, timestamp: new Date().toISOString(), meta: metas }],
116
+ };
117
+ }
118
+
119
+ module.exports = { FIELD_PATHS, resolvePath, sensorId, sanitize, sanitizeZone, buildDelta, buildMetaDelta };
@@ -0,0 +1,224 @@
1
+ "use strict";
2
+
3
+ const { normalizeAdvertisement } = require("./ble-advertisement");
4
+ const { identifySensorType } = require("./sensor-types");
5
+ const { buildDelta, buildMetaDelta, sanitizeZone } = require("./path-mapper");
6
+
7
+ // The SignalK-spec path other plugins (barometer trend, weather routing,
8
+ // etc.) expect for the boat's ambient outside pressure — distinct from this
9
+ // plugin's own environment.<zone>.pressure paths, which are keyed by
10
+ // whatever zone name the user gave each sensor.
11
+ const OUTSIDE_PRESSURE_PATH = "environment.outside.pressure";
12
+
13
+ // If a registered sensor hasn't been heard from in this long, mark its
14
+ // "reachable" path false. Advertisement intervals for these sensors are
15
+ // typically a few seconds, so 5 minutes is a generous margin against a
16
+ // couple of missed beacons.
17
+ const NO_CONTACT_MS = 5 * 60 * 1000;
18
+
19
+ function normalizeMac(mac) {
20
+ return String(mac).toLowerCase();
21
+ }
22
+
23
+ // Owns the live BLE Manager API subscription and all runtime state: which
24
+ // advertised devices have been recognised as a supported sensor type (for
25
+ // the config UI's MAC dropdown) and which of those the user has registered
26
+ // (for actually publishing SignalK deltas). Talks to app.bleApi and
27
+ // app.handleMessage directly, so — like lib/device.js and lib/scanner.js in
28
+ // the sibling signalk-bluetti-plugin — it's BLE/SignalK integration glue,
29
+ // exercised via the real server rather than unit-tested here; the decoding
30
+ // and path-mapping it calls into are deterministic and covered separately.
31
+ class SensorManager {
32
+ constructor(app, pluginId, log) {
33
+ this._app = app;
34
+ this._pluginId = pluginId;
35
+ this._log = log;
36
+ this._recognized = new Map(); // normalized mac -> { mac, name, sensorTypeId, sensorTypeName, providesPressure (actually observed), rssi, lastSeen }
37
+ this._configured = new Map(); // normalized mac -> config entry from options.sensors
38
+ this._noContactTimers = new Map(); // normalized mac -> Timeout
39
+ this._metaSent = new Set(); // normalized macs whose units/description meta has been published
40
+ this._unmatchedLogged = new Set(); // normalized macs already debug-logged as unrecognized
41
+ this._outsidePressureSourceMac = null; // normalized mac whose pressure also publishes to environment.outside.pressure
42
+ this._outsidePressureSourceMacRaw = null; // same, original casing, for the config schema
43
+ this._unsubscribe = null;
44
+ }
45
+
46
+ configure(options = {}) {
47
+ const sensors = options.sensors || [];
48
+ this._configured = new Map(sensors.filter((s) => s && s.mac).map((s) => [normalizeMac(s.mac), s]));
49
+ this._outsidePressureSourceMacRaw = options.outsidePressureSource || null;
50
+ this._outsidePressureSourceMac = options.outsidePressureSource ? normalizeMac(options.outsidePressureSource) : null;
51
+ }
52
+
53
+ // Devices seen so far that matched a known sensor type — used to populate
54
+ // the config schema's MAC dropdown. Devices with no mappable sensor data
55
+ // never make it into this map (see _onAdvertisement).
56
+ getRecognizedDevices() {
57
+ return [...this._recognized.values()];
58
+ }
59
+
60
+ // Sensors registered in the config screen, regardless of whether they've
61
+ // been re-observed since the plugin last started — _recognized resets on
62
+ // every restart (it's runtime-only), so without this a MAC the user
63
+ // already registered could vanish from the config dropdown's options until
64
+ // the sensor happens to broadcast again, making a saved selection look
65
+ // like it "disappeared" even though it's still there in options.sensors.
66
+ getConfiguredDevices() {
67
+ return [...this._configured.values()];
68
+ }
69
+
70
+ // Same rationale as getConfiguredDevices(), for the single outsidePressureSource pick.
71
+ getOutsidePressureSourceMac() {
72
+ return this._outsidePressureSourceMacRaw;
73
+ }
74
+
75
+ start() {
76
+ if (!this._app.bleApi) {
77
+ throw new Error("BLE Manager API (app.bleApi) is not available on this SignalK server — requires server >= 2.31.0.");
78
+ }
79
+ this._unsubscribe = this._app.bleApi.onAdvertisement(this._pluginId, (adv) => this._onAdvertisement(adv));
80
+ }
81
+
82
+ stop() {
83
+ if (this._unsubscribe) {
84
+ this._unsubscribe();
85
+ this._unsubscribe = null;
86
+ }
87
+ for (const timer of this._noContactTimers.values()) clearTimeout(timer);
88
+ this._noContactTimers.clear();
89
+ }
90
+
91
+ _onAdvertisement(rawAdv) {
92
+ let adv;
93
+ try {
94
+ adv = normalizeAdvertisement(rawAdv);
95
+ } catch (err) {
96
+ this._log(`Failed to parse advertisement from ${rawAdv && rawAdv.mac}: ${err.message}`);
97
+ return;
98
+ }
99
+
100
+ const sensorType = identifySensorType(adv);
101
+ if (!sensorType) {
102
+ this._logUnmatchedOnce(adv);
103
+ return; // no mappable sensor data (e.g. RSSI-only) — ignore
104
+ }
105
+
106
+ const normMac = normalizeMac(adv.mac);
107
+ const config = this._configured.get(normMac);
108
+ const isActive = !!config && config.enabled !== false;
109
+
110
+ // Decoded for every recognised device (not just registered ones) so the
111
+ // config screen can tell whether this particular device actually reports
112
+ // pressure — the decoder's providesPressure flag is only a model-family
113
+ // capability, and sensor-less variants (e.g. RuuviTag Pro IP68) broadcast
114
+ // the "not available" sentinel instead. Decoding is a few buffer reads.
115
+ let values;
116
+ let decodeError = null;
117
+ try {
118
+ values = sensorType.decode(adv);
119
+ } catch (err) {
120
+ decodeError = err;
121
+ }
122
+
123
+ const previous = this._recognized.get(normMac);
124
+ const reportsPressure =
125
+ !!sensorType.providesPressure &&
126
+ ((previous && previous.providesPressure) || (!!values && typeof values.pressure === "number" && !Number.isNaN(values.pressure)));
127
+ this._recognized.set(normMac, {
128
+ mac: adv.mac,
129
+ name: adv.name,
130
+ sensorTypeId: sensorType.id,
131
+ sensorTypeName: sensorType.name,
132
+ // Sticky once observed, so one odd advertisement can't drop a device
133
+ // from the pressure-source dropdown mid-session.
134
+ providesPressure: reportsPressure,
135
+ rssi: adv.rssi,
136
+ lastSeen: Date.now(),
137
+ });
138
+
139
+ if (!isActive) return;
140
+
141
+ if (decodeError) {
142
+ this._log(`Failed to decode ${sensorType.name} advertisement from ${adv.mac}: ${decodeError.message}`);
143
+ return;
144
+ }
145
+ values.rssi = adv.rssi;
146
+ values.reachable = true;
147
+
148
+ this._publish(adv, config, sensorType, values);
149
+ this._scheduleNoContactCheck(normMac, adv, config, sensorType);
150
+ }
151
+
152
+ // Debug aid for "my sensor isn't showing up in the dropdown": logs the raw
153
+ // manufacturer/service data of a device that broadcasts a payload but
154
+ // doesn't match any decoder's identify(), once per MAC, so a user can
155
+ // enable plugin debug logging and paste the output when filing an issue
156
+ // for an unsupported sensor/firmware variant. Devices with no payload at
157
+ // all (phones, fitness trackers, RSSI-only beacons) are skipped as noise.
158
+ _logUnmatchedOnce(adv) {
159
+ if (adv.manufacturerData.size === 0 && adv.serviceData.size === 0) return;
160
+ const normMac = normalizeMac(adv.mac);
161
+ if (this._unmatchedLogged.has(normMac)) return;
162
+ this._unmatchedLogged.add(normMac);
163
+
164
+ const mfg = [...adv.manufacturerData.entries()].map(([id, buf]) => `0x${id.toString(16)}:${buf.toString("hex")}`);
165
+ const svc = [...adv.serviceData.entries()].map(([uuid, buf]) => `${uuid}:${buf.toString("hex")}`);
166
+ this._log(
167
+ `No known sensor type matched ${adv.mac} (name: "${adv.name}"). manufacturerData=[${mfg.join(", ")}] serviceData=[${svc.join(", ")}]`,
168
+ );
169
+ }
170
+
171
+ _publish(adv, config, sensorType, values) {
172
+ const name = config.name || adv.name || sensorType.name;
173
+ const zone = config.zone;
174
+ const source = `${this._pluginId}.${sensorType.id}`;
175
+
176
+ const normMac = normalizeMac(adv.mac);
177
+ if (!this._metaSent.has(normMac)) {
178
+ const meta = buildMetaDelta({ name, zone, values, source });
179
+ if (meta) {
180
+ this._app.handleMessage(this._pluginId, meta);
181
+ this._metaSent.add(normMac);
182
+ }
183
+ }
184
+
185
+ const delta = buildDelta({ name, zone, values, source });
186
+
187
+ // Optionally cross-publish this sensor's pressure to the SignalK-spec
188
+ // environment.outside.pressure path (which already has server-provided
189
+ // units metadata, unlike our own environment.<zone>.* paths — no meta
190
+ // delta needed here) so other plugins that expect it there — barometer
191
+ // trend, weather routing — can use it without knowing this plugin's zone
192
+ // naming. Skipped when the sensor's own zone already resolves there, to
193
+ // avoid publishing the identical path twice in one update.
194
+ if (
195
+ this._outsidePressureSourceMac === normMac &&
196
+ typeof values.pressure === "number" &&
197
+ !Number.isNaN(values.pressure) &&
198
+ sanitizeZone(zone) !== "outside"
199
+ ) {
200
+ const outsidePressureDelta = {
201
+ updates: [
202
+ { $source: source, timestamp: new Date().toISOString(), values: [{ path: OUTSIDE_PRESSURE_PATH, value: values.pressure }] },
203
+ ],
204
+ };
205
+ this._app.handleMessage(this._pluginId, outsidePressureDelta);
206
+ }
207
+
208
+ if (delta) this._app.handleMessage(this._pluginId, delta);
209
+ }
210
+
211
+ _scheduleNoContactCheck(normMac, adv, config, sensorType) {
212
+ const existing = this._noContactTimers.get(normMac);
213
+ if (existing) clearTimeout(existing);
214
+
215
+ const timer = setTimeout(() => {
216
+ this._noContactTimers.delete(normMac);
217
+ this._publish(adv, config, sensorType, { reachable: false });
218
+ }, NO_CONTACT_MS);
219
+ timer.unref?.();
220
+ this._noContactTimers.set(normMac, timer);
221
+ }
222
+ }
223
+
224
+ module.exports = SensorManager;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+
3
+ // Registry of supported passive-advertisement sensor decoders. Each decoder
4
+ // is a pure { id, name, domain, identify(adv), decode(adv) } module — no BLE
5
+ // or SignalK dependencies — so they're trivially unit-testable in isolation.
6
+ //
7
+ // Order matters only where two decoders could otherwise both claim the same
8
+ // advertisement; switchbot-th and switchbot-meter-plus share a manufacturer
9
+ // ID but are disambiguated by model byte, so ordering isn't load-bearing
10
+ // today, but keep more specific identify() checks earlier if that changes.
11
+ const decoders = [
12
+ require("./decoders/switchbot-th"),
13
+ require("./decoders/switchbot-meter-plus"),
14
+ require("./decoders/ruuvitag"),
15
+ require("./decoders/xiaomi-atc"),
16
+ require("./decoders/govee"),
17
+ ];
18
+
19
+ // Returns the first decoder that claims this advertisement, or null if none
20
+ // do — callers should treat null as "no mappable sensor data" and ignore the
21
+ // advertisement entirely (e.g. a device only broadcasting RSSI/UUIDs).
22
+ function identifySensorType(adv) {
23
+ for (const decoder of decoders) {
24
+ if (decoder.identify(adv)) return decoder;
25
+ }
26
+ return null;
27
+ }
28
+
29
+ module.exports = { decoders, identifySensorType };
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@rhizomatics/signalk-ble-sensors-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Passive BLE sensor listening for SignalK (SwitchBot, RuuviTag, and others) via the SignalK BLE Manager API — no GATT connection required.",
5
+ "keywords": [
6
+ "ble",
7
+ "bluetooth",
8
+ "environment",
9
+ "humidity",
10
+ "marine",
11
+ "ruuvitag",
12
+ "sensors",
13
+ "signalk",
14
+ "signalk-category-hardware",
15
+ "signalk-node-plugin",
16
+ "signalk-node-server-plugin",
17
+ "switchbot",
18
+ "temperature"
19
+ ],
20
+ "homepage": "https://github.com/rhizomatics/signalk-ble-sensors-plugin",
21
+ "bugs": {
22
+ "url": "https://github.com/rhizomatics/signalk-ble-sensors-plugin/issues"
23
+ },
24
+ "license": "Apache-2.0",
25
+ "author": "Jey Burrows",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/rhizomatics/signalk-ble-sensors-plugin.git"
29
+ },
30
+ "files": [
31
+ "index.js",
32
+ "lib/",
33
+ "docs/assets/",
34
+ "README.md",
35
+ "CHANGELOG.md"
36
+ ],
37
+ "main": "index.js",
38
+ "scripts": {
39
+ "start": "node index.js",
40
+ "fmt": "oxfmt",
41
+ "fmt:check": "oxfmt --check",
42
+ "lint": "oxlint",
43
+ "test": "node --test",
44
+ "test:coverage": "node --experimental-test-coverage --test-coverage-include=\"lib/**/*.js\" --test-coverage-exclude=\"lib/sensor-manager.js\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 --test"
45
+ },
46
+ "devDependencies": {
47
+ "oxfmt": "^0.76.0",
48
+ "oxlint": "^1.91.0"
49
+ },
50
+ "engines": {
51
+ "node": ">=22.0.0",
52
+ "signalk-server": ">=2.31.0"
53
+ },
54
+ "signalk": {
55
+ "displayName": "BLE Sensors (Passive)",
56
+ "appIcon": "docs/assets/icon.svg",
57
+ "recommends": [
58
+ "@rhizomatics/signalk-bluetti-plugin",
59
+ "@rhizomatics/signalk-einklabel-plugin"
60
+ ]
61
+ },
62
+ "signalk-plugin-enabled-by-default": false
63
+ }