heliobind 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,17 @@
1
+ Heliobind
2
+ Copyright 2026 Simon Eisenmann
3
+
4
+ This product includes software developed by Simon Eisenmann.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
7
+ this file except in compliance with the License. You may obtain a copy of the
8
+ License in the LICENSE file distributed with this work, or at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Heliobind interoperates with Growatt hardware by means of a protocol
13
+ specification produced through independent analysis of Bluetooth traffic on
14
+ owned equipment. It is not affiliated with, endorsed by, or derived from any
15
+ source code of Growatt New Energy Co., Ltd. "Growatt", "Nexa", "Noah", "Aura"
16
+ and "Veta" are the trademarks of their respective owners and are used here only
17
+ to identify the hardware this software interoperates with.
package/README.md ADDED
@@ -0,0 +1,252 @@
1
+ # Heliobind
2
+
3
+ Find and read a Growatt balcony battery over Bluetooth, from a browser. Eventually: join it to a Wi-Fi
4
+ network and point it at a server of your choosing, without the vendor app.
5
+
6
+ Named for what it does: the datalogger calls its handshake credential the _bind key_, and binding a device
7
+ is the vendor's own word for the ritual this replaces. It is the Bluetooth half of
8
+ [heliobridge](https://github.com/longsleep/heliobridge), which serves the same devices over the network.
9
+
10
+ **A NEXA 2000 is what it is developed against, not what it is limited to.** The Bluetooth interface belongs
11
+ to the datalogger, which is shared across the family — NOAH 2000, NEXA 2000, AURA 5000 and VETA 2000 — so
12
+ the configuration space, the framing and the cipher are common to all of them.
13
+
14
+ **This version is read-only.** It can discover a device, connect, and read its configuration parameters. It
15
+ cannot change anything — there is no write path in the code at all yet.
16
+
17
+ > **A personal weekend project, built with heavy AI assistance.** It runs against exactly one device — the
18
+ > author's — and it is written to be honest about what has actually been observed rather than to be a
19
+ > product. Treat it accordingly. It is not affiliated with or endorsed by Growatt.
20
+
21
+ ## Requirements
22
+
23
+ **Chrome or Edge**, on Android, Windows, macOS or ChromeOS. Desktop works if the machine has a Bluetooth
24
+ adapter and is close enough to the device — a few metres of open air is not enough.
25
+
26
+ **On Linux, Web Bluetooth ships disabled.** Chromium calls Linux partially implemented and unsupported, so
27
+ `navigator.bluetooth` does not exist until you enable
28
+ `chrome://flags/#enable-experimental-web-platform-features` and restart. BlueZ 5.41 or newer is also needed.
29
+
30
+ **No browser on iOS** supports it, whatever it is called; they are all Safari underneath. The page says so
31
+ rather than failing at the first tap.
32
+
33
+ Served over HTTPS, or from `localhost`. Web Bluetooth requires a secure context.
34
+
35
+ **Three constants, which this project does not distribute.** See below.
36
+
37
+ ## The constants this app does not ship
38
+
39
+ The Bluetooth interface needs three values that are not in this repository: a cipher key, a cipher IV, and
40
+ the handshake key a device is greeted with. Enter them under **Protocol constants** in the app; they are
41
+ kept in the browser's own storage and typed once. Until all three are present, nothing connects.
42
+
43
+ They are held back deliberately. The values are the same on every device of this family, the device accepts
44
+ them from anyone in radio range, and nothing on the vendor's side limits what may then be read or written —
45
+ so they open a neighbour's battery exactly as readily as your own.
46
+
47
+ All three are recoverable from the vendor's Android application by anyone willing to decompile it. That is
48
+ the point: it is a small effort for someone doing protocol work on hardware they own, and one this project
49
+ declines to remove for everyone else.
50
+
51
+ > Anything you enter is stored in that browser profile and never leaves the device — the app makes no
52
+ > network requests at all, which its content security policy enforces rather than promises. On a shared
53
+ > machine, use **Forget these**.
54
+
55
+ ## Running it
56
+
57
+ The quickest way, if you have [Bun](https://bun.com):
58
+
59
+ ```sh
60
+ bunx heliobind
61
+ ```
62
+
63
+ That serves the built app on `http://127.0.0.1:8787` and prints the address. Open it in Chrome. `--port`
64
+ and `--host` are accepted.
65
+
66
+ It has to be `bunx` rather than `npx`: the server is a TypeScript file run by Bun, and Node will not
67
+ execute it.
68
+
69
+ Localhost is a secure context, which is why this needs no certificate. It is also why it is the desktop
70
+ path — a phone cannot reach your laptop's localhost. For that, see the reverse proxy below.
71
+
72
+ ### From a checkout
73
+
74
+ ```sh
75
+ bun install --frozen-lockfile
76
+ bun run dev # http://localhost:3000
77
+ ```
78
+
79
+ ```sh
80
+ bun run check # lint, types, tests
81
+ bun run build # static site into dist/
82
+ bun run build:local # the same, with the protocol constants compiled in
83
+ ```
84
+
85
+ `build` never compiles the constants in, even with `.env.local` present, and fails if one reaches the
86
+ output by any other route. `build:local` is the opt-in for a copy you install on your own phone — do not
87
+ publish what it produces.
88
+
89
+ ### Testing on a phone
90
+
91
+ Bluetooth needs a secure context, so the phone has to reach the page over HTTPS. This app does not
92
+ terminate TLS; put a reverse proxy in front that does.
93
+
94
+ The packaged server is the easier target. Leave it on loopback and let the proxy reach it there:
95
+
96
+ ```sh
97
+ bunx heliobind # http://127.0.0.1:8787
98
+ ```
99
+
100
+ ```caddy
101
+ # Caddyfile — Caddy obtains the certificate itself
102
+ heliobind.example.org {
103
+ reverse_proxy 127.0.0.1:8787
104
+ }
105
+ ```
106
+
107
+ or with nginx, inside a server block that already has a certificate:
108
+
109
+ ```nginx
110
+ location / {
111
+ proxy_pass http://127.0.0.1:8787;
112
+ proxy_set_header Host $host;
113
+ }
114
+ ```
115
+
116
+ If the proxy runs on a different machine, bind wider — `bunx heliobind --host 0.0.0.0` — and firewall the
117
+ port. Do not open the plain HTTP port to the phone directly: without TLS the browser will not treat it as
118
+ a secure context, and Bluetooth stays unavailable however the page looks.
119
+
120
+ **No host allowlist to fight.** The packaged server answers whatever `Host` the proxy sends, so a DNS name
121
+ works with nothing to configure. The development server is stricter — see below — which is the main reason
122
+ to prefer `bunx heliobind` for this.
123
+
124
+ To proxy the development server instead, while editing code:
125
+
126
+ ```sh
127
+ bun run dev --host=0.0.0.0
128
+ ```
129
+
130
+ Arguments after the script name are forwarded straight to the server, so `--host` and `--port` work there.
131
+ `PORT` on its own also comes from `.env.local`, which Bun reads without being asked — copy `.env.example`.
132
+ A host cannot come from there: `.env` files reach the runtime but not the shell that expands
133
+ `package.json` scripts.
134
+
135
+ ### Getting past "Blocked: Host header does not match the dev server"
136
+
137
+ The server checks the `Host` header against its own bind address, and there is no setting to extend the
138
+ list. It accepts `localhost`, any bare IPv4 literal, a bracketed IPv6 literal, or an exact match for the
139
+ host it was started with — so a proxy forwarding a DNS name is refused. Three ways out, cheapest first:
140
+
141
+ 1. **Reach the proxy by IP.** Nothing to configure; a bare IPv4 `Host` is always accepted.
142
+ 2. **Start the server under the name the proxy sends**, which works when that name resolves to an address
143
+ on this machine:
144
+
145
+ ```sh
146
+ bun run dev --host=my-host.example
147
+ ```
148
+
149
+ `--host` sets the bind address as well as the accepted name, so a name pointing elsewhere cannot be
150
+ bound.
151
+
152
+ 3. **Have the proxy rewrite the header**, e.g. `proxy_set_header Host localhost;` in nginx.
153
+
154
+ The server also validates `Origin` on the hot-reload socket, so hot reload may not survive a proxy even
155
+ once the page loads — reload by hand. To exercise the real bundle and the content security policy, which
156
+ the development server does not apply, run `bun run build` and serve `dist/` with any static server.
157
+
158
+ Everything runs on Bun 1.4.0, pinned. There are no runtime dependencies; the four development ones are the
159
+ type checker, the linter, and two sets of type definitions.
160
+
161
+ ## What it does
162
+
163
+ 1. Filters for devices advertising the vendor's service, so the browser's chooser shows only these.
164
+ 2. Connects and subscribes to the command characteristic.
165
+ 3. Sends a configuration read and decodes the reply.
166
+
167
+ The reply is shown as raw octets and as text, because how a reply body is laid out is not yet established —
168
+ raw is more honest than a guess at structure.
169
+
170
+ ## Safety
171
+
172
+ **Nothing here writes to the device.** That is deliberate rather than incidental: the parameters that carry
173
+ Wi-Fi credentials are known, and writing them wrongly takes the device off the network. Recovery means
174
+ provisioning it again, and until this app can do that reliably, the recovery path is the vendor app. Reads
175
+ prove the framing, the cipher and the checksum end to end while being unable to change anything, so reads
176
+ come first.
177
+
178
+ When writes do arrive they will be gated, will name the parameter and value before sending, and will start
179
+ with the server address rather than the credentials — a wrong server address is recoverable over Bluetooth,
180
+ a wrong network name is not.
181
+
182
+ ## Privacy
183
+
184
+ The page makes no network requests. Its content security policy sets `connect-src 'none'`, so that is
185
+ enforced by the browser rather than promised by the author. Nothing is stored, nothing is logged, and no
186
+ analytics are present. When the app eventually asks for a Wi-Fi passphrase, that passphrase goes to the
187
+ device over Bluetooth and nowhere else.
188
+
189
+ The dependency tree is kept at nearly nothing for the same reason: a page that handles a passphrase should
190
+ be small enough for one person to read in a sitting.
191
+
192
+ ### One gap, and it is the host's
193
+
194
+ The policy is delivered in a `<meta>` tag, because **GitHub Pages cannot serve custom response headers** —
195
+ there is no `_headers` file, no `.htaccess`, no configuration of any kind. A meta tag carries most of CSP
196
+ but not all of it: `frame-ancestors`, `report-uri` and `sandbox` are ignored there by specification. So on
197
+ Pages this page **cannot stop itself being framed**, and `X-Frame-Options` is a header too and equally
198
+ unavailable.
199
+
200
+ The policy therefore omits `frame-ancestors` rather than listing a directive that does nothing. If framing
201
+ matters for your deployment, serve the built output from somewhere that can set headers — a static host
202
+ with a `_headers` file, or a CDN in front of Pages — and set the whole policy there as a real header,
203
+ adding `frame-ancestors 'none'`.
204
+
205
+ ## Layout
206
+
207
+ ```
208
+ src/protocol/ pure functions over bytes — framing, checksum, cipher, parameters
209
+ src/transport/ Web Bluetooth: discovery, connection, chunked writes, reassembly
210
+ src/ui/ styles
211
+ src/main.ts the only file that touches the document
212
+ ```
213
+
214
+ `protocol/` imports nothing from `transport/` and never touches the DOM, which is what lets it be tested
215
+ without a device. Its tests sit beside it and run in milliseconds.
216
+
217
+ ## The protocol, briefly
218
+
219
+ The Bluetooth interface speaks the same application protocol the device uses over the network, with the body
220
+ encrypted rather than obfuscated. An eight-octet header, an AES-128-CBC body, and a CRC-16/MODBUS trailer
221
+ appended big-endian — every multi-octet field is big-endian, including the checksum, which is a deviation
222
+ from Modbus RTU.
223
+
224
+ The key and initialisation vector are fixed strings shipped in the vendor app, identical on every device.
225
+ They authenticate nothing: **anyone within Bluetooth range can speak this protocol.** Treat the interface as
226
+ unauthenticated, because it is.
227
+
228
+ One quirk a reimplementation has to match: outbound bodies are PKCS7-padded and inbound ones are not, the
229
+ plaintext being trimmed by a length field in the header instead. Web Crypto has no unpadded mode, so
230
+ `protocol/crypto.ts` synthesises a padding block the browser will accept and strip. The reasoning is in the
231
+ comment there, with a test that proves it.
232
+
233
+ ## Contributing
234
+
235
+ `bun run check` must pass. If you are looking at a Zed workspace and the editor reports rules this project
236
+ has turned off, point its Biome at the config explicitly — the extension looks for `biome.json` by name and
237
+ does not find `biome.jsonc`:
238
+
239
+ ```json
240
+ { "lsp": { "biome": { "settings": { "config_path": "biome.jsonc" } } } }
241
+ ```
242
+
243
+ ## Licence
244
+
245
+ Licensed under the Apache License, Version 2.0 — see [LICENSE](LICENSE).
246
+
247
+ Copyright 2026 Simon Eisenmann. See [NOTICE](NOTICE).
248
+
249
+ Heliobind interoperates with Growatt hardware through a protocol worked out by independent analysis of
250
+ Bluetooth traffic on owned equipment. It is not affiliated with, endorsed by, or derived from any source
251
+ code of Growatt New Energy Co., Ltd. "Growatt", "Nexa", "Noah", "Aura" and "Veta" are the trademarks of
252
+ their respective owners and are used here only to identify the hardware this software talks to.
package/dist/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/dist/NOTICE ADDED
@@ -0,0 +1,17 @@
1
+ Heliobind
2
+ Copyright 2026 Simon Eisenmann
3
+
4
+ This product includes software developed by Simon Eisenmann.
5
+
6
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use
7
+ this file except in compliance with the License. You may obtain a copy of the
8
+ License in the LICENSE file distributed with this work, or at
9
+
10
+ http://www.apache.org/licenses/LICENSE-2.0
11
+
12
+ Heliobind interoperates with Growatt hardware by means of a protocol
13
+ specification produced through independent analysis of Bluetooth traffic on
14
+ owned equipment. It is not affiliated with, endorsed by, or derived from any
15
+ source code of Growatt New Energy Co., Ltd. "Growatt", "Nexa", "Noah", "Aura"
16
+ and "Veta" are the trademarks of their respective owners and are used here only
17
+ to identify the hardware this software interoperates with.
@@ -0,0 +1 @@
1
+ :root{--buncss-light:initial;--buncss-dark: ;color-scheme:light dark;--fg:#16181d;--bg:#fbfbfc;--muted:#5c6270;--line:#d8dbe2;--accent:#1f6feb;--warn-bg:#fff6e0;--warn-line:#e0b64a}@media (prefers-color-scheme:dark){:root{--buncss-light: ;--buncss-dark:initial;--fg:#e6e8ec;--bg:#14161a;--muted:#9aa1ae;--line:#2c313a;--accent:#6aa8ff;--warn-bg:#2b2413;--warn-line:#6b5a26}}*{box-sizing:border-box}body{color:var(--fg);background:var(--bg);margin:0;padding:1.25rem;font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif;font-size:1rem;line-height:1.5}main{max-width:34rem;margin:0 auto}h1{margin:0 0 1rem;font-size:1.35rem}.note{border:1px solid var(--warn-line);background:var(--warn-bg);border-radius:6px;padding:.6rem .8rem;font-size:.9rem}button{font:inherit;color:#fff;background:var(--accent);border:1px solid #0000;border-radius:6px;min-height:2.75rem;padding:.6rem 1rem}button:disabled{opacity:.5}select,input[type=text]{display:block;box-sizing:border-box;font:inherit;border:1px solid var(--line);color:var(--fg);background:var(--bg);border-radius:6px;width:100%;min-height:2.75rem;padding:.5rem}input[type=text]{margin-top:.5rem;font-family:ui-monospace,monospace;font-size:.9rem}input[type=text]::placeholder{color:var(--muted);font-family:system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif}input[type=text]:focus-visible{outline:2px solid var(--accent);outline-offset:2px}select:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}label{display:block;margin:1rem 0 .25rem;font-weight:600}dl{display:grid;grid-template-columns:auto 1fr;gap:.25rem 1rem;margin:1rem 0;font-size:.95rem}dt{color:var(--muted)}dd{overflow-wrap:anywhere;margin:0}pre{overflow-x:auto;border:1px solid var(--line);white-space:pre-wrap;overflow-wrap:anywhere;border-radius:6px;margin:.75rem 0 0;padding:.75rem;font-size:.85rem}footer{color:var(--muted);margin-top:2rem;font-size:.8rem}.actions{display:flex;flex-wrap:wrap;gap:.5rem;margin-top:.75rem}.actions button{flex:8rem}.secrets{border:1px solid var(--line);border-radius:6px;margin:1rem 0;padding:.75rem .9rem}.secrets summary{cursor:pointer;font-weight:600}.secrets label:first-of-type{margin-top:.75rem}.topbar{display:flex;justify-content:space-between;align-items: center;gap:1rem}.source{display:inline-flex;color:var(--muted);border-radius:6px;flex:none;justify-content:center;align-items: center;width:2.5rem;height:2.5rem}.source:hover{color:var(--accent)}.source:focus-visible{color:var(--accent)}.brand{display:flex;align-items: center;gap:.6rem}.brand-mark{color:var(--accent);flex:none;width:1.6em;height:1.6em}.brand h1{margin:0}pre:empty:before{content:"nothing yet";color:var(--muted)}.update{display:flex;border:1px solid var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);border-radius:6px;justify-content:space-between;align-items: center;gap:1rem;margin:.75rem 0 0;padding:.6rem .5rem .6rem .9rem}.update button{flex:none;min-height:0;padding:.35rem .9rem}.pane-heading{display:flex;justify-content:space-between;align-items: center;gap:1rem;margin:1rem 0 .25rem}.secrets summary .pane-heading{display:inline-flex;vertical-align:middle;width:calc(100% - 1.5rem);margin:0}.pane-heading label{margin:0}.clear{color:var(--muted,inherit);opacity:.7;background:0 0;border:1px solid;flex:none;min-height:0;padding:.25rem .7rem;font-size:.8rem;line-height:1.2}.clear:hover{opacity:1}.clear:focus-visible{opacity:1}[hidden]{display:none}
@@ -0,0 +1,4 @@
1
+ var E=null;function ee(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1)t[n]=e.charCodeAt(n);return t}var Ye=new Uint8Array(16);class b extends Error{}var A=null;function te(e){for(let[t,n]of[["key",e.key],["IV",e.iv]]){if(n.length!==16)throw new b(`the cipher ${t} must be 16 characters, got ${n.length}`);if(!/^[\x20-\x7e]+$/.test(n))throw new b(`the cipher ${t} must be printable ASCII`)}E=e,A=null}function ne(){E=null,A=null}function re(){return E!==null}function oe(){if(!E)throw new b("the cipher constants have not been set; see the note in the README");return E}function ie(){return ee(oe().iv)}function ae(){return A??=crypto.subtle.importKey("raw",ee(oe().key),{name:"AES-CBC"},!1,["encrypt","decrypt"]),A}async function se(e){let t=await crypto.subtle.encrypt({name:"AES-CBC",iv:ie()},await ae(),e);return new Uint8Array(t)}async function ce(e){if(e.length===0||e.length%16!==0)throw new b(`ciphertext is ${e.length} octets, not a whole number of blocks`);let t=await ae(),n=e.subarray(e.length-16),r=new Uint8Array(16).fill(16),i=new Uint8Array(16);for(let p=0;p<16;p+=1)i[p]=r[p]^n[p];let c=(await Ze(t,i)).subarray(0,16),a=new Uint8Array(e.length+16);a.set(e,0),a.set(c,e.length);let d=await crypto.subtle.decrypt({name:"AES-CBC",iv:ie()},t,a);return new Uint8Array(d)}async function Ze(e,t){if(t.length!==16)throw new b("raw encryption takes exactly one block");let n=await crypto.subtle.encrypt({name:"AES-CBC",iv:Ye},e,t);return new Uint8Array(n)}var B={writeConfig:24,readConfig:25};class h extends Error{}function de(e){let t=65535;for(let n of e){t^=n;for(let r=0;r<8;r+=1)t=t&1?t>>>1^40961:t>>>1}return t}function u(e,t,n){if(t+2>e.length)throw new h(`no room for a u16 at ${t}`);e[t]=n>>>8&255,e[t+1]=n&255}function f(e,t){if(t+2>e.length)throw new h(`no u16 available at ${t}`);return(e[t]&255)<<8|e[t+1]&255}function K(e){let t=new Uint8Array(e.length);for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>127)throw new h(`value is not ASCII: ${JSON.stringify(e)}`);t[n]=r}return t}function H(e){return Array.from(e,(t)=>String.fromCharCode(t)).join("")}function M(e,t="0000000000"){if(e.length===0)throw new h("a read needs at least one parameter");let n=K(t),r=new Uint8Array(n.length+2+e.length*2);r.set(n,0),u(r,n.length,e.length);for(let[i,c]of e.entries())u(r,n.length+2+i*2,c);return r}function pe(e,t="0000000000"){if(e.length===0)throw new h("a write needs at least one parameter");let n=e.map((d)=>K(d.value)),r=n.reduce((d,p)=>d+4+p.length,0),i=K(t),c=new Uint8Array(i.length+4+r);c.set(i,0),u(c,i.length,e.length),u(c,i.length+2,r);let a=i.length+4;return e.forEach((d,p)=>{let v=n[p];u(c,a,d.param),u(c,a+2,v.length),c.set(v,a+4),a+=4+v.length}),c}function he(e,t,n){let r=new Uint8Array(8+t.length+2);return u(r,0,8+t.length-2+2),u(r,2,6),u(r,4,n+2),r[6]=1,r[7]=e,r.set(t,8),u(r,r.length-2,de(r.subarray(0,r.length-2))),r}function W(e){if(e.length<2)return null;return f(e,0)+2}function ue(e){let t=W(e);if(t===null)return null;if(t<10)return!1;if(e.length<4)return null;let n=f(e,2);return n===6||n===7}function fe(e){if(e.length<10)throw new h(`frame is ${e.length} octets, shorter than a header and CRC`);let t=f(e,0)+2;if(t!==e.length)throw new h(`header declares ${t} octets, got ${e.length}`);let n=de(e.subarray(0,e.length-2)),r=f(e,e.length-2);if(n!==r)throw new h(`CRC mismatch: computed ${le(n)}, frame carries ${le(r)}`);let i=f(e,4)-2;if(i<0)throw new h("plaintext length field is less than two");return{protocol:f(e,2),address:e[6],function:e[7],plaintextLen:i,body:e.subarray(8,e.length-2)}}function le(e){return`0x${e.toString(16).padStart(4,"0")}`}function s(e,t,n,r){return{number:e,name:t,summary:r,writable:!1,confidence:n}}var me=s(8,"serial_number","device","The device serial, also its MQTT client id."),ge=s(20,"model_id","device","Model identifier."),ye=s(21,"sw_version","device","Datalogger firmware version."),ve=s(22,"hw_version","device","Hardware revision."),be=s(9,"protocol_version","device","Wire protocol version."),Je=s(13,"device_type","inferred","A numeric type code."),Qe=s(16,"mac_address","device","MAC-shaped, but a constant shared across the product family rather than this unit's."),et=s(7,"password","device","A six-digit vendor default."),R=s(54,"bind_key","device","The handshake key. Presenting it is authentication rather than configuration, and Device.open is the only thing that writes it."),tt=s(61,"sdk_version","device","ESP-IDF version of the running build."),we=s(56,"wifi_ssid","device","Wi-Fi network name. Readable in clear. Writing this wrongly takes the device off the network."),xe=s(57,"wifi_password","device","Wi-Fi passphrase. Returned in clear by a read."),ke=s(76,"wifi_signal","device","Signal strength in dBm, sign as sent."),Ee=s(139,"dhcp_lease_0","device","Address, mask, gateway and resolver of the joined network."),_e=s(140,"dhcp_lease_1","device","Address, mask, gateway and resolver of the joined network."),Ce=s(12,"dns_ip","device","Resolver the device is configured with."),Le=s(17,"server_address","device","Hostname or address the device reports to. Reads back the vendor's broker; a write is untested."),Se=s(18,"remote_port","device","Port the device dials."),Ae=s(19,"remote_url","device","Hostname the device dials."),Be=s(4,"data_interval","device","Telemetry cadence in seconds."),Re=s(31,"datetime","device","The device clock."),nt=s(30,"timezone","device","Reports GMT+8, and is not what the clock follows."),rt=s(32,"restart","vendor-app",'Write "1" to restart the datalogger. Recoverable: it reboots and reconnects by itself.'),ot=s(35,"clear_log","vendor-app",'Write "1" to clear the datalogger log.'),it=s(14,"local_ip","device","Reports 192.168.5.1 and does not describe the live network."),at=s(25,"subnet_mask","device","Inert default, like local_ip."),st=s(26,"default_gateway","device","Inert default, like local_ip."),ct=s(105,"network_mac","inferred","A second MAC-shaped field, equal to 16."),lt=s(106,"network_ip","inferred","A second address field."),dt=s(107,"network_mask","inferred","A second mask field."),pt=s(108,"network_gateway","inferred","A second gateway field."),ht=s(109,"network_dns","inferred","A second resolver field."),ut=s(80,"update_url","device","The last update URL the device was told to install."),ft=s(121,"link_diagnostics","device","A string of labelled fields: state, err_wifi, reconnect, server."),mt=s(144,"assembled_values","inferred","A concatenation of other parameters, including the handshake key of 54."),gt=s(55,"unknown_55","inferred","Read by the vendor app during provisioning. Contents unknown, which is why it is a good first read."),yt=s(60,"unknown_60","device",'Reads back "16". Meaning unestablished.'),vt=Array.from({length:15},(e,t)=>s(124+t,`connection_event_${String(t).padStart(2,"0")}`,"device","One timestamped connection record: time, network, endpoint. A slot in a ring buffer.")),V=[Be,et,me,be,Ce,Je,it,Qe,Le,Se,Ae,ge,ye,ve,at,st,nt,Re,rt,ot,R,gt,we,xe,yt,tt,ke,ut,ct,lt,dt,pt,ht,ft,...vt,Ee,_e,mt],Ie=[me,ge,ye,ve,be,R,we,xe,ke,Ee,_e,Ce,Le,Se,Ae,Be,Re],z=145;function I(){return Array.from({length:z+1},(e,t)=>t)}function Te(e){return e.map((t)=>t.number)}function Pe(e,t){let n=Math.max(1,Math.floor(t)),r=[];for(let i=0;i<e.length;i+=n)r.push(e.slice(i,i+n));return r}var bt=new Map(V.map((e)=>[e.number,e]));function wt(e){return bt.get(e)}function T(e){return wt(e)?.name??`unknown_${e}`}var j=10,Ne=j+2,G=Ne+1;class _ extends Error{}function q(e){return e.status===0}function Oe(e){if(e.length<G)throw new _(`response is ${e.length} octets, shorter than the ${G} it must have`);let t=H(e.subarray(0,j)),n=f(e,j),r=e[Ne],i=[],c=G;while(c<e.length){if(c+4>e.length)throw new _(`a parameter header is cut short ${e.length-c} octets from the end`);let a=f(e,c),d=f(e,c+2);if(c+4+d>e.length)throw new _(`parameter ${a} claims ${d} octets, more than the body holds`);i.push({param:a,value:H(e.subarray(c+4,c+4+d))}),c+=4+d}if(i.length>n)throw new _(`count says ${n} parameters, the body holds ${i.length}`);return{serial:t,count:n,status:r,values:i}}class De extends Error{}function xt(e){return e instanceof Error?e.message:String(e)}class P extends De{status;constructor(e){super(`the device refused the key, status ${e}`);this.status=e}}class N{connection;serial;constructor(e,t){this.connection=e;this.serial=t}static async open(e,t){let n=await F(e,B.writeConfig,pe([{param:R.number,value:t}]));if(!q(n))throw new P(n.status);return new N(e,n.serial)}get connected(){return this.connection.connected}async read(e){return F(this.connection,B.readConfig,M(e))}async*sweep(e=1,t=I()){for(let n of Pe(t,e)){let r;try{r=await this.read(n)}catch(a){yield{kind:"unanswered",params:n,reason:xt(a)};continue}for(let a of r.values)yield{kind:"value",param:a.param,value:a.value};let i=new Set(r.values.map((a)=>a.param)),c=n.filter((a)=>!i.has(a));if(c.length>0)yield{kind:"silent",params:c}}}async readVia(e,t){return F(this.connection,B.readConfig,M(e),t)}}async function F(e,t,n,r){let i=he(t,await se(n),n.length),c=r?await e.requestVia(i,r):await e.request(i),a=fe(c),d=(await ce(a.body)).subarray(0,a.plaintextLen);return Oe(d)}var Ue=!1;async function $e(e){if(!("serviceWorker"in navigator))return"this browser does not support offline use";let t;try{t=await navigator.serviceWorker.register("./sw.js",{scope:"./"})}catch(r){return r instanceof Error?r.message:String(r)}navigator.serviceWorker.addEventListener("controllerchange",()=>{if(Ue)return;Ue=!0,window.location.reload()}),e.onAccept(()=>{t.waiting?.postMessage("take-over")});let n=(r)=>{if(r?.state==="installed"&&navigator.serviceWorker.controller)e.show()};n(t.waiting),t.addEventListener("updatefound",()=>{let r=t.installing;r?.addEventListener("statechange",()=>n(r))});try{await t.update()}catch{}return null}var O={cipherKey:"heliobind.cipher.key",cipherIv:"heliobind.cipher.iv",bindKey:"heliobind.bind.key"},X={cipherKey:process.env.BUN_PUBLIC_HELIOBIND_CIPHER_KEY??"",cipherIv:process.env.BUN_PUBLIC_HELIOBIND_CIPHER_IV??"",bindKey:process.env.BUN_PUBLIC_HELIOBIND_BIND_KEY??""};function Ke(){return{cipherKey:Y("cipherKey")||X.cipherKey,cipherIv:Y("cipherIv")||X.cipherIv,bindKey:Y("bindKey")||X.bindKey}}function He(e,t){try{if(t)localStorage.setItem(O[e],t);else localStorage.removeItem(O[e])}catch{}}function Me(){for(let e of Object.values(O))try{localStorage.removeItem(e)}catch{}}function Y(e){try{return localStorage.getItem(O[e])??""}catch{return""}}var We=255,w={service:"000000ff-0000-1000-8000-00805f9b34fb",io:"0000ff01-0000-1000-8000-00805f9b34fb",info:"0000ff02-0000-1000-8000-00805f9b34fb",ff04:"0000ff04-0000-1000-8000-00805f9b34fb"},kt=5000;class g extends Error{}function Z(){return typeof navigator<"u"&&"bluetooth"in navigator}async function Ve(){if(!Z())throw new g("this browser does not support Web Bluetooth");return navigator.bluetooth.requestDevice({filters:[{services:[We]}],optionalServices:[We]})}class D{device;io;onNotification=null;constructor(e,t){this.device=e;this.io=t}static async open(e){let t=e.gatt;if(!t)throw new g("device exposes no GATT server");let i=await(await(await t.connect()).getPrimaryService(w.service)).getCharacteristic(w.io),c=new D(e,i);return i.addEventListener("characteristicvaluechanged",()=>{let a=i.value;if(a)c.onNotification?.(new Uint8Array(a.buffer.slice(0)))}),await i.startNotifications(),c}get connected(){return this.device.gatt?.connected??!1}async close(){if(this.connected)this.device.gatt?.disconnect()}async readInfo(){let e=await this.device.gatt?.getPrimaryService(w.service);if(!e)throw new g("not connected");let n=await(await e.getCharacteristic(w.info)).readValue();return new Uint8Array(n.buffer.slice(0))}async request(e){if(!this.connected)throw new g("not connected");let t=this.collect();return await this.write(e),t}async requestVia(e,t){if(!this.connected)throw new g("not connected");let n=this.io;if(t.characteristic==="ff04"){let i=await this.device.gatt?.getPrimaryService(w.service);if(!i)throw new g("not connected");n=await i.getCharacteristic(w.ff04)}let r=this.collect();if(t.withoutResponse)await n.writeValueWithoutResponse(e);else await n.writeValueWithResponse(e);return r}async write(e){await this.io.writeValueWithResponse(e)}collect(){return new Promise((e,t)=>{let n=new Uint8Array(0),r=(a)=>{clearTimeout(i),this.io.removeEventListener("characteristicvaluechanged",c),a()},i=setTimeout(()=>{r(()=>t(new g(n.length===0?"no reply within the timeout":`reply incomplete: ${n.length} octets after the timeout`)))},kt),c=()=>{let a=this.io.value;if(!a)return;let d=new Uint8Array(a.buffer.slice(0)),p=new Uint8Array(n.length+d.length);if(p.set(n,0),p.set(d,n.length),n=p,ue(n)===!1){n=new Uint8Array(0);return}let v=W(n);if(v!==null&&n.length>=v){let Xe=n.subarray(0,v);r(()=>e(Xe))}};this.io.addEventListener("characteristicvaluechanged",c)})}}function l(e){let t=document.getElementById(e);if(!t)throw Error(`missing element: ${e}`);return t}var o={unsupported:l("unsupported"),app:l("app"),secrets:l("secrets"),cipherKey:l("cipher-key"),cipherIv:l("cipher-iv"),key:l("key"),forget:l("forget"),connect:l("connect"),device:l("device"),deviceName:l("device-name"),deviceStatus:l("device-status"),deviceSerial:l("device-serial"),readout:l("readout"),param:l("param"),read:l("read"),readProvisioning:l("read-provisioning"),readSpace:l("read-space"),info:l("info"),clearResult:l("clear-result"),clearLog:l("clear-log"),result:l("result"),log:l("log"),update:l("update"),updateNow:l("update-now"),build:l("build")};function x(e){o.deviceStatus.textContent=e}function ze(e){let t="";for(let n of e){let r=n.charCodeAt(0);t+=r>=32&&r<=126?n:`\\x${r.toString(16).padStart(2,"0")}`}return t}function Ge(){o.result.textContent=""}function je(){o.log.textContent=""}function y(e){o.result.textContent=o.result.textContent?`${o.result.textContent}
2
+ ${e}`:e,o.result.scrollTop=o.result.scrollHeight}function m(e){let t=new Date().toISOString().slice(11,23),n=o.log.textContent;o.log.textContent=n?`${n}
3
+ ${t} ${e}`:`${t} ${e}`}function U(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function qe(e){for(let t of e){let n=document.createElement("option");n.value=String(t.number),n.textContent=`${t.number} — ${t.name}`,n.title=t.summary,o.param.append(n)}}var k={unsupported(){o.unsupported.hidden=!1},ready(){o.app.hidden=!1},device(e){o.device.hidden=!e},readout(e){o.readout.hidden=!e}};async function J(e,t){for(let n of e)n.disabled=!0;try{return await t()}finally{for(let n of e)n.disabled=!1}}var Et="development",C=null,L=null;async function _t(){o.connect.disabled=!0;try{let e=await Ve();k.device(!0),o.deviceName.textContent=e.name??"(unnamed)",x("connecting"),e.addEventListener("gattserverdisconnected",Ct),C=await D.open(e),C.onNotification=(t)=>m(`notify ${t.length} octets`),m("connected"),x("authenticating"),L=await N.open(C,o.key.value.trim()),o.deviceSerial.textContent=L.serial,x("ready"),m(`authenticated; the device reports serial ${L.serial}`),k.readout(!0),y("Authenticated. Reads should now be answered.")}catch(e){x(e instanceof P?"key refused":"not connected"),y(U(e)),m(U(e)),S()}}function Ct(){C=null,L=null,m("device disconnected"),x("disconnected"),k.readout(!1),S()}function S(){let t=![o.cipherKey,o.cipherIv,o.key].some((n)=>n.value.trim()==="")&&re();o.connect.disabled=!t,o.connect.title=t?"":"Enter the protocol constants first"}async function Q(e,t){let n=L;if(!n)return;y(`reading ${t}…`),await J([o.read,o.readProvisioning,o.readSpace],async()=>{let r=0,i=0,c=0;for await(let a of n.sweep(1,e))switch(a.kind){case"value":if(a.value.length>0)r+=1;else i+=1;y(`${T(a.param).padEnd(22)} ${ze(a.value)}`);break;case"silent":i+=a.params.length;break;case"unanswered":c+=a.params.length,m(`no answer for ${a.params.join(", ")}: ${a.reason}`);break}y(`
4
+ ${r} held a value, ${i} answered nothing, ${c} went unanswered`),m(`read ${e.length} parameters: ${r} values, ${i} empty, ${c} lost`)})}async function Lt(){let e=C;if(!e)return;await J([o.info],async()=>{try{let t=await e.readInfo();y(`0xFF02 returned ${t.length} octets: ${new TextDecoder().decode(t)}`)}catch(t){y(U(t))}})}function St(){$e({show:()=>{o.update.hidden=!1,m("a newer version is ready; press Update to switch to it")},onAccept:(e)=>o.updateNow.addEventListener("click",e)}).then((e)=>{})}function At(){let e=Ke();o.cipherKey.value=e.cipherKey,o.cipherIv.value=e.cipherIv,o.key.value=e.bindKey;let t=()=>{try{te({key:o.cipherKey.value.trim(),iv:o.cipherIv.value.trim()})}catch{ne()}},n=(r,i)=>{i.addEventListener("input",()=>{if(r!=="bindKey")t();S()}),i.addEventListener("change",()=>He(r,i.value.trim()))};n("cipherKey",o.cipherKey),n("cipherIv",o.cipherIv),n("bindKey",o.key),o.forget.addEventListener("click",(r)=>{r.preventDefault(),r.stopPropagation(),Me();for(let i of[o.cipherKey,o.cipherIv,o.key])i.value="";o.secrets.open=!0,S(),m("the stored constants were forgotten")}),t(),S(),o.secrets.open=!(e.cipherKey&&e.cipherIv&&e.bindKey)}function Fe(){if(o.build.textContent=`build ${Et} · read-only`,St(),!Z()){k.unsupported();return}qe(V),At(),k.ready(),o.connect.addEventListener("click",()=>void _t()),o.read.addEventListener("click",()=>{let e=Number(o.param.value);Q([e],T(e))}),o.readProvisioning.addEventListener("click",()=>void Q(Te(Ie),"the provisioning settings")),o.readSpace.addEventListener("click",()=>void Q(I(),`parameters 0 to ${z}`)),o.clearResult.addEventListener("click",Ge),o.clearLog.addEventListener("click",je),o.info.addEventListener("click",()=>void Lt())}Fe();
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Heliobind">
2
+ <title>Heliobind</title>
3
+ <rect width="64" height="64" rx="14" fill="#1f6feb"/>
4
+ <circle cx="24" cy="32" r="9" fill="#fff"/>
5
+ <path d="M38 24a11 11 0 0 1 0 16" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round"/>
6
+ <path d="M45 18a20 20 0 0 1 0 28" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" opacity="0.5"/>
7
+ </svg>
Binary file
@@ -0,0 +1,11 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Heliobind">
2
+ <title>Heliobind</title>
3
+ <!-- Maskable: the whole square is the ground and the glyph is scaled into the centre 60%, so a circular
4
+ crop on Android takes only the field and never the mark. -->
5
+ <rect width="64" height="64" fill="#1f6feb"/>
6
+ <g transform="translate(32 32) scale(0.62) translate(-32 -32)">
7
+ <circle cx="24" cy="32" r="9" fill="#fff"/>
8
+ <path d="M38 24a11 11 0 0 1 0 16" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round"/>
9
+ <path d="M45 18a20 20 0 0 1 0 28" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" opacity="0.5"/>
10
+ </g>
11
+ </svg>
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Heliobind">
2
+ <title>Heliobind</title>
3
+ <rect width="64" height="64" rx="14" fill="#1f6feb"/>
4
+ <circle cx="24" cy="32" r="9" fill="#fff"/>
5
+ <path d="M38 24a11 11 0 0 1 0 16" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round"/>
6
+ <path d="M45 18a20 20 0 0 1 0 28" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" opacity="0.5"/>
7
+ </svg>
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,203 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; manifest-src 'self'; worker-src 'self'; connect-src 'none'; form-action 'none'; base-uri 'none'">
6
+ <meta name="viewport" content="width=device-width, initial-scale=1">
7
+
8
+ <!--
9
+ The content security policy is injected here by scripts/build.ts, and deliberately not written
10
+ in this file. It forbids network access outright, which the development server cannot live with:
11
+ that server injects an inline script and opens a WebSocket for hot reload, so a policy strict
12
+ enough to be worth having in production stops the page loading while it is being worked on.
13
+
14
+ Putting it in the build means the policy that ships is exact and verifiable in dist/index.html,
15
+ and the cost is that a violation introduced during development only surfaces at build time. The
16
+ build fails rather than shipping a page without it.
17
+ -->
18
+ <meta name="referrer" content="no-referrer">
19
+ <meta name="color-scheme" content="light dark">
20
+
21
+ <title>Heliobind — Bluetooth setup</title>
22
+ <meta name="theme-color" content="#1f6feb">
23
+ <link rel="manifest" href="./manifest-w9cqzme5.webmanifest">
24
+ <link rel="icon" href="./heliobind-pd6mv76e.svg" type="image/svg+xml">
25
+ <link rel="apple-touch-icon" href="./apple-touch-icon-78jb078y.png">
26
+
27
+ <link rel="stylesheet" crossorigin href="./chunk-h2a7cxvg.css"><script type="module" crossorigin src="./chunk-hap08v1b.js"></script></head>
28
+
29
+ <body>
30
+ <main>
31
+ <div class="topbar">
32
+ <div class="brand">
33
+ <!-- Inline rather than an <img>: it is part of the heading, it must take the accent colour in both
34
+ themes, and it saves a request on a page that is meant to work offline. -->
35
+ <svg
36
+ class="brand-mark"
37
+ viewBox="0 0 64 64"
38
+ width="32"
39
+ height="32"
40
+ aria-hidden="true"
41
+ focusable="false"
42
+ >
43
+ <circle cx="24" cy="32" r="9" fill="currentColor" />
44
+ <path
45
+ d="M38 24a11 11 0 0 1 0 16"
46
+ fill="none"
47
+ stroke="currentColor"
48
+ stroke-width="4"
49
+ stroke-linecap="round"
50
+ />
51
+ <path
52
+ d="M45 18a20 20 0 0 1 0 28"
53
+ fill="none"
54
+ stroke="currentColor"
55
+ stroke-width="4"
56
+ stroke-linecap="round"
57
+ opacity="0.5"
58
+ />
59
+ </svg>
60
+ <h1>Heliobind</h1>
61
+ </div>
62
+
63
+ <!--
64
+ Inline for the same reason as the mark, and because a page that works offline should not depend on
65
+ a remote image to show where its source lives. `rel` is set because `target="_blank"` otherwise
66
+ hands the new tab a handle on this one.
67
+ -->
68
+ <a
69
+ class="source"
70
+ href="https://github.com/longsleep/heliobind"
71
+ target="_blank"
72
+ rel="noopener noreferrer"
73
+ aria-label="Heliobind source on GitHub"
74
+ title="Source on GitHub"
75
+ >
76
+ <svg viewBox="0 0 16 16" width="22" height="22" aria-hidden="true" focusable="false">
77
+ <path
78
+ fill="currentColor"
79
+ d="M8 0a8 8 0 0 0-2.53 15.59c.4.07.55-.17.55-.38l-.01-1.49c-2.01.36-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82a7.4 7.4 0 0 1 4 0c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48l-.01 2.19c0 .21.15.46.55.38A8 8 0 0 0 8 0Z"
80
+ />
81
+ </svg>
82
+ </a>
83
+ </div>
84
+
85
+ <!--
86
+ Shown only once a newer version has installed and is waiting. Updating replaces the running app, so
87
+ it is offered rather than done: a sweep of 146 parameters takes minutes and a reload in the middle
88
+ of one loses the readings.
89
+ -->
90
+ <div id="update" class="update" hidden>
91
+ <span>A newer version is ready.</span>
92
+ <button id="update-now" type="button">Update</button>
93
+ </div>
94
+
95
+ <p id="unsupported" hidden>
96
+ This browser cannot use Bluetooth from a web page. Chrome or Edge can, on Android, Windows, macOS and
97
+ ChromeOS. On <strong>Linux</strong> it ships disabled: enable
98
+ <code>chrome://flags/#enable-experimental-web-platform-features</code>, restart the browser, and
99
+ reload. No browser on iOS supports it at all, whatever it is called.
100
+ </p>
101
+
102
+ <section id="app" hidden>
103
+ <p class="note">
104
+ Read-only. This version can find a device and read its settings; it cannot change anything.
105
+ </p>
106
+
107
+ <!--
108
+ The three constants this project does not ship. They come from the vendor application; see the
109
+ README. Kept in one block so it is obvious they belong together, and remembered in the browser so
110
+ they are typed once.
111
+ -->
112
+ <details id="secrets" class="secrets">
113
+ <summary>
114
+ <!--
115
+ The row sits inside the summary rather than being the summary, so the disclosure marker
116
+ survives: `display: flex` on a summary removes it in every engine. The button's own click
117
+ handler stops it toggling the block it sits in.
118
+ -->
119
+ <span class="pane-heading">
120
+ <span>Protocol constants</span>
121
+ <button id="forget" class="clear" type="button">Clear</button>
122
+ </span>
123
+ </summary>
124
+ <p class="note">
125
+ Not distributed with this app. The cipher key and IV are sixteen characters each; the handshake
126
+ key is what a device is greeted with. The same values work on any device of this family within
127
+ range, so treat them as you would a password.
128
+ </p>
129
+
130
+ <label for="cipher-key">Cipher key</label>
131
+ <input
132
+ id="cipher-key"
133
+ type="text"
134
+ autocomplete="off"
135
+ spellcheck="false"
136
+ maxlength="16"
137
+ placeholder="16 characters"
138
+ >
139
+
140
+ <label for="cipher-iv">Cipher IV</label>
141
+ <input
142
+ id="cipher-iv"
143
+ type="text"
144
+ autocomplete="off"
145
+ spellcheck="false"
146
+ maxlength="16"
147
+ placeholder="16 characters"
148
+ >
149
+
150
+ <label for="key">Key presented on connecting</label>
151
+ <input id="key" type="text" autocomplete="off" spellcheck="false" placeholder="handshake key">
152
+ </details>
153
+
154
+ <div class="actions">
155
+ <button id="connect" type="button">Find a device</button>
156
+ </div>
157
+
158
+ <dl id="device" hidden>
159
+ <dt>Name</dt>
160
+ <dd id="device-name">—</dd>
161
+ <dt>Status</dt>
162
+ <dd id="device-status">—</dd>
163
+ <dt>Reported serial</dt>
164
+ <dd id="device-serial">—</dd>
165
+ </dl>
166
+
167
+ <div id="readout" hidden>
168
+ <label for="param">Parameter</label>
169
+ <select id="param"></select>
170
+ <div class="actions">
171
+ <button id="read" type="button">Read</button>
172
+ <button id="read-provisioning" type="button">Read provisioning settings</button>
173
+ <button id="read-space" type="button">Read every parameter</button>
174
+ <button id="info" type="button">Read 0xFF02</button>
175
+ </div>
176
+ </div>
177
+
178
+ <!--
179
+ Both panes sit outside the block above, which is hidden when the device goes away. What they hold
180
+ is worth keeping after a disconnect — a sweep takes minutes and the device may drop at the end of
181
+ one — so each is cleared on request and never automatically.
182
+ -->
183
+ <div class="pane-heading">
184
+ <label for="result">Readings</label>
185
+ <button id="clear-result" class="clear" type="button">Clear</button>
186
+ </div>
187
+ <pre id="result" aria-live="polite"></pre>
188
+
189
+ <div class="pane-heading">
190
+ <label for="log">Everything the device has sent</label>
191
+ <button id="clear-log" class="clear" type="button">Clear</button>
192
+ </div>
193
+ <pre id="log"></pre>
194
+ </section>
195
+
196
+ <footer>
197
+ <p id="build">—</p>
198
+ </footer>
199
+ </main>
200
+
201
+
202
+ </body>
203
+ </html>
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "Heliobind",
3
+ "short_name": "Heliobind",
4
+ "description": "Find, read and provision a Growatt balcony battery over Bluetooth.",
5
+ "start_url": "./",
6
+ "scope": "./",
7
+ "display": "standalone",
8
+ "orientation": "portrait",
9
+ "background_color": "#fbfbfc",
10
+ "theme_color": "#1f6feb",
11
+ "icons": [
12
+ { "src": "./icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
13
+ { "src": "./icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
14
+ { "src": "./icons/icon-192-maskable.png", "sizes": "192x192", "type": "image/png", "purpose": "maskable" },
15
+ { "src": "./icons/icon-512-maskable.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable" }
16
+ ]
17
+ }
package/dist/sw.js ADDED
@@ -0,0 +1,76 @@
1
+ /* Generated by scripts/build.ts. Edit scripts/service-worker.ts instead. */
2
+ const CACHE = "heliobind-development";
3
+
4
+ const ASSETS = [
5
+ "./",
6
+ "./chunk-hap08v1b.js",
7
+ "./index.html",
8
+ "./chunk-h2a7cxvg.css",
9
+ "./manifest-w9cqzme5.webmanifest",
10
+ "./heliobind-pd6mv76e.svg",
11
+ "./apple-touch-icon-78jb078y.png",
12
+ "./icons/heliobind-maskable.svg",
13
+ "./icons/heliobind.svg",
14
+ "./icons/icon-512.png",
15
+ "./icons/icon-192-maskable.png",
16
+ "./icons/apple-touch-icon.png",
17
+ "./icons/icon-192.png",
18
+ "./icons/icon-512-maskable.png",
19
+ ];
20
+
21
+ self.addEventListener("install", (event) => {
22
+ // No skipWaiting here: a fresh worker waits until the page asks for it.
23
+ event.waitUntil(caches.open(CACHE).then((cache) => cache.addAll(ASSETS)));
24
+ });
25
+
26
+ self.addEventListener("activate", (event) => {
27
+ event.waitUntil(
28
+ (async () => {
29
+ // Every build gets its own cache, so activation is also the only cleanup there is.
30
+ const names = await caches.keys();
31
+ await Promise.all(names.filter((name) => name !== CACHE).map((name) => caches.delete(name)));
32
+ await self.clients.claim();
33
+ })(),
34
+ );
35
+ });
36
+
37
+ self.addEventListener("fetch", (event) => {
38
+ const request = event.request;
39
+ if (request.method !== "GET") return;
40
+
41
+ const url = new URL(request.url);
42
+ if (url.origin !== self.location.origin) return;
43
+
44
+ event.respondWith(
45
+ (async () => {
46
+ const cache = await caches.open(CACHE);
47
+
48
+ // A navigation is answered with the app shell whatever the path, so a reload deep in the app works
49
+ // offline and an unknown path does not produce the browser's error page.
50
+ if (request.mode === "navigate") {
51
+ return (await cache.match("./")) ?? (await cache.match("./index.html")) ?? fetch(request);
52
+ }
53
+
54
+ const hit = await cache.match(request);
55
+ if (hit) return hit;
56
+
57
+ // Not precached — an icon a manifest asked for late, say. Fetch it and keep it, but never fail the
58
+ // request because the network is down.
59
+ try {
60
+ const response = await fetch(request);
61
+ if (response.ok) await cache.put(request, response.clone());
62
+ return response;
63
+ } catch (error) {
64
+ const fallback = await cache.match("./");
65
+ if (fallback) return fallback;
66
+ throw error;
67
+ }
68
+ })(),
69
+ );
70
+ });
71
+
72
+ self.addEventListener("message", (event) => {
73
+ // The one thing the page may command: stop waiting and take over. The page reloads itself when the
74
+ // controller changes.
75
+ if (event.data === "take-over") void self.skipWaiting();
76
+ });
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "heliobind",
3
+ "version": "0.1.0",
4
+ "description": "Find, read and provision a Growatt balcony battery over Bluetooth, from a browser",
5
+ "license": "Apache-2.0",
6
+ "author": "Simon Eisenmann",
7
+ "homepage": "https://github.com/longsleep/heliobind#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/longsleep/heliobind.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/longsleep/heliobind/issues"
14
+ },
15
+ "keywords": [
16
+ "growatt",
17
+ "nexa",
18
+ "noah",
19
+ "bluetooth",
20
+ "web-bluetooth",
21
+ "solar",
22
+ "balcony",
23
+ "pwa"
24
+ ],
25
+ "type": "module",
26
+ "bin": {
27
+ "heliobind": "./scripts/serve.ts"
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "scripts/serve.ts",
32
+ "LICENSE",
33
+ "NOTICE",
34
+ "README.md"
35
+ ],
36
+ "packageManager": "bun@1.4.0",
37
+ "engines": {
38
+ "bun": ">=1.4.0"
39
+ },
40
+ "scripts": {
41
+ "dev": "bun ./index.html",
42
+ "build": "bun run scripts/build.ts",
43
+ "test": "bun test",
44
+ "typecheck": "tsc --noEmit",
45
+ "lint": "biome check .",
46
+ "format": "biome check --write .",
47
+ "check": "bun run lint && bun run typecheck && bun test",
48
+ "serve": "bun ./scripts/serve.ts",
49
+ "prepack": "bun run build",
50
+ "build:local": "HELIOBIND_INLINE=1 bun run scripts/build.ts"
51
+ },
52
+ "dependencies": {},
53
+ "devDependencies": {
54
+ "@biomejs/biome": "2.5.10",
55
+ "@types/bun": "1.4.0",
56
+ "@types/web-bluetooth": "0.0.21",
57
+ "typescript": "7.0.2"
58
+ },
59
+ "trustedDependencies": []
60
+ }
@@ -0,0 +1,77 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * `bunx heliobind` — serve the built app on this machine.
4
+ *
5
+ * Web Bluetooth needs a secure context, which means HTTPS or `localhost`. Serving on localhost is therefore
6
+ * the one arrangement that needs no certificate, and it is why this exists: `bunx heliobind` and a browser
7
+ * is the whole setup.
8
+ *
9
+ * That also fixes what it is for. A phone cannot reach this laptop's localhost, so this is the desktop
10
+ * path: Chrome with a Bluetooth adapter, close enough to the device. On Linux that additionally needs
11
+ * `chrome://flags/#enable-experimental-web-platform-features`, where Web Bluetooth ships disabled.
12
+ * Reaching this from a phone means a reverse proxy with a certificate, which the README covers and this
13
+ * does not attempt.
14
+ *
15
+ * Files come from the `dist/` shipped inside the package, not from the current directory: the command is
16
+ * meant to be run from anywhere.
17
+ */
18
+
19
+ import { existsSync } from "node:fs";
20
+ import { join, normalize } from "node:path";
21
+
22
+ const ROOT = join(import.meta.dir, "..", "dist");
23
+
24
+ /** Read `--name value` and `--name=value` alike, because both are what people type. */
25
+ function option(name: string, fallback: string): string {
26
+ const args = Bun.argv;
27
+ const exact = args.indexOf(`--${name}`);
28
+ if (exact !== -1 && args[exact + 1]) return args[exact + 1] as string;
29
+ const joined = args.find((arg) => arg.startsWith(`--${name}=`));
30
+ return joined ? joined.slice(name.length + 3) : fallback;
31
+ }
32
+
33
+ if (Bun.argv.includes("--help") || Bun.argv.includes("-h")) {
34
+ console.log(`heliobind — serve the Bluetooth setup app locally
35
+
36
+ bunx heliobind [--port 8787] [--host 127.0.0.1]
37
+
38
+ Open the printed address in Chrome. Bluetooth from a web page needs a secure
39
+ context, so localhost works and a plain LAN address does not.`);
40
+ process.exit(0);
41
+ }
42
+
43
+ if (!existsSync(join(ROOT, "index.html"))) {
44
+ console.error(`no built app at ${ROOT}\nThis package should ship one; please report it.`);
45
+ process.exit(1);
46
+ }
47
+
48
+ const port = Number(option("port", "8787"));
49
+ // Loopback by default. A LAN address would not be a secure context anyway, so binding wider by default
50
+ // would offer a page that cannot do the one thing it is for.
51
+ const host = option("host", "127.0.0.1");
52
+
53
+ const server = Bun.serve({
54
+ port,
55
+ hostname: host,
56
+ async fetch(request) {
57
+ const { pathname } = new URL(request.url);
58
+
59
+ // `normalize` collapses `..` before it is joined, so a crafted path cannot climb out of dist.
60
+ const relative = normalize(decodeURIComponent(pathname)).replace(/^(\.\.[/\\])+/, "");
61
+ const candidate = join(ROOT, relative);
62
+ const file = Bun.file(candidate);
63
+ if (relative !== "/" && (await file.exists())) {
64
+ return new Response(file);
65
+ }
66
+
67
+ // Anything else is the app: a reload deep in it, or a path the service worker has not cached.
68
+ return new Response(Bun.file(join(ROOT, "index.html")), {
69
+ headers: { "content-type": "text/html; charset=utf-8" },
70
+ });
71
+ },
72
+ });
73
+
74
+ console.log(`heliobind serving ${ROOT}
75
+ ${server.url}
76
+
77
+ Open it in Chrome. Press Ctrl-C to stop.`);