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/src/serial.js ADDED
@@ -0,0 +1,169 @@
1
+ // Kamoji on USB: its log, the `app.*` serial commands and `app.shot` screenshots. Same rules as
2
+ // kamoji-cms worker/rig/device.py:
3
+ // - DTR on, RTS off (DTR off with RTS on resets the ESP32-S3);
4
+ // - long command lines in 256-byte pieces, 20 ms apart (the USB RX ring holds 512 bytes);
5
+ // - after a reset the USB device goes away and comes back: re-open and carry on;
6
+ // - `app.shot:<q>` answers SHOT:BEGIN:<w>:<h>:<size>, SHOT:<base64>…, SHOT:END as log lines.
7
+ // Installing over USB is not possible without rewriting the whole storage partition (see README).
8
+ import { clean } from './logfilter.js'
9
+
10
+ export const ESPRESSIF_VID = '303a'
11
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
12
+
13
+ /** The Espressif USB serial ports (macOS: the /dev/cu.* ones). */
14
+ export async function findPorts() {
15
+ const { SerialPort } = await import('serialport')
16
+ const all = await SerialPort.list()
17
+ const found = all.filter((p) => String(p.vendorId ?? '').toLowerCase() === ESPRESSIF_VID).map((p) => p.path)
18
+ const cu = found.filter((p) => p.includes('/cu.'))
19
+ return cu.length ? cu : found
20
+ }
21
+
22
+ /** Opens a real port: resolves to { onData(cb), onClose(cb), write(buf), close() }. */
23
+ export async function openSerialPort(path) {
24
+ const { SerialPort } = await import('serialport')
25
+ const port = new SerialPort({ path, baudRate: 115200, autoOpen: false, hupcl: false })
26
+ await new Promise((res, rej) => port.open((e) => (e ? rej(e) : res())))
27
+ // Opening raises DTR and RTS together (no reset); drop RTS, keep DTR, in one call.
28
+ await new Promise((res) => port.set({ dtr: true, rts: false }, () => res()))
29
+ return {
30
+ onData: (cb) => port.on('data', cb),
31
+ onClose: (cb) => port.on('close', cb),
32
+ write: (buf) => new Promise((res, rej) => port.write(buf, (e) => (e ? rej(e) : port.drain(() => res())))),
33
+ close: () => new Promise((res) => (port.isOpen ? port.close(() => res()) : res())),
34
+ }
35
+ }
36
+
37
+ export class SerialLog {
38
+ /**
39
+ * @param {string} path
40
+ * @param {{open?: (path:string)=>Promise<any>, onLine?: (line:string)=>void, reopenMs?: number}} [opts]
41
+ */
42
+ constructor(path, opts = {}) {
43
+ this.path = path
44
+ this.opener = opts.open ?? openSerialPort
45
+ this.onLine = opts.onLine
46
+ this.reopenMs = opts.reopenMs ?? 20000
47
+ this.lines = []
48
+ this.listeners = new Set()
49
+ this.port = null
50
+ this.closed = false
51
+ this.buf = ''
52
+ }
53
+
54
+ async start() {
55
+ this.port = await this.opener(this.path)
56
+ this._wire()
57
+ }
58
+
59
+ _wire() {
60
+ this.port.onData((d) => {
61
+ this.buf += Buffer.from(d).toString('utf8')
62
+ let i
63
+ while ((i = this.buf.indexOf('\n')) >= 0) {
64
+ const line = this.buf.slice(0, i).replace(/\r$/, '')
65
+ this.buf = this.buf.slice(i + 1)
66
+ this._add(line)
67
+ }
68
+ })
69
+ this.port.onClose(() => {
70
+ if (this.closed) return
71
+ this._add('### USB port lost (Kamoji restarted, or the cable was unplugged)')
72
+ this._reopen()
73
+ })
74
+ }
75
+
76
+ async _reopen() {
77
+ const end = Date.now() + this.reopenMs
78
+ while (!this.closed && Date.now() < end) {
79
+ await sleep(300)
80
+ try {
81
+ this.port = await this.opener(this.path)
82
+ this.buf = ''
83
+ this._wire()
84
+ this._add('### USB port back')
85
+ return
86
+ } catch {
87
+ // not there yet (USB re-enumerating)
88
+ }
89
+ }
90
+ if (!this.closed) this._add('### USB port did not come back: USB log stopped')
91
+ }
92
+
93
+ _add(line) {
94
+ this.lines.push(line)
95
+ if (this.lines.length > 5000) this.lines.splice(0, 1000)
96
+ for (const l of this.listeners) l(line)
97
+ try {
98
+ this.onLine?.(line)
99
+ } catch {
100
+ // a printing error never stops the reader
101
+ }
102
+ }
103
+
104
+ async close() {
105
+ this.closed = true
106
+ await this.port?.close().catch(() => undefined)
107
+ }
108
+
109
+ async send(line) {
110
+ const data = Buffer.from(`${line}\n`)
111
+ for (let i = 0; i < data.length; i += 256) {
112
+ if (i) await sleep(20)
113
+ await this.port.write(data.subarray(i, i + 256))
114
+ }
115
+ }
116
+
117
+ /** Resolves with the first line (cleaned) for which pred is true, or null after ms. */
118
+ waitLine(pred, ms) {
119
+ return new Promise((resolve) => {
120
+ const l = (raw) => {
121
+ const c = clean(raw)
122
+ if (pred(c)) done(c)
123
+ }
124
+ const timer = setTimeout(() => done(null), ms)
125
+ const done = (v) => {
126
+ clearTimeout(timer)
127
+ this.listeners.delete(l)
128
+ resolve(v)
129
+ }
130
+ this.listeners.add(l)
131
+ })
132
+ }
133
+
134
+ /** One `app.shot` JPEG (3 tries, like the rig). */
135
+ async screenshot(quality = 90, timeoutMs = 20000) {
136
+ let last = 'screenshot failed'
137
+ for (let attempt = 0; attempt < 3; attempt++) {
138
+ let size = null
139
+ let parts = []
140
+ const r = new Promise((resolve) => {
141
+ const l = (raw) => {
142
+ const ln = clean(raw)
143
+ let m
144
+ if ((m = /SHOT:BEGIN:(\d+):(\d+):(\d+)/.exec(ln))) {
145
+ size = Number(m[3])
146
+ parts = []
147
+ } else if (ln.includes('SHOT:END') && size !== null) {
148
+ const data = Buffer.from(parts.join(''), 'base64')
149
+ done(data.length === size ? data : `screenshot size ${data.length} != ${size} (a line was lost)`)
150
+ } else if ((m = /SHOT:([A-Za-z0-9+/=]+)$/.exec(ln)) && size !== null) parts.push(m[1])
151
+ else if (ln.includes('APP:ERR:')) done(ln.split('APP:ERR:')[1])
152
+ }
153
+ const timer = setTimeout(() => done('screenshot timed out'), timeoutMs)
154
+ const done = (v) => {
155
+ clearTimeout(timer)
156
+ this.listeners.delete(l)
157
+ resolve(v)
158
+ }
159
+ this.listeners.add(l)
160
+ })
161
+ await this.send(`app.shot:${quality}`)
162
+ const v = await r
163
+ if (Buffer.isBuffer(v)) return v
164
+ last = v
165
+ await sleep(1000)
166
+ }
167
+ throw new Error(last)
168
+ }
169
+ }
package/src/watch.js ADDED
@@ -0,0 +1,106 @@
1
+ // Saves → one reload: a burst of file events (an editor writes a temp file, renames, touches) waits
2
+ // until the folder has been quiet for `quietMs`, and a save during a reload runs one more reload after it.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { isJunk } from './check.js'
6
+
7
+ export class Reloader {
8
+ /**
9
+ * @param {() => Promise<void>} run
10
+ * @param {{quietMs?: number, timers?: {setTimeout: Function, clearTimeout: Function}}} [opts]
11
+ */
12
+ constructor(run, opts = {}) {
13
+ this.run = run
14
+ this.quietMs = opts.quietMs ?? 400
15
+ this.timers = opts.timers ?? { setTimeout, clearTimeout }
16
+ this.timer = null
17
+ this.running = false
18
+ this.pending = false
19
+ this.idle = Promise.resolve()
20
+ }
21
+
22
+ /** A file changed. */
23
+ trigger() {
24
+ if (this.timer) this.timers.clearTimeout(this.timer)
25
+ this.timer = this.timers.setTimeout(() => {
26
+ this.timer = null
27
+ this.fire()
28
+ }, this.quietMs)
29
+ }
30
+
31
+ /** Reload now (or right after the reload in progress). */
32
+ fire() {
33
+ if (this.running) {
34
+ this.pending = true
35
+ return this.idle
36
+ }
37
+ this.running = true
38
+ this.idle = (async () => {
39
+ try {
40
+ do {
41
+ this.pending = false
42
+ await this.run()
43
+ } while (this.pending)
44
+ } finally {
45
+ this.running = false
46
+ }
47
+ })()
48
+ return this.idle
49
+ }
50
+
51
+ stop() {
52
+ if (this.timer) this.timers.clearTimeout(this.timer)
53
+ this.timer = null
54
+ }
55
+ }
56
+
57
+ /** Calls onChange(relPath) for every change in the folder that is not an editor / OS file. Returns stop(). */
58
+ export function watchFolder(folder, onChange) {
59
+ const ignored = (rel) => !rel || rel.split(/[\\/]/).some((part) => isJunk(part))
60
+ try {
61
+ const w = fs.watch(folder, { recursive: true }, (_ev, name) => {
62
+ const rel = name ? String(name) : ''
63
+ if (rel && ignored(rel)) return
64
+ onChange(rel)
65
+ })
66
+ return () => w.close()
67
+ } catch {
68
+ // No recursive fs.watch here: poll the folder's file times instead.
69
+ let last = snapshot(folder)
70
+ const t = setInterval(() => {
71
+ const now = snapshot(folder)
72
+ if (now !== last) {
73
+ last = now
74
+ onChange('')
75
+ }
76
+ }, 500)
77
+ return () => clearInterval(t)
78
+ }
79
+ }
80
+
81
+ function snapshot(folder) {
82
+ const out = []
83
+ const walk = (dir, rel) => {
84
+ let ents = []
85
+ try {
86
+ ents = fs.readdirSync(dir, { withFileTypes: true })
87
+ } catch {
88
+ return
89
+ }
90
+ for (const e of ents) {
91
+ if (isJunk(e.name)) continue
92
+ const full = path.join(dir, e.name)
93
+ const r = rel ? `${rel}/${e.name}` : e.name
94
+ if (e.isDirectory()) walk(full, r)
95
+ else
96
+ try {
97
+ const st = fs.statSync(full)
98
+ out.push(`${r}:${st.size}:${st.mtimeMs}`)
99
+ } catch {
100
+ // gone meanwhile
101
+ }
102
+ }
103
+ }
104
+ walk(folder, '')
105
+ return out.sort().join('\n')
106
+ }