desky-agent 0.0.0-stage → 0.3.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 +21 -0
- package/README.md +49 -2
- package/assets/clawd.ico +0 -0
- package/assets/clawd.png +0 -0
- package/bin/cli.js +206 -0
- package/electron/icons.js +79 -0
- package/electron/main.js +219 -0
- package/firmware/boot_app0.bin +0 -0
- package/firmware/bootloader.bin +0 -0
- package/firmware/firmware.bin +0 -0
- package/firmware/manifest.json +33 -0
- package/firmware/partitions.bin +0 -0
- package/package.json +38 -4
- package/src/autostart.js +106 -0
- package/src/board.js +69 -0
- package/src/core.js +172 -0
- package/src/daemon.js +446 -0
- package/src/firmware.js +207 -0
- package/src/flasher.js +113 -0
- package/src/hook.js +86 -0
- package/src/install.js +375 -0
- package/src/link.js +207 -0
- package/src/paths.js +44 -0
- package/src/updater.js +138 -0
- package/src/webserial.js +130 -0
- package/ui/app.html +1470 -0
- package/ui/clawd3d.js +375 -0
- package/ui/models/A04_cap_J2.stl +0 -0
- package/ui/models/A04_cap_J3.stl +0 -0
- package/ui/models/A04_cap_J4.stl +0 -0
- package/ui/models/B0_base.stl +0 -0
- package/ui/models/B1_body.stl +0 -0
- package/ui/models/B2_face_plate.stl +0 -0
- package/ui/models/B3_side_left.stl +0 -0
- package/ui/models/B4_side_right.stl +0 -0
- package/ui/models/C1_column.stl +0 -0
- package/ui/models/C2_column_lid.stl +0 -0
- package/ui/models/D1_desk_frame.stl +0 -0
- package/ui/models/D2_desk_top.stl +0 -0
- package/ui/models/L1_laptop.stl +0 -0
- package/ui/models/P1_mug.stl +0 -0
- package/ui/models/P2_plant.stl +0 -0
- package/ui/models/R1_arm_left.stl +0 -0
- package/ui/models/R2_arm_right.stl +0 -0
- package/ui/models/S1_seat.stl +0 -0
- package/ui/models/S2_spacer.stl +0 -0
- package/ui/vendor/OrbitControls.js +1532 -0
- package/ui/vendor/RoomEnvironment.js +144 -0
- package/ui/vendor/STLLoader.js +410 -0
- package/ui/vendor/three.LICENSE +21 -0
- package/ui/vendor/three.module.min.js +6 -0
package/src/daemon.js
ADDED
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The daemon: holds the C3's port, takes hook events on localhost, ticks the Core, serves the control app.
|
|
3
|
+
// It runs inside the tray app (electron/main.js) and, for debugging, on plain Node ("desky-agent run").
|
|
4
|
+
//
|
|
5
|
+
// POST /event body: the hook's JSON as Claude Code wrote it
|
|
6
|
+
// GET /status connection, state, sessions, the C3's last heartbeat, manual mode, firmware update
|
|
7
|
+
// POST /stop quit (the old remote needs the port; the installer replaces the app)
|
|
8
|
+
// GET / the control app (ui/app.html): joints, scenes, calibration, settings, monitor
|
|
9
|
+
// POST /cmd {"line": "pose 0 10 80 80", "hand": true}: one line to the C3, as typed in a serial
|
|
10
|
+
// monitor; "hand" (a move, not a question like "where") starts manual mode
|
|
11
|
+
// GET /lines?since=N what went to and came from the C3 since line N
|
|
12
|
+
// POST /manual {"on": true}: keep manual mode (the app drives Desky, the agent's states wait). Ends 15 s
|
|
13
|
+
// after the app's last call (window closed) or a minute after the last hand command (window
|
|
14
|
+
// left open and forgotten), and Desky goes back to the agent.
|
|
15
|
+
// POST /reset restart the C3 (RTS pulse)
|
|
16
|
+
// GET /config settings in force and their defaults; POST /config {...} saves to config.json
|
|
17
|
+
//
|
|
18
|
+
// One instance only: a second one cannot bind the port.
|
|
19
|
+
|
|
20
|
+
const fs = require('fs');
|
|
21
|
+
const http = require('http');
|
|
22
|
+
const path = require('path');
|
|
23
|
+
const { Core, DEFAULTS, COLORS } = require('./core');
|
|
24
|
+
const paths = require('./paths');
|
|
25
|
+
|
|
26
|
+
const UI_DIR = path.join(__dirname, '..', 'ui');
|
|
27
|
+
const UI = path.join(UI_DIR, 'app.html');
|
|
28
|
+
const VERSION = require('../package.json').version;
|
|
29
|
+
const { verdict } = require('./board');
|
|
30
|
+
const fw = require('./firmware');
|
|
31
|
+
const MANUAL_TTL = 15;
|
|
32
|
+
const MANUAL_IDLE = 60;
|
|
33
|
+
|
|
34
|
+
function log(text) {
|
|
35
|
+
const line = new Date().toISOString().replace('T', ' ').slice(0, 19) + ' ' + text + '\n';
|
|
36
|
+
if (process.env.CLAWD_LOG_CONSOLE) process.stdout.write(line);
|
|
37
|
+
try {
|
|
38
|
+
fs.mkdirSync(paths.STATE, { recursive: true });
|
|
39
|
+
try {
|
|
40
|
+
if (fs.statSync(paths.LOG).size > 1 << 20) fs.renameSync(paths.LOG, paths.LOG + '.old');
|
|
41
|
+
} catch (e) { /* no log yet */ }
|
|
42
|
+
fs.appendFileSync(paths.LOG, line);
|
|
43
|
+
} catch (e) { /* a log is not worth failing for */ }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function loadConfig(file = paths.CONFIG) {
|
|
47
|
+
try {
|
|
48
|
+
return { ...DEFAULTS, ...JSON.parse(fs.readFileSync(file, 'utf8')) };
|
|
49
|
+
} catch (e) {
|
|
50
|
+
if (e.code !== 'ENOENT') log('config.json не читається (' + e.message + '): беру значення за замовчуванням');
|
|
51
|
+
return { ...DEFAULTS };
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Keep known keys, with the type of their default; throw on nonsense. */
|
|
56
|
+
function cleanConfig(next) {
|
|
57
|
+
const out = {};
|
|
58
|
+
for (const [k, v0] of Object.entries(next || {})) {
|
|
59
|
+
if (!(k in DEFAULTS)) continue;
|
|
60
|
+
const d = DEFAULTS[k];
|
|
61
|
+
let v = v0;
|
|
62
|
+
if (Array.isArray(d) && typeof d[0] === 'number') {
|
|
63
|
+
v = (Array.isArray(v) ? v : []).map(x => Math.trunc(Number(x)));
|
|
64
|
+
if (v.length !== 2 || !v.every(x => x >= 0 && x <= 24)) throw new Error(k);
|
|
65
|
+
} else if (Array.isArray(d)) {
|
|
66
|
+
if (!Array.isArray(v)) throw new Error(k);
|
|
67
|
+
v = v.map(x => String(x).trim()).filter(Boolean);
|
|
68
|
+
} else if (typeof d === 'number') {
|
|
69
|
+
v = Number.isInteger(d) ? Math.trunc(Number(v)) : Number(v);
|
|
70
|
+
if (!Number.isFinite(v) || v < 0) throw new Error(k);
|
|
71
|
+
if (k === 'port' && !(v >= 1024 && v <= 65535)) throw new Error(k);
|
|
72
|
+
}
|
|
73
|
+
if (k === 'color' && !COLORS.includes(v)) throw new Error(k);
|
|
74
|
+
out[k] = v;
|
|
75
|
+
}
|
|
76
|
+
return out;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
class Daemon {
|
|
80
|
+
constructor({ config, configPath = paths.CONFIG, linkFactory, clock = () => Date.now() / 1000, httpPort,
|
|
81
|
+
onStop = () => {}, updater } = {}) {
|
|
82
|
+
this.configPath = configPath;
|
|
83
|
+
this.cfg = config || loadConfig(configPath);
|
|
84
|
+
this.clock = clock;
|
|
85
|
+
this.httpPort = httpPort === undefined ? this.cfg.port : httpPort;
|
|
86
|
+
this.onStop = onStop;
|
|
87
|
+
if (!linkFactory) {
|
|
88
|
+
const { Link } = require('./link');
|
|
89
|
+
linkFactory = opts => new Link(opts);
|
|
90
|
+
}
|
|
91
|
+
this.link = linkFactory({ onConnect: () => this.connected(), onLine: ln => this.c3Line(ln),
|
|
92
|
+
onSilent: usb => this.silent(usb) });
|
|
93
|
+
this.updater = updater || require('./updater');
|
|
94
|
+
this.fwBusy = false; // flashing: the Link is stopped, the port is the flasher's
|
|
95
|
+
this.fwTried = new Set(); // boards flashed (or tried) by this run: one attempt each, no loops
|
|
96
|
+
this.fwWarned = new Set();
|
|
97
|
+
this.fwUpdate = null; // { state: updating | done | failed, text } for /status and the tray
|
|
98
|
+
this.closed = false;
|
|
99
|
+
this.core = new Core(line => this.agentSend(line), { clock, config: this.cfg });
|
|
100
|
+
this.lines = []; // {n, kind, text}: kind me / agent / c3 / info
|
|
101
|
+
this.lineN = 0;
|
|
102
|
+
this.beat = null; // last "жив ..." from the C3, and when
|
|
103
|
+
this.manualOn = false;
|
|
104
|
+
this.manualUntil = 0;
|
|
105
|
+
this.lastHand = 0;
|
|
106
|
+
this.server = http.createServer((req, res) => this.handle(req, res));
|
|
107
|
+
this.timer = null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
get manual() {
|
|
111
|
+
const t = this.clock();
|
|
112
|
+
return this.manualOn && t < this.manualUntil && t - this.lastHand < MANUAL_IDLE;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// ------------------------------------------------------------ the monitor
|
|
116
|
+
note(kind, text) {
|
|
117
|
+
this.lineN += 1;
|
|
118
|
+
this.lines.push({ n: this.lineN, kind, text });
|
|
119
|
+
if (this.lines.length > 500) this.lines.shift();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
c3Line(ln) {
|
|
123
|
+
if (ln.startsWith('жив ')) { // every 3 s: not worth a line in the monitor
|
|
124
|
+
this.beat = [ln, Date.now()];
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
this.note('c3', ln);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** From the Core: an agent state or sound. Held back while the app drives. */
|
|
131
|
+
agentSend(line) {
|
|
132
|
+
if (this.manual) return;
|
|
133
|
+
log('-> ' + line);
|
|
134
|
+
this.note('agent', line);
|
|
135
|
+
this.link.send(line);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
command(line, hand = false) {
|
|
139
|
+
if (hand) {
|
|
140
|
+
const t = this.clock();
|
|
141
|
+
if (!this.manualOn) this.note('info', 'ручне керування: стани агента не надсилаються');
|
|
142
|
+
this.manualOn = true;
|
|
143
|
+
this.manualUntil = t + MANUAL_TTL;
|
|
144
|
+
this.lastHand = t;
|
|
145
|
+
}
|
|
146
|
+
this.note('me', line);
|
|
147
|
+
return this.link.send(line);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
setManual(on) {
|
|
151
|
+
if (on) { // only keeps it: a window left open must not hold Desky once its minute is up
|
|
152
|
+
if (this.manual) this.manualUntil = this.clock() + MANUAL_TTL;
|
|
153
|
+
} else {
|
|
154
|
+
this.manualUntil = 0;
|
|
155
|
+
this.expireManual();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Hand Desky back to the agent once the app stopped asking for him (or said so): say the state again. */
|
|
160
|
+
expireManual() {
|
|
161
|
+
if (this.manualOn && !this.manual) {
|
|
162
|
+
this.manualOn = false;
|
|
163
|
+
this.note('info', 'ручне керування вимкнено: Desky знову показує агента');
|
|
164
|
+
this.core.resend();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
connected() {
|
|
169
|
+
const t = Date.now();
|
|
170
|
+
this.connectedAt = t;
|
|
171
|
+
const again = this.lastConnect && this.lastConnect.dev === this.link.dev && t - this.lastConnect.t < 60000;
|
|
172
|
+
if (again) {
|
|
173
|
+
this.reconnects = (this.reconnects || 0) + 1;
|
|
174
|
+
if (this.reconnects === 3) log('плата перепідключається знову й знову: перевір кабель і живлення серво');
|
|
175
|
+
} else {
|
|
176
|
+
this.reconnects = 0;
|
|
177
|
+
log('плата на зв\'язку: ' + this.link.dev);
|
|
178
|
+
}
|
|
179
|
+
this.lastConnect = { dev: this.link.dev, t };
|
|
180
|
+
this.note('info', 'плата на зв\'язку: ' + this.link.dev + (again ? ` (перепідключення ${this.reconnects})` : ''));
|
|
181
|
+
if (!this.manual) this.core.resend();
|
|
182
|
+
this.checkFirmware();
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// ------------------------------------------------------------ firmware (docs/firmware_contract.md, 3 and 5)
|
|
186
|
+
fwBundle() {
|
|
187
|
+
try {
|
|
188
|
+
return this.updater.bundle();
|
|
189
|
+
} catch (e) {
|
|
190
|
+
if (!this.fwWarned.has('bundle')) {
|
|
191
|
+
this.fwWarned.add('bundle');
|
|
192
|
+
log('прошивка в пакеті не пройшла перевірку: ' + e.message);
|
|
193
|
+
}
|
|
194
|
+
return undefined;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** A board answered "who": an older firmware is updated right away, a newer one only noted. */
|
|
199
|
+
checkFirmware() {
|
|
200
|
+
const who = this.link.info;
|
|
201
|
+
if (this.fwBusy || !who) return;
|
|
202
|
+
const usb = this.link.usb || { path: this.link.dev, serialNumber: null };
|
|
203
|
+
const bundle = this.fwBundle();
|
|
204
|
+
if (bundle === undefined) return;
|
|
205
|
+
const d = fw.decide({ who, usb, bundle, refused: fw.refusedChip(usb) });
|
|
206
|
+
const key = usb.serialNumber || usb.path;
|
|
207
|
+
if (d.action === 'warn' || d.action === 'skip') {
|
|
208
|
+
if (!this.fwWarned.has(key + d.why)) {
|
|
209
|
+
this.fwWarned.add(key + d.why);
|
|
210
|
+
log('прошивка: ' + d.why);
|
|
211
|
+
this.note('info', 'прошивка: ' + d.why);
|
|
212
|
+
}
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (d.action !== 'flash' || this.fwTried.has(key)) return;
|
|
216
|
+
this.fwTried.add(key);
|
|
217
|
+
this.flashBoard(usb, bundle, who, d.why);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** A 303A:1001 port that stays silent: repaired only when this computer's marker says an update was cut short. */
|
|
221
|
+
silent(usb) {
|
|
222
|
+
if (this.fwBusy || this.closed) return;
|
|
223
|
+
const marker = fw.readMarker();
|
|
224
|
+
if (!fw.markerMatches(marker, usb)) return;
|
|
225
|
+
const key = usb.serialNumber || usb.path;
|
|
226
|
+
if (this.fwTried.has(key)) return;
|
|
227
|
+
const bundle = this.fwBundle();
|
|
228
|
+
if (!bundle) return;
|
|
229
|
+
const d = fw.decide({ who: null, usb, bundle, marker, refused: fw.refusedChip(usb) });
|
|
230
|
+
if (d.action !== 'flash') return;
|
|
231
|
+
this.fwTried.add(key);
|
|
232
|
+
setImmediate(() => this.flashBoard(usb, bundle, null, d.why));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async flashBoard(usb, bundle, who, why) {
|
|
236
|
+
this.fwBusy = true;
|
|
237
|
+
this.fwUpdate = { state: 'updating', text: `оновлюю прошивку Desky до ${bundle.version}, не від'єднуй плату` };
|
|
238
|
+
log(why + ': ' + this.fwUpdate.text);
|
|
239
|
+
this.note('info', this.fwUpdate.text);
|
|
240
|
+
let r;
|
|
241
|
+
try {
|
|
242
|
+
await this.link.stop();
|
|
243
|
+
r = await this.updater.update(usb, { bundle, from: who && who.fw, sn: who && who.sn, log });
|
|
244
|
+
} catch (e) {
|
|
245
|
+
r = { ok: false, text: 'прошивка не оновилася: ' + (e.message || e) };
|
|
246
|
+
}
|
|
247
|
+
this.fwUpdate = { state: r.ok ? 'done' : 'failed', text: r.text };
|
|
248
|
+
log(r.text);
|
|
249
|
+
this.note('info', r.text);
|
|
250
|
+
this.fwBusy = false;
|
|
251
|
+
if (!this.closed) this.link.start();
|
|
252
|
+
return r;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// ------------------------------------------------------------ hooks and status
|
|
256
|
+
event(ev) {
|
|
257
|
+
this.core.event(ev && typeof ev === 'object' ? ev : {});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
status() {
|
|
261
|
+
const st = this.core.status();
|
|
262
|
+
st.quiet_now = this.core.quiet(this.clock());
|
|
263
|
+
return Object.assign(st, {
|
|
264
|
+
app: 'desky-agent', version: VERSION, connected: this.link.connected, port: this.link.dev || null,
|
|
265
|
+
board: this.link.info || null,
|
|
266
|
+
firmware: this.link.connected ? verdict(this.link.info) : null,
|
|
267
|
+
firmware_update: this.fwUpdate,
|
|
268
|
+
manual: this.manual, heartbeat: this.beat ? this.beat[0] : null,
|
|
269
|
+
heartbeat_age: this.beat ? Math.round((Date.now() - this.beat[1]) / 100) / 10 : null,
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
getLines(since) {
|
|
274
|
+
return this.lines.filter(l => l.n > since);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
saveConfig(next) {
|
|
278
|
+
next = cleanConfig(next);
|
|
279
|
+
let saved = {};
|
|
280
|
+
try { saved = JSON.parse(fs.readFileSync(this.configPath, 'utf8')); } catch (e) { /* new file */ }
|
|
281
|
+
Object.assign(saved, next);
|
|
282
|
+
fs.mkdirSync(path.dirname(this.configPath), { recursive: true });
|
|
283
|
+
const tmp = this.configPath + '.tmp';
|
|
284
|
+
fs.writeFileSync(tmp, JSON.stringify(saved, null, 2));
|
|
285
|
+
fs.renameSync(tmp, this.configPath);
|
|
286
|
+
Object.assign(this.cfg, next);
|
|
287
|
+
Object.assign(this.core.cfg, next);
|
|
288
|
+
return this.cfg;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// ------------------------------------------------------------ HTTP
|
|
292
|
+
localPage(req) {
|
|
293
|
+
// only the app's own page may drive the robot: a web page elsewhere could POST here too
|
|
294
|
+
const origin = req.headers.origin;
|
|
295
|
+
const port = this.server.address().port;
|
|
296
|
+
return !origin || origin === 'http://127.0.0.1:' + port || origin === 'http://localhost:' + port;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async handle(req, res) {
|
|
300
|
+
const reply = (code, obj, type = 'application/json; charset=utf-8') => {
|
|
301
|
+
const body = Buffer.isBuffer(obj) ? obj : Buffer.from(JSON.stringify(obj));
|
|
302
|
+
res.writeHead(code, { 'Content-Type': type, 'Content-Length': body.length, 'Cache-Control': 'no-store' });
|
|
303
|
+
res.end(body);
|
|
304
|
+
};
|
|
305
|
+
const port = this.server.address().port;
|
|
306
|
+
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(String(req.headers.host || '').toLowerCase())) {
|
|
307
|
+
return reply(403, { error: 'host' });
|
|
308
|
+
}
|
|
309
|
+
const u = new URL(req.url, 'http://127.0.0.1');
|
|
310
|
+
try {
|
|
311
|
+
if (req.method === 'GET') {
|
|
312
|
+
if (u.pathname === '/' || u.pathname === '/app.html') {
|
|
313
|
+
try {
|
|
314
|
+
return reply(200, fs.readFileSync(UI), 'text/html; charset=utf-8');
|
|
315
|
+
} catch (e) {
|
|
316
|
+
return reply(404, { error: 'no ui' });
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
// the 3D Desky in the app: three.js (ui/vendor) and the print STLs (ui/models), nothing else from ui/
|
|
320
|
+
const asset = u.pathname.match(/^\/((?:vendor|models)\/[\w.-]+\.(js|stl)|clawd3d\.(js))$/);
|
|
321
|
+
if (asset) {
|
|
322
|
+
try {
|
|
323
|
+
return reply(200, fs.readFileSync(path.join(UI_DIR, asset[1])),
|
|
324
|
+
asset[2] === 'stl' ? 'model/stl' : 'text/javascript; charset=utf-8');
|
|
325
|
+
} catch (e) {
|
|
326
|
+
return reply(404, { error: 'not found' });
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (u.pathname === '/status') return reply(200, this.status());
|
|
330
|
+
if (u.pathname === '/lines') return reply(200, this.getLines(Number(u.searchParams.get('since') || 0)));
|
|
331
|
+
if (u.pathname === '/config') return reply(200, { config: this.cfg, defaults: DEFAULTS });
|
|
332
|
+
return reply(404, { error: 'not found' });
|
|
333
|
+
}
|
|
334
|
+
if (req.method !== 'POST') return reply(405, { error: 'method' });
|
|
335
|
+
if (!this.localPage(req)) return reply(403, { error: 'origin' });
|
|
336
|
+
let body;
|
|
337
|
+
try {
|
|
338
|
+
const raw = await readBody(req);
|
|
339
|
+
body = raw.length ? JSON.parse(raw) : {};
|
|
340
|
+
} catch (e) {
|
|
341
|
+
if (e.code === 413) return reply(413, { error: 'too big' });
|
|
342
|
+
return reply(400, { error: 'bad json' });
|
|
343
|
+
}
|
|
344
|
+
const p = u.pathname;
|
|
345
|
+
if (p === '/event') {
|
|
346
|
+
this.event(body);
|
|
347
|
+
return reply(200, { ok: true });
|
|
348
|
+
}
|
|
349
|
+
if (p === '/cmd') {
|
|
350
|
+
const line = String(body.line || '').trim();
|
|
351
|
+
if (!line || line.includes('\n')) return reply(400, { error: 'one line' });
|
|
352
|
+
return reply(200, { ok: this.command(line, Boolean(body.hand)) });
|
|
353
|
+
}
|
|
354
|
+
if (p === '/manual') {
|
|
355
|
+
this.setManual(Boolean(body.on));
|
|
356
|
+
return reply(200, { manual: this.manual });
|
|
357
|
+
}
|
|
358
|
+
if (p === '/reset') {
|
|
359
|
+
const ok = this.link.reset ? await this.link.reset() : false;
|
|
360
|
+
this.note('info', ok ? 'перезапуск плати' : 'перезапуск не вдався: плату не під\'єднано');
|
|
361
|
+
return reply(200, { ok });
|
|
362
|
+
}
|
|
363
|
+
if (p === '/config') {
|
|
364
|
+
try {
|
|
365
|
+
return reply(200, { config: this.saveConfig(body) });
|
|
366
|
+
} catch (e) {
|
|
367
|
+
return reply(400, { error: 'неправильне значення: ' + e.message });
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if (p === '/stop') {
|
|
371
|
+
reply(200, { ok: true });
|
|
372
|
+
setImmediate(() => this.onStop());
|
|
373
|
+
return undefined;
|
|
374
|
+
}
|
|
375
|
+
return reply(404, { error: 'not found' });
|
|
376
|
+
} catch (e) {
|
|
377
|
+
log('помилка HTTP: ' + (e.stack || e));
|
|
378
|
+
if (!res.headersSent) reply(500, { error: String(e.message || e) });
|
|
379
|
+
return undefined;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** Bind 127.0.0.1:port. Rejects with EADDRINUSE when another Desky (or the old Python daemon) has it. */
|
|
384
|
+
listen() {
|
|
385
|
+
return new Promise((resolve, reject) => {
|
|
386
|
+
const fail = e => reject(e);
|
|
387
|
+
this.server.once('error', fail);
|
|
388
|
+
this.server.listen(this.httpPort, '127.0.0.1', () => {
|
|
389
|
+
this.server.off('error', fail);
|
|
390
|
+
this.httpPort = this.server.address().port;
|
|
391
|
+
resolve(this.httpPort);
|
|
392
|
+
});
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
start() {
|
|
397
|
+
this.link.start();
|
|
398
|
+
log('слухаю 127.0.0.1:' + this.httpPort);
|
|
399
|
+
let n = 0;
|
|
400
|
+
this.timer = setInterval(() => {
|
|
401
|
+
this.expireManual();
|
|
402
|
+
this.core.tick();
|
|
403
|
+
n += 1;
|
|
404
|
+
if (n % 15 === 0 && this.link.connected) this.link.send('ping'); // every 3 s: the C3's heartbeat
|
|
405
|
+
if (n % 5 === 0) this.watchLink();
|
|
406
|
+
}, 200);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** A board that rebooted can leave the old port open and silent (macOS, 2026-11-11: the device came back under
|
|
410
|
+
* the same name, no close or error ever arrived). No answer to ping for 12 s: drop it and look again. */
|
|
411
|
+
watchLink() {
|
|
412
|
+
if (!this.link.connected || this.fwBusy || !this.connectedAt) return;
|
|
413
|
+
const t = Date.now();
|
|
414
|
+
const heard = Math.max(this.connectedAt, this.beat ? this.beat[1] : 0);
|
|
415
|
+
if (t - heard < 12000) return;
|
|
416
|
+
log('плата не відповідає 12 с: перепідключаюся');
|
|
417
|
+
this.note('info', 'плата не відповідає: перепідключаюся');
|
|
418
|
+
this.connectedAt = 0;
|
|
419
|
+
Promise.resolve(this.link.drop()).then(() => this.link.later && this.link.later()).catch(() => {});
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async close() {
|
|
423
|
+
this.closed = true;
|
|
424
|
+
clearInterval(this.timer);
|
|
425
|
+
this.server.close();
|
|
426
|
+
if (this.server.closeAllConnections) this.server.closeAllConnections();
|
|
427
|
+
// closing a port mid-read can hang on some drivers: give it 2 s, then go anyway
|
|
428
|
+
await Promise.race([Promise.resolve(this.link.stop()), new Promise(r => setTimeout(r, 2000))]);
|
|
429
|
+
log('зупинено');
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function readBody(req) {
|
|
434
|
+
return new Promise((resolve, reject) => {
|
|
435
|
+
const chunks = [];
|
|
436
|
+
let size = 0;
|
|
437
|
+
req.on('data', c => {
|
|
438
|
+
size += c.length;
|
|
439
|
+
if (size <= 1 << 20) chunks.push(c); // over the limit: read to the end, keep nothing, answer 413
|
|
440
|
+
});
|
|
441
|
+
req.on('end', () => (size > 1 << 20 ? reject(Object.assign(new Error('too big'), { code: 413 })) : resolve(Buffer.concat(chunks).toString('utf8').replace(/^/, '')))); // a BOM from PowerShell pipes
|
|
442
|
+
req.on('error', reject);
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
module.exports = { Daemon, loadConfig, cleanConfig, log, VERSION };
|
package/src/firmware.js
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// The firmware this package carries and the rules for writing it: docs/firmware_contract.md, section 5.
|
|
3
|
+
// Pure parts (the write plan, the decision what to do with a board) plus the small state files the updater keeps:
|
|
4
|
+
//
|
|
5
|
+
// state/firmware-update.json written right before the flash is written, removed once the board answers "who"
|
|
6
|
+
// with the new version. Its presence lets a silent board be repaired (contract, 5).
|
|
7
|
+
// state/firmware-refused.json boards whose bootloader said they are not an ESP32-S3: never tried again.
|
|
8
|
+
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const crypto = require('crypto');
|
|
12
|
+
const paths = require('./paths');
|
|
13
|
+
const { verdict, PKG_VERSION } = require('./board');
|
|
14
|
+
|
|
15
|
+
const DIR = path.join(__dirname, '..', 'firmware');
|
|
16
|
+
const FLASH_BYTES = 4 * 1024 * 1024;
|
|
17
|
+
const NVS = { start: 0x9000, end: 0xE000 }; // calibration and serial number live here: never written
|
|
18
|
+
const LAYOUT = { // default.csv on 4 MB; the partition table never changes
|
|
19
|
+
'bootloader.bin': 0x0,
|
|
20
|
+
'partitions.bin': 0x8000,
|
|
21
|
+
'boot_app0.bin': 0xE000,
|
|
22
|
+
'firmware.bin': 0x10000,
|
|
23
|
+
};
|
|
24
|
+
const MARKER = () => path.join(paths.STATE, 'firmware-update.json');
|
|
25
|
+
const REFUSED = () => path.join(paths.STATE, 'firmware-refused.json');
|
|
26
|
+
|
|
27
|
+
class FirmwareError extends Error {}
|
|
28
|
+
|
|
29
|
+
const hex = n => '0x' + n.toString(16).toUpperCase();
|
|
30
|
+
const sha256 = data => crypto.createHash('sha256').update(data).digest('hex');
|
|
31
|
+
|
|
32
|
+
/** Check a manifest and its parts against the contract and return what to write:
|
|
33
|
+
* { version, parts: [{ file, address, data, sha256 }] } sorted by address. readPart(file) -> Buffer.
|
|
34
|
+
* Throws FirmwareError (Russian text) on anything off: wrong version or chip, a part missing, a SHA-256 that does
|
|
35
|
+
* not match, a part that touches NVS, overlaps another or leaves the 4 MB, an address other than the layout's. */
|
|
36
|
+
function plan(manifest, readPart, version = PKG_VERSION) {
|
|
37
|
+
const fail = text => { throw new FirmwareError(text); };
|
|
38
|
+
if (!manifest || typeof manifest !== 'object') fail('маніфест прошивки не читається');
|
|
39
|
+
if (manifest.name !== 'clawd-desk') fail('маніфест не від прошивки Desky: name = ' + manifest.name);
|
|
40
|
+
if (manifest.chip !== 'esp32s3') fail('прошивка не для ESP32-S3: chip = ' + manifest.chip);
|
|
41
|
+
if (manifest.version !== version) fail(`у маніфесті прошивка ${manifest.version}, а пакет ${version}`);
|
|
42
|
+
if (!Array.isArray(manifest.parts) || !manifest.parts.length) fail('у маніфесті немає частин');
|
|
43
|
+
|
|
44
|
+
const parts = [];
|
|
45
|
+
const seen = new Set();
|
|
46
|
+
for (const p of manifest.parts) {
|
|
47
|
+
const file = String(p && p.file);
|
|
48
|
+
if (!/^[\w.-]+\.bin$/.test(file)) fail('дивна назва частини: ' + file);
|
|
49
|
+
if (seen.has(file)) fail('частина двічі: ' + file);
|
|
50
|
+
seen.add(file);
|
|
51
|
+
if (!/^0x[0-9a-f]+$/i.test(String(p.address))) fail(`адреса ${file} не шістнадцяткова: ${p.address}`);
|
|
52
|
+
const address = Number.parseInt(p.address, 16);
|
|
53
|
+
let data;
|
|
54
|
+
try {
|
|
55
|
+
data = readPart(file);
|
|
56
|
+
} catch (e) {
|
|
57
|
+
fail('немає частини ' + file);
|
|
58
|
+
}
|
|
59
|
+
if (data.length !== p.size) fail(`${file}: ${data.length} байт, а в маніфесті ${p.size}`);
|
|
60
|
+
const sum = sha256(data);
|
|
61
|
+
if (sum !== String(p.sha256).toLowerCase()) fail(`${file}: SHA-256 не збігається з маніфестом`);
|
|
62
|
+
parts.push({ file, address, data, sha256: sum });
|
|
63
|
+
}
|
|
64
|
+
parts.sort((a, b) => a.address - b.address);
|
|
65
|
+
checkSpans(parts);
|
|
66
|
+
for (const p of parts) {
|
|
67
|
+
if (!(p.file in LAYOUT)) fail('зайва частина: ' + p.file);
|
|
68
|
+
if (LAYOUT[p.file] !== p.address) fail(`${p.file} має лежати на ${hex(LAYOUT[p.file])}, а не на ${hex(p.address)}`);
|
|
69
|
+
}
|
|
70
|
+
for (const f of Object.keys(LAYOUT)) if (!seen.has(f)) fail('немає частини ' + f);
|
|
71
|
+
for (const f of ['bootloader.bin', 'firmware.bin']) {
|
|
72
|
+
if (parts.find(p => p.file === f).data[0] !== 0xE9) fail(f + ' не образ ESP (немає 0xE9 на початку)');
|
|
73
|
+
}
|
|
74
|
+
return { version: manifest.version, parts };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** No part may touch NVS, overlap another or run past the flash. Also the last guard right before writing. */
|
|
78
|
+
function checkSpans(parts) {
|
|
79
|
+
const sorted = [...parts].sort((a, b) => a.address - b.address);
|
|
80
|
+
for (const p of sorted) {
|
|
81
|
+
const end = p.address + p.data.length;
|
|
82
|
+
if (p.address < NVS.end && end > NVS.start) {
|
|
83
|
+
throw new FirmwareError(`${p.file} (${hex(p.address)}–${hex(end - 1)}) зачіпає пам'ять робота `
|
|
84
|
+
+ '0x9000–0xDFFF: так стерлося б калібрування. Не пишу');
|
|
85
|
+
}
|
|
86
|
+
if (end > FLASH_BYTES) throw new FirmwareError(p.file + ' виходить за 4 MB');
|
|
87
|
+
}
|
|
88
|
+
for (let i = 1; i < sorted.length; i++) {
|
|
89
|
+
if (sorted[i - 1].address + sorted[i - 1].data.length > sorted[i].address) {
|
|
90
|
+
throw new FirmwareError(`${sorted[i - 1].file} налазить на ${sorted[i].file}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The firmware in this package (app/firmware, put there by prepack), checked; null when the package has none
|
|
96
|
+
* (a checkout that was not packed). Throws FirmwareError when it is there but wrong. */
|
|
97
|
+
function loadBundle(dir = DIR, version = PKG_VERSION) {
|
|
98
|
+
const file = path.join(dir, 'manifest.json');
|
|
99
|
+
if (!fs.existsSync(file)) return null;
|
|
100
|
+
let manifest;
|
|
101
|
+
try {
|
|
102
|
+
manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
103
|
+
} catch (e) {
|
|
104
|
+
throw new FirmwareError('manifest.json не читається: ' + e.message);
|
|
105
|
+
}
|
|
106
|
+
return plan(manifest, f => fs.readFileSync(path.join(dir, f)), version);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ---------------------------------------------------------------- state files
|
|
110
|
+
function readJson(file, fallback) {
|
|
111
|
+
try {
|
|
112
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
113
|
+
} catch (e) {
|
|
114
|
+
return fallback;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function writeJson(file, data) {
|
|
119
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
120
|
+
fs.writeFileSync(file + '.tmp', JSON.stringify(data, null, 2) + '\n');
|
|
121
|
+
fs.renameSync(file + '.tmp', file);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** "An update started on this board": { port, usbSerial, sn, from, to, started }. */
|
|
125
|
+
const MAX_REPAIRS = 2; // automatic rewrites of a board that stays silent; then it is left to a person
|
|
126
|
+
|
|
127
|
+
function writeMarker({ port, usbSerial = null, sn = null, from = null, to }) {
|
|
128
|
+
const old = readMarker();
|
|
129
|
+
const same = old && old.to === to && markerMatches(old, { path: port, serialNumber: usbSerial });
|
|
130
|
+
writeJson(MARKER(), { port, usbSerial, sn, from, to, started: new Date().toISOString(),
|
|
131
|
+
attempts: (same ? old.attempts || 1 : 0) + 1 }); // a marker from 0.2.0 has no count: it was one
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function readMarker() {
|
|
135
|
+
const m = readJson(MARKER(), null);
|
|
136
|
+
return m && typeof m === 'object' && m.port ? m : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function clearMarker() {
|
|
140
|
+
fs.rmSync(MARKER(), { force: true });
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Is this port the board the marker was written for? Same USB serial (the chip's MAC), or the same port name
|
|
144
|
+
* when the OS did not give a serial. */
|
|
145
|
+
function markerMatches(marker, usb) {
|
|
146
|
+
if (!marker || !usb) return false;
|
|
147
|
+
if (marker.usbSerial && usb.serialNumber) return marker.usbSerial === usb.serialNumber;
|
|
148
|
+
return marker.port === usb.path;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function refusedList() {
|
|
152
|
+
const list = readJson(REFUSED(), []);
|
|
153
|
+
return Array.isArray(list) ? list : [];
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function refusedChip(usb) {
|
|
157
|
+
if (!usb) return null;
|
|
158
|
+
const hit = refusedList().find(r => (r.usbSerial && usb.serialNumber ? r.usbSerial === usb.serialNumber
|
|
159
|
+
: r.port === usb.path));
|
|
160
|
+
return hit ? hit.chip : null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function rememberRefused(usb, chip) {
|
|
164
|
+
const list = refusedList().filter(r => !(usb.serialNumber ? r.usbSerial === usb.serialNumber : r.port === usb.path));
|
|
165
|
+
list.push({ port: usb.path, usbSerial: usb.serialNumber || null, chip, at: new Date().toISOString() });
|
|
166
|
+
writeJson(REFUSED(), list);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// ---------------------------------------------------------------- what to do with a board
|
|
170
|
+
/** One board, one decision.
|
|
171
|
+
* who its parsed "who", or null when it stayed silent
|
|
172
|
+
* usb { path, serialNumber }
|
|
173
|
+
* bundle loadBundle() result or null
|
|
174
|
+
* marker readMarker()
|
|
175
|
+
* refused refusedChip(usb): the chip name a bootloader reported before, or null
|
|
176
|
+
* confirmed the user said "this silent board is my Desky" (--yes or the question)
|
|
177
|
+
* force "firmware update": write even when the versions already match (never an older one)
|
|
178
|
+
* -> { action: 'none' | 'flash' | 'warn' | 'ask' | 'skip', why, recover? } */
|
|
179
|
+
function decide({ who, usb, bundle, marker = null, refused = null, confirmed = false, force = false }) {
|
|
180
|
+
const version = bundle ? bundle.version : PKG_VERSION;
|
|
181
|
+
if (refused) return { action: 'skip', why: `на ${usb.path} ${refused}, не ESP32-S3: прошивка Desky для неї не підходить` };
|
|
182
|
+
if (who && who.chip && who.chip !== 'esp32s3') {
|
|
183
|
+
return { action: 'skip', why: `плата повідомляє chip=${who.chip}: прошивка Desky лише для ESP32-S3` };
|
|
184
|
+
}
|
|
185
|
+
if (!who) {
|
|
186
|
+
if (!bundle) return { action: 'skip', why: `${usb.path} мовчить на who, а прошивки в пакеті немає` };
|
|
187
|
+
if (markerMatches(marker, usb)) {
|
|
188
|
+
if ((marker.attempts || 1) >= MAX_REPAIRS && !confirmed) {
|
|
189
|
+
return { action: 'skip', why: `${usb.path} мовчить і після ${marker.attempts} записів прошивки ${marker.to}: `
|
|
190
|
+
+ 'плата не завантажується, справа в живленні або залізі. Більше не прошиваю сам' };
|
|
191
|
+
}
|
|
192
|
+
return { action: 'flash', recover: true, why: `на ${usb.path} перерване оновлення до ${marker.to}: дописую` };
|
|
193
|
+
}
|
|
194
|
+
if (confirmed) return { action: 'flash', recover: true, why: `${usb.path} мовчить на who, ти підтвердив, що це Desky` };
|
|
195
|
+
return { action: 'ask', why: `${usb.path} (303A:1001) не відповідає як Desky` };
|
|
196
|
+
}
|
|
197
|
+
const v = verdict(who, version);
|
|
198
|
+
const flash = why => (bundle ? { action: 'flash', why }
|
|
199
|
+
: { action: 'warn', why: why + ', але прошивки в цій копії пакета немає' });
|
|
200
|
+
if (v.action === 'update') return flash(v.why);
|
|
201
|
+
if (v.action === 'ok') return force ? flash('перепрошиваю ту саму версію ' + version) : { action: 'none', why: v.why };
|
|
202
|
+
if (v.action === 'mismatch') return force ? flash(v.why + '; перепрошиваю') : { action: 'warn', why: v.why };
|
|
203
|
+
return { action: 'warn', why: v.why }; // newer, upgrade-package: never go back
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
module.exports = { plan, checkSpans, loadBundle, decide, writeMarker, readMarker, clearMarker, markerMatches,
|
|
207
|
+
refusedChip, rememberRefused, FirmwareError, LAYOUT, NVS, DIR, sha256 };
|