kamoji-dev 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +134 -2
- package/bin/kamoji.js +9 -0
- package/package.json +31 -4
- package/spec/VALIDATION.md +68 -0
- package/src/ble.js +215 -0
- package/src/check.js +77 -0
- package/src/cli.js +293 -0
- package/src/core/bytes.js +112 -0
- package/src/core/check.js +222 -0
- package/src/core/dev.js +398 -0
- package/src/core/protocol.js +749 -0
- package/src/dev.js +62 -0
- package/src/keys.js +37 -0
- package/src/logfilter.js +91 -0
- package/src/protocol.js +47 -0
- package/src/serial.js +169 -0
- package/src/watch.js +106 -0
package/README.md
CHANGED
|
@@ -1,3 +1,135 @@
|
|
|
1
|
-
#
|
|
1
|
+
# kamoji-dev
|
|
2
2
|
|
|
3
|
-
|
|
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; a save sends only the files that changed (firmware 0.3.3). Your app's log
|
|
6
|
+
(`print()` lines, Lua errors, CPU budget warnings) streams into the same terminal: over the USB
|
|
7
|
+
cable when one is plugged in (crashes too), else over Bluetooth (firmware 0.3.3).
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm i -g kamoji-dev
|
|
11
|
+
kamoji dev ./my-app
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
or without installing: `npx kamoji-dev dev ./my-app`.
|
|
15
|
+
|
|
16
|
+
Needs Node.js 20 or newer, a computer with Bluetooth LE (macOS, Windows 10+, Linux) and a Kamoji
|
|
17
|
+
with firmware 0.3.0 or newer (mini apps from 0.1.80; 0.3.3 for changed-files reloads and the log
|
|
18
|
+
over Bluetooth).
|
|
19
|
+
|
|
20
|
+
## Before you start
|
|
21
|
+
|
|
22
|
+
- **Disconnect the Kamoji app on your phone.** Kamoji takes one Bluetooth connection at a time:
|
|
23
|
+
while your phone is connected, `kamoji` can't reach it (it says so). Close the app, or disconnect
|
|
24
|
+
in it.
|
|
25
|
+
- **The first time, keep the computer right next to Kamoji** (in the car). Kamoji only starts
|
|
26
|
+
trusting a new device when it is close (-72 dBm or stronger, a few metres at most). From then on
|
|
27
|
+
it works from any distance. Kamoji remembers 10 devices; this computer is one of them.
|
|
28
|
+
- **macOS:** the first run asks whether your terminal (Terminal, iTerm, VS Code…) may use Bluetooth.
|
|
29
|
+
Allow it in System Settings > Privacy & Security > Bluetooth, then run again.
|
|
30
|
+
- **Linux:** Bluetooth goes through HCI sockets: run
|
|
31
|
+
`sudo setcap cap_net_raw+eip $(eval readlink -f $(which node))` once (or run as root), and make
|
|
32
|
+
sure BlueZ isn't holding the adapter (`sudo systemctl stop bluetooth` if the scan finds nothing).
|
|
33
|
+
- **Windows:** Windows 10 build 15063 or newer with a Bluetooth LE adapter.
|
|
34
|
+
|
|
35
|
+
## Commands
|
|
36
|
+
|
|
37
|
+
| Command | What it does |
|
|
38
|
+
|---|---|
|
|
39
|
+
| `kamoji dev <folder>` | Check, install and open the mini app; then again on every save (400 ms after the last change), sending only the changed files. Keys while it runs: Enter = install again (every file), `o` = open, `s` = screenshot, `b` = restart Kamoji, `q` = quit |
|
|
40
|
+
| `kamoji install <folder>` | Check, install and open once (exit code 0 = on screen) |
|
|
41
|
+
| `kamoji check <folder>` | Only check the folder, like the Mini Apps store does (`--json` for tools) |
|
|
42
|
+
| `kamoji apps` | List the mini apps on Kamoji, with their mode numbers and sizes |
|
|
43
|
+
| `kamoji shot` | Save a screenshot (over USB when plugged in, else Bluetooth) to `./kamoji-shots` |
|
|
44
|
+
| `kamoji logs` | Kamoji's log: USB, or over Bluetooth without a cable or with `--ble` (`--app <id>` to follow one app, `--verbose` for every USB line) |
|
|
45
|
+
| `kamoji forget` | Kamoji forgets this computer, and the key is deleted |
|
|
46
|
+
|
|
47
|
+
Options: `--device KMJ-XXXX` (several Kamoji nearby; the last four characters are enough),
|
|
48
|
+
`--port /dev/cu.usbmodemXXXX` (USB port, found by itself otherwise), `--ble` (no USB log even with a
|
|
49
|
+
cable: the app log comes over Bluetooth), `--ble-logs` (the app log over Bluetooth even with a cable;
|
|
50
|
+
USB then adds only crashes and resets), `--usb` (require the cable), `--out DIR` (screenshots), `--reboot` (restart Kamoji by itself
|
|
51
|
+
when the mini app's Bluetooth services need it), `--no-lua`, `--verbose`.
|
|
52
|
+
|
|
53
|
+
What you see:
|
|
54
|
+
|
|
55
|
+
```text
|
|
56
|
+
10:02:11 Looking for Kamoji over Bluetooth…
|
|
57
|
+
10:02:14 Connected to KMJ-1A2B "Bob": firmware 0.3.1, R7.
|
|
58
|
+
10:02:14 3 mini app(s) on it, storage 1.3 MB of 8.0 MB used.
|
|
59
|
+
10:02:14 USB log from /dev/cu.usbmodem11301.
|
|
60
|
+
10:02:16 Installed my-app 1.0.0 in 1.9 s (3 file(s), 6.2 KB, 3.3 KB/s).
|
|
61
|
+
10:02:16 my-app is on screen (mode 7, 2.2 s after the first byte).
|
|
62
|
+
10:02:16 [entered] [my-app] entered in 118 ms: 4 bindings, Lua 2311 bytes
|
|
63
|
+
10:02:17 [print] tick 1
|
|
64
|
+
10:02:19 [warn] [my-app] main.lua: main.lua:12: attempt to perform arithmetic on a nil value
|
|
65
|
+
10:02:31 Updated my-app: 1 file changed (main.lua, 0.4 KB) in 0.6 s.
|
|
66
|
+
10:02:31 my-app is on screen (mode 7, 0.8 s after the first byte).
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Firmware 0.3.3 and older
|
|
70
|
+
|
|
71
|
+
| | Firmware 0.3.3 or newer | Older firmware |
|
|
72
|
+
|---|---|---|
|
|
73
|
+
| A save | Only the changed and new files are sent, removed ones deleted (`APP_FILES`, `APP_EDIT`, `APP_DELETE`). The app's `config.json` and `data/` are never deleted. Same files already there: `Nothing changed` | Every file (a note says so once) |
|
|
74
|
+
| Log without a USB cable | Over Bluetooth (`APP_LOG`): `print()`, lifecycle, warnings, Lua errors, at most 20 lines a second (`Kamoji dropped N log line(s)` otherwise). Crashes and resets need the cable | None (a note says so once) |
|
|
75
|
+
| Finding Kamoji | Fast for 30 s after a boot or a disconnect | Up to 30 s on Wi-Fi |
|
|
76
|
+
|
|
77
|
+
Whenever Kamoji can't do a changed-files update (the app isn't on it yet, it answers an error, a
|
|
78
|
+
line of the file list got lost), the tool sends every file instead; Enter always does.
|
|
79
|
+
|
|
80
|
+
## What it checks before sending
|
|
81
|
+
|
|
82
|
+
The store's rules (manifest `id`, `version`, `api_version` 1, known `permissions` / `features` /
|
|
83
|
+
`platforms`, `params`, file paths, 64 files, 2 MB), plus what Kamoji itself refuses or skips:
|
|
84
|
+
`ble` without `ble.gatt`, `layout.json` that isn't JSON or names an unknown widget, unclosed
|
|
85
|
+
`{{ … }}` bindings, and Lua syntax with `luac -p` when a Lua compiler is installed (Kamoji runs
|
|
86
|
+
Lua 5.4; another `luac` only warns). Errors stop the install with the file and the reason; nothing
|
|
87
|
+
is sent until they are fixed. Once connected: the firmware must be at least `min_firmware`, and the
|
|
88
|
+
app must fit in Kamoji's free storage. Hidden files, `node_modules` and editor files (`*~`, `*.swp`)
|
|
89
|
+
are never sent. The full table is in `spec/VALIDATION.md` of the source.
|
|
90
|
+
|
|
91
|
+
## How it works
|
|
92
|
+
|
|
93
|
+
The same Bluetooth commands as the Kamoji app's **Install from file**
|
|
94
|
+
([Sideloading](https://docs.kamoji.bot/docs/apps/sideloading#bluetooth-install-protocol)):
|
|
95
|
+
`APP_PUT` + `ASSET_DATA` per file, `APP_COMMIT`, then `SET_MODE` to the app's mode (from
|
|
96
|
+
`APPS_LIST`). From firmware 0.3.3 a save of an installed app starts with `APP_FILES` (the md5 and
|
|
97
|
+
size of every installed file) and `APP_EDIT` (Kamoji stages a copy of it), then sends only what
|
|
98
|
+
changed and commits the same way; older firmware gets every file (unchanged saves are skipped). The
|
|
99
|
+
app's settings (`config.json`) and `data/` stay. A mini app that is on screen restarts with the new
|
|
100
|
+
version. Bluetooth is slow-ish: about 3-15 KB/s depending on the
|
|
101
|
+
computer, so a 10 KB app reloads in 1-3 s.
|
|
102
|
+
|
|
103
|
+
Over USB the tool only reads: Kamoji has no install over USB (that would mean rewriting its whole
|
|
104
|
+
storage), so the cable is for the log and fast screenshots.
|
|
105
|
+
|
|
106
|
+
## Keys
|
|
107
|
+
|
|
108
|
+
Each Kamoji gets its own key for this computer: 32 random bytes in `~/.config/kamoji/<KMJ-XXXX>.key`
|
|
109
|
+
(readable by you only; `KAMOJI_CONFIG_DIR` moves the folder). The key is never printed. Whoever has
|
|
110
|
+
it can control that Kamoji: don't share it. `kamoji forget` removes it from Kamoji and the computer.
|
|
111
|
+
The Python tool in the Kamoji repositories (`kamoji_dev.py`) uses the same files.
|
|
112
|
+
|
|
113
|
+
## Troubleshooting
|
|
114
|
+
|
|
115
|
+
| Message | What to do |
|
|
116
|
+
|---|---|
|
|
117
|
+
| No Kamoji found nearby | Is it on and close? Is the Kamoji app disconnected? Bluetooth permission for the terminal (macOS)? |
|
|
118
|
+
| KMJ-… is connected to another device | Disconnect it in the Kamoji app, or close the app |
|
|
119
|
+
| too far to start | First time only: hold the computer next to Kamoji |
|
|
120
|
+
| needs firmware … or newer | Update Kamoji in the Kamoji app |
|
|
121
|
+
| Kamoji is out of storage space | Remove a mini app in the Kamoji app (Apps) |
|
|
122
|
+
| its Bluetooth services go live after a restart | Press `b` (or run with `--reboot`) |
|
|
123
|
+
| This firmware sends no app log over Bluetooth | Update Kamoji to 0.3.3, or plug in a USB-C **data** cable; `--port` if several boards are plugged in |
|
|
124
|
+
| This firmware installs whole mini apps only | Nothing to do (every file is sent); update Kamoji to 0.3.3 for faster reloads |
|
|
125
|
+
|
|
126
|
+
## Development
|
|
127
|
+
|
|
128
|
+
```sh
|
|
129
|
+
npm test # node:test, fake Kamoji, no device needed
|
|
130
|
+
node spec/make-conversation.mjs # after changing the protocol: re-record spec/conversation*.json
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Bluetooth is [@stoprocent/noble](https://github.com/stoprocent/noble) (maintained, prebuilt for
|
|
134
|
+
macOS, Windows and Linux, so installing needs no compiler), USB is
|
|
135
|
+
[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,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kamoji-dev",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
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": [
|
|
22
|
+
"kamoji",
|
|
23
|
+
"mini-apps",
|
|
24
|
+
"ble",
|
|
25
|
+
"esp32"
|
|
26
|
+
],
|
|
27
|
+
"homepage": "https://docs.kamoji.bot/docs/apps",
|
|
28
|
+
"license": "MIT",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@stoprocent/noble": "2.8.0",
|
|
31
|
+
"serialport": "13.0.0"
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -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
|
+
}
|
package/src/check.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Reading a mini app folder and checking it before it is sent: the rules and their ids are in
|
|
2
|
+
// spec/VALIDATION.md (shared with the Python worker/rig/kamoji_dev.py of kamoji-cms). The rules themselves
|
|
3
|
+
// are in core/check.js (shared with the web IDE); this file reads the folder and runs the Lua compiler.
|
|
4
|
+
import fs from 'node:fs'
|
|
5
|
+
import path from 'node:path'
|
|
6
|
+
import { spawnSync } from 'node:child_process'
|
|
7
|
+
import { checkFiles, isJunk } from './core/check.js'
|
|
8
|
+
import { md5Hex } from './protocol.js'
|
|
9
|
+
|
|
10
|
+
export * from './core/check.js'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Every file of the folder that would be sent: [{path, data, md5}] sorted by path, plus what was skipped.
|
|
14
|
+
*/
|
|
15
|
+
export function readAppFolder(folder) {
|
|
16
|
+
const files = []
|
|
17
|
+
const skipped = []
|
|
18
|
+
const walk = (dir, rel) => {
|
|
19
|
+
for (const ent of fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
20
|
+
const r = rel ? `${rel}/${ent.name}` : ent.name
|
|
21
|
+
if (isJunk(ent.name)) {
|
|
22
|
+
skipped.push(r)
|
|
23
|
+
continue
|
|
24
|
+
}
|
|
25
|
+
const full = path.join(dir, ent.name)
|
|
26
|
+
if (ent.isSymbolicLink()) skipped.push(r)
|
|
27
|
+
else if (ent.isDirectory()) walk(full, r)
|
|
28
|
+
else if (ent.isFile()) {
|
|
29
|
+
const data = fs.readFileSync(full)
|
|
30
|
+
files.push({ path: r, data, md5: md5Hex(data) })
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
walk(folder, '')
|
|
35
|
+
files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
|
|
36
|
+
return { files, skipped }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let luacCache
|
|
40
|
+
/** The Lua compiler on this computer: { cmd, version: '5.4' | '5.5' | … } or null. */
|
|
41
|
+
export function findLuac() {
|
|
42
|
+
if (luacCache !== undefined) return luacCache
|
|
43
|
+
luacCache = null
|
|
44
|
+
for (const cmd of [process.env.KAMOJI_LUAC, 'luac5.4', 'luac54', 'luac'].filter(Boolean)) {
|
|
45
|
+
const r = spawnSync(cmd, ['-v'], { encoding: 'utf8' })
|
|
46
|
+
if (r.error) continue
|
|
47
|
+
const m = /Lua (\d+\.\d+)/.exec(`${r.stdout}${r.stderr}`)
|
|
48
|
+
luacCache = { cmd, version: m ? m[1] : '?' }
|
|
49
|
+
break
|
|
50
|
+
}
|
|
51
|
+
return luacCache
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function checkLua(file, add) {
|
|
55
|
+
const luac = findLuac()
|
|
56
|
+
if (!luac) return false
|
|
57
|
+
const r = spawnSync(luac.cmd, ['-p', '-'], { input: file.data, encoding: 'utf8' })
|
|
58
|
+
if (r.status !== 0) {
|
|
59
|
+
const msg = `${r.stderr || r.stdout}`.trim().split('\n')[0].replace(/^\S*luac\S*:\s*/, '').replace(/^(stdin|=stdin|-):/, `${file.path}:`)
|
|
60
|
+
if (luac.version === '5.4') add('error', 'lua-syntax', msg, file.path)
|
|
61
|
+
else add('warning', 'lua-other-version', `${msg} (checked with Lua ${luac.version}; Kamoji runs Lua 5.4: confirm on Kamoji)`, file.path)
|
|
62
|
+
}
|
|
63
|
+
return true
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Check a folder. Returns { problems:[{level,id,message,where}], errors, warnings, manifest, appId, files, skipped, bytes }.
|
|
68
|
+
* @param {{lua?: boolean}} [opts] lua: false skips the Lua compiler
|
|
69
|
+
*/
|
|
70
|
+
export function checkApp(folder, opts = {}) {
|
|
71
|
+
const folderName = path.basename(path.resolve(folder))
|
|
72
|
+
const { files, skipped } = readAppFolder(folder)
|
|
73
|
+
return checkFiles(
|
|
74
|
+
{ files, skipped, folderName },
|
|
75
|
+
opts.lua === false ? {} : { luaCheck: checkLua, luaMissing: 'no Lua compiler (luac5.4 / luac) found: Lua is checked by Kamoji only' },
|
|
76
|
+
)
|
|
77
|
+
}
|