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/src/firmware.js CHANGED
@@ -1,207 +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 };
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 };
package/src/flasher.js CHANGED
@@ -1,113 +1,113 @@
1
- 'use strict';
2
- // Write Desky's firmware with esptool-js over node serialport: no Python, no PlatformIO on the user's machine.
3
- // docs/firmware_contract.md, section 5:
4
- //
5
- // - the four parts at their manifest addresses in one write_flash, flash mode/frequency/size "keep";
6
- // - never erase_flash, never erase_region, never a merged image: NVS (0x9000-0xDFFF) keeps the calibration;
7
- // - the bootloader must say ESP32-S3, anything else is put back into its own program and left alone;
8
- // - after the write a hard reset, then the board must answer "who" with the package's version.
9
-
10
- const { NodeSerial } = require('./webserial');
11
- const { checkSpans, FirmwareError } = require('./firmware');
12
- const crypto = require('crypto');
13
-
14
- const sleep = ms => new Promise(r => setTimeout(r, ms));
15
- const STALL_MS = 45000; // no progress this long: the link is dead
16
-
17
- class ChipError extends FirmwareError {
18
- constructor(chip) {
19
- super(`це ${chip}, а не ESP32-S3: прошивка Desky на неї не стане`);
20
- this.chip = chip;
21
- }
22
- }
23
-
24
- let esptool = null;
25
- async function loadEsptool() {
26
- // esptool-js checks image digests with WebCrypto; Node 18 has it only under require('crypto')
27
- if (!globalThis.crypto || !globalThis.crypto.subtle) globalThis.crypto = crypto.webcrypto;
28
- if (!esptool) esptool = await import('esptool-js');
29
- return esptool;
30
- }
31
-
32
- /** RTS pulse with DTR (BOOT) low: the chip restarts into its program. esptool-js's own HardReset only lowers RTS. */
33
- async function hardReset(transport) {
34
- await transport.setDTR(false);
35
- await transport.setRTS(true);
36
- await sleep(120);
37
- await transport.setRTS(false);
38
- }
39
-
40
- /** Flash bundle.parts (firmware.plan() output) to the board on `path`.
41
- * beforeWrite() runs once the chip is known to be an ESP32-S3, right before the first byte is written
42
- * (the updater writes its "update started" marker there)
43
- * onProgress(n) 0..100
44
- * log(text) esptool's own lines, for the log file
45
- * Throws ChipError for any chip but the S3 (nothing written, board reset back into its program), FirmwareError
46
- * for a plan that would touch NVS, other errors from the port or the bootloader. SerialPort and esptool are
47
- * replaceable for tests. */
48
- async function writeParts({ path, bundle, beforeWrite = async () => {}, onProgress = () => {}, log = () => {},
49
- SerialPort, esptool: esp, stallMs = STALL_MS } = {}) {
50
- checkSpans(bundle.parts);
51
- esp = esp || await loadEsptool();
52
- const device = new NodeSerial({ path, SerialPort });
53
- class Transport extends esp.Transport {
54
- trace(text) { // the base class prints some of these to the console even with tracing off
55
- if (this.tracing) log('esptool: ' + text);
56
- }
57
- }
58
- const transport = new Transport(device, false);
59
- const terminal = { clean() {}, write() {}, writeLine: text => log(String(text).trim()) };
60
- const loader = new esp.ESPLoader({ transport, baudrate: 115200, romBaudrate: 115200, terminal });
61
- try {
62
- try {
63
- await loader.detectChip('default_reset');
64
- } catch (e) {
65
- if (e instanceof esp.UnexpectedChipIdError || e instanceof esp.UnexpectedChipMagicError) {
66
- await hardReset(transport).catch(() => {});
67
- throw new ChipError('невідомий чип');
68
- }
69
- throw e;
70
- }
71
- const chip = loader.chip && loader.chip.CHIP_NAME;
72
- if (chip !== 'ESP32-S3') {
73
- await hardReset(transport).catch(() => {});
74
- throw new ChipError(chip || 'невідомий чип');
75
- }
76
- await loader.runStub();
77
- await beforeWrite();
78
- const total = bundle.parts.reduce((n, p) => n + p.data.length, 0);
79
- const before = bundle.parts.map((p, i) => bundle.parts.slice(0, i).reduce((n, q) => n + q.data.length, 0));
80
- let last = Date.now();
81
- let stalled = null;
82
- const watch = new Promise((_, reject) => {
83
- stalled = setInterval(() => {
84
- if (Date.now() - last > stallMs) {
85
- reject(new Error(`запис зупинився більш ніж на ${Math.round(stallMs / 1000)} с: зв'язок із платою обірвався`));
86
- device.close().catch(() => {}); // unblocks esptool-js's pending read
87
- }
88
- }, 1000);
89
- });
90
- await Promise.race([watch, loader.writeFlash({
91
- fileArray: bundle.parts.map(p => ({ data: new Uint8Array(p.data), address: p.address })),
92
- flashMode: 'keep',
93
- flashFreq: 'keep',
94
- flashSize: 'keep',
95
- eraseAll: false,
96
- compress: true,
97
- // esptool-js reads the flash back as MD5 after each part and throws on a difference
98
- calculateMD5Hash: image => crypto.createHash('md5').update(image).digest('hex'),
99
- reportProgress: (i, written, size) => {
100
- last = Date.now();
101
- const done = before[i] + Math.min(written / (size || 1), 1) * bundle.parts[i].data.length;
102
- onProgress(Math.round((done / total) * 100));
103
- },
104
- })]).finally(() => clearInterval(stalled));
105
- await hardReset(transport);
106
- } finally {
107
- // the reset may drop the device off USB under us: closing must not hang
108
- await Promise.race([transport.disconnect().catch(() => {}), sleep(2000)]);
109
- await device.close().catch(() => {});
110
- }
111
- }
112
-
113
- module.exports = { writeParts, hardReset, loadEsptool, ChipError };
1
+ 'use strict';
2
+ // Write Desky's firmware with esptool-js over node serialport: no Python, no PlatformIO on the user's machine.
3
+ // docs/firmware_contract.md, section 5:
4
+ //
5
+ // - the four parts at their manifest addresses in one write_flash, flash mode/frequency/size "keep";
6
+ // - never erase_flash, never erase_region, never a merged image: NVS (0x9000-0xDFFF) keeps the calibration;
7
+ // - the bootloader must say ESP32-S3, anything else is put back into its own program and left alone;
8
+ // - after the write a hard reset, then the board must answer "who" with the package's version.
9
+
10
+ const { NodeSerial } = require('./webserial');
11
+ const { checkSpans, FirmwareError } = require('./firmware');
12
+ const crypto = require('crypto');
13
+
14
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
15
+ const STALL_MS = 45000; // no progress this long: the link is dead
16
+
17
+ class ChipError extends FirmwareError {
18
+ constructor(chip) {
19
+ super(`це ${chip}, а не ESP32-S3: прошивка Desky на неї не стане`);
20
+ this.chip = chip;
21
+ }
22
+ }
23
+
24
+ let esptool = null;
25
+ async function loadEsptool() {
26
+ // esptool-js checks image digests with WebCrypto; Node 18 has it only under require('crypto')
27
+ if (!globalThis.crypto || !globalThis.crypto.subtle) globalThis.crypto = crypto.webcrypto;
28
+ if (!esptool) esptool = await import('esptool-js');
29
+ return esptool;
30
+ }
31
+
32
+ /** RTS pulse with DTR (BOOT) low: the chip restarts into its program. esptool-js's own HardReset only lowers RTS. */
33
+ async function hardReset(transport) {
34
+ await transport.setDTR(false);
35
+ await transport.setRTS(true);
36
+ await sleep(120);
37
+ await transport.setRTS(false);
38
+ }
39
+
40
+ /** Flash bundle.parts (firmware.plan() output) to the board on `path`.
41
+ * beforeWrite() runs once the chip is known to be an ESP32-S3, right before the first byte is written
42
+ * (the updater writes its "update started" marker there)
43
+ * onProgress(n) 0..100
44
+ * log(text) esptool's own lines, for the log file
45
+ * Throws ChipError for any chip but the S3 (nothing written, board reset back into its program), FirmwareError
46
+ * for a plan that would touch NVS, other errors from the port or the bootloader. SerialPort and esptool are
47
+ * replaceable for tests. */
48
+ async function writeParts({ path, bundle, beforeWrite = async () => {}, onProgress = () => {}, log = () => {},
49
+ SerialPort, esptool: esp, stallMs = STALL_MS } = {}) {
50
+ checkSpans(bundle.parts);
51
+ esp = esp || await loadEsptool();
52
+ const device = new NodeSerial({ path, SerialPort });
53
+ class Transport extends esp.Transport {
54
+ trace(text) { // the base class prints some of these to the console even with tracing off
55
+ if (this.tracing) log('esptool: ' + text);
56
+ }
57
+ }
58
+ const transport = new Transport(device, false);
59
+ const terminal = { clean() {}, write() {}, writeLine: text => log(String(text).trim()) };
60
+ const loader = new esp.ESPLoader({ transport, baudrate: 115200, romBaudrate: 115200, terminal });
61
+ try {
62
+ try {
63
+ await loader.detectChip('default_reset');
64
+ } catch (e) {
65
+ if (e instanceof esp.UnexpectedChipIdError || e instanceof esp.UnexpectedChipMagicError) {
66
+ await hardReset(transport).catch(() => {});
67
+ throw new ChipError('невідомий чип');
68
+ }
69
+ throw e;
70
+ }
71
+ const chip = loader.chip && loader.chip.CHIP_NAME;
72
+ if (chip !== 'ESP32-S3') {
73
+ await hardReset(transport).catch(() => {});
74
+ throw new ChipError(chip || 'невідомий чип');
75
+ }
76
+ await loader.runStub();
77
+ await beforeWrite();
78
+ const total = bundle.parts.reduce((n, p) => n + p.data.length, 0);
79
+ const before = bundle.parts.map((p, i) => bundle.parts.slice(0, i).reduce((n, q) => n + q.data.length, 0));
80
+ let last = Date.now();
81
+ let stalled = null;
82
+ const watch = new Promise((_, reject) => {
83
+ stalled = setInterval(() => {
84
+ if (Date.now() - last > stallMs) {
85
+ reject(new Error(`запис зупинився більш ніж на ${Math.round(stallMs / 1000)} с: зв'язок із платою обірвався`));
86
+ device.close().catch(() => {}); // unblocks esptool-js's pending read
87
+ }
88
+ }, 1000);
89
+ });
90
+ await Promise.race([watch, loader.writeFlash({
91
+ fileArray: bundle.parts.map(p => ({ data: new Uint8Array(p.data), address: p.address })),
92
+ flashMode: 'keep',
93
+ flashFreq: 'keep',
94
+ flashSize: 'keep',
95
+ eraseAll: false,
96
+ compress: true,
97
+ // esptool-js reads the flash back as MD5 after each part and throws on a difference
98
+ calculateMD5Hash: image => crypto.createHash('md5').update(image).digest('hex'),
99
+ reportProgress: (i, written, size) => {
100
+ last = Date.now();
101
+ const done = before[i] + Math.min(written / (size || 1), 1) * bundle.parts[i].data.length;
102
+ onProgress(Math.round((done / total) * 100));
103
+ },
104
+ })]).finally(() => clearInterval(stalled));
105
+ await hardReset(transport);
106
+ } finally {
107
+ // the reset may drop the device off USB under us: closing must not hang
108
+ await Promise.race([transport.disconnect().catch(() => {}), sleep(2000)]);
109
+ await device.close().catch(() => {});
110
+ }
111
+ }
112
+
113
+ module.exports = { writeParts, hardReset, loadEsptool, ChipError };