kamoji-dev 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,116 @@
1
- # Temporary Holding Version
1
+ # kamoji-dev
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
+ Develop [Kamoji Mini Apps](https://docs.kamoji.bot/docs/apps) on your own Kamoji: edit the files in
4
+ your editor, save, and the mini app is checked, installed over Bluetooth and reopened on Kamoji's
5
+ screen within seconds. With a USB cable plugged in, Kamoji's log (your `print()` lines, Lua errors,
6
+ CPU budget warnings, crashes) streams into the same terminal.
7
+
8
+ ```sh
9
+ npm i -g kamoji-dev
10
+ kamoji dev ./my-app
11
+ ```
12
+
13
+ or without installing: `npx kamoji-dev dev ./my-app`.
14
+
15
+ Needs Node.js 20 or newer, a computer with Bluetooth LE (macOS, Windows 10+, Linux) and a Kamoji
16
+ with firmware 0.3.0 or newer (mini apps from 0.1.80).
17
+
18
+ ## Before you start
19
+
20
+ - **Disconnect the Kamoji app on your phone.** Kamoji takes one Bluetooth connection at a time:
21
+ while your phone is connected, `kamoji` can't reach it (it says so). Close the app, or disconnect
22
+ in it.
23
+ - **The first time, keep the computer right next to Kamoji** (in the car). Kamoji only starts
24
+ trusting a new device when it is close (-72 dBm or stronger, a few metres at most). From then on
25
+ it works from any distance. Kamoji remembers 10 devices; this computer is one of them.
26
+ - **macOS:** the first run asks whether your terminal (Terminal, iTerm, VS Code…) may use Bluetooth.
27
+ Allow it in System Settings > Privacy & Security > Bluetooth, then run again.
28
+ - **Linux:** Bluetooth goes through HCI sockets: run
29
+ `sudo setcap cap_net_raw+eip $(eval readlink -f $(which node))` once (or run as root), and make
30
+ sure BlueZ isn't holding the adapter (`sudo systemctl stop bluetooth` if the scan finds nothing).
31
+ - **Windows:** Windows 10 build 15063 or newer with a Bluetooth LE adapter.
32
+
33
+ ## Commands
34
+
35
+ | Command | What it does |
36
+ |---|---|
37
+ | `kamoji dev <folder>` | Check, install and open the mini app; then again on every save (400 ms after the last change). Keys while it runs: Enter = install again, `o` = open, `s` = screenshot, `b` = restart Kamoji, `q` = quit |
38
+ | `kamoji install <folder>` | Check, install and open once (exit code 0 = on screen) |
39
+ | `kamoji check <folder>` | Only check the folder, like the Mini Apps store does (`--json` for tools) |
40
+ | `kamoji apps` | List the mini apps on Kamoji, with their mode numbers and sizes |
41
+ | `kamoji shot` | Save a screenshot (over USB when plugged in, else Bluetooth) to `./kamoji-shots` |
42
+ | `kamoji logs` | Kamoji's USB log (`--app <id>` to follow one app, `--verbose` for every line) |
43
+ | `kamoji forget` | Kamoji forgets this computer, and the key is deleted |
44
+
45
+ Options: `--device KMJ-XXXX` (several Kamoji nearby; the last four characters are enough),
46
+ `--port /dev/cu.usbmodemXXXX` (USB port, found by itself otherwise), `--ble` (no USB log even with a
47
+ cable), `--usb` (require the cable), `--out DIR` (screenshots), `--reboot` (restart Kamoji by itself
48
+ when the mini app's Bluetooth services need it), `--no-lua`, `--verbose`.
49
+
50
+ What you see:
51
+
52
+ ```text
53
+ 10:02:11 Looking for Kamoji over Bluetooth…
54
+ 10:02:14 Connected to KMJ-1A2B "Bob": firmware 0.3.1, R7.
55
+ 10:02:14 3 mini app(s) on it, storage 1.3 MB of 8.0 MB used.
56
+ 10:02:14 USB log from /dev/cu.usbmodem11301.
57
+ 10:02:16 Installed my-app 1.0.0 in 1.9 s (3 file(s), 6.2 KB, 3.3 KB/s).
58
+ 10:02:16 my-app is on screen (mode 7, 2.2 s after the first byte).
59
+ 10:02:16 [entered] [my-app] entered in 118 ms: 4 bindings, Lua 2311 bytes
60
+ 10:02:17 [print] tick 1
61
+ 10:02:19 [warn] [my-app] main.lua: main.lua:12: attempt to perform arithmetic on a nil value
62
+ ```
63
+
64
+ ## What it checks before sending
65
+
66
+ The store's rules (manifest `id`, `version`, `api_version` 1, known `permissions` / `features` /
67
+ `platforms`, `params`, file paths, 64 files, 2 MB), plus what Kamoji itself refuses or skips:
68
+ `ble` without `ble.gatt`, `layout.json` that isn't JSON or names an unknown widget, unclosed
69
+ `{{ … }}` bindings, and Lua syntax with `luac -p` when a Lua compiler is installed (Kamoji runs
70
+ Lua 5.4; another `luac` only warns). Errors stop the install with the file and the reason; nothing
71
+ is sent until they are fixed. Once connected: the firmware must be at least `min_firmware`, and the
72
+ app must fit in Kamoji's free storage. Hidden files, `node_modules` and editor files (`*~`, `*.swp`)
73
+ are never sent. The full table is in `spec/VALIDATION.md` of the source.
74
+
75
+ ## How it works
76
+
77
+ The same Bluetooth commands as the Kamoji app's **Install from file**
78
+ ([Sideloading](https://docs.kamoji.bot/docs/apps/sideloading#bluetooth-install-protocol)):
79
+ `APP_PUT` + `ASSET_DATA` per file, `APP_COMMIT`, then `SET_MODE` to the app's mode (from
80
+ `APPS_LIST`). An install replaces the whole mini app, so every save sends every file (unchanged
81
+ saves are skipped); the app's settings (`config.json`) and `data/` stay. A mini app that is on
82
+ screen restarts with the new version. Bluetooth is slow-ish: about 3-15 KB/s depending on the
83
+ computer, so a 10 KB app reloads in 1-3 s.
84
+
85
+ Over USB the tool only reads: Kamoji has no install over USB (that would mean rewriting its whole
86
+ storage), so the cable is for the log and fast screenshots.
87
+
88
+ ## Keys
89
+
90
+ Each Kamoji gets its own key for this computer: 32 random bytes in `~/.config/kamoji/<KMJ-XXXX>.key`
91
+ (readable by you only; `KAMOJI_CONFIG_DIR` moves the folder). The key is never printed. Whoever has
92
+ it can control that Kamoji: don't share it. `kamoji forget` removes it from Kamoji and the computer.
93
+ The Python tool in the Kamoji repositories (`kamoji_dev.py`) uses the same files.
94
+
95
+ ## Troubleshooting
96
+
97
+ | Message | What to do |
98
+ |---|---|
99
+ | No Kamoji found nearby | Is it on and close? Is the Kamoji app disconnected? Bluetooth permission for the terminal (macOS)? |
100
+ | KMJ-… is connected to another device | Disconnect it in the Kamoji app, or close the app |
101
+ | too far to start | First time only: hold the computer next to Kamoji |
102
+ | needs firmware … or newer | Update Kamoji in the Kamoji app |
103
+ | Kamoji is out of storage space | Remove a mini app in the Kamoji app (Apps) |
104
+ | its Bluetooth services go live after a restart | Press `b` (or run with `--reboot`) |
105
+ | No USB cable: no Kamoji log | Plug in a USB-C **data** cable; `--port` if several boards are plugged in |
106
+
107
+ ## Development
108
+
109
+ ```sh
110
+ npm test # node:test, fake Kamoji, no device needed
111
+ node spec/make-conversation.mjs # after changing the protocol: re-record spec/conversation.json
112
+ ```
113
+
114
+ Bluetooth is [@stoprocent/noble](https://github.com/stoprocent/noble) (maintained, prebuilt for
115
+ macOS, Windows and Linux, so installing needs no compiler), USB is
116
+ [serialport](https://serialport.io). No other dependencies.
package/bin/kamoji.js ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.js'
3
+
4
+ const major = Number(process.versions.node.split('.')[0])
5
+ if (major < 20) {
6
+ console.error(`kamoji needs Node.js 20 or newer (this is ${process.versions.node}).`)
7
+ process.exit(2)
8
+ }
9
+ main().then((code) => process.exit(code ?? 0))
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "kamoji-dev",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Develop Kamoji Mini Apps on your own Kamoji: check, install over Bluetooth and reload on every save, with the USB log and screenshots.",
5
+ "type": "module",
6
+ "bin": {
7
+ "kamoji": "bin/kamoji.js"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "src/",
12
+ "README.md",
13
+ "spec/VALIDATION.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test test/*.test.js"
20
+ },
21
+ "keywords": ["kamoji", "mini-apps", "ble", "esp32"],
22
+ "homepage": "https://docs.kamoji.bot/docs/apps",
23
+ "license": "MIT",
24
+ "dependencies": {
25
+ "@stoprocent/noble": "2.8.0",
26
+ "serialport": "13.0.0"
27
+ }
28
+ }
@@ -0,0 +1,68 @@
1
+ # Mini app checks (shared by `kamoji` on npm and `worker/rig/kamoji_dev.py`)
2
+
3
+ Both command lines check a mini app folder with **these rules, with these ids**, before anything is
4
+ sent to a Kamoji. The test suites of both run the fixture apps in `spec/apps/` and compare the ids
5
+ with `spec/fixtures.json`, so a rule changed in one place must be changed in the other two.
6
+
7
+ Sources: the Mini Apps store (kamoji-cms `src/utils/appBundle.ts`: `APP_ID_RE`, `SEMVER_RE`,
8
+ `APP_PERMISSIONS`, `APP_FEATURES`, `APP_PLATFORMS`, `BUNDLE_LIMITS`, `checkAppPath`), the firmware
9
+ (kamoji-esphome `kamoji_app_manager.cpp`: `APP_COMMIT` manifest check, 16 KB manifest, `api_version`
10
+ 1, widget types, param types) and docs.kamoji.bot (Mini Apps: Manifest, Layout and Widgets, Bluetooth
11
+ Services, HTTP Requests). The store does not check layouts or Lua today; these are extra checks.
12
+
13
+ `error` blocks the install. `warning` is printed, the install goes on. `info` is printed only.
14
+
15
+ ## Files
16
+
17
+ | id | level | rule |
18
+ |---|---|---|
19
+ | `manifest-missing` | error | `manifest.json` at the root of the folder |
20
+ | `path` | error | Every path: not absolute, no `\`, no control characters, no empty / `.` / `..` segment, no segment starting with `.`, at most 63 bytes (UTF-8), at most 3 levels |
21
+ | `too-many-files` | error | At most 64 files |
22
+ | `too-large` | error | At most 2 MB (2 × 1024 × 1024 bytes) in all |
23
+ | `skipped` | info | Not sent: hidden files and folders (`.*`), `.DS_Store`, `Thumbs.db`, `__MACOSX`, `node_modules`, editor files (`*~`, `*.swp`, `*.swo`, `*.tmp`, `#*#`, `4913`), symbolic links |
24
+
25
+ ## manifest.json
26
+
27
+ | id | level | rule |
28
+ |---|---|---|
29
+ | `manifest-size` | error | At most 16 KB (16384 bytes) |
30
+ | `manifest-json` | error | Valid JSON (a UTF-8 BOM is allowed), and an object |
31
+ | `id` | error | `id` matches `^[a-z0-9][a-z0-9-]{1,39}$` |
32
+ | `id-folder` | warning | `id` differs from the folder name (the store and Kamoji use the id as the folder name) |
33
+ | `version` | error | `version` is a string matching the store's semver: `MAJOR.MINOR.PATCH`, optional `-pre.release`, no `+build` |
34
+ | `api-version` | error | `api_version` is the integer `1` (Kamoji refuses anything else) |
35
+ | `permissions` | error | `permissions`, if present, is an array of known permissions: `sensors.imu`, `sensors.light`, `sensors.mic`, `sensors.env`, `sensors.obd`, `events.drive`, `events.device`, `touch`, `net.http`, `net.mqtt`, `net.phone`, `phone.navigation`, `ble.gatt` |
36
+ | `features` | error | `features`, if present, is an array of: `gyro`, `temperature`, `light`, `microphone`, `fft`, `wifi`, `ble`, `gatt`, `mqtt`, `http`, `time`, `rgb_leds` |
37
+ | `platforms` | error | `platforms`, if present, is a non-empty array of `android` / `ios` |
38
+ | `min-firmware` | error | `min_firmware`, if present, is a version string like `0.3.0` |
39
+ | `ble-permission` | error | A `ble` object needs the `ble.gatt` permission (Kamoji refuses the install: `APP:ERR:bad_ble`) |
40
+ | `http-permission` | warning | An `http` object without the `net.http` permission (`http` is `nil` in Lua) |
41
+ | `min-firmware-030` | warning | `ble` or `http` needs firmware 0.3.0: set `"min_firmware": "0.3.0"` or newer |
42
+ | `params` | error | `params`, if present, is an array of objects, each with a unique string `key` and a `type` (default `string`) among `number`, `bool`, `string`, `enum`, `color`, `secret`; an `enum` has a non-empty `options` array |
43
+
44
+ ## layout.json (optional)
45
+
46
+ | id | level | rule |
47
+ |---|---|---|
48
+ | `layout-json` | error | Valid JSON |
49
+ | `layout-shape` | error | An array of widgets, or an object whose `widgets` is an array |
50
+ | `widget-type` | warning | Each widget is an object whose `type` is one of `label`, `rect`, `circle`, `arc`, `bar`, `line`, `polyline`, `bitmap`, `chart`, `image` (Kamoji skips any other) |
51
+ | `align` | warning | `align`, if present, is one of `center`, `top_left`, `top_mid`, `top_right`, `left_mid`, `right_mid`, `bottom_left`, `bottom_mid`, `bottom_right` |
52
+ | `binding-braces` | warning | Every `{{` in a string has its `}}` |
53
+ | `layout-on` | error | `on`, if present, is an object whose values are strings (Lua statements) |
54
+
55
+ ## Lua (`*.lua`)
56
+
57
+ | id | level | rule |
58
+ |---|---|---|
59
+ | `lua-syntax` | error | Compiles with `luac -p` when the compiler on the computer is **Lua 5.4** (Kamoji runs 5.4.7 with 32-bit numbers) |
60
+ | `lua-other-version` | warning | A syntax error from another Lua version's `luac` (5.5 reserves `global`, 5.3 lacks `<const>`…): confirm on Kamoji |
61
+ | `lua-missing` | info | No `luac5.4` / `luac` found: Lua is checked by Kamoji only |
62
+
63
+ ## On the Kamoji (after connecting)
64
+
65
+ | id | level | rule |
66
+ |---|---|---|
67
+ | `firmware-too-old` | error | Kamoji's firmware (`GET_INFO` `FW:`) is older than `min_firmware` |
68
+ | `no-space` | error | The app is larger than Kamoji's free storage (`APP:STORAGE` total − used): the staged copy needs room next to the installed one |
package/src/ble.js ADDED
@@ -0,0 +1,215 @@
1
+ // Finding and connecting to a Kamoji over Bluetooth with @stoprocent/noble (a maintained fork of noble
2
+ // with prebuilt binaries for macOS, Windows and Linux, so `npm i` needs no compiler).
3
+ //
4
+ // Kamoji advertises as KMJ-XXXX with the control service; the scan response carries manufacturer data
5
+ // (company 0xFFFF): MAC (6), hardware revision (1: 7 = R7, 8 = R8), firmware version (ASCII). While a
6
+ // phone is connected, newer firmware advertises *not connectable* (docs.kamoji.bot Bluetooth Protocol).
7
+ import { CMD_UUID, KamojiError, SERVICE_UUID, TX_UUID } from './protocol.js'
8
+
9
+ const short = (uuid) => uuid.replace(/-/g, '').toLowerCase()
10
+ const SVC = short(SERVICE_UUID)
11
+
12
+ export const NOT_FOUND_HINT = [
13
+ 'Check that:',
14
+ ' - Kamoji is on and close by;',
15
+ ' - the Kamoji app on your phone is disconnected from it (Kamoji takes one Bluetooth connection at a time:',
16
+ ' close the app, or disconnect in it);',
17
+ " - Bluetooth is on, and (macOS) your terminal may use it: System Settings > Privacy & Security > Bluetooth.",
18
+ ].join('\n')
19
+
20
+ export const BUSY_HINT =
21
+ 'Kamoji takes one Bluetooth connection at a time: disconnect it in the Kamoji app (or close the app), then run this again.'
22
+
23
+ /** Manufacturer data → { mac, revision, firmware } (null fields when absent). */
24
+ export function parseManufacturerData(buf) {
25
+ if (!buf || buf.length < 8) return { mac: null, revision: null, firmware: null }
26
+ const b = buf.subarray(2) // company id 0xFFFF
27
+ const mac = [...b.subarray(0, 6)].map((x) => x.toString(16).padStart(2, '0')).join(':').toUpperCase()
28
+ let revision = null
29
+ let ver = b.subarray(6)
30
+ if (ver.length && ver[0] < 0x20) {
31
+ revision = ver[0] === 7 ? 'R7' : ver[0] === 8 ? 'R8' : null
32
+ ver = ver.subarray(1)
33
+ }
34
+ const firmware = ver.toString('ascii').replace(/[^\x20-\x7e]/g, '').trim() || null
35
+ return { mac, revision, firmware }
36
+ }
37
+
38
+ /** A scan result as the rest of the tool sees it. */
39
+ export function describe(p) {
40
+ const adv = p.advertisement ?? {}
41
+ const md = parseManufacturerData(adv.manufacturerData)
42
+ return {
43
+ id: p.id,
44
+ name: adv.localName || null,
45
+ rssi: p.rssi,
46
+ connectable: p.connectable !== false,
47
+ hasService: (adv.serviceUuids ?? []).map(short).includes(SVC),
48
+ ...md,
49
+ peripheral: p,
50
+ }
51
+ }
52
+
53
+ export function isKamoji(d) {
54
+ return (d.name && /^KMJ?-/.test(d.name)) || d.hasService
55
+ }
56
+
57
+ /**
58
+ * Pick the Kamoji to use from what the scan saw. Throws KamojiError with a hint.
59
+ * @param {ReturnType<typeof describe>[]} seen
60
+ * @param {string} [want] --device: KMJ-XXXX, its last 4 characters, or a Bluetooth id/address
61
+ */
62
+ export function chooseKamoji(seen, want) {
63
+ const kamojis = seen.filter(isKamoji)
64
+ let list = kamojis
65
+ if (want) {
66
+ const w = want.toLowerCase()
67
+ list = kamojis.filter(
68
+ (d) => (d.name ?? '').toLowerCase() === w || (d.name ?? '').toLowerCase().endsWith(`-${w}`) ||
69
+ d.id?.toLowerCase() === w || (d.mac ?? '').toLowerCase() === w,
70
+ )
71
+ if (!list.length)
72
+ throw new KamojiError(
73
+ 'not_found',
74
+ `${want} was not found.${kamojis.length ? ` Seen: ${kamojis.map((d) => d.name ?? d.id).join(', ')}.` : ''}`,
75
+ NOT_FOUND_HINT,
76
+ )
77
+ }
78
+ if (!list.length) throw new KamojiError('not_found', 'No Kamoji found nearby.', NOT_FOUND_HINT)
79
+ if (list.length > 1) {
80
+ const names = list
81
+ .sort((a, b) => b.rssi - a.rssi)
82
+ .map((d) => `${d.name ?? d.id} (${d.rssi} dBm${d.connectable ? '' : ', in use'})`)
83
+ .join(', ')
84
+ throw new KamojiError('ambiguous', `More than one Kamoji nearby: ${names}.`, 'Pick one with --device KMJ-XXXX.')
85
+ }
86
+ const d = list[0]
87
+ if (!d.connectable) throw new KamojiError('busy', `${d.name ?? 'Kamoji'} is connected to another device (a phone?).`, BUSY_HINT)
88
+ return d
89
+ }
90
+
91
+ let noblePromise
92
+ export async function loadNoble() {
93
+ noblePromise ??= import('@stoprocent/noble')
94
+ .then((m) => m.default ?? m)
95
+ .catch((e) => {
96
+ throw new KamojiError(
97
+ 'no_ble',
98
+ `Bluetooth support could not load (@stoprocent/noble): ${e.message}`,
99
+ 'Reinstall kamoji-dev for this Node version (npm i -g kamoji-dev), or use the Python kamoji_dev.py.',
100
+ )
101
+ })
102
+ return noblePromise
103
+ }
104
+
105
+ export async function poweredOn(noble, ms = 8000) {
106
+ try {
107
+ await noble.waitForPoweredOnAsync(ms)
108
+ } catch {
109
+ const state = noble.state
110
+ if (state === 'unauthorized')
111
+ throw new KamojiError(
112
+ 'ble_permission',
113
+ 'This terminal may not use Bluetooth.',
114
+ 'macOS: System Settings > Privacy & Security > Bluetooth: allow your terminal app (Terminal, iTerm, VS Code), then run again.',
115
+ )
116
+ if (state === 'poweredOff') throw new KamojiError('ble_off', 'Bluetooth is off on this computer.', 'Turn it on and try again.')
117
+ if (state === 'unsupported') throw new KamojiError('ble_unsupported', 'This computer has no usable Bluetooth LE adapter.')
118
+ throw new KamojiError('ble_state', `Bluetooth is not ready (${state}).`)
119
+ }
120
+ }
121
+
122
+ /** Scan for `ms` (stopping early when `want` matches a connectable Kamoji). */
123
+ export async function scan(noble, { ms = 6000, want, ui } = {}) {
124
+ const seen = new Map()
125
+ let early
126
+ const stopEarly = new Promise((r) => (early = r))
127
+ const onDiscover = (p) => {
128
+ const d = describe(p)
129
+ const prev = seen.get(d.id)
130
+ // Names and service UUIDs may come in separate packets: keep what any packet said.
131
+ seen.set(d.id, { ...prev, ...d, name: d.name ?? prev?.name ?? null, hasService: d.hasService || !!prev?.hasService })
132
+ if (want) {
133
+ try {
134
+ if (chooseKamoji([seen.get(d.id)], want)) early()
135
+ } catch {
136
+ // not this one (yet)
137
+ }
138
+ }
139
+ }
140
+ noble.on('discover', onDiscover)
141
+ await noble.startScanningAsync([], true)
142
+ // Kamoji advertises every 0.7-0.9 s, and less often on air while it uses Wi-Fi: say why a scan takes a while.
143
+ const slow = ui && want ? setTimeout(() => ui.info(`Still looking for ${want}… (a Kamoji on Wi-Fi can take up to half a minute to be seen)`), 10000) : null
144
+ await Promise.race([new Promise((r) => setTimeout(r, ms)), stopEarly])
145
+ if (slow) clearTimeout(slow)
146
+ await noble.stopScanningAsync().catch(() => undefined)
147
+ noble.removeListener('discover', onDiscover)
148
+ return [...seen.values()]
149
+ }
150
+
151
+ const withTimeout = (p, ms, what) =>
152
+ Promise.race([p, new Promise((_r, rej) => setTimeout(() => rej(new Error(`${what} timed out`)), ms))])
153
+
154
+ /**
155
+ * Connect, find CMD / TX, subscribe. Returns a link for protocol.Session plus disconnect().
156
+ * @param {ReturnType<typeof describe>} d
157
+ */
158
+ export async function connect(d, { onDisconnect } = {}) {
159
+ const p = d.peripheral
160
+ try {
161
+ await withTimeout(p.connectAsync(), 15000, 'connecting')
162
+ } catch (e) {
163
+ throw new KamojiError('connect', `Could not connect to ${d.name ?? 'Kamoji'}: ${e.message}.`, BUSY_HINT)
164
+ }
165
+ let cmd
166
+ let tx
167
+ try {
168
+ const { characteristics } = await withTimeout(
169
+ p.discoverSomeServicesAndCharacteristicsAsync([SVC], [short(CMD_UUID), short(TX_UUID)]),
170
+ 10000,
171
+ 'service discovery',
172
+ )
173
+ cmd = characteristics.find((c) => c.uuid === short(CMD_UUID))
174
+ tx = characteristics.find((c) => c.uuid === short(TX_UUID))
175
+ if (!cmd || !tx) throw new Error('the Kamoji control service is missing')
176
+ await tx.subscribeAsync()
177
+ } catch (e) {
178
+ await p.disconnectAsync().catch(() => undefined)
179
+ throw new KamojiError('connect', `Connected, but ${e.message}.`)
180
+ }
181
+ // macOS reports the largest write without response directly; the HCI and Windows bindings the ATT MTU.
182
+ if (!p.mtu) await new Promise((r) => { p.once('mtu', r); setTimeout(r, 1000) })
183
+ const maxWrite = () => {
184
+ const mtu = p.mtu || 23
185
+ return process.platform === 'darwin' ? mtu : mtu - 3
186
+ }
187
+ const handlers = new Set()
188
+ tx.on('data', (data) => {
189
+ const text = Buffer.from(data).toString('utf8')
190
+ for (const h of handlers) h(text)
191
+ })
192
+ let lock = Promise.resolve()
193
+ const locked = (fn) => {
194
+ const run = lock.then(fn, fn)
195
+ lock = run.catch(() => undefined)
196
+ return run
197
+ }
198
+ let closing = false
199
+ p.once('disconnect', (reason) => {
200
+ if (!closing) onDisconnect?.(reason)
201
+ })
202
+ return {
203
+ send: (text) => locked(() => cmd.writeAsync(Buffer.from(text, 'ascii'), false)),
204
+ sendRaw: (buf) => locked(() => cmd.writeAsync(buf, true)),
205
+ maxWrite,
206
+ onMessage: (h) => {
207
+ handlers.add(h)
208
+ return () => handlers.delete(h)
209
+ },
210
+ disconnect: async () => {
211
+ closing = true
212
+ await p.disconnectAsync().catch(() => undefined)
213
+ },
214
+ }
215
+ }