-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflash.html
More file actions
496 lines (412 loc) · 15.4 KB
/
flash.html
File metadata and controls
496 lines (412 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
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
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
<!---
MIT License
Copyright (c) 2025 Breezedude
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>WS85 Web Flasher</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: monospace;
background-color: #f3f4f6;
color: #1f2937;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
padding: 2.5rem 1rem;
}
.container {
background-color: #fff;
padding: 2rem;
border-radius: 1rem;
box-shadow: 0 10px 15px rgba(0,0,0,0.1);
width: 100%;
max-width: 1400px;
}
h1 {
font-size: 2rem;
font-weight: bold;
margin-bottom: 1rem;
text-align: center;
}
label {
display: block;
font-weight: 600;
margin-bottom: 0.5rem;
}
input[type="file"] {
width: 350px;
padding: 0.5rem;
border-radius: 0.5rem;
border: 1px solid #d1d5db; /* gray-300 */
}
button {
background-color: #2563eb; /* blue-600 */
color: white;
font-weight: bold;
padding: 0.5rem 1.5rem;
border-radius: 0.75rem;
margin: 10px;
border: none;
cursor: pointer;
transition: background-color 0.2s;
}
button:hover {
background-color: #1d4ed8; /* blue-700 */
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.progress-wrapper {
width: 100%;
height: 1rem;
background-color: #e5e7eb; /* gray-200 */
border-radius: 9999px;
margin-bottom: 1rem;
overflow: hidden;
}
.progress-bar {
background-color: #10b981; /* green-500 */
height: 100%;
width: 0%;
border-radius: 9999px;
transition: width 0.2s;
}
#terminal {
background-color: #000;
color: #22c55e; /* green-400 */
font-family: monospace;
font-size: 0.875rem; /* text-sm */
padding: 0.75rem;
border-radius: 0.75rem;
height: 16rem;
overflow-x: auto; /* allow horizontal scroll */
overflow-y: auto;
white-space: pre; /* do not wrap lines */
}
#footer {
text-align: center;
margin-top: 40px;
color: #777;
font-size: 13px;
}
</style>
</head>
<body>
<div class="container">
<h1>WS85 Web Flasher</h1>
<div class="mb-4">
<label for="fileInput">Select WS85 Firmware (.hex) <br><a href="https://www.ecowitt.com/api/quickstart/product?id=308" target="_blank" style="color: #777;">FW available here</a></label>
<input id="fileInput" type="file" accept=".hex">
</div>
<div id="compatWarning" style="
display:none;
background-color:#fee2e2; /* light red */
color:#b91c1c; /* dark red */
border:1px solid #fca5a5;
padding:0.75rem 1rem;
border-radius:0.5rem;
margin:3rem;
text-align:center;
font-weight:bold;
">
⚠️ WebHID is not supported in this browser.<br>
Please use <strong>Google Chrome</strong>, <strong>Microsoft Edge</strong>, <strong>Brave</strong>, or another Chromium-based browser on desktop.<br>
For more info visit <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebHID_API">WebHID MDN</a>
</div>
<div class="mb-4" style="text-align:center;">
<button id="flashBtn">Connect & Flash</button>
</div>
<div class="progress-wrapper">
<div id="progressBar" class="progress-bar"></div>
</div>
<div id="versionLabels" style="text-align:center; margin-bottom: 1rem;">
<span id="bootloaderVer" style="font-weight:bold;">Bootloader: -</span>
|
<span id="firmwareVer" style="font-weight:bold;">Old Firmware: -</span>
</div>
<div id="terminal"></div>
<div id="footer">
Breezedude © 2025 - <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-github" viewBox="0 0 16 16">
<path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27s1.36.09 2 .27c1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.01 8.01 0 0 0 16 8c0-4.42-3.58-8-8-8"/>
</svg>
<a href="https://github.com/Breezedude/WS85_WebFlasher" target="_blank" style="color: #777;">WS85_WebFlasher</a>
</div>
</div>
<script>
window.addEventListener("DOMContentLoaded", () => {
if (!("hid" in navigator)) {
const warn = document.getElementById("compatWarning");
if (warn) warn.style.display = "block";
// Optionally, disable interaction
document.getElementById("flashBtn").disabled = true;
document.getElementById("fileInput").disabled = true;
}
});
const VID = 0x1209;
const PID = 0x0021;
const REPORT_SIZE = 64;
const CMD_INIT = 0x01;
const CMD_GET_FW = 0x04;
const CMD_WRITE = 0x22;
const CMD_SET_TARGET = 0x30;
const CMD_FIN1 = 0x33;
const CMD_FIN2 = 0x23;
const CMD_FIN3 = 0x06;
const CMD_UUID = 0x0F;
const ACK_OK = 0x9F;
const FW_RES = 0xA4;
const FIN_OK = 0xA5;
const NACK = 0xDF;
let device;
let firmware = null;
const MAX_TERMINAL_LINES = 100;
function log(msg) {
const term = document.getElementById('terminal');
// Split existing content into lines
let lines = term.textContent.split("\n");
lines.push(msg); // add new line
// Keep only the last MAX_TERMINAL_LINES lines
if (lines.length > MAX_TERMINAL_LINES) {
lines = lines.slice(lines.length - MAX_TERMINAL_LINES);
}
// Update terminal
term.textContent = lines.join("\n");
// Scroll to bottom
term.scrollTop = term.scrollHeight;
}
function formatVersion(num) {
// Converts numeric version like 116 -> "V1.1.6"
if (typeof num !== "number") num = parseInt(num);
if (isNaN(num)) return "V?.?.?";
const major = Math.floor(num / 100);
const minor = Math.floor((num % 100) / 10);
const patch = num % 10;
return `V${major}.${minor}.${patch}`;
}
// change_label(type, new_number)
// type = "bootloader" or "firmware"
function change_label(type, new_number) {
const versionText = formatVersion(new_number);
if (type === "bootloader") {
document.getElementById("bootloaderVer").textContent =
`Bootloader: ${versionText}`;
} else if (type === "firmware") {
document.getElementById("firmwareVer").textContent =
`Old Firmware: ${versionText}`;
}
}
// Remove trailing 0x00 bytes
function trimTrailingZeros(arr) {
let end = arr.length;
while (end > 0 && arr[end - 1] === 0x00) {
end--;
}
return arr.slice(0, end);
}
async function sendCommand(cmd, data = [], forceLength = null) {
const length = forceLength !== null ? forceLength : data.length;
const payload = new Uint8Array(REPORT_SIZE).fill(0);
payload[0] = 0x68; // SOF
payload[1] = cmd; // command
payload[2] = (length >> 8) & 0xff;
payload[3] = length & 0xff;
// Copy data starting at byte 4
payload.set(data, 4);
// Compute second-last byte (simple sum mod 256)
let sum = 0;
for (let i = 0; i < 4 + data.length; i++) sum += payload[i];
sum &= 0xFF;
// Append checksum and fixed terminator 0x16
payload[4 + data.length] = sum; // second-last byte
payload[5 + data.length] = 0x16; // last byte
log(`TX: ${Array.from(payload.slice(0, Math.max(8, 4 + data.length + 2))).map(b => b.toString(16).padStart(2,"0")).join(" ")}`);
// ---- SEND ----
await device.sendReport(0, payload);
// ---- RECEIVE ----
const event = await new Promise(resolve => {
const handler = e => {
device.removeEventListener("inputreport", handler);
resolve(e);
};
device.addEventListener("inputreport", handler);
});
const bytes = new Uint8Array(event.data.buffer);
const header = bytes[0];
const ack = bytes[1];
const trimmedBytes = trimTrailingZeros(new Uint8Array(bytes));
log(`RX: ${Array.from(trimmedBytes).map(b => b.toString(16).padStart(2,"0")).join(" ")}`);
log(`ACK: 0x${ack.toString(16)}`);
if (header !== 0x68) throw new Error(`Unexpected header ${header.toString(16)}`);
if ((ack !== ACK_OK) && (ack !== FW_RES) && (ack !== FIN_OK)) throw new Error(`Bad ACK: ${ack.toString(16)}`);
if(ack === FW_RES){
let current_bootloader = (bytes[4] << 8) | bytes[5];
let current_fw = (bytes[6] << 8) | bytes[7];
console.log(bytes[5])
change_label("bootloader", current_bootloader);
change_label("firmware", current_fw);
}
}
async function flashFirmware() {
if (!firmware) { log("No firmware selected."); return; }
const finalizePayload = await buildFinalizeBlock(firmware);
console.log(finalizePayload)
try {
log("Requesting HID device...");
device = await navigator.hid.requestDevice({ filters: [{ vendorId: VID, productId: PID }] });
if (!device || device.length === 0) { log("No device selected."); return; }
device = device[0];
await device.open();
log(`Connected to ${device.productName || "CMSemicon HID ISP"}`);
// Attach helper promise for HID input
device.receiveReport = () =>
new Promise(resolve => {
const handler = e => {
device.removeEventListener('inputreport', handler);
resolve(e);
};
device.addEventListener('inputreport', handler);
});
log("Sending INIT...");
await sendCommand(CMD_INIT);
await sendCommand(CMD_INIT);
await sendCommand(CMD_INIT); // required 3 times, don't ask
log("Init OK");
// Get current FW
log("Check FW...");
await sendCommand(CMD_GET_FW);
// SET_TARGET
log("Setting Target...");
await sendCommand(CMD_SET_TARGET, [0x08, 0x00, 0x08, 0x00] );
log("OK");
await sendCommand(CMD_FIN3);
// Write firmware
const chunkSize = 32;
let offset = 0;
const total = firmware.length;
let lastPct = -1; // track last integer percentage
log(`Writing ${total} bytes`);
while (offset < total) {
const chunk = firmware.slice(offset, offset + chunkSize);
await sendCommand(CMD_WRITE, chunk);
offset += chunkSize;
const pct = Math.floor((offset / total) * 100);
if (pct !== lastPct) {
lastPct = pct;
document.getElementById('progressBar').style.width = pct + '%';
// force repaint for smoother UX
await new Promise(r => requestAnimationFrame(r));
}
}
log("Flash complete.");
document.getElementById('progressBar').style.width = '100%';
// SET_TARGET
log("Finishing...");
await sendCommand(CMD_FIN1, finalizePayload);
// No idea what this does, but its constant
await sendCommand(CMD_FIN2, [0x06, 0x00, 0xf5, 0xe0, 0x00, 0x00, 0x00, 0x10] ); // 682300080600f5e0000000107e16
await sendCommand(CMD_SET_TARGET, [0x08, 0x03, 0xFE, 0x00] ); // 683000040803fe00a516
await sendCommand(CMD_FIN3); // 680600006e16
await sendCommand(CMD_WRITE, [0xce, 0xae, 0x49, 0x31, 0x42, 0x0d, 0x01, 0xf3, 0xef, 0xf6, 0x67, 0xc8, 0x3a, 0x2e, 0x0c, 0x99]); // 68220010ceae4931420d01f3eff667c83a2e0c99 f416
await sendCommand(CMD_UUID); // 680f00007716
log("OK");
log("Update Successful");
} catch (e) {
console.error(e);
log("Error: " + e.message);
} finally {
if (device && device.opened) device.close();
log("Disconnected.");
}
}
document.getElementById('fileInput').addEventListener('change', async e => {
const file = e.target.files[0];
if (!file) return;
try {
// Read file as text
const text = await file.text();
console.log("HEX preview:", text.slice(0, 64));
// Parse HEX into contiguous firmware bytes
firmware = parseIntelHexContiguous(text);
log(`Loaded ${firmware.length} bytes from ${file.name}`);
console.log("Firmware preview:", firmware.slice(0, 32));
} catch (err) {
console.error("Failed to load HEX file:", err);
log("Error loading HEX: " + err.message);
}
});
// --- Parser that ignores addresses and returns contiguous bytes ---
function parseIntelHexContiguous(data) {
const firmware = [];
data = data.replace(/\r\n/g, "\n"); // normalize line endings
const lines = data.split("\n");
for (let lineNum = 0; lineNum < lines.length; lineNum++) {
const line = lines[lineNum].trim();
if (!line) continue;
if (line[0] !== ":") throw new Error(`Line ${lineNum + 1} does not start with ':'`);
const byteCount = parseInt(line.substr(1, 2), 16);
const recordType = parseInt(line.substr(7, 2), 16);
const dataField = line.substr(9, byteCount * 2);
const checksum = parseInt(line.substr(9 + byteCount * 2, 2), 16);
const dataBytes = byteCount > 0
? Array.from(dataField.match(/.{2}/g).map(b => parseInt(b, 16)))
: [];
// Verify checksum
let sum = byteCount + parseInt(line.substr(3,2),16) + parseInt(line.substr(5,2),16) + recordType;
for (let b of dataBytes) sum += b;
sum = (sum + checksum) & 0xFF;
if (sum !== 0) throw new Error(`Checksum error on line ${lineNum + 1}`);
switch (recordType) {
case 0x00: // Data record
firmware.push(...dataBytes);
break;
case 0x01: // End of file
return new Uint8Array(firmware);
case 0x04: // Extended linear address, ignore
default:
break;
}
}
throw new Error("Missing EOF record in HEX file");
}
async function buildFinalizeBlock(firmware) {
const size = firmware.length;
// Calculate 32-bit additive checksum (sum of 16-bit words)
let sum = 0;
for (let i = 0; i < firmware.length; i++){
sum = (sum + firmware[i]) >>> 0; // 32-bit wrap
}
const toBE = v => [24,16,8,0].map(s => (v >> s) & 0xFF);
const sizeBytes = toBE(size);
const sumBytes = toBE(sum);
// Return combined payload
return sizeBytes.concat(sumBytes);
}
document.getElementById('flashBtn').addEventListener('click', flashFirmware);
</script>
</body>
</html>