-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
7741 lines (7184 loc) · 337 KB
/
Copy pathapp.py
File metadata and controls
7741 lines (7184 loc) · 337 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import json
import ipaddress
import os
import re
import shutil
import subprocess
import sys
import threading
import time
import webbrowser
from datetime import datetime
from pathlib import Path
from threading import RLock
from typing import Any
from urllib.error import HTTPError, URLError
from urllib import request as urlrequest
from urllib.parse import urlsplit
import cv2
from flask import Flask, jsonify, render_template, render_template_string, request, send_file
from jinja2 import TemplateNotFound
from camera_manager import CameraCaptureError, CameraManager, mask_camera_url, mjpeg_generator
from config_manager import ConfigManager
from console_log import ConsoleLog
from job_manager import JobManager
from ray5_client import Ray5Client
from ray5_status_monitor import Ray5StatusMonitor
BASE_DIR = Path(__file__).resolve().parent
app = Flask(__name__, template_folder=str(BASE_DIR / "web" / "templates"), static_folder=str(BASE_DIR / "web" / "static"))
@app.before_request
def guard_state_changing_requests():
if request.method not in {"POST", "PUT", "PATCH", "DELETE"}:
return None
if request.headers.get("X-Ray5-Pilot-Request") == "1":
return None
if request.headers.get("X-Requested-With") == "XMLHttpRequest":
return None
console.add(
"warn",
f"[REQUEST GUARD BLOCKED] method={request.method} path={request.path} remote_addr={request.remote_addr}",
)
return jsonify({"ok": False, "error": "Request guard header missing."}), 403
@app.after_request
def add_security_headers(response):
response.headers.setdefault("X-Content-Type-Options", "nosniff")
response.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
response.headers.setdefault("Referrer-Policy", "no-referrer")
response.headers.setdefault("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
req_path = str(getattr(request, "path", "") or "")
if (
req_path.startswith("/api/")
or req_path.startswith("/debug")
or req_path.startswith("/update_logs")
or req_path.startswith("/backups")
):
response.headers.setdefault("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
response.headers.setdefault("Pragma", "no-cache")
response.headers.setdefault("Expires", "0")
return response
ESP32_TEMPLATE_FALLBACK = r"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Ray5 Pilot ESP32</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
<link rel="alternate icon" href="/static/favicon.ico">
<link rel="stylesheet" href="/static/style.css">
<style>
:root{
--esp-bg:#101622;
--esp-bg-soft:#151c2b;
--esp-border:#2b364d;
--esp-text:#d6deef;
--esp-muted:#9fb0cf;
--esp-focus:#3ea6ff;
--esp-amber-bg:#2a2111;
--esp-green-bg:#162a1f;
--esp-red-bg:#2a181b;
--esp-orange-bg:#2c2114;
}
.esp-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}
.esp-info-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
.cmd-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px}
.edit-controls-grid{display:grid;grid-template-columns:2fr 1fr;gap:12px;align-items:start}
.edit-controls-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center}
.edit-controls-meta{display:flex;flex-direction:column;gap:8px}
.checkbox-group{display:flex;flex-direction:column;gap:6px}
.checkbox-group label{display:flex;align-items:center;gap:8px}
.action-row{display:flex;justify-content:space-between;align-items:center;gap:10px;flex-wrap:wrap}
.action-main{display:flex;gap:8px;flex-wrap:wrap}
.kv{border:1px solid var(--esp-border);border-radius:8px;padding:8px;background:var(--esp-bg-soft)}
.kv .k{font-size:12px;color:var(--esp-muted)}
.kv .v{font-weight:600;word-break:break-word;color:var(--esp-text)}
.badge{display:inline-block;padding:2px 8px;border-radius:999px;background:#1b2740;color:#b8c8ea;font-size:12px;border:1px solid #2f436c}
.unsaved-badge{display:inline-block;padding:3px 10px;border-radius:999px;font-size:12px;border:1px solid var(--esp-border);background:#182136;color:var(--esp-muted)}
.unsaved-badge.has-changes{background:var(--esp-amber-bg);border-color:#5a4420;color:#f0c37a}
.mono{font-family:ui-monospace,SFMono-Regular,Consolas,monospace}
.table-wrap{max-height:60vh;overflow:auto;border:1px solid var(--esp-border);border-radius:8px;width:100%}
.table-wrap table{margin:0;width:100%;table-layout:auto}
.table-wrap thead th{position:sticky;top:0;background:#141c2c;z-index:1}
.table-wrap th,.table-wrap td{background:transparent;color:var(--esp-text)}
td.compact-cell{white-space:nowrap}
.value-input{height:30px;padding:4px 8px;line-height:1.2;background:#0f1726;color:var(--esp-text);border:1px solid var(--esp-border);border-radius:6px}
.value-input:focus{outline:none;border-color:var(--esp-focus);box-shadow:0 0 0 1px color-mix(in srgb, var(--esp-focus) 45%, transparent)}
.value-input.text{min-width:200px}
.value-input.number{width:120px}
.value-input.ip{width:160px}
.value-input.select{min-width:170px}
.sensitive-wrap{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.sensitive-note{font-size:12px;color:var(--esp-muted)}
.options-muted{font-size:12px;color:var(--esp-muted)}
.row-changed td{background:var(--esp-amber-bg)!important}
.row-changed .value-input,.row-changed .edit-input{border-color:#6a4d23}
.muted-line{color:var(--esp-muted);font-size:12px}
.status-badge{font-size:12px;padding:2px 6px;border-radius:6px;display:inline-block}
.status-changed{background:var(--esp-amber-bg);color:#f0c37a;border:1px solid #5a4420}
.status-saved{background:var(--esp-green-bg);color:#8fd6a8;border:1px solid #2f5f40}
.status-failed{background:var(--esp-red-bg);color:#f1a3a3;border:1px solid #6a2e34}
.status-blocked{background:var(--esp-orange-bg);color:#efb66d;border:1px solid #6b4a1f}
.status-validation{background:#2b1c15;color:#efaf7e;border:1px solid #724028}
.status-cancelled{background:#2a2233;color:#c5b4ec;border:1px solid #57457a}
.save-summary{margin-top:8px;font-size:13px;padding:8px 10px;border-radius:8px;background:#162338;border:1px solid #2c4062;color:#c4d6f6;display:none}
.save-summary.show{display:block}
.save-warning{margin-top:8px;font-size:12px;padding:8px 10px;border-radius:8px;background:#1d2230;border:1px solid #3a445d;color:#b9c7e8}
.details-group summary{cursor:pointer;color:var(--esp-muted)}
.details-group[open] summary{color:var(--esp-text)}
.path-col{display:flex;align-items:center;gap:6px}
.group-chip{font-size:10px;border:1px solid var(--esp-border);background:#1a2437;border-radius:999px;padding:1px 6px;color:var(--esp-muted)}
input,select,textarea{background:#0f1726;color:var(--esp-text);border:1px solid var(--esp-border);border-radius:6px}
input:focus,select:focus,textarea:focus{outline:none;border-color:var(--esp-focus);box-shadow:0 0 0 1px color-mix(in srgb, var(--esp-focus) 45%, transparent)}
@media (max-width:980px){.esp-grid,.esp-info-grid,.cmd-grid,.edit-controls-grid{grid-template-columns:1fr}}
</style>
</head>
<body>
<header>
<div class="brand brand-logo-only"><img src="/static/logo.svg" alt="Ray5 Pilot" class="brand-logo-main"></div>
<nav><a href="/">Dashboard</a><a href="/setup">Settings</a><a href="/machine-settings">GRBL</a><a href="/esp32">ESP32</a></nav>
</header>
<main>
<section class="card">
<h2>ESP32 / ESP3D</h2>
<div class="action-row">
<div class="action-main">
<button id="refreshAll">Refresh All</button>
<button id="openNative">Open Native ESP32 Page</button>
</div>
<details class="details-group">
<summary>More actions</summary>
<div class="button-row" style="margin-top:8px;">
<button id="refreshInfo">Refresh ESP3D Info</button>
<button id="refreshEeprom">Refresh EEPROM</button>
<button id="refreshWs">Refresh WS Status</button>
</div>
</details>
</div>
<div id="msg" class="muted small"></div>
</section>
<div class="esp-grid">
<section class="card">
<h2>ESP3D Info</h2>
<div id="espInfoGrid" class="esp-info-grid"></div>
<details class="details-group" style="margin-top:10px;"><summary>Raw ESP3D Info</summary><pre id="espInfoRaw" class="muted small mono"></pre></details>
</section>
<section class="card">
<h2>WebSocket Status</h2>
<div id="wsInfoGrid" class="esp-info-grid"></div>
<details class="details-group" style="margin-top:10px;"><summary>Advanced WebSocket JSON</summary><pre id="wsAdvanced" class="muted small mono"></pre></details>
</section>
</div>
<section class="card">
<h2>EEPROM Settings</h2>
<section class="card" style="margin-bottom:10px;">
<h3 style="margin-top:0;">Edit Controls</h3>
<div class="edit-controls-grid">
<div>
<div class="edit-controls-actions">
<button id="backupEeprom">Download Backup</button>
<button id="saveChanges" disabled>Save Changes</button>
<button id="discardChanges" disabled>Discard Changes</button>
</div>
<div id="backupStatus" class="muted small" style="margin-top:8px;"></div>
<div id="saveSummary" class="save-summary"></div>
</div>
<div class="edit-controls-meta">
<span id="changedBadge" class="unsaved-badge">Unsaved: 0</span>
</div>
</div>
<div class="save-warning">Changing ESP32 settings can affect Wi-Fi, network access, and controller behavior. Download a backup before saving.</div>
</section>
<div class="button-row" style="margin-top:8px; margin-bottom:8px;">
<input id="eepromFilter" placeholder="Search path/label/value" style="min-width:280px;width:100%;max-width:420px;">
</div>
<div class="table-wrap">
<table>
<thead><tr><th>Path</th><th>Label</th><th>Type</th><th>Value</th><th>Range</th><th>Options</th><th>Status</th></tr></thead>
<tbody id="eepromBody"></tbody>
</table>
</div>
</section>
<section class="card">
<h2>Backup List / Compare</h2>
<div class="button-row">
<select id="backupSelect" style="min-width:280px;"></select>
<button id="loadBackup">View Backup</button>
<button id="compareBackup">Compare To Current</button>
</div>
<pre id="backupView" class="muted small mono"></pre>
<pre id="backupDiff" class="muted small mono"></pre>
</section>
<section class="card">
<h2>Command Box</h2>
<div class="cmd-grid">
<div>
<h3>G-code (commandText)</h3>
<input id="gcodeCmd" placeholder="e.g. ?" style="width:100%">
<div class="button-row" style="margin-top:8px;"><button id="sendGcode">Send G-code</button></div>
<div id="gcodeLast" class="muted-line mono"></div>
</div>
<div>
<h3>ESP command (cmd / commandText auto)</h3>
<input id="espCmd" placeholder="e.g. [ESP800]json=yes" style="width:100%">
<div class="button-row" style="margin-top:8px;"><button id="sendEsp">Send ESP cmd</button></div>
<div id="espLast" class="muted-line mono"></div>
</div>
</div>
</section>
<section class="card">
<details class="details-group">
<summary>Raw Log</summary>
<div class="button-row" style="margin:8px 0;"><button id="clearRawLog">Clear Log</button></div>
<pre id="rawLog" class="muted small mono"></pre>
</details>
</section>
</main>
<script>
let eepromSettings=[];
let backupList=[];
let dirty={};
let rowStatus={};
let hasSessionBackup=false;
let sessionBackupDownloaded=false;
let latestBackup=null;
const NATIVE_ESP32_URL = {{ (native_esp32_url or '')|tojson }};
const NETWORK_SENSITIVE_PATHS = new Set([
'Sta/SSID',
'Sta/Password',
'Sta/IPMode',
'Sta/IP',
'Sta/Gateway',
'Sta/Netmask',
'AP/SSID',
'AP/Password',
'AP/IP',
'Http/Port',
'Radio/Mode'
]);
async function api(url, method='GET', body=null){
const opt={method,headers:{'Content-Type':'application/json','X-Ray5-Pilot-Request':'1'}};
if(body!==null) opt.body=JSON.stringify(body);
try{
const r=await fetch(url,opt);
let j={};
try{ j=await r.json(); }catch(_){ j={ok:false,error:`HTTP ${r.status}`}; }
j._http_status=r.status;
return j;
}catch(e){
return {ok:false,offline:true,error:`Request failed: ${e.message||e}`,_http_status:0};
}
}
function esc(v){return JSON.stringify(v,null,2)}
function setMsg(t){document.getElementById('msg').textContent=t;}
function setSaveSummary(t){
const el=document.getElementById('saveSummary');
if(!t){el.textContent='';el.classList.remove('show');return;}
el.textContent=t;
el.classList.add('show');
}
function maskSensitiveText(text){
return String(text||'').replace(/(password|pass|token|key|secret)\s*[:=]\s*[^\s,#\]]+/ig,'$1=******');
}
function logRaw(label,data){
const el=document.getElementById('rawLog');
const t='['+new Date().toLocaleTimeString()+'] '+label+'\n'+maskSensitiveText(esc(data))+'\n\n';
el.textContent=t+el.textContent;
}
function renderInfoGrid(el, rows){
el.innerHTML='';
rows.forEach(([k,v])=>{
const d=document.createElement('div');d.className='kv';
d.innerHTML=`<div class="k">${k}</div><div class="v">${v??''}</div>`;
el.appendChild(d);
});
}
function fmtOptions(options){
if(!Array.isArray(options)||!options.length) return '';
const parts=[];
for(const o of options){
if(o && typeof o==='object' && !Array.isArray(o)){
for(const [k,v] of Object.entries(o)) parts.push(`${k} = ${v}`);
} else parts.push(String(o));
}
return parts.join(', ');
}
function optionLabelForValue(options,value){
if(!Array.isArray(options)) return null;
const val=String(value??'');
for(const o of options){
if(o && typeof o==='object' && !Array.isArray(o)){
for(const [k,v] of Object.entries(o)) if(String(v)===val) return `${k} (${val})`;
}
}
return null;
}
function rangeText(minv,maxv){
const hasMin=minv!==undefined&&minv!==null&&String(minv)!=='';
const hasMax=maxv!==undefined&&maxv!==null&&String(maxv)!=='';
if(hasMin&&hasMax) return `${minv}\u2013${maxv}`;
if(hasMax) return String(maxv);
if(hasMin) return String(minv);
return '';
}
function statusMarkup(status){
if(!status) return '';
if(status.state==='Changed') return '<span class="status-badge status-changed">Changed</span>';
if(status.state==='Saved') return `<span class="status-badge status-saved" title="${status.message||''}">Saved${status.mode?` via ${status.mode}`:''}</span>`;
if(status.state==='Failed') return `<span class="status-badge status-failed" title="${status.message||''}">Failed</span>`;
if(status.state==='Blocked') return `<span class="status-badge status-blocked" title="${status.message||''}">Blocked</span>`;
if(status.state==='Validation error') return `<span class="status-badge status-validation" title="${status.message||''}">Validation error</span>`;
if(status.state==='Cancelled') return `<span class="status-badge status-cancelled" title="${status.message||''}">Cancelled</span>`;
return '';
}
function updateDirtyBadge(){
const c=Object.keys(dirty).length;
const badge=document.getElementById('changedBadge');
badge.textContent=`Unsaved: ${c}`;
badge.classList.toggle('has-changes', c>0);
const saveBtn=document.getElementById('saveChanges');
const canSave=c>0;
saveBtn.disabled=!canSave;
document.getElementById('discardChanges').disabled=(c===0);
}
function isSensitive(setting){
const s=((setting.path||'')+' '+(setting.label||'')).toLowerCase();
return /(password|pass|token|key|secret)/.test(s);
}
function renderValueEditor(setting, key){
const original = setting.raw_value ?? setting.value ?? '';
const current = (dirty[key]!==undefined)?dirty[key]:original;
if(isSensitive(setting)){
const changed = dirty[key]!==undefined;
return `<div class="sensitive-wrap"><label><input type="checkbox" data-k="${key}" class="sens-enable" ${changed?'checked':''}> Change password</label>${changed?`<input data-k="${key}" class="sens-input value-input text" type="password" placeholder="New value">`:'<span class="sensitive-note">Leave unchanged</span>'}</div>`;
}
const t=String(setting.type||'').toUpperCase();
if((t==='B' || (Array.isArray(setting.options)&&setting.options.length))){
const opts=[];
for(const o of (setting.options||[])) if(o&&typeof o==='object') for(const [k,v] of Object.entries(o)) opts.push({label:k,val:String(v)});
const html=opts.map(o=>`<option value="${o.val}" ${String(current)===o.val?'selected':''}>${o.label} (${o.val})</option>`).join('');
return `<select data-k="${key}" class="edit-input value-input select">${html}</select>`;
}
const inputType = t==='I'?'number':'text';
let inputClass='value-input text';
if(t==='I') inputClass='value-input number';
if(t==='A') inputClass='value-input ip';
return `<input data-k="${key}" class="edit-input ${inputClass}" type="${inputType}" value="${String(current).replace(/"/g,'"')}">`;
}
function renderEeprom(){
const body=document.getElementById('eepromBody');
const q=document.getElementById('eepromFilter').value.trim().toLowerCase();
body.innerHTML='';
eepromSettings.forEach(s=>{
const key=s.path||`idx:${s.index}`;
const orig=s.raw_value ?? s.value ?? '';
const hay=(`${s.group||''} ${s.path||''} ${s.label||''} ${orig}`).toLowerCase();
if(q && !hay.includes(q)) return;
const changed = dirty[key]!==undefined;
const status = changed ? {state:'Changed'} : (rowStatus[key] || null);
const tr=document.createElement('tr');
if(changed) tr.classList.add('row-changed');
tr.innerHTML=`
<td class="mono"><div class="path-col"><span class="group-chip">${s.group??''}</span><span>${s.path??''}</span></div></td>
<td>${s.label??''}</td>
<td>${s.type??''}</td>
<td>${renderValueEditor(s,key)}</td>
<td class="compact-cell">${rangeText(s.min,s.size_or_max)}</td>
<td><span class="options-muted">${fmtOptions(s.options||[])}</span></td>
<td>${statusMarkup(status)}</td>`;
body.appendChild(tr);
});
body.querySelectorAll('.edit-input').forEach(el=>{
el.addEventListener('change', ()=>{dirty[el.dataset.k]=el.value; rowStatus[el.dataset.k]={state:'Changed'}; updateDirtyBadge(); renderEeprom();});
});
body.querySelectorAll('.sens-enable').forEach(el=>{
el.addEventListener('change', ()=>{
const k=el.dataset.k;
if(!el.checked){ delete dirty[k]; delete rowStatus[k]; } else { dirty[k]=''; rowStatus[k]={state:'Changed'}; }
updateDirtyBadge(); renderEeprom();
});
});
body.querySelectorAll('.sens-input').forEach(el=>{
el.addEventListener('change', ()=>{dirty[el.dataset.k]=el.value; rowStatus[el.dataset.k]={state:'Changed'}; updateDirtyBadge();});
});
}
async function loadInfo(){
const d=await api('/api/esp32/info');
if(!d.ok){
renderInfoGrid(document.getElementById('espInfoGrid'),[
['Firmware Version',''],['Firmware Target',''],['Hardware',''],['Hostname',''],['Axis',''],
['Web Communication',''],['WebSocket Port',''],['WebSocket IPs',''],
['Primary SD',''],['Secondary SD',''],['Authentication',''],['HTTP Host',''],['HTTP Port','']
]);
document.getElementById('espInfoRaw').textContent=maskSensitiveText(typeof d.raw==='string'?d.raw:esc(d.raw||{}));
logRaw('ESP3D Info Offline', d);
setMsg('Timed out waiting for ESP32 info response. Ray5 may be offline or unreachable.');
return;
}
renderInfoGrid(document.getElementById('espInfoGrid'),[
['Firmware Version',d.fw_version||''],['Firmware Target',d.fw_target||''],['Hardware',d.fw_hw||''],['Hostname',d.hostname||''],['Axis',d.axis||''],
['Web Communication',d.web_communication||''],['WebSocket Port',d.websocket_port||''],['WebSocket IPs',Array.isArray(d.websocket_ips)?d.websocket_ips.join(', '):(d.websocket_ip||'')],
['Primary SD',d.primary_sd||''],['Secondary SD',d.secondary_sd||''],['Authentication',d.authentication||''],['HTTP Host',d.http_host||''],['HTTP Port',d.http_port||'']
]);
document.getElementById('espInfoRaw').textContent=maskSensitiveText(typeof d.raw==='string'?d.raw:esc(d.raw));
logRaw('ESP3D Info', d);
}
async function loadEeprom(){
const d=await api('/api/esp32/eeprom');
if(!d.ok){
eepromSettings=[];
dirty={};
renderEeprom();
logRaw('EEPROM Offline', d);
setMsg('Timed out waiting for ESP32 EEPROM response. Ray5 may be offline or unreachable.');
return;
}
eepromSettings=d.settings||[];
renderEeprom();
logRaw('EEPROM', d);
}
async function loadWsStatus(){
const d=await api('/api/status/live');
if(!d.ok){
renderInfoGrid(document.getElementById('wsInfoGrid'),[
['WebSocket Connected','false'],['PAGEID',''],['Active ID',''],
['State',''],['MPos',''],['WPos',''],
['Feed',''],['Spindle',''],['Last Raw Status','WebSocket disconnected or no status received.'],['Last Message Age',''],['Reconnect Count','']
]);
document.getElementById('wsAdvanced').textContent=esc(d);
logRaw('WS Offline', d);
return;
}
const latest=d.latest_status||{}; const parsed=latest.parsed||{};
renderInfoGrid(document.getElementById('wsInfoGrid'),[
['WebSocket Connected',String(d.websocket_connected??'')],['PAGEID',d.page_id??d.websocket_page_id??''],['Active ID',d.active_id??''],
['State',parsed.state??latest.state??''],['MPos',Array.isArray(parsed.mpos)?parsed.mpos.join(', '):''],['WPos',Array.isArray(parsed.wpos)?parsed.wpos.join(', '):''],
['Feed',parsed.feed??''],['Spindle',parsed.spindle??''],['Last Raw Status',d.last_raw_status??latest.raw??''],['Last Message Age',d.last_status_age_seconds??''],['Reconnect Count',d.reconnect_count??'']
]);
document.getElementById('wsAdvanced').textContent=esc(d);
}
async function loadBackups(){
const d=await api('/api/esp32/eeprom/backups');
if(!d.ok){
backupList=[]; latestBackup=null;
const sel=document.getElementById('backupSelect'); sel.innerHTML='';
document.getElementById('backupStatus').textContent='No backups available.';
logRaw('EEPROM Backups Offline', d);
return;
}
backupList=d.backups||[]; latestBackup=d.latest||null;
const sel=document.getElementById('backupSelect'); sel.innerHTML='';
backupList.forEach(b=>{const o=document.createElement('option');o.value=b.name;o.textContent=`${b.name} (${b.setting_count??'?'} settings)`;sel.appendChild(o);});
hasSessionBackup = backupList.length>0;
document.getElementById('backupStatus').textContent = backupList.length ? `Latest backup: ${backupList[0].name}` : 'No backups yet for this folder.';
updateDirtyBadge();
}
async function doBackup(){
const d=await api('/api/esp32/eeprom/backup','POST',{});
hasSessionBackup=true;
sessionBackupDownloaded=true;
document.getElementById('backupStatus').textContent=`Backup created: ${d.backup_file} (${d.setting_count} settings)`;
await loadBackups();
logRaw('EEPROM Backup', d);
return d;
}
function triggerBackupDownload(filename){
const a=document.createElement('a');
a.href=`/api/esp32/eeprom/backups/${encodeURIComponent(filename)}/download`;
a.style.display='none';
document.body.appendChild(a);
a.click();
a.remove();
}
async function saveChanges(){
if(!Array.isArray(eepromSettings) || !eepromSettings.length){
setMsg('Cannot save ESP32 settings because EEPROM settings are not loaded.');
return;
}
const changes=[];
const changedPaths=[];
for(const s of eepromSettings){
const key=s.path||`idx:${s.index}`;
if(dirty[key]===undefined) continue;
changes.push({path:s.path,type:s.type,value:dirty[key]});
changedPaths.push(s.path);
}
if(!changes.length) return;
const networkTouched = changedPaths.filter((p)=>NETWORK_SENSITIVE_PATHS.has(String(p||'')));
if(networkTouched.length){
const confirmedNetwork = confirm('You are changing network-related ESP32 settings. This could disconnect Ray5 Pilot from the laser. Continue?');
if(!confirmedNetwork){
networkTouched.forEach((p)=>{ rowStatus[p] = {state:'Cancelled', message:'network warning cancelled'}; });
renderEeprom();
logRaw('EEPROM Save Cancelled', {reason:'network warning cancelled', paths: networkTouched});
setMsg('Save cancelled.');
return;
}
}
if(!sessionBackupDownloaded){
const confirmedNoBackup = confirm('No current EEPROM backup has been downloaded this session. It is recommended to download a backup first. Continue anyway?');
if(!confirmedNoBackup){
changedPaths.forEach((p)=>{ rowStatus[p] = {state:'Cancelled', message:'backup warning cancelled'}; });
renderEeprom();
logRaw('EEPROM Save Cancelled', {reason:'backup warning cancelled', paths: changedPaths});
setMsg('Save cancelled.');
return;
}
}
const payload={
changes,
backup_required: false,
allow_network_changes: true
};
const resp = await fetch('/api/esp32/eeprom/save',{
method:'POST',
headers:{'Content-Type':'application/json','X-Ray5-Pilot-Request':'1'},
body: JSON.stringify(payload)
});
let d={};
try{ d=await resp.json(); }catch(_){ d={ok:false,error:`HTTP ${resp.status}`}; }
logRaw('EEPROM Save', d);
const results = Array.isArray(d.results) ? d.results : [];
let savedAny = false;
for(const r of results){
const k = r.path || '';
if(!k) continue;
if(r.ok){
savedAny = true;
rowStatus[k] = {state:'Saved', mode:r.mode||'', message:r.response||r.message||''};
} else {
rowStatus[k] = {state:'Failed', mode:r.mode||'', message:r.response||r.message||''};
}
}
if(Array.isArray(d.failed)){
for(const f of d.failed){
const k = f.path || '';
if(!k) continue;
const msg = String(f.response||f.message||'');
const lower = msg.toLowerCase();
if(lower.includes('network-changing settings require confirmation')){
rowStatus[k] = {state:'Blocked', mode:f.mode||'', message:msg};
} else if(lower.includes('validation')){
rowStatus[k] = {state:'Validation error', mode:f.mode||'', message:msg};
} else {
rowStatus[k] = {state:'Failed', mode:f.mode||'', message:msg};
}
}
}
const okCount = Number(d.ok_count||0);
const failedCount = Number(d.failed_count||0);
const backupFile = d && d.backup && d.backup.file ? String(d.backup.file).split('/').pop() : '';
if(okCount>0 && failedCount===0){
setSaveSummary(`Saved ${okCount} setting${okCount===1?'':'s'}.${backupFile?` Backup created: ${backupFile}.`:''}`);
} else if(okCount>0 && failedCount>0){
setSaveSummary(`Saved ${okCount} setting${okCount===1?'':'s'}, ${failedCount} failed.${backupFile?` Backup created: ${backupFile}.`:''}`);
} else {
setSaveSummary(`Save failed. ${okCount} settings saved.`);
}
if(!resp.ok || !d.ok){ renderEeprom(); throw new Error((d.failed||[]).map(x=>x.path+': '+(x.response||x.message||'failed')).join('; ')||d.error||'Save failed'); }
dirty={}; updateDirtyBadge();
if(savedAny){ await loadEeprom(); }
renderEeprom();
setMsg('');
}
document.getElementById('refreshAll').onclick=async()=>{setMsg('Refreshing...'); await loadInfo(); await loadEeprom(); await loadWsStatus(); await loadBackups(); setMsg('Loaded.');};
document.getElementById('refreshInfo').onclick=async()=>{try{setMsg('Loading ESP3D info...');await loadInfo();setMsg('ESP3D info loaded.');}catch(e){setMsg('Info failed: '+e.message)}};
document.getElementById('refreshEeprom').onclick=async()=>{try{setMsg('Loading EEPROM...');await loadEeprom();setMsg('EEPROM loaded.');}catch(e){setMsg('EEPROM failed: '+e.message)}};
document.getElementById('refreshWs').onclick=async()=>{try{await loadWsStatus();setMsg('WS status loaded.');}catch(e){setMsg('WS status failed: '+e.message)}};
document.getElementById('openNative').onclick=async()=>{
const i=await api('/api/esp32/info');
const configuredNative=String((i&&i.native_url)||NATIVE_ESP32_URL||'').trim();
const fallbackNative=`http://${(i&&i.http_host)||'127.0.0.1'}:${(i&&i.http_port)||8848}`;
const targetUrl=configuredNative||fallbackNative;
if(!targetUrl){
setMsg('Open native failed: no native URL configured.');
return;
}
window.open(targetUrl,'_blank','noopener,noreferrer');
};
document.getElementById('sendGcode').onclick=async()=>{const c=document.getElementById('gcodeCmd').value.trim();if(!c)return;try{const d=await api('/api/esp32/command','POST',{command:c});document.getElementById('gcodeLast').textContent=maskSensitiveText(esc(d));logRaw('GCODE '+c,d);setMsg('G-code sent.');}catch(e){setMsg('G-code failed: '+e.message)}};
document.getElementById('sendEsp').onclick=async()=>{const c=document.getElementById('espCmd').value.trim();if(!c)return;try{const d=await api('/api/esp32/esp-command','POST',{cmd:c});document.getElementById('espLast').textContent=maskSensitiveText(esc(d));logRaw('ESP '+c,d);setMsg('ESP cmd sent.');}catch(e){setMsg('ESP cmd failed: '+e.message)}};
document.getElementById('backupEeprom').onclick=async()=>{
try{
const d=await doBackup();
if(!d || !d.backup_file) throw new Error('Backup file not returned');
triggerBackupDownload(d.backup_file);
setMsg('Backup downloaded.');
}catch(e){setMsg('Download backup failed: '+e.message)}
};
document.getElementById('loadBackup').onclick=async()=>{try{const n=document.getElementById('backupSelect').value;if(!n) throw new Error('Select a backup');const d=await api('/api/esp32/eeprom/backups/'+encodeURIComponent(n));document.getElementById('backupView').textContent=maskSensitiveText(esc(d));}catch(e){setMsg('View backup failed: '+e.message)}};
document.getElementById('compareBackup').onclick=async()=>{try{const n=document.getElementById('backupSelect').value;if(!n) throw new Error('Select a backup');const d=await api('/api/esp32/eeprom/compare?backup='+encodeURIComponent(n));document.getElementById('backupDiff').textContent=maskSensitiveText(esc(d));}catch(e){setMsg('Compare failed: '+e.message)}};
document.getElementById('discardChanges').onclick=()=>{dirty={};rowStatus={};updateDirtyBadge();renderEeprom();setSaveSummary('');setMsg('Unsaved changes discarded.');};
document.getElementById('saveChanges').onclick=async()=>{try{await saveChanges();}catch(e){setMsg('Save failed: '+e.message)}};
document.getElementById('eepromFilter').oninput=()=>renderEeprom();
document.getElementById('clearRawLog').onclick=()=>{document.getElementById('rawLog').textContent='';};
(async()=>{await loadInfo();await loadEeprom();await loadWsStatus();await loadBackups();updateDirtyBadge(); if(!eepromSettings.length){ setMsg('ESP32 page loaded. Some sections are offline.'); } else { setMsg('Loaded.'); }})();
</script>
</body>
</html>
"""
cfg_mgr = ConfigManager(BASE_DIR)
cfg = cfg_mgr.ensure_config()
console = ConsoleLog()
ray5 = Ray5Client(cfg)
camera = CameraManager(cfg, BASE_DIR)
jobs = JobManager(BASE_DIR, cfg)
_cached_status: dict[str, Any] = {"state": "UNKNOWN", "x": None, "y": None, "z": None, "raw": "", "source": "synthetic"}
_last_logged_status_source: str | None = None
_last_logged_job_progress_payload_signature: tuple[Any, ...] | None = None
_last_logged_job_progress_raw_override_signature: tuple[Any, ...] | None = None
_last_logged_job_progress_source_signature: tuple[Any, ...] | None = None
_last_logged_laser_power_signature: tuple[Any, ...] | None = None
_last_logged_laser_display_signature: tuple[Any, ...] | None = None
_status_error_logged = False
_watch_stop = threading.Event()
_watch_thread: threading.Thread | None = None
status_monitor: Ray5StatusMonitor | None = None
_placeholder_host_warned = False
_placeholder_api_warned = False
app_state_lock = RLock()
sd_list_lock = RLock()
runtime_started = False
ray5_comm_busy_lock = RLock()
ray5_comm_busy_state: dict[str, Any] = {
"active": False,
"reason": "",
"filename": "",
"started_at": None,
"expires_at": None,
"last_message": "",
}
timelapse_lock = RLock()
timelapse_capture_lock = RLock()
timelapse_stop_event = threading.Event()
timelapse_thread: threading.Thread | None = None
timelapse_stop_worker: threading.Thread | None = None
timelapse_duplicate_log_at: dict[str, float] = {}
timelapse_state: dict[str, Any] = {
"enabled": False,
"armed": False,
"active": False,
"paused": False,
"stopping": False,
"error": "",
"job_name": "",
"job_source": "",
"control_mode": "",
"started_at": None,
"last_snapshot_at": None,
"interval_seconds": 30,
"final_capture_delay_seconds": 3.0,
"playback_fps": 10.0,
"output_dir": "timelapse",
"snapshot_count": 0,
"session_dir": "",
"session_id": "",
"stop_pending": False,
"build_in_progress": False,
"stop_reason": "",
"stop_pending_session_id": "",
"status": "Disabled",
}
system_check_state: dict[str, Any] = {
"ray5_http_reachable": None,
"ray5_http_at": None,
"sd_card_list_working": None,
"sd_card_list_at": None,
"camera_test_passed": None,
"camera_test_at": None,
"last_auto_check_at": None,
"auto_check_in_progress": False,
"last_auto_check_log_at": None,
"last_active_skip_log_at": None,
}
ray5_comm_safety_state: dict[str, Any] = {
"comm_lost_during_job": False,
"last_known_machine_state": "",
"last_job_start_time": None,
"last_comm_ok_time": None,
"job_start_sent": False,
"message": "",
"entered_at": None,
"last_skip_log_at": None,
"last_suppressed_log_at": None,
}
upload_transfer_state: dict[str, Any] = {
"upload_in_progress": False,
"upload_kind": "",
"upload_filename": "",
"upload_started_at": None,
}
air_pump_state: dict[str, Any] = {
"state": "unknown",
"source": "unknown",
"updated_at": None,
"last_accessory_flags": "",
}
laser_runtime_state: dict[str, Any] = {
"instant_value": 0.0,
"active": False,
"state_label": "Off",
"last_nonzero_value": None,
"last_nonzero_at": None,
"peak_recent_value": None,
"recent_window_seconds": 3.0,
"source": "unknown",
}
laser_power_state: dict[str, Any] = {
"commanded_s": None,
"source": "unknown",
"updated_at": None,
"fire_test_active_until": None,
"fire_test_s": None,
"last_active_at": None,
"last_active_power_percent": None,
"last_active_s": None,
"hold_seconds": 3.0,
}
laser_job_power_cache: dict[str, dict[str, Any]] = {}
job_progress_state: dict[str, Any] = {
"active": False,
"complete": False,
"aborted": False,
"last_state": "",
"last_file": "",
"last_progress_percent": None,
"last_time_seconds": None,
"run_started_at": None,
"pause_started_at": None,
"paused_total_seconds": 0.0,
"controller_time_seconds": None,
"source": None,
}
github_update_status: dict[str, Any] = {
"checked": False,
"checking": False,
"ok": None,
"current_version": "unknown",
"latest_version": "",
"update_available": False,
"message": "Checking...",
"checked_at": None,
"last_checked": None,
"error": "",
"release_url": GITHUB_REPO_URL if "GITHUB_REPO_URL" in globals() else "",
"source_zip_url": "",
"source_zip_sha256": "",
"checksum_source": "",
"checksum_url": "",
"checksum_available": False,
"update_installable": False,
}
github_update_check_started = False
github_update_lock = RLock()
github_update_check_thread: threading.Thread | None = None
GITHUB_UPDATE_CACHE_TTL_SECONDS = 1800.0
camera_stream_clients = 0
camera_stream_clients_lock = RLock()
watch_state_lock = RLock()
watched_import_lock = RLock()
_watch_state: dict[str, Any] = {
"running": False,
"enabled": True,
"thread_name": "",
"last_poll_at": None,
"poll_seconds": 3.0,
"last_import_count": 0,
"last_error": "",
"status": "idle",
}
firmware_settings_collect_lock = RLock()
firmware_settings_collect_state: dict[str, Any] = {
"job_id": "",
"running": False,
"started_at": None,
"completed_at": None,
"ok": None,
"message": "Idle",
"error": "",
"timed_out": False,
"raw": "",
"settings": [],
"grbl_version": {},
"grbl_identity_raw": "",
}
console.add("info", f"CONFIG PATH: {cfg_mgr.config_path}")
console.add("info", f"CONFIG EXISTS: {cfg_mgr.config_path.exists()}")
console.add("info", f"RAY5 HOST: {cfg.get('ray5', {}).get('host', '')}")
console.add("info", f"RAY5 PORT: {cfg.get('ray5', {}).get('port', '')}")
console.add("info", f"RAY5 BASE URL: {ray5._base()}")
_SENSITIVE_DEBUG_TOKENS = ("password", "pass", "key", "token", "secret", "credential", "auth", "pwd", "ssid", "wifi", "sta", "ap_")
GITHUB_REPO_URL = "https://github.com/P0k3sm0t/Ray5-Pilot"
GITHUB_SOURCE_ZIP_FALLBACK_URL = "https://github.com/P0k3sm0t/Ray5-Pilot/archive/refs/heads/main.zip"
GITHUB_MAIN_VERSION_URL = "https://raw.githubusercontent.com/P0k3sm0t/Ray5-Pilot/main/VERSION"
GITHUB_LATEST_RELEASE_API_URL = "https://api.github.com/repos/P0k3sm0t/Ray5-Pilot/releases/latest"
UPDATE_STATUS_PATH = BASE_DIR / "update_logs" / "update_status.json"
_update_shutdown_started = False
calibration_lock = RLock()
calibration_process: subprocess.Popen[Any] | None = None
def _is_sensitive_key(name: str) -> bool:
n = str(name or "").strip().lower()
return any(tok in n for tok in _SENSITIVE_DEBUG_TOKENS)
def _sanitize_debug_value(key: str, value: str) -> str:
if _is_sensitive_key(key):
return "******"
v = str(value or "").strip()
if any(tok in v.lower() for tok in _SENSITIVE_DEBUG_TOKENS):
return "******"
return v
def _sanitize_debug_obj(obj: Any, key_name: str = "") -> Any:
if isinstance(obj, dict):
# ESP400 entries often describe field identity in P/H/F/K then store value in V.
descriptor = " ".join(
[
str(obj.get("P", "")),
str(obj.get("H", "")),
str(obj.get("F", "")),
str(obj.get("K", "")),
str(obj.get("name", "")),
str(obj.get("path", "")),
]
).lower()
descriptor_sensitive = any(tok in descriptor for tok in _SENSITIVE_DEBUG_TOKENS)
out: dict[str, Any] = {}
for k, v in obj.items():
k_str = str(k)
if _is_sensitive_key(k_str):
out[k_str] = "******"
continue
if k_str == "V" and descriptor_sensitive:
out[k_str] = "******"
continue
out[k_str] = _sanitize_debug_obj(v, key_name=k_str)
return out
if isinstance(obj, list):
return [_sanitize_debug_obj(item, key_name=key_name) for item in obj]
if isinstance(obj, str):
return _sanitize_debug_value(key_name, obj)
return obj
def _parse_and_sanitize_esp400(raw: str) -> Any:
txt = str(raw or "").strip()
if txt.startswith("{") or txt.startswith("["):
try:
parsed = json.loads(txt)
return _sanitize_debug_obj(parsed)
except Exception:
pass
lines: list[dict[str, str]] = []
for ln in txt.replace("\r", "\n").split("\n"):
s = ln.strip()
if not s:
continue
if "=" in s:
k, v = s.split("=", 1)
key = k.strip()
val = _sanitize_debug_value(key, v)
lines.append({"K": key, "V": val})
else:
lines.append({"K": s, "V": ""})
return lines
def _sanitize_plain_text_lines(raw: str) -> list[str]:
out: list[str] = []
for ln in str(raw or "").replace("\r", "\n").split("\n"):
s = ln.strip()
if not s:
continue
if ":" in s:
k, v = s.split(":", 1)
key = k.strip()
val = _sanitize_debug_value(key, v)
out.append(f"{key}: {val}")
elif "=" in s:
k, v = s.split("=", 1)
key = k.strip()
val = _sanitize_debug_value(key, v)
out.append(f"{key}={val}")
else:
if any(tok in s.lower() for tok in _SENSITIVE_DEBUG_TOKENS):
out.append("******")
else:
out.append(s)
return out
def _normalize_version_text(value: str) -> str:
txt = str(value or "").strip().lstrip("\ufeff")
if txt.lower().startswith("v"):
txt = txt[1:]
return txt
def _parse_version_parts(value: str) -> tuple[int, ...]:
core = _normalize_version_text(value).split("-", 1)[0].strip()
if not re.fullmatch(r"\d+(?:\.\d+)*", core):
return tuple()
parts = [int(token) for token in core.split(".")]
return tuple(parts)
def _compare_versions(current: str, latest: str) -> int:
cur = list(_parse_version_parts(current))
lat = list(_parse_version_parts(latest))
if not cur or not lat:
return 0
while len(cur) < len(lat):
cur.append(0)
while len(lat) < len(cur):
lat.append(0)
if cur < lat:
return -1
if cur > lat:
return 1
return 0
def _read_local_version() -> str:
try:
return _normalize_version_text((BASE_DIR / "VERSION").read_text(encoding="utf-8").strip())
except Exception:
return ""
def _fetch_remote_main_version(timeout_seconds: float = 5.0) -> str:
req = urlrequest.Request(
GITHUB_MAIN_VERSION_URL,
headers={"User-Agent": "Ray5-Pilot-UpdateCheck"},
method="GET",
)
with urlrequest.urlopen(req, timeout=timeout_seconds) as resp:
raw = resp.read().decode("utf-8", errors="replace").strip()
return _normalize_version_text(raw)
def _extract_sha256_from_text(text: str, expected_filename: str = "") -> str:
raw = str(text or "").strip()
if not raw:
return ""
expected = str(expected_filename or "").strip().lower()
lines = raw.splitlines() or [raw]
# Prefer hashes from lines that reference the expected ZIP name when available.
if expected:
for line in lines:
line_l = line.lower()
if expected not in line_l: