desky-agent 0.3.0 → 0.3.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 +10 -3
- package/bin/cli.js +216 -206
- package/electron/icons.js +79 -79
- package/electron/main.js +244 -219
- package/firmware/firmware.bin +0 -0
- package/firmware/manifest.json +2 -2
- package/package.json +41 -40
- package/src/autostart.js +106 -106
- package/src/board.js +69 -69
- package/src/core.js +193 -172
- package/src/daemon.js +522 -446
- package/src/firmware.js +207 -207
- package/src/flasher.js +113 -113
- package/src/hook.js +92 -86
- package/src/install.js +418 -375
- package/src/link.js +207 -207
- package/src/paths.js +44 -44
- package/src/release.js +131 -0
- package/src/selfupdate.js +58 -0
- package/src/updater.js +138 -138
- package/ui/app.html +1519 -1470
- package/ui/clawd3d.js +377 -375
- package/ui/vendor/OrbitControls.js +1532 -1532
- package/ui/vendor/RoomEnvironment.js +144 -144
- package/ui/vendor/STLLoader.js +410 -410
- package/ui/vendor/three.LICENSE +21 -21
- package/ui/vendor/three.module.min.js +6 -6
package/src/daemon.js
CHANGED
|
@@ -1,446 +1,522 @@
|
|
|
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
|
-
//
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
const
|
|
22
|
-
const
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
const
|
|
28
|
-
const
|
|
29
|
-
const
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
if (
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
this.
|
|
84
|
-
this.
|
|
85
|
-
this.
|
|
86
|
-
this.
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
this.
|
|
95
|
-
this.
|
|
96
|
-
this.
|
|
97
|
-
this.
|
|
98
|
-
this.
|
|
99
|
-
this.
|
|
100
|
-
this.
|
|
101
|
-
this.
|
|
102
|
-
this.
|
|
103
|
-
this.
|
|
104
|
-
this.
|
|
105
|
-
this.
|
|
106
|
-
this.
|
|
107
|
-
this.
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
this.
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
this.
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
this.
|
|
174
|
-
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
this.
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
this.
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
this.fwUpdate = { state:
|
|
248
|
-
log(
|
|
249
|
-
this.note('info',
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
this.
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
if (
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
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
|
+
// POST /app-update install the newer version npm has (src/release.js): the app quits and comes back new
|
|
18
|
+
//
|
|
19
|
+
// One instance only: a second one cannot bind the port.
|
|
20
|
+
|
|
21
|
+
const fs = require('fs');
|
|
22
|
+
const http = require('http');
|
|
23
|
+
const path = require('path');
|
|
24
|
+
const { Core, DEFAULTS, COLORS } = require('./core');
|
|
25
|
+
const paths = require('./paths');
|
|
26
|
+
|
|
27
|
+
const UI_DIR = path.join(__dirname, '..', 'ui');
|
|
28
|
+
const UI = path.join(UI_DIR, 'app.html');
|
|
29
|
+
const VERSION = require('../package.json').version;
|
|
30
|
+
const { verdict } = require('./board');
|
|
31
|
+
const fw = require('./firmware');
|
|
32
|
+
const MANUAL_TTL = 15;
|
|
33
|
+
const MANUAL_IDLE = 60;
|
|
34
|
+
|
|
35
|
+
function log(text) {
|
|
36
|
+
const line = new Date().toISOString().replace('T', ' ').slice(0, 19) + ' ' + text + '\n';
|
|
37
|
+
if (process.env.CLAWD_LOG_CONSOLE) process.stdout.write(line);
|
|
38
|
+
try {
|
|
39
|
+
fs.mkdirSync(paths.STATE, { recursive: true });
|
|
40
|
+
try {
|
|
41
|
+
if (fs.statSync(paths.LOG).size > 1 << 20) fs.renameSync(paths.LOG, paths.LOG + '.old');
|
|
42
|
+
} catch (e) { /* no log yet */ }
|
|
43
|
+
fs.appendFileSync(paths.LOG, line);
|
|
44
|
+
} catch (e) { /* a log is not worth failing for */ }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function loadConfig(file = paths.CONFIG) {
|
|
48
|
+
try {
|
|
49
|
+
return { ...DEFAULTS, ...JSON.parse(fs.readFileSync(file, 'utf8')) };
|
|
50
|
+
} catch (e) {
|
|
51
|
+
if (e.code !== 'ENOENT') log('config.json не читається (' + e.message + '): беру значення за замовчуванням');
|
|
52
|
+
return { ...DEFAULTS };
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Keep known keys, with the type of their default; throw on nonsense. */
|
|
57
|
+
function cleanConfig(next) {
|
|
58
|
+
const out = {};
|
|
59
|
+
for (const [k, v0] of Object.entries(next || {})) {
|
|
60
|
+
if (!(k in DEFAULTS)) continue;
|
|
61
|
+
const d = DEFAULTS[k];
|
|
62
|
+
let v = v0;
|
|
63
|
+
if (Array.isArray(d) && typeof d[0] === 'number') {
|
|
64
|
+
v = (Array.isArray(v) ? v : []).map(x => Math.trunc(Number(x)));
|
|
65
|
+
if (v.length !== 2 || !v.every(x => x >= 0 && x <= 24)) throw new Error(k);
|
|
66
|
+
} else if (Array.isArray(d)) {
|
|
67
|
+
if (!Array.isArray(v)) throw new Error(k);
|
|
68
|
+
v = v.map(x => String(x).trim()).filter(Boolean);
|
|
69
|
+
} else if (typeof d === 'number') {
|
|
70
|
+
v = Number.isInteger(d) ? Math.trunc(Number(v)) : Number(v);
|
|
71
|
+
if (!Number.isFinite(v) || v < 0) throw new Error(k);
|
|
72
|
+
if (k === 'port' && !(v >= 1024 && v <= 65535)) throw new Error(k);
|
|
73
|
+
}
|
|
74
|
+
if (k === 'color' && !COLORS.includes(v)) throw new Error(k);
|
|
75
|
+
out[k] = v;
|
|
76
|
+
}
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
class Daemon {
|
|
81
|
+
constructor({ config, configPath = paths.CONFIG, linkFactory, clock = () => Date.now() / 1000, httpPort,
|
|
82
|
+
onStop = () => {}, updater, release } = {}) {
|
|
83
|
+
this.configPath = configPath;
|
|
84
|
+
this.cfg = config || loadConfig(configPath);
|
|
85
|
+
this.clock = clock;
|
|
86
|
+
this.httpPort = httpPort === undefined ? this.cfg.port : httpPort;
|
|
87
|
+
this.onStop = onStop;
|
|
88
|
+
if (!linkFactory) {
|
|
89
|
+
const { Link } = require('./link');
|
|
90
|
+
linkFactory = opts => new Link(opts);
|
|
91
|
+
}
|
|
92
|
+
this.link = linkFactory({ onConnect: () => this.connected(), onLine: ln => this.c3Line(ln),
|
|
93
|
+
onSilent: usb => this.silent(usb) });
|
|
94
|
+
this.updater = updater || require('./updater');
|
|
95
|
+
this.fwBusy = false; // flashing: the Link is stopped, the port is the flasher's
|
|
96
|
+
this.fwTried = new Set(); // boards flashed (or tried) by this run: one attempt each, no loops
|
|
97
|
+
this.fwWarned = new Set();
|
|
98
|
+
this.fwUpdate = null; // { state: updating | done | failed, text } for /status and the tray
|
|
99
|
+
this.release = release || require('./release');
|
|
100
|
+
this.latest = null; // npm's latest version, once asked
|
|
101
|
+
this.appUpdate = this.release.takeResult(); // the last app update: { state, text }, or updating now
|
|
102
|
+
this.releaseTimers = [];
|
|
103
|
+
this.closed = false;
|
|
104
|
+
this.core = new Core(line => this.agentSend(line), { clock, config: this.cfg });
|
|
105
|
+
this.lines = []; // {n, kind, text}: kind me / agent / c3 / info
|
|
106
|
+
this.lineN = 0;
|
|
107
|
+
this.beat = null; // last "жив ..." from the C3, and when
|
|
108
|
+
this.manualOn = false;
|
|
109
|
+
this.manualUntil = 0;
|
|
110
|
+
this.lastHand = 0;
|
|
111
|
+
this.server = http.createServer((req, res) => this.handle(req, res));
|
|
112
|
+
this.timer = null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
get manual() {
|
|
116
|
+
const t = this.clock();
|
|
117
|
+
return this.manualOn && t < this.manualUntil && t - this.lastHand < MANUAL_IDLE;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ------------------------------------------------------------ the monitor
|
|
121
|
+
note(kind, text) {
|
|
122
|
+
this.lineN += 1;
|
|
123
|
+
this.lines.push({ n: this.lineN, kind, text });
|
|
124
|
+
if (this.lines.length > 500) this.lines.shift();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
c3Line(ln) {
|
|
128
|
+
if (ln.startsWith('жив ')) { // every 3 s: not worth a line in the monitor
|
|
129
|
+
this.beat = [ln, Date.now()];
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
this.note('c3', ln);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** From the Core: an agent state or sound. Held back while the app drives. */
|
|
136
|
+
agentSend(line) {
|
|
137
|
+
if (this.manual) return;
|
|
138
|
+
log('-> ' + line);
|
|
139
|
+
this.note('agent', line);
|
|
140
|
+
this.link.send(line);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
command(line, hand = false) {
|
|
144
|
+
if (hand) {
|
|
145
|
+
const t = this.clock();
|
|
146
|
+
if (!this.manualOn) this.note('info', 'ручне керування: стани агента не надсилаються');
|
|
147
|
+
this.manualOn = true;
|
|
148
|
+
this.manualUntil = t + MANUAL_TTL;
|
|
149
|
+
this.lastHand = t;
|
|
150
|
+
}
|
|
151
|
+
this.note('me', line);
|
|
152
|
+
return this.link.send(line);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** hold: the app is calibrating (the wizard or the calibration page is open). Then a keep-alive counts as a hand
|
|
156
|
+
* command too: reading a step for a minute must not hand Desky back to the agent, whose poses hold the arms at 65. */
|
|
157
|
+
setManual(on, hold = false) {
|
|
158
|
+
if (on) { // only keeps it: a window left open must not hold Desky once its minute is up
|
|
159
|
+
if (this.manual) {
|
|
160
|
+
this.manualUntil = this.clock() + MANUAL_TTL;
|
|
161
|
+
if (hold) this.lastHand = this.clock();
|
|
162
|
+
}
|
|
163
|
+
} else {
|
|
164
|
+
this.manualUntil = 0;
|
|
165
|
+
this.expireManual();
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Hand Desky back to the agent once the app stopped asking for him (or said so): say the state again. */
|
|
170
|
+
expireManual() {
|
|
171
|
+
if (this.manualOn && !this.manual) {
|
|
172
|
+
this.manualOn = false;
|
|
173
|
+
this.note('info', 'ручне керування вимкнено: Desky знову показує агента');
|
|
174
|
+
this.core.resend();
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
connected() {
|
|
179
|
+
const t = Date.now();
|
|
180
|
+
this.connectedAt = t;
|
|
181
|
+
const again = this.lastConnect && this.lastConnect.dev === this.link.dev && t - this.lastConnect.t < 60000;
|
|
182
|
+
if (again) {
|
|
183
|
+
this.reconnects = (this.reconnects || 0) + 1;
|
|
184
|
+
if (this.reconnects === 3) log('плата перепідключається знову й знову: перевір кабель і живлення серво');
|
|
185
|
+
} else {
|
|
186
|
+
this.reconnects = 0;
|
|
187
|
+
log('плата на зв\'язку: ' + this.link.dev);
|
|
188
|
+
}
|
|
189
|
+
this.lastConnect = { dev: this.link.dev, t };
|
|
190
|
+
this.note('info', 'плата на зв\'язку: ' + this.link.dev + (again ? ` (перепідключення ${this.reconnects})` : ''));
|
|
191
|
+
if (!this.manual) this.core.resend();
|
|
192
|
+
this.checkFirmware();
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ------------------------------------------------------------ firmware (docs/firmware_contract.md, 3 and 5)
|
|
196
|
+
fwBundle() {
|
|
197
|
+
try {
|
|
198
|
+
return this.updater.bundle();
|
|
199
|
+
} catch (e) {
|
|
200
|
+
if (!this.fwWarned.has('bundle')) {
|
|
201
|
+
this.fwWarned.add('bundle');
|
|
202
|
+
log('прошивка в пакеті не пройшла перевірку: ' + e.message);
|
|
203
|
+
}
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** A board answered "who": an older firmware is updated right away, a newer one only noted. */
|
|
209
|
+
checkFirmware() {
|
|
210
|
+
const who = this.link.info;
|
|
211
|
+
if (this.fwBusy || !who) return;
|
|
212
|
+
const usb = this.link.usb || { path: this.link.dev, serialNumber: null };
|
|
213
|
+
const bundle = this.fwBundle();
|
|
214
|
+
if (bundle === undefined) return;
|
|
215
|
+
const d = fw.decide({ who, usb, bundle, refused: fw.refusedChip(usb) });
|
|
216
|
+
const key = usb.serialNumber || usb.path;
|
|
217
|
+
if (d.action === 'warn' || d.action === 'skip') {
|
|
218
|
+
if (!this.fwWarned.has(key + d.why)) {
|
|
219
|
+
this.fwWarned.add(key + d.why);
|
|
220
|
+
log('прошивка: ' + d.why);
|
|
221
|
+
this.note('info', 'прошивка: ' + d.why);
|
|
222
|
+
}
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (d.action !== 'flash' || this.fwTried.has(key)) return;
|
|
226
|
+
this.fwTried.add(key);
|
|
227
|
+
this.flashBoard(usb, bundle, who, d.why);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** A 303A:1001 port that stays silent: repaired only when this computer's marker says an update was cut short. */
|
|
231
|
+
silent(usb) {
|
|
232
|
+
if (this.fwBusy || this.closed) return;
|
|
233
|
+
const marker = fw.readMarker();
|
|
234
|
+
if (!fw.markerMatches(marker, usb)) return;
|
|
235
|
+
const key = usb.serialNumber || usb.path;
|
|
236
|
+
if (this.fwTried.has(key)) return;
|
|
237
|
+
const bundle = this.fwBundle();
|
|
238
|
+
if (!bundle) return;
|
|
239
|
+
const d = fw.decide({ who: null, usb, bundle, marker, refused: fw.refusedChip(usb) });
|
|
240
|
+
if (d.action !== 'flash') return;
|
|
241
|
+
this.fwTried.add(key);
|
|
242
|
+
setImmediate(() => this.flashBoard(usb, bundle, null, d.why));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
async flashBoard(usb, bundle, who, why) {
|
|
246
|
+
this.fwBusy = true;
|
|
247
|
+
this.fwUpdate = { state: 'updating', text: `оновлюю прошивку Desky до ${bundle.version}, не від'єднуй плату` };
|
|
248
|
+
log(why + ': ' + this.fwUpdate.text);
|
|
249
|
+
this.note('info', this.fwUpdate.text);
|
|
250
|
+
let r;
|
|
251
|
+
try {
|
|
252
|
+
await this.link.stop();
|
|
253
|
+
r = await this.updater.update(usb, { bundle, from: who && who.fw, sn: who && who.sn, log });
|
|
254
|
+
} catch (e) {
|
|
255
|
+
r = { ok: false, text: 'прошивка не оновилася: ' + (e.message || e) };
|
|
256
|
+
}
|
|
257
|
+
this.fwUpdate = { state: r.ok ? 'done' : 'failed', text: r.text };
|
|
258
|
+
log(r.text);
|
|
259
|
+
this.note('info', r.text);
|
|
260
|
+
this.fwBusy = false;
|
|
261
|
+
if (!this.closed) this.link.start();
|
|
262
|
+
return r;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// ------------------------------------------------------------ new versions of the app (src/release.js)
|
|
266
|
+
async checkRelease() {
|
|
267
|
+
try {
|
|
268
|
+
const v = await this.release.latest();
|
|
269
|
+
if (v !== this.latest && this.release.newer(v, VERSION)) {
|
|
270
|
+
log(`вийшла нова версія Desky: ${v} (стоїть ${VERSION})`);
|
|
271
|
+
this.note('info', `вийшла нова версія Desky: ${v}`);
|
|
272
|
+
}
|
|
273
|
+
this.latest = v;
|
|
274
|
+
} catch (e) {
|
|
275
|
+
log('нову версію не перевірив: ' + (e.message || e));
|
|
276
|
+
}
|
|
277
|
+
return this.latest;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
appUpdateStatus() {
|
|
281
|
+
const available = Boolean(this.latest && this.release.newer(this.latest, VERSION));
|
|
282
|
+
let can = false;
|
|
283
|
+
if (available) {
|
|
284
|
+
try { can = this.release.canUpdate(); } catch (e) { /* no */ }
|
|
285
|
+
}
|
|
286
|
+
return { version: VERSION, latest: this.latest, available, can, ...(this.appUpdate || {}) };
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The button: start the installer of the new version. It stops this app over /stop and starts the new one. */
|
|
290
|
+
startAppUpdate() {
|
|
291
|
+
if (this.appUpdate && this.appUpdate.state === 'updating') return this.appUpdate;
|
|
292
|
+
if (!this.latest || !this.release.newer(this.latest, VERSION)) throw new Error('нової версії немає');
|
|
293
|
+
this.release.start(this.latest);
|
|
294
|
+
this.appUpdate = { state: 'updating', text: `оновлюю Desky до ${this.latest}: вікно закриється й відкриється знову` };
|
|
295
|
+
this.updateStarted = Date.now();
|
|
296
|
+
log(this.appUpdate.text);
|
|
297
|
+
this.note('info', this.appUpdate.text);
|
|
298
|
+
return this.appUpdate;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/** While an update runs this app may outlive it (npm could not fetch the package): take its word when it ends. */
|
|
302
|
+
watchAppUpdate() {
|
|
303
|
+
if (!this.appUpdate || this.appUpdate.state !== 'updating') return;
|
|
304
|
+
const r = this.release.takeResult();
|
|
305
|
+
if (r) {
|
|
306
|
+
this.appUpdate = r;
|
|
307
|
+
log(r.text);
|
|
308
|
+
this.note('info', r.text);
|
|
309
|
+
} else if (Date.now() - this.updateStarted > 20 * 60 * 1000) {
|
|
310
|
+
this.appUpdate = { state: 'failed', text: 'оновлення не закінчилося за 20 хвилин. Лог: ' + this.release.UPDATE_LOG };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// ------------------------------------------------------------ hooks and status
|
|
315
|
+
event(ev) {
|
|
316
|
+
this.core.event(ev && typeof ev === 'object' ? ev : {});
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
status() {
|
|
320
|
+
const st = this.core.status();
|
|
321
|
+
st.quiet_now = this.core.quiet(this.clock());
|
|
322
|
+
return Object.assign(st, {
|
|
323
|
+
app: 'desky-agent', version: VERSION, connected: this.link.connected, port: this.link.dev || null,
|
|
324
|
+
board: this.link.info || null,
|
|
325
|
+
firmware: this.link.connected ? verdict(this.link.info) : null,
|
|
326
|
+
firmware_update: this.fwUpdate,
|
|
327
|
+
app_update: this.appUpdateStatus(),
|
|
328
|
+
manual: this.manual, heartbeat: this.beat ? this.beat[0] : null,
|
|
329
|
+
heartbeat_age: this.beat ? Math.round((Date.now() - this.beat[1]) / 100) / 10 : null,
|
|
330
|
+
});
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
getLines(since) {
|
|
334
|
+
return this.lines.filter(l => l.n > since);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
saveConfig(next) {
|
|
338
|
+
next = cleanConfig(next);
|
|
339
|
+
let saved = {};
|
|
340
|
+
try { saved = JSON.parse(fs.readFileSync(this.configPath, 'utf8')); } catch (e) { /* new file */ }
|
|
341
|
+
Object.assign(saved, next);
|
|
342
|
+
fs.mkdirSync(path.dirname(this.configPath), { recursive: true });
|
|
343
|
+
const tmp = this.configPath + '.tmp';
|
|
344
|
+
fs.writeFileSync(tmp, JSON.stringify(saved, null, 2));
|
|
345
|
+
fs.renameSync(tmp, this.configPath);
|
|
346
|
+
Object.assign(this.cfg, next);
|
|
347
|
+
Object.assign(this.core.cfg, next);
|
|
348
|
+
return this.cfg;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// ------------------------------------------------------------ HTTP
|
|
352
|
+
localPage(req) {
|
|
353
|
+
// only the app's own page may drive the robot: a web page elsewhere could POST here too
|
|
354
|
+
const origin = req.headers.origin;
|
|
355
|
+
const port = this.server.address().port;
|
|
356
|
+
return !origin || origin === 'http://127.0.0.1:' + port || origin === 'http://localhost:' + port;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
async handle(req, res) {
|
|
360
|
+
const reply = (code, obj, type = 'application/json; charset=utf-8') => {
|
|
361
|
+
const body = Buffer.isBuffer(obj) ? obj : Buffer.from(JSON.stringify(obj));
|
|
362
|
+
res.writeHead(code, { 'Content-Type': type, 'Content-Length': body.length, 'Cache-Control': 'no-store' });
|
|
363
|
+
res.end(body);
|
|
364
|
+
};
|
|
365
|
+
const port = this.server.address().port;
|
|
366
|
+
if (![`127.0.0.1:${port}`, `localhost:${port}`].includes(String(req.headers.host || '').toLowerCase())) {
|
|
367
|
+
return reply(403, { error: 'host' });
|
|
368
|
+
}
|
|
369
|
+
const u = new URL(req.url, 'http://127.0.0.1');
|
|
370
|
+
try {
|
|
371
|
+
if (req.method === 'GET') {
|
|
372
|
+
if (u.pathname === '/' || u.pathname === '/app.html') {
|
|
373
|
+
try {
|
|
374
|
+
return reply(200, fs.readFileSync(UI), 'text/html; charset=utf-8');
|
|
375
|
+
} catch (e) {
|
|
376
|
+
return reply(404, { error: 'no ui' });
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
// the 3D Desky in the app: three.js (ui/vendor) and the print STLs (ui/models), nothing else from ui/
|
|
380
|
+
const asset = u.pathname.match(/^\/((?:vendor|models)\/[\w.-]+\.(js|stl)|clawd3d\.(js))$/);
|
|
381
|
+
if (asset) {
|
|
382
|
+
try {
|
|
383
|
+
return reply(200, fs.readFileSync(path.join(UI_DIR, asset[1])),
|
|
384
|
+
asset[2] === 'stl' ? 'model/stl' : 'text/javascript; charset=utf-8');
|
|
385
|
+
} catch (e) {
|
|
386
|
+
return reply(404, { error: 'not found' });
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
if (u.pathname === '/status') return reply(200, this.status());
|
|
390
|
+
if (u.pathname === '/lines') return reply(200, this.getLines(Number(u.searchParams.get('since') || 0)));
|
|
391
|
+
if (u.pathname === '/config') return reply(200, { config: this.cfg, defaults: DEFAULTS });
|
|
392
|
+
return reply(404, { error: 'not found' });
|
|
393
|
+
}
|
|
394
|
+
if (req.method !== 'POST') return reply(405, { error: 'method' });
|
|
395
|
+
if (!this.localPage(req)) return reply(403, { error: 'origin' });
|
|
396
|
+
let body;
|
|
397
|
+
try {
|
|
398
|
+
const raw = await readBody(req);
|
|
399
|
+
body = raw.length ? JSON.parse(raw) : {};
|
|
400
|
+
} catch (e) {
|
|
401
|
+
if (e.code === 413) return reply(413, { error: 'too big' });
|
|
402
|
+
return reply(400, { error: 'bad json' });
|
|
403
|
+
}
|
|
404
|
+
const p = u.pathname;
|
|
405
|
+
if (p === '/event') {
|
|
406
|
+
this.event(body);
|
|
407
|
+
return reply(200, { ok: true });
|
|
408
|
+
}
|
|
409
|
+
if (p === '/cmd') {
|
|
410
|
+
const line = String(body.line || '').trim();
|
|
411
|
+
if (!line || line.includes('\n')) return reply(400, { error: 'one line' });
|
|
412
|
+
return reply(200, { ok: this.command(line, Boolean(body.hand)) });
|
|
413
|
+
}
|
|
414
|
+
if (p === '/manual') {
|
|
415
|
+
this.setManual(Boolean(body.on), Boolean(body.hold));
|
|
416
|
+
return reply(200, { manual: this.manual });
|
|
417
|
+
}
|
|
418
|
+
if (p === '/reset') {
|
|
419
|
+
const ok = this.link.reset ? await this.link.reset() : false;
|
|
420
|
+
this.note('info', ok ? 'перезапуск плати' : 'перезапуск не вдався: плату не під\'єднано');
|
|
421
|
+
return reply(200, { ok });
|
|
422
|
+
}
|
|
423
|
+
if (p === '/config') {
|
|
424
|
+
try {
|
|
425
|
+
return reply(200, { config: this.saveConfig(body) });
|
|
426
|
+
} catch (e) {
|
|
427
|
+
return reply(400, { error: 'неправильне значення: ' + e.message });
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
if (p === '/app-update') {
|
|
431
|
+
try {
|
|
432
|
+
return reply(200, this.startAppUpdate());
|
|
433
|
+
} catch (e) {
|
|
434
|
+
return reply(409, { error: e.message || String(e) });
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (p === '/stop') {
|
|
438
|
+
reply(200, { ok: true });
|
|
439
|
+
setImmediate(() => this.onStop());
|
|
440
|
+
return undefined;
|
|
441
|
+
}
|
|
442
|
+
return reply(404, { error: 'not found' });
|
|
443
|
+
} catch (e) {
|
|
444
|
+
log('помилка HTTP: ' + (e.stack || e));
|
|
445
|
+
if (!res.headersSent) reply(500, { error: String(e.message || e) });
|
|
446
|
+
return undefined;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Bind 127.0.0.1:port. Rejects with EADDRINUSE when another Desky (or the old Python daemon) has it. */
|
|
451
|
+
listen() {
|
|
452
|
+
return new Promise((resolve, reject) => {
|
|
453
|
+
const fail = e => reject(e);
|
|
454
|
+
this.server.once('error', fail);
|
|
455
|
+
this.server.listen(this.httpPort, '127.0.0.1', () => {
|
|
456
|
+
this.server.off('error', fail);
|
|
457
|
+
this.httpPort = this.server.address().port;
|
|
458
|
+
resolve(this.httpPort);
|
|
459
|
+
});
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
start() {
|
|
464
|
+
this.link.start();
|
|
465
|
+
log('слухаю 127.0.0.1:' + this.httpPort);
|
|
466
|
+
let n = 0;
|
|
467
|
+
this.timer = setInterval(() => {
|
|
468
|
+
this.expireManual();
|
|
469
|
+
this.core.tick();
|
|
470
|
+
n += 1;
|
|
471
|
+
if (n % 15 === 0 && this.link.connected) this.link.send('ping'); // every 3 s: the C3's heartbeat
|
|
472
|
+
if (n % 5 === 0) this.watchLink();
|
|
473
|
+
if (n % 10 === 0) this.watchAppUpdate();
|
|
474
|
+
}, 200);
|
|
475
|
+
if (!process.env.CLAWD_NO_RELEASE_CHECK) { // once a little after start, then every 6 hours
|
|
476
|
+
const later = setTimeout(() => this.checkRelease(), 10000);
|
|
477
|
+
const every = setInterval(() => this.checkRelease(), 6 * 3600 * 1000);
|
|
478
|
+
later.unref();
|
|
479
|
+
every.unref();
|
|
480
|
+
this.releaseTimers.push(later, every);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** A board that rebooted can leave the old port open and silent (macOS, 2026-11-11: the device came back under
|
|
485
|
+
* the same name, no close or error ever arrived). No answer to ping for 12 s: drop it and look again. */
|
|
486
|
+
watchLink() {
|
|
487
|
+
if (!this.link.connected || this.fwBusy || !this.connectedAt) return;
|
|
488
|
+
const t = Date.now();
|
|
489
|
+
const heard = Math.max(this.connectedAt, this.beat ? this.beat[1] : 0);
|
|
490
|
+
if (t - heard < 12000) return;
|
|
491
|
+
log('плата не відповідає 12 с: перепідключаюся');
|
|
492
|
+
this.note('info', 'плата не відповідає: перепідключаюся');
|
|
493
|
+
this.connectedAt = 0;
|
|
494
|
+
Promise.resolve(this.link.drop()).then(() => this.link.later && this.link.later()).catch(() => {});
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
async close() {
|
|
498
|
+
this.closed = true;
|
|
499
|
+
clearInterval(this.timer);
|
|
500
|
+
for (const t of this.releaseTimers) clearTimeout(t);
|
|
501
|
+
this.server.close();
|
|
502
|
+
if (this.server.closeAllConnections) this.server.closeAllConnections();
|
|
503
|
+
// closing a port mid-read can hang on some drivers: give it 2 s, then go anyway
|
|
504
|
+
await Promise.race([Promise.resolve(this.link.stop()), new Promise(r => setTimeout(r, 2000))]);
|
|
505
|
+
log('зупинено');
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function readBody(req) {
|
|
510
|
+
return new Promise((resolve, reject) => {
|
|
511
|
+
const chunks = [];
|
|
512
|
+
let size = 0;
|
|
513
|
+
req.on('data', c => {
|
|
514
|
+
size += c.length;
|
|
515
|
+
if (size <= 1 << 20) chunks.push(c); // over the limit: read to the end, keep nothing, answer 413
|
|
516
|
+
});
|
|
517
|
+
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
|
|
518
|
+
req.on('error', reject);
|
|
519
|
+
});
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
module.exports = { Daemon, loadConfig, cleanConfig, log, VERSION };
|