-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1739 lines (1718 loc) · 104 KB
/
Copy pathapp.js
File metadata and controls
1739 lines (1718 loc) · 104 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
"use strict";
const CONTROLLER_PROFILES = {
"grbl-fluidnc": {
label: "GRBL / FluidNC(標準)",
phase: "標準",
summary: "従来のGRBL / FluidNC互換設定です。既存のPlotterFlow動作を維持します。",
notes: [
"G21 / G90をG-codeヘッダへ出力します。",
"Stopはfeed hold(!)後にペンアップを送ります。",
"コマンドごとのok応答待ちは15秒です。"
],
settings: {
baudrate: 115200, header: "G21\nG90", footer: "",
penUpCommand: "M3 S1400", penDownCommand: "M3 S1000",
okTimeoutMs: 15000, stopStrategy: "hold-pen-up",
initializeCommand: "", disconnectCommand: ""
}
},
"xl330-pio": {
development: true,
label: "XL330 PIO / Pico・Pico 2(開発中)",
phase: "開発中",
summary: "PicoのPIOでXL330-M077-Tを直結し、X/Yを多回転制御する試作ファームウェア用です。",
notes: [
"Serial接続後、安全を確認して初期化(M17)を1回だけ実行します。M17時点がセッション原点です。",
"長い多回転移動に備えてok応答待ちを120秒へ延長します。",
"Stopは0x85で現在移動をキャンセルしてからペンアップを送ります。",
"切断時はM18を送り、3台のトルクを無効にします。",
"電源再投入後の多回転絶対位置は保持されないため、毎回原点確認が必要です。"
],
settings: {
baudrate: 115200, header: "G21\nG90", footer: "",
penUpCommand: "M3 S1400", penDownCommand: "M3 S1000",
okTimeoutMs: 120000, stopStrategy: "cancel-pen-up",
initializeCommand: "M17", disconnectCommand: "M18"
}
},
"xl330-pio-id1-test": {
development: true,
label: "XL330 ID1 単体安全テスト(開発中)",
phase: "実機テスト",
summary: "MOTION_LOCKED=1を維持したまま、ID 1のXL330を低速・小刻みで回転確認するCファーム専用プロファイルです。",
notes: [
"接続後の初期化はSCAN 1だけを送り、Pingと現在位置を読み出します。",
"X左右だけを正転・逆転JOGとして使用します。Y方向、通常G-code、M17、ペン指令はロックされたままです。",
"移動量の単位は回転です。初期値は1/16回転、1操作の上限は2回転です。",
"速度欄はmm/minではなくXL330のProfile Velocity raw値です。初期値20、上限100です。",
"各JOGの完了・停止・失敗後にTorqueをOFFにします。1台・無負荷・電流制限付き5 V電源で使用してください。"
],
capabilities: { jogCommand: "xl330-test", jogAxes: ["X"] },
settings: {
baudrate: 115200, header: "", footer: "",
penUpCommand: "G0 Z1", penDownCommand: "G0 Z0",
okTimeoutMs: 30000, stopStrategy: "cancel-pen-up",
initializeCommand: "SCAN 1", disconnectCommand: "M18", jogAutoDisable: false,
jogStep: 0.0625, jogFeed: 20
}
},
"rp2040-geek-sts3215-id2-id3": {
label: "RP2040/RP2350-GEEK STS3215 XYZ直結G-code",
phase: "動作確認",
summary: "Rθ差動化前に、G-codeのXYZをSTS3215へ直接割り当てて確認する暫定プロファイルです。",
notes: [
"暫定割当はID 2=X、ID 1=Y、ID 3=Zです。設定画面からXYZのID・pulse/mm・反転を変更できます。",
"Mode 0、Min/Max Angle Limit=0、Phase BIT4=1、Angle Resolution=1のときだけ動作し、符号付き約±7回転の範囲を使います。",
"送信開始時の現在位置をXYZ=0として、G0/G1のmm座標を絶対多回転位置へ変換します。ZはID 3のペン軸として有効です。",
"Z -5° / +5°はRθ差動化前の単体動作確認専用です。最終的な機械座標の意味はまだ確定していません。",
"移動後は元の位置へ戻りません。Torque OFF後も、次の指令はその時点の現在位置から加算されます。",
"速度はファームウェア側でraw 3400、加速度raw 150に固定されています。Stopは0x85で現在の往復動作を中止します。"
],
capabilities: {
jogCommand: "sts3215-test", jogAxes: ["X", "Y", "Z"],
directAxes: true, statusPolling: false
},
settings: {
baudrate: 115200, header: "G21\nG90", footer: "M18",
penUpCommand: "G0 Z1", penDownCommand: "G0 Z0",
okTimeoutMs: 20000, stopStrategy: "cancel-pen-up",
initializeCommand: "M17\nG21\nG90\nG10 L20 P0 X0 Y0", disconnectCommand: "M18", jogAutoDisable: false,
jogStep: 45, jogFeed: 3400, penUpDelay: 0, penDownDelay: 0, penUpClearanceDelay: 0,
stsAxisXId: 2, stsAxisYId: 1, stsAxisZId: 3,
stsAxisXPulsesPerMm: 128, stsAxisYPulsesPerMm: 128, stsAxisZPulsesPerMm: 128,
stsAxisXInvert: false, stsAxisYInvert: false, stsAxisZInvert: false, stsAxisZEnabled: true
}
},
"pico2-tmc2209-planar": {
development: true,
label: "Pico 2 TMC2209 XY Planar(開発中)",
phase: "開発中",
summary: "Pico 2とTMC2209 2個でA/B・C/D相のXY平面リニアステッパをG-code駆動する試作ファームウェア用です。",
notes: [
"初期キャンバスと確認範囲は30×30 mmを推奨します。0.1 mmジョグと低速feedから確認してください。",
"ジョブ送信時のヘッダでM17、G21、G90、G10 L20 P0 X0 Y0を送り、現在位置をワーク原点にします。",
"M3 S1400 / M3 S1000はペン互換コマンドとして維持します。実際のペン、電磁石、外部アクチュエータ割り当てはPico側で扱います。",
"Stopは0x85で現在移動をキャンセルしてからペンアップを送ります。",
"切断時はM18を送り、TMCドライバを無効にします。"
],
settings: {
baudrate: 115200, header: "M17\nG21\nG90\nG10 L20 P0 X0 Y0", footer: "M122 P\nM18",
penUpCommand: "M3 S1400", penDownCommand: "M3 S1000",
okTimeoutMs: 30000, stopStrategy: "cancel-pen-up",
initializeCommand: "M18\nG21\nG90", disconnectCommand: "M18", jogAutoDisable: true,
travelFeed: 500, drawFeed: 300, jogStep: 40, jogFeed: 2400,
sampleInterval: 0.5, optimization: "safe", yFlip: true
}
},
"pico2-drv8835-planar": {
development: true,
label: "Pico 2 DRV8835 XY Planar(開発中)",
phase: "開発中",
summary: "Pico 2とDRV8835 4個でXY平面リニアステッパを駆動し、GP12のPWMサーボでZ上下する試作ファームウェア用です。",
notes: [
"ジョブ開始前にM18で出力を止め、M281でGP12サーボを上1000us・下1800us・待機150msへ設定します。",
"M980で単相U1・XYピーク100%・停止後500ms保持・初期捕捉100ms・移動軸だけ励磁を設定します。",
"滑らか動作を試す場合はカスタム設定でU8へ変更できますが、通常運転は動作確認済みの単相励磁を優先します。",
"ペン上はG0 Z1、ペン下はG1 Z0です。DYNAMIXELプロファイルのM3 S1400/S1000は変更しません。",
"G0/G1と$Jジョグを使用し、診断用M974~M978は通常運転では送りません。",
"Stopは0x85で現在移動をキャンセルしてペンを上げ、切断時はM18で全DRV8835入力をLowへ戻します。",
"VM 3V、電源制限1.5A、各相1.5Ω直列抵抗から実機確認してください。"
],
capabilities: { positionSensors: true },
settings: {
baudrate: 115200,
header: "M18\nM281 U1000 D1800 T150 Z0.5\nM980 U1 X100 Y100 H500 A1 C100\nG0 Z1\nM17\nG21\nG90\nG10 L20 P0 X0 Y0 Z1",
footer: "M122\nM18",
penUpCommand: "G0 Z1", penDownCommand: "G1 Z0",
okTimeoutMs: 30000, stopStrategy: "cancel-pen-up",
initializeCommand: "M18\nM281 U1000 D1800 T150 Z0.5\nM980 U1 X100 Y100 H500 A1 C100\nG0 Z1\nG21\nG90",
disconnectCommand: "M18", jogAutoDisable: false,
travelFeed: 500, drawFeed: 300, jogStep: 2.5, jogFeed: 300,
sampleInterval: 0.5, optimization: "safe", yFlip: true
}
},
"m5stack-drv8835-planar": {
development: true,
label: "M5Stack Basic DRV8835 XY Planar(開発中)",
phase: "開発中",
summary: "M5Stack BasicとDRV8835 4個でXY平面リニアステッパとPWMサーボを制御し、USB実行、microSD保存、SDファイル管理に対応する試作ファームウェア用です。",
notes: [
"M5Stack起動時にUSB SERIALを選択すると、通常実行とmicroSDへのG-code転送をPlotterFlowから切り替えられます。",
"SD転送はM28/M29を使い、完了時だけ正式な.gcodeファイルとして確定します。",
"転送中はG-codeを実行せずDRV8835出力をLowへ戻します。",
"転送後はM5StackをSD CARDモードへ戻し、本体ボタンからファイルを選択して実行します。",
"停止・切断・転送失敗時は未完成ファイルを破棄します。",
"SDカード管理ではPCからモードを指定し、一覧同期、名前変更、削除ができます。"
],
capabilities: { sdUpload: true, sdManagement: true },
settings: {
baudrate: 115200,
header: "M18\nM281 U1400 D1000 T150 Z0.5\nM980 U1 X100 Y100 H500 A1 C100\nG0 Z1\nM17\nG21\nG90\nG10 L20 P0 X0 Y0 Z1",
footer: "M122\nM18",
penUpCommand: "G0 Z1", penDownCommand: "G1 Z0",
okTimeoutMs: 30000, stopStrategy: "cancel-pen-up",
initializeCommand: "M18\nM281 U1400 D1000 T150 Z0.5\nM980 U1 X100 Y100 H500 A1 C100\nG0 Z1\nG21\nG90",
disconnectCommand: "M18", jogAutoDisable: false,
travelFeed: 500, drawFeed: 300, jogStep: 2.5, jogFeed: 300,
sampleInterval: 0.5, optimization: "safe", yFlip: true
}
},
custom: {
label: "カスタム(値を維持)",
phase: "手動設定",
summary: "現在の各設定値を維持し、個別に調整します。プロファイルによる上書きは行いません。",
notes: ["接続先の仕様に合わせて、出力・接続欄とペン命令を手動で設定してください。"],
settings: null
}
};
const DEFAULTS = {
controllerProfile: "grbl-fluidnc",
penUpCommand: "M3 S1400", penDownCommand: "M3 S1000",
penUpDelay: 0.1, penDownDelay: 0.1, penUpClearanceDelay: 0.1, upDelayMode: "fixed",
longMoveThreshold: 100, penUpDelayShort: 0.1, penUpDelayLong: 0.3,
baseDelay: 0.1, delayPer100: 0.1, maxDelay: 1,
travelFeed: 500, drawFeed: 500, sampleInterval: 0.5,
scale: 1, offsetX: 0, offsetY: 0, yFlip: true,
optimization: "overlap_up", downLeadDistance: 5, requiredPenDownTime: 0.1,
baudrate: 115200, jogStep: 1, jogFeed: 1000, jogAutoDisable: false, header: "G21\nG90", footer: "",
okTimeoutMs: 15000, stopStrategy: "hold-pen-up", initializeCommand: "", disconnectCommand: "",
stsAxisXId: 2, stsAxisYId: 3, stsAxisZId: 1,
stsAxisXPulsesPerMm: 128, stsAxisYPulsesPerMm: 128, stsAxisZPulsesPerMm: 128,
stsAxisXInvert: false, stsAxisYInvert: false, stsAxisZInvert: false, stsAxisZEnabled: false,
serialDestination: "execute",
reloadGcode: `M3 S1600
G1 X0 Y45 F500
G1 Y-7 F500
G1 Y0 F500`
};
const DEVELOPMENT_MODE_KEY = "plotterflow.developmentModeV1";
const state = {
developmentMode: false,
settings: loadJSON("plotterflow.settings", DEFAULTS), svgText: "", paths: [], gcodeMoves: [],
library: loadJSON("plotterflow.library", []), jobSets: loadJSON("plotterflow.jobSets", []), currentId: null, currentJobSetId: null, port: null, reader: null, writer: null,
serialLogLimit: 200, lastSentLine: "", lastReceivedLine: "", lastOkAt: 0, lastSendAt: 0,
serialUiTimer: null, pendingSerialProgress: null, pendingPositionDisplay: false, pendingJobProgress: null,
readBuffer: "", okWaiters: [], sending: false, sdUploading: false, sdManagementActive: false, sdFiles: [], sdListReceiving: false, jogging: false, keyboardJogEnabled: false, paused: false, stopped: false, jobStopped: false,
previewMode: "svg", previewNormalizeY: false, position: null, machinePosition: null, workPosition: null, workOffset: null, controllerState: "未接続", statusPollTimer: null,
positionTelemetryEnabled: false,
positionSensors: { presentMask: 0, magnetMask: 0, joints: [{ raw: 0, degrees: 180 }, { raw: 0, degrees: 180 }] },
armCalibration: loadJSON("plotterflow.armCalibration", { offset1: 0, offset2: 0, invert1: false, invert2: false, calibrated: false })
};
const $ = (s, root = document) => root.querySelector(s);
const $$ = (s, root = document) => [...root.querySelectorAll(s)];
const fmt = n => Number(n.toFixed(3)).toString();
const sleep = ms => new Promise(r => setTimeout(r, ms));
function loadJSON(key, fallback) {
try {
const parsed = JSON.parse(localStorage.getItem(key));
if (parsed == null) return Array.isArray(fallback) ? [...fallback] : { ...fallback };
return Array.isArray(fallback) ? (Array.isArray(parsed) ? parsed : [...fallback]) : { ...fallback, ...parsed };
} catch { return Array.isArray(fallback) ? [...fallback] : { ...fallback }; }
}
function saveJSON(key, value) { localStorage.setItem(key, JSON.stringify(value)); }
function isDevelopmentProfile(profileId = state.settings.controllerProfile) {
return CONTROLLER_PROFILES[profileId]?.development === true;
}
function migrateDevelopmentMode() {
const saved = localStorage.getItem(DEVELOPMENT_MODE_KEY);
if (saved === null) {
state.developmentMode = isDevelopmentProfile() || state.settings.optimization === "overlap_down";
localStorage.setItem(DEVELOPMENT_MODE_KEY, state.developmentMode ? "1" : "0");
return;
}
state.developmentMode = saved === "1";
if (!state.developmentMode && isDevelopmentProfile()) {
state.developmentMode = true;
localStorage.setItem(DEVELOPMENT_MODE_KEY, "1");
}
}
function migrateDrv8835RobustMode() {
const migrationKey = "plotterflow.drv8835RobustModeV1";
if (localStorage.getItem(migrationKey)) return;
if (state.settings.controllerProfile === "pico2-drv8835-planar") {
const robustCommand = command => String(command || "").replace(/^M980[^\r\n]*$/m,
"M980 U1 X100 Y100 H500 A1 C100");
state.settings.header = robustCommand(state.settings.header);
state.settings.initializeCommand = robustCommand(state.settings.initializeCommand);
state.settings.jogStep = 2.5;
state.settings.jogFeed = 300;
saveJSON("plotterflow.settings", state.settings);
}
localStorage.setItem(migrationKey, "1");
}
function migrateDrv8835ServoDirection() {
const migrationKey = "plotterflow.drv8835ServoDirectionV1";
if (localStorage.getItem(migrationKey)) return;
if (state.settings.controllerProfile === "pico2-drv8835-planar") {
const reversedServo = command => String(command || "").replace(/^M281[^\r\n]*$/m,
"M281 U1000 D1800 T150 Z0.5");
state.settings.header = reversedServo(state.settings.header);
state.settings.initializeCommand = reversedServo(state.settings.initializeCommand);
saveJSON("plotterflow.settings", state.settings);
}
localStorage.setItem(migrationKey, "1");
}
function migrateSts3215DirectAxesProfile() {
if (state.settings.controllerProfile === "rp2040-geek-sts3215-id2-id3") {
const oldInitialize = cleanLines(String(state.settings.initializeCommand || ""));
const isOldScanOnly = oldInitialize.length === 2 && oldInitialize[0] === "SCAN 2" && oldInitialize[1] === "SCAN 3";
const compactInitialize = String(state.settings.initializeCommand || "").replace(/\s+/g, "").toUpperCase();
const isCollapsedOldScan = compactInitialize === "SCAN2SCAN3";
const isCollapsedDirectInit = compactInitialize === "M17G21G90G10L20P0X0Y0";
if (isOldScanOnly || isCollapsedOldScan || isCollapsedDirectInit || oldInitialize.length === 0) {
state.settings.initializeCommand = "M17\nG21\nG90\nG10 L20 P0 X0 Y0";
if (!String(state.settings.header || "").trim()) state.settings.header = "G21\nG90";
if (!String(state.settings.footer || "").trim()) state.settings.footer = "M18";
saveJSON("plotterflow.settings", state.settings);
}
}
const xyzMigrationKey = "plotterflow.sts3215X2Y1Z3V2";
if (!localStorage.getItem(xyzMigrationKey)) {
if (state.settings.controllerProfile === "rp2040-geek-sts3215-id2-id3") {
if (+state.settings.stsAxisXId === 2 && +state.settings.stsAxisYId === 3 && +state.settings.stsAxisZId === 1) {
state.settings.stsAxisYId = 1;
state.settings.stsAxisZId = 3;
}
state.settings.stsAxisZEnabled = true;
state.settings.stsAxisZPulsesPerMm = 128;
if (!String(state.settings.penUpCommand || "").trim()) state.settings.penUpCommand = "G0 Z1";
if (!String(state.settings.penDownCommand || "").trim()) state.settings.penDownCommand = "G0 Z0";
saveJSON("plotterflow.settings", state.settings);
}
localStorage.setItem(xyzMigrationKey, "1");
}
}
function toast(message) { const el = $("#toast"); el.textContent = message; el.classList.add("show"); clearTimeout(toast.timer); toast.timer = setTimeout(() => el.classList.remove("show"), 2200); }
function uid() { return crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`; }
function switchTab(name) { $$(".tab").forEach(x => x.classList.toggle("active", x.dataset.tab === name)); $$(".panel").forEach(x => x.classList.toggle("active", x.id === `tab-${name}`)); }
function installLocalTestBridge() {
if (!["127.0.0.1", "localhost"].includes(location.hostname)) return;
Object.defineProperties(window, {
state: { value: state, configurable: true },
CONTROLLER_PROFILES: { value: CONTROLLER_PROFILES, configurable: true }
});
}
function init() {
migrateDevelopmentMode();
migrateDrv8835RobustMode();
migrateDrv8835ServoDirection();
migrateSts3215DirectAxesProfile();
if (!localStorage.getItem("plotterflow.svgOrientationV1")) { state.settings.yFlip = true; saveJSON("plotterflow.settings", state.settings); localStorage.setItem("plotterflow.svgOrientationV1", "1"); }
$$(".tab").forEach(b => b.addEventListener("click", () => switchTab(b.dataset.tab)));
bindSvg(); bindEditor(); bindSettings(); bindSerial(); bindJobs();
populateSettings(); refreshLibrary(); updateEditorStats(); renderJobs();
if (!("serial" in navigator)) log("Web SerialはChrome/EdgeのHTTPSまたはlocalhostで利用できます。", "rx");
installLocalTestBridge();
document.documentElement.dataset.plotterflowReady = "true";
}
function bindSvg() {
const file = $("#svgFile"), drop = $("#dropZone");
file.addEventListener("change", () => file.files[0] && readSvgFile(file.files[0]));
["dragenter", "dragover"].forEach(e => drop.addEventListener(e, ev => { ev.preventDefault(); drop.classList.add("drag"); }));
["dragleave", "drop"].forEach(e => drop.addEventListener(e, ev => { ev.preventDefault(); drop.classList.remove("drag"); }));
drop.addEventListener("drop", e => e.dataTransfer.files[0] && readSvgFile(e.dataTransfer.files[0]));
$("#loadSvgText").addEventListener("click", () => loadSvg($("#svgText").value));
$("#generateGcode").addEventListener("click", () => generateGcode());
$("#generateAndSendSvg").addEventListener("click", generateAndSendSvg);
$("#svgOrientationFlip").addEventListener("change", event => { state.settings.yFlip=event.target.checked;$("#settingsForm").elements.yFlip.checked=event.target.checked;saveJSON("plotterflow.settings",state.settings); });
$("#showSvgPreview").addEventListener("click", () => setPreviewMode("svg"));
$("#showGcodePreview").addEventListener("click", () => setPreviewMode("gcode"));
}
async function readSvgFile(file) { if (!file.name.toLowerCase().endsWith(".svg")) return setSvgStatus("SVGファイルを選択してください。", true); loadSvg(await file.text(), file.name); }
function loadSvg(text, name = "") {
try {
const doc = new DOMParser().parseFromString(text, "image/svg+xml");
if (doc.querySelector("parsererror") || doc.documentElement.localName !== "svg") throw new Error("有効なSVGではありません");
doc.querySelectorAll("script,foreignObject").forEach(n => n.remove());
state.svgText = new XMLSerializer().serializeToString(doc.documentElement);
$("#svgText").value = state.svgText;
const host = mountSvgForMeasurement(state.svgText);
state.paths = extractPaths(host);
renderSvgPreview();
setSvgStatus(`${name ? name + ": " : ""}${state.paths.length}個の描画要素を読み込みました。`);
} catch (e) { setSvgStatus(e.message, true); }
}
function mountSvgForMeasurement(text) {
const doc = new DOMParser().parseFromString(text, "image/svg+xml"),host = $("#previewSvg");
[...host.attributes].forEach(a => !["id", "aria-label", "style"].includes(a.name) && host.removeAttribute(a.name));
host.innerHTML = doc.documentElement.innerHTML;
[...doc.documentElement.attributes].forEach(a => { if (a.name !== "xmlns") host.setAttribute(a.name, a.value); });
if (!host.getAttribute("viewBox")) {
const w = parseFloat(doc.documentElement.getAttribute("width")) || 100, h = parseFloat(doc.documentElement.getAttribute("height")) || 100;
host.setAttribute("viewBox", `0 0 ${w} ${h}`);
}
return host;
}
function setSvgStatus(msg, error = false) { const el = $("#svgStatus"); el.textContent = msg; el.classList.toggle("error", error); }
function extractPaths(svg) {
const supported = "path,line,polyline,polygon,rect,circle,ellipse";
const shapes = $$(supported, svg).filter(el => !el.closest("defs") && getComputedStyle(el).display !== "none" && getComputedStyle(el).visibility !== "hidden");
const viewBox = svg.viewBox.baseVal;
const mmScale = getSvgMmScale(svg, viewBox);
const intervalMm = Math.max(0.05, +state.settings.sampleInterval || .5);
const outputScale = Math.max(0.0001, Math.abs(+state.settings.scale || 1));
return shapes.map(el => {
let length;
try { length = el.getTotalLength(); } catch { return null; }
if (!Number.isFinite(length) || length <= 0) return null;
const rootCtm = svg.getScreenCTM(), elementCtm = el.getScreenCTM();
if (!rootCtm || !elementCtm) return null;
const ctm = rootCtm.inverse().multiply(elementCtm);
const localScale = Math.max(Math.hypot(ctm.a, ctm.b), Math.hypot(ctm.c, ctm.d)) * mmScale;
const count = Math.max(1, Math.ceil(length * localScale * outputScale / intervalMm));
const points = [];
for (let i = 0; i <= count; i++) {
const p = el.getPointAtLength(length * i / count);
const q = new DOMPoint(p.x, p.y).matrixTransform(ctm);
points.push({ x: q.x * mmScale, y: q.y * mmScale });
}
return points;
}).filter(Boolean);
}
function getSvgMmScale(svg, vb) {
const raw = svg.getAttribute("width") || ""; const value = parseFloat(raw);
const unit = (raw.match(/[a-z%]+/i) || [""])[0].toLowerCase();
const unitMm = { mm: 1, cm: 10, in: 25.4, pt: 25.4 / 72, pc: 25.4 / 6, px: 25.4 / 96 }[unit || "px"] || 25.4 / 96;
return value && vb.width ? value * unitMm / vb.width : 25.4 / 96;
}
function transformedPaths() {
return transformOutputPaths(state.paths);
}
function transformOutputPaths(sourcePaths) {
const s = state.settings; const scale = +s.scale || 1, ox = +s.offsetX || 0, oy = +s.offsetY || 0;
let paths = sourcePaths.map(path => path.map(p => ({ x: p.x * scale + ox, y: p.y * scale + oy })));
if (s.yFlip && paths.length) {
const ys = paths.flat().map(p => p.y), axis = Math.min(...ys) + Math.max(...ys);
paths = paths.map(path => path.map(p => ({ x: p.x, y: axis - p.y })));
}
return paths;
}
function requiredUpDelay(distance) {
const s = state.settings;
if (s.upDelayMode === "threshold") return distance >= +s.longMoveThreshold ? +s.penUpDelayLong : +s.penUpDelayShort;
if (s.upDelayMode === "distance") return Math.min(+s.maxDelay, +s.baseDelay + distance / 100 * +s.delayPer100);
return +s.penUpDelay;
}
function dwell(lines, seconds) { if (seconds > 0.0001) lines.push(`G4 P${fmt(seconds)}`); }
function appendTravelMove(lines, moves, from, to, feed, splitXThenY = false) {
if (!splitXThenY) {
lines.push(`G0 X${fmt(to.x)} Y${fmt(to.y)} F${fmt(feed)}`);
moves.push({ type: "travel", from, to });
return;
}
let current = from;
if (Math.abs(to.x - current.x) > 0.000001) {
const xTarget = { x: to.x, y: current.y };
lines.push(`G0 X${fmt(xTarget.x)} F${fmt(feed)}`);
moves.push({ type: "travel", from: current, to: xTarget });
current = xTarget;
}
if (Math.abs(to.y - current.y) > 0.000001) {
const yTarget = { x: current.x, y: to.y };
lines.push(`G0 Y${fmt(yTarget.y)} F${fmt(feed)}`);
moves.push({ type: "travel", from: current, to: yTarget });
}
}
function generateGcode(options = {}) {
if (!state.paths.length) return setSvgStatus("先にSVGを読み込んでください。", true);
state.paths = extractPaths(mountSvgForMeasurement(state.svgText));
return buildGcodeFromPaths(transformedPaths(), "", { normalizeYPreview: !!state.settings.yFlip, stayOnCurrentTab: !!options.stayOnCurrentTab });
}
async function generateAndSendSvg() {
const code = generateGcode({ stayOnCurrentTab: true });
if (code) {
$("#sdFilename").value = sanitizeSdFilename($("#gcodeName").value);
openSerialTrajectory(code, $("#gcodeName").value);
await startConfiguredTransfer(code, $("#gcodeName").value);
}
}
function buildGcodeFromPaths(paths, outputName = "", previewOptions = {}) {
const s = state.settings, lines = [], moves = [];
lines.push(...String(s.header).split(/\r?\n/).filter(Boolean));
let previous = { x: 0, y: 0 };
let isFirstDrawablePath = true;
for (const path of paths) {
if (path.length < 2) continue;
const start = path[0], distance = Math.hypot(start.x - previous.x, start.y - previous.y);
const splitInitialTravel = isFirstDrawablePath && isPicoDrv8835Profile();
lines.push(s.penUpCommand);
const upDelay = Math.max(0, requiredUpDelay(distance));
const travelSpeed = Math.max(1, +s.travelFeed) / 60;
const clearanceDelay = Math.min(upDelay, Math.max(0, +s.penUpClearanceDelay || 0));
const overlapEnabled = s.optimization === "overlap_up" || s.optimization === "overlap_down";
const preTravelDelay = overlapEnabled ? clearanceDelay : upDelay;
dwell(lines, preTravelDelay);
if (s.optimization === "overlap_down" && distance > +s.downLeadDistance) {
const lead = Math.min(distance, +s.downLeadDistance), ratio = (distance - lead) / distance;
const leadPoint = { x: previous.x + (start.x - previous.x) * ratio, y: previous.y + (start.y - previous.y) * ratio };
appendTravelMove(lines, moves, previous, leadPoint, +s.travelFeed, splitInitialTravel);
dwell(lines, Math.max(0, upDelay - preTravelDelay - (distance - lead) / travelSpeed));
lines.push(s.penDownCommand);
lines.push(`G0 X${fmt(start.x)} Y${fmt(start.y)} F${fmt(+s.travelFeed)}`); moves.push({ type: "travel", from: leadPoint, to: start });
const absorbed = lead / travelSpeed; dwell(lines, Math.max(0, +s.requiredPenDownTime - absorbed));
} else {
appendTravelMove(lines, moves, previous, start, +s.travelFeed, splitInitialTravel);
if (overlapEnabled) dwell(lines, Math.max(0, upDelay - preTravelDelay - distance / travelSpeed));
lines.push(s.penDownCommand); dwell(lines, +s.penDownDelay);
}
for (let i = 1; i < path.length; i++) {
const p = path[i], from = path[i - 1]; lines.push(`G1 X${fmt(p.x)} Y${fmt(p.y)} F${fmt(+s.drawFeed)}`); moves.push({ type: "draw", from, to: p });
}
previous = path[path.length - 1];
isFirstDrawablePath = false;
}
lines.push(s.penUpCommand); dwell(lines, +s.penUpDelay); lines.push(...String(s.footer).split(/\r?\n/).filter(Boolean));
$("#gcodeEditor").value = lines.join("\n"); state.gcodeMoves = moves; state.previewNormalizeY = !!previewOptions.normalizeYPreview; state.currentId = null;
$("#gcodeName").value = outputName ? ensureExt(outputName.replace(/\.plotter\.json$/i, "")) : `plot-${new Date().toISOString().slice(0, 19).replaceAll(":", "-")}.gcode`;
updateEditorStats(); setPreviewMode("gcode"); renderGcodePreview(); if (!previewOptions.stayOnCurrentTab) switchTab("gcode"); toast("G-codeを生成しました");
return lines.join("\n");
}
function generateFromLayoutPaths(paths, outputName = "") { return buildGcodeFromPaths(transformOutputPaths(paths), outputName, { normalizeYPreview: !!state.settings.yFlip }); }
function notifyReloadSimulation(code = state.settings.reloadGcode) { window.dispatchEvent(new CustomEvent("plotterflow:reload-start", { detail: { gcode: code || "" } })); }
function simulationGcodeOptions() { return [{ id: "editor", name: "現在のエディタ" }, ...state.library.map(item => ({ id: item.id, name: item.name }))]; }
function simulationGcode(id) { return id === "editor" ? $("#gcodeEditor").value : state.library.find(item => item.id === id)?.gcode || ""; }
window.PlotterFlow = { generateFromPaths: generateFromLayoutPaths, switchTab, getSettings: () => state.settings, parseGcodeMoves, simulateReload: notifyReloadSimulation, simulationGcodeOptions, simulationGcode };
function setPreviewMode(mode) { state.previewMode = mode; $("#showSvgPreview").classList.toggle("active", mode === "svg"); $("#showGcodePreview").classList.toggle("active", mode === "gcode"); mode === "svg" ? renderSvgPreview() : renderGcodePreview(); }
function renderSvgPreview() { if (!state.svgText) return; const svg = $("#previewSvg"); svg.style.display = "block"; }
function renderGcodePreview() {
const svg = $("#previewSvg"); let moves = parseGcodeMoves($("#gcodeEditor").value);
let previewPosition = state.position;
if (state.previewNormalizeY && moves.length) {
const drawnPoints = moves.filter(m => m.type === "draw").flatMap(m => [m.from, m.to]);
const referencePoints = drawnPoints.length ? drawnPoints : moves.flatMap(m => [m.from, m.to]);
const ys = referencePoints.map(p => p.y), axis = Math.min(...ys) + Math.max(...ys);
const flipPoint = p => ({ x: p.x, y: axis - p.y });
moves = moves.map(m => ({ ...m, from: flipPoint(m.from), to: flipPoint(m.to) }));
if (previewPosition) previewPosition = flipPoint(previewPosition);
}
renderTrajectorySvg(svg, moves, previewPosition);
if ($("#serialSource")?.value === "editor") renderSerialTrajectory($("#gcodeEditor").value, $("#gcodeName").value);
}
function renderTrajectorySvg(svg, moves, previewPosition = null) {
const pts = moves.flatMap(m => [m.from, m.to]); if (!pts.length) { svg.innerHTML = ""; svg.removeAttribute("viewBox"); return; }
const xs = pts.map(p => p.x), ys = pts.map(p => p.y), pad = Math.max(5, (Math.max(...xs)-Math.min(...xs))*.05);
svg.setAttribute("viewBox", `${Math.min(...xs)-pad} ${Math.min(...ys)-pad} ${Math.max(...xs)-Math.min(...xs)+2*pad || 10} ${Math.max(...ys)-Math.min(...ys)+2*pad || 10}`);
svg.innerHTML = moves.map(m => `<line x1="${m.from.x}" y1="${m.from.y}" x2="${m.to.x}" y2="${m.to.y}" stroke="${m.type === "draw" ? "#087985" : "#df8a32"}" stroke-width="0.5" ${m.type === "travel" ? 'stroke-dasharray="2 2"' : ""} vector-effect="non-scaling-stroke"/>`).join("") + (previewPosition ? `<circle cx="${previewPosition.x}" cy="${previewPosition.y}" r="2" fill="#d02f52" vector-effect="non-scaling-stroke"/>` : "");
}
function renderSerialTrajectory(code, name = "送信データ") {
renderTrajectorySvg($("#serialTrajectorySvg"), parseGcodeMoves(String(code || "")), state.position);
$("#serialTrajectoryName").textContent = name || "送信データ";
}
function renderSelectedSerialTrajectory() {
const payload = selectedSerialPayload();
renderSerialTrajectory(payload.code, payload.name);
}
function scrollToSerialTrajectory() {
requestAnimationFrame(() => requestAnimationFrame(() => $("#serialTrajectoryCard").scrollIntoView({ behavior: "smooth", block: "start" })));
}
function openSerialTrajectory(code, name) {
switchTab("serial");
renderSerialTrajectory(code, name);
scrollToSerialTrajectory();
}
function parseGcodeMoves(code) {
let pos = { x: 0, y: 0 }, absolute = true; const moves = [];
for (const raw of code.split(/\r?\n/)) {
const line = raw.replace(/;.*|\([^)]*\)/g, "").trim().toUpperCase();
if (/\bG90\b/.test(line)) absolute = true; if (/\bG91\b/.test(line)) absolute = false;
const motion = line.match(/\bG([01])\b/); if (!motion) continue;
const xm = line.match(/\bX(-?\d*\.?\d+)/), ym = line.match(/\bY(-?\d*\.?\d+)/); if (!xm && !ym) continue;
const to = { x: xm ? (absolute ? +xm[1] : pos.x + +xm[1]) : pos.x, y: ym ? (absolute ? +ym[1] : pos.y + +ym[1]) : pos.y };
moves.push({ type: motion[1] === "0" ? "travel" : "draw", from: { ...pos }, to }); pos = to;
}
return moves;
}
function bindEditor() {
$("#gcodeEditor").addEventListener("input", () => { state.previewNormalizeY = false; updateEditorStats(); if (state.previewMode === "gcode") renderGcodePreview(); });
$("#gcodeName").addEventListener("input", () => updateSdFilenameFromSource(true));
$("#saveGcode").addEventListener("click", saveCurrentGcode); $("#downloadGcode").addEventListener("click", downloadGcode); $("#downloadSdGcode").addEventListener("click", downloadSdGcode);
$("#newGcode").addEventListener("click", () => loadEditor(null)); $("#duplicateGcode").addEventListener("click", duplicateGcode);
$("#renameGcode").addEventListener("click", renameGcode); $("#deleteGcode").addEventListener("click", deleteGcode);
$("#gcodeLibrary").addEventListener("change", e => loadEditor(e.target.value));
$("#gcodeFile").addEventListener("change", event => event.target.files[0] && loadGcodeFile(event.target.files[0]));
$("#sendFromEditor").addEventListener("click", () => { const code=$("#gcodeEditor").value,name=$("#gcodeName").value; openSerialTrajectory(code,name); $("#sdFilename").value = sanitizeSdFilename(name); startConfiguredTransfer(code,name); });
}
async function loadGcodeFile(file) {
if (!/\.(gcode|nc|tap|txt)$/i.test(file.name)) return toast("G-codeファイルを選択してください");
state.currentId = null; state.previewNormalizeY = false;
$("#gcodeName").value = ensureExt(file.name); $("#gcodeEditor").value = await file.text();
$("#gcodeLibrary").value = ""; updateEditorStats(); renderGcodePreview(); toast(`${file.name}を読み込みました`);
}
function updateEditorStats() { const text = $("#gcodeEditor").value, lines = text ? text.split(/\r?\n/).length : 0; $("#gcodeStats").textContent = `${lines}行 / ${new Blob([text]).size} bytes`; }
function refreshLibrary() {
const select = $("#gcodeLibrary"), source = $("#serialSource");
const options = state.library.sort((a,b) => b.updated-a.updated).map(x => `<option value="${x.id}">${escapeHtml(x.name)}</option>`).join("");
select.innerHTML = `<option value="">未選択</option>${options}`; source.innerHTML = `<option value="editor">現在のエディタ</option><option value="__reload__">リロード動作(設定)</option>${options}`;
if (state.currentId) select.value = state.currentId; renderJobs();
window.dispatchEvent(new CustomEvent("plotterflow:gcode-library-changed"));
}
function saveCurrentGcode() {
const name = ensureExt($("#gcodeName").value.trim() || "untitled.gcode"), gcode = $("#gcodeEditor").value;
let item = state.library.find(x => x.id === state.currentId);
if (item) Object.assign(item, { name, gcode, settings: { ...state.settings }, updated: Date.now() });
else { item = { id: uid(), name, gcode, settings: { ...state.settings }, updated: Date.now() }; state.library.push(item); state.currentId = item.id; }
saveJSON("plotterflow.library", state.library); refreshLibrary(); toast("G-codeを保存しました");
}
function loadEditor(id) { const item = state.library.find(x => x.id === id); state.currentId = item?.id || null; state.previewNormalizeY = false; $("#gcodeName").value = item?.name || "untitled.gcode"; $("#gcodeEditor").value = item?.gcode || ""; updateEditorStats(); updateSdFilenameFromSource(true); renderGcodePreview(); }
function duplicateGcode() { const item = state.library.find(x => x.id === state.currentId); if (!item) return toast("複製するG-codeを選択してください"); state.currentId = null; $("#gcodeName").value = item.name.replace(/(\.gcode)?$/, "-copy.gcode"); saveCurrentGcode(); }
function renameGcode() { const item = state.library.find(x => x.id === state.currentId); if (!item) return toast("名前を変更する項目を選択してください"); const name = prompt("新しい名前", item.name); if (name) { item.name = ensureExt(name); item.updated = Date.now(); saveJSON("plotterflow.library", state.library); refreshLibrary(); $("#gcodeName").value = item.name; } }
function deleteGcode() { if (!state.currentId || !confirm("選択中のG-codeを削除しますか?")) return; state.library = state.library.filter(x => x.id !== state.currentId); saveJSON("plotterflow.library", state.library); loadEditor(null); refreshLibrary(); }
function downloadGcode() { const blob = new Blob([$("#gcodeEditor").value], { type: "text/plain" }), a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = ensureExt($("#gcodeName").value); a.click(); URL.revokeObjectURL(a.href); }
function downloadSdGcode() {
if (!isSts3215DirectAxes()) return toast("STS3215 XYZ直結プロファイルを選択してください");
const setup = [sts3215AxisConfigCommand(), "M17", "G21", "G90", "G10 L20 P0 X0 Y0"];
const body = cleanLines($("#gcodeEditor").value);
const text = [...setup, ...body, "M18", ""].join("\n");
const blob = new Blob([text], { type: "text/plain" }), a = document.createElement("a");
const sourceName = ensureExt($("#gcodeName").value.trim() || "untitled.gcode");
a.href = URL.createObjectURL(blob);
a.download = sourceName.replace(/\.(gcode|nc|tap)$/i, "-sd.gcode");
a.click(); URL.revokeObjectURL(a.href);
toast("GEEK本体SD用G-codeをダウンロードしました");
}
function ensureExt(name) { return /\.(gcode|nc|tap)$/i.test(name) ? name : `${name}.gcode`; }
function escapeHtml(s) { const d = document.createElement("div"); d.textContent = s; return d.innerHTML; }
function bindSettings() {
$("#settingsForm").addEventListener("submit", e => { e.preventDefault(); readSettings(); saveJSON("plotterflow.settings", state.settings); $("#svgOrientationFlip").checked=state.settings.yFlip; $("#serialBaud").value = state.settings.baudrate; updateSerialProfileDisplay(); $("#settingsStatus").textContent = "保存しました。"; toast("設定を保存しました"); });
$("#developmentModeToggle").addEventListener("change", handleDevelopmentModeChange);
$("#controllerProfile").addEventListener("change", event => applyControllerProfile(event.target.value));
$("#resetSettings").addEventListener("click", () => { if (confirm("設定を初期値へ戻しますか?")) { state.settings = { ...DEFAULTS }; populateSettings(); saveJSON("plotterflow.settings", state.settings); } });
}
function populateSettings() { const f = $("#settingsForm"); renderDevelopmentMode(); for (const [k,v] of Object.entries(state.settings)) if (f.elements[k]) f.elements[k].type === "checkbox" ? f.elements[k].checked = !!v : f.elements[k].value = v; $("#svgOrientationFlip").checked=state.settings.yFlip; $("#serialBaud").value = state.settings.baudrate; populateJogSettings(); renderControllerProfile(); updateSerialProfileDisplay(); }
function readSettings() { const f = $("#settingsForm"); for (const k of Object.keys(DEFAULTS)) if (f.elements[k]) state.settings[k] = f.elements[k].type === "checkbox" ? f.elements[k].checked : f.elements[k].type === "number" ? +f.elements[k].value : f.elements[k].value; }
function developmentModeBusy() {
return !!(state.port || state.sending || state.jogging || state.sdUploading || state.sdManagementActive);
}
function renderDevelopmentMode() {
const toggle = $("#developmentModeToggle"), select = $("#controllerProfile");
if (toggle) toggle.checked = state.developmentMode;
document.documentElement.dataset.developmentMode = state.developmentMode ? "true" : "false";
if (select) {
const selected = state.settings.controllerProfile;
select.replaceChildren(...Object.entries(CONTROLLER_PROFILES)
.filter(([, profile]) => state.developmentMode || !profile.development)
.map(([id, profile]) => new Option(profile.label, id, false, id === selected)));
}
const experimentalOptimization = $('#settingsForm [name="optimization"] option[value="overlap_down"]');
if (experimentalOptimization) {
experimentalOptimization.hidden = !state.developmentMode;
experimentalOptimization.disabled = !state.developmentMode;
}
const stsSettings = $("#stsDirectAxesSettings");
if (stsSettings) stsSettings.hidden = !isSts3215DirectAxes();
}
function handleDevelopmentModeChange(event) {
const requested = event.target.checked;
if (developmentModeBusy()) {
event.target.checked = state.developmentMode;
return toast("Serial接続・送信・ジョグ・SD操作中は開発中機能を切り替えられません");
}
const leavesDevelopmentProfile = !requested && isDevelopmentProfile();
const leavesExperimentalOptimization = !requested && state.settings.optimization === "overlap_down";
if ((leavesDevelopmentProfile || leavesExperimentalOptimization) && !confirm("開発中機能を非表示にして、通常設定へ切り替えますか?")) {
event.target.checked = true;
return;
}
state.developmentMode = requested;
localStorage.setItem(DEVELOPMENT_MODE_KEY, requested ? "1" : "0");
if (leavesExperimentalOptimization) state.settings.optimization = "overlap_up";
if (leavesDevelopmentProfile) return applyControllerProfile("grbl-fluidnc");
populateSettings();
saveJSON("plotterflow.settings", state.settings);
toast(requested ? "開発中機能を表示しました" : "開発中機能を非表示にしました");
}
function applyControllerProfile(profileId) {
if (state.sdManagementActive && profileId !== state.settings.controllerProfile) {
$("#controllerProfile").value = state.settings.controllerProfile;
return toast("SDカード管理を終了してからプロファイルを変更してください");
}
const previousProfile = state.settings.controllerProfile;
const profile = CONTROLLER_PROFILES[profileId] || CONTROLLER_PROFILES.custom;
if (profile.development && !state.developmentMode) {
$("#controllerProfile").value = previousProfile;
return toast("先に「開発中機能を表示」を有効にしてください");
}
if (previousProfile === "pico2-drv8835-planar" && profileId !== previousProfile && state.positionTelemetryEnabled) void setPositionTelemetryEnabled(false);
state.settings.controllerProfile = profileId;
if (profile.settings) Object.assign(state.settings, profile.settings);
populateSettings();
saveJSON("plotterflow.settings", state.settings);
$("#settingsStatus").textContent = `${profile.label}を反映しました。必要に応じて各値を調整して保存してください。`;
toast(`${profile.label}を反映しました`);
}
function activeControllerProfile() { return CONTROLLER_PROFILES[state.settings.controllerProfile] || CONTROLLER_PROFILES.custom; }
function isSts3215DirectAxes() { return activeControllerProfile().capabilities?.directAxes === true; }
function sts3215AxisConfigCommand() {
const s = state.settings;
const id = key => Math.max(0, Math.min(253, Math.round(+s[key] || 0)));
const ppm = key => Math.max(0.001, Math.min(28672, +s[key] || 128));
return `M950 X${id("stsAxisXId")} Y${id("stsAxisYId")} Z${id("stsAxisZId")} ` +
`PX${fmt(ppm("stsAxisXPulsesPerMm"))} PY${fmt(ppm("stsAxisYPulsesPerMm"))} PZ${fmt(ppm("stsAxisZPulsesPerMm"))} ` +
`IX${s.stsAxisXInvert ? 1 : 0} IY${s.stsAxisYInvert ? 1 : 0} IZ${s.stsAxisZInvert ? 1 : 0} EZ${s.stsAxisZEnabled ? 1 : 0}`;
}
function sts3215SetupLines() { return isSts3215DirectAxes() ? [sts3215AxisConfigCommand(), "M17"] : []; }
function renderControllerProfile() {
const profile = activeControllerProfile(), host = $("#controllerProfileDescription");
if (!host) return;
host.innerHTML = `<div class="profile-description-heading"><strong>${escapeHtml(profile.label)}</strong><span>${escapeHtml(profile.phase)}</span></div><p>${escapeHtml(profile.summary)}</p><ul>${profile.notes.map(note => `<li>${escapeHtml(note)}</li>`).join("")}</ul>`;
}
function updateSerialProfileDisplay() {
const profile = activeControllerProfile(), badge = $("#serialControllerProfile"), button = $("#initializeController");
if (badge) badge.textContent = profile.label;
if (button) {
const command = String(state.settings.initializeCommand || "").trim();
button.hidden = !command;
button.textContent = command ? `初期化 (${command})` : "初期化";
}
updateSerialDestinationUi();
updateJogProfileUi();
updatePlanarArmVisibility();
const sdDownload = $("#downloadSdGcode");
if (sdDownload) sdDownload.hidden = !isSts3215DirectAxes();
const stsSettings = $("#stsDirectAxesSettings");
if (stsSettings) stsSettings.hidden = !isSts3215DirectAxes();
}
function isPicoDrv8835Profile() { return state.settings.controllerProfile === "pico2-drv8835-planar"; }
function updatePlanarArmVisibility() {
const panel = $("#planarArmPanel");
if (!panel) return;
panel.hidden = !isPicoDrv8835Profile();
if (panel.hidden && state.positionTelemetryEnabled) disablePositionTelemetry(false);
renderPlanarArm();
}
function supportsSdUpload() {
return activeControllerProfile().capabilities?.sdUpload === true;
}
function supportsSdManagement() {
return activeControllerProfile().capabilities?.sdManagement === true;
}
function effectiveSerialDestination() {
return supportsSdUpload() && state.settings.serialDestination === "sd" ? "sd" : "execute";
}
function sanitizeSdFilename(name) {
const source = String(name || "").split(/[\\/]/).pop();
const extensionMatch = source.match(/\.(gcode|gc|nc|tap)$/i);
const extension = extensionMatch ? `.${extensionMatch[1].toLowerCase()}` : ".gcode";
const rawStem = extensionMatch ? source.slice(0, -extensionMatch[0].length) : source;
const stem = rawStem.normalize("NFKD").replace(/[^A-Za-z0-9._-]+/g, "-")
.replace(/^[._-]+|[._-]+$/g, "") || "plot";
return `${stem.slice(0, 48 - extension.length)}${extension}`;
}
function selectedSerialPayload() {
const id = $("#serialSource").value;
if (id === "editor") return { code: $("#gcodeEditor").value, name: $("#gcodeName").value };
if (id === "__reload__") return { code: state.settings.reloadGcode, name: "reload.gcode", reload: true };
const item = state.library.find(entry => entry.id === id);
return { code: item?.gcode || "", name: item?.name || "plot.gcode" };
}
function updateSdFilenameFromSource(force = false) {
const input = $("#sdFilename");
if (!input) return;
const suggested = sanitizeSdFilename(selectedSerialPayload().name);
if (force || !input.value) input.value = suggested;
}
function updateSerialDestinationUi() {
const group = $("#serialDestinationGroup");
if (!group) return;
const supported = supportsSdUpload();
group.hidden = !supported;
const mode = $("#m5OperationMode");
if (!supportsSdManagement()) mode.value = "normal";
const managerSelected = supportsSdManagement() && mode.value === "sd-manager";
const destination = $("#serialDestination");
destination.value = supported && state.settings.serialDestination === "sd" ? "sd" : "execute";
const sdSelected = supported && !managerSelected && destination.value === "sd";
$("#serialDestinationLabel").hidden = managerSelected;
$("#sdFilenameLabel").hidden = !sdSelected;
$("#sdTransferHint").hidden = !sdSelected;
$("#serialTransferControls").hidden = managerSelected;
$("#sdManager").hidden = !managerSelected;
$("#startSend").textContent = sdSelected ? "SDカードへ転送" : "送信開始";
$("#sendFromEditor").textContent = sdSelected ? "SDカードへ転送" : "Serialで送信";
if (sdSelected) updateSdFilenameFromSource(false);
renderSdFileList();
}
function bindSerial() {
$("#connectSerial").addEventListener("click", connectSerial); $("#disconnectSerial").addEventListener("click", disconnectSerial);
$("#serialBaud").addEventListener("change", e => { state.settings.baudrate = +e.target.value || 115200; saveJSON("plotterflow.settings", state.settings); });
$("#serialDestination").addEventListener("change", event => {
state.settings.serialDestination = event.target.value === "sd" ? "sd" : "execute";
saveJSON("plotterflow.settings", state.settings);
updateSerialDestinationUi();
});
$("#m5OperationMode").addEventListener("change", async event => {
if (event.target.value === "sd-manager") {
await enterSdManagement();
} else {
await exitSdManagement();
}
updateSerialDestinationUi();
});
$("#refreshSdFiles").addEventListener("click", refreshSdFiles);
$("#closeSdManager").addEventListener("click", async () => {
$("#m5OperationMode").value = "normal";
await exitSdManagement();
updateSerialDestinationUi();
});
$("#serialSource").addEventListener("change", () => { updateSdFilenameFromSource(true); renderSelectedSerialTrajectory(); });
$("#sdFilename").addEventListener("change", event => { event.target.value = sanitizeSdFilename(event.target.value); });
populateJogSettings();
$("#jogStep").addEventListener("change", saveJogSettings); $("#jogFeed").addEventListener("input", updateJogPreview); $("#jogFeed").addEventListener("change", saveJogSettings);
$$('[data-jog-axis]').forEach(button => button.addEventListener("click", () => sendJog(
button.dataset.jogAxis, +button.dataset.jogSign, +(button.dataset.jogDegrees || 0) || null
)));
$("#keyboardJogToggle").addEventListener("change", event => setKeyboardJogEnabled(event.target.checked));
document.addEventListener("keydown", handleKeyboardJog);
$("#jogCancel").addEventListener("click", cancelJog); updateJogPreview();
$("#setXyZero").addEventListener("click", setCurrentXyZero); updateSerialPositionDisplay();
$("#positionTelemetryToggle").addEventListener("change", event => setPositionTelemetryEnabled(event.target.checked));
$("#armJ1Invert").addEventListener("change", saveArmCalibrationFromUi);
$("#armJ2Invert").addEventListener("change", saveArmCalibrationFromUi);
$("#calibrateArmDown").addEventListener("click", calibrateArmDown);
renderPlanarArm();
$("#initializeController").addEventListener("click", initializeController);
$$('[data-command]').forEach(b => b.addEventListener("click", () => sendRealtime(b.dataset.command + "\n")));
$("#sendManual").addEventListener("click", () => { const c = $("#manualCommand").value; if (c) sendRealtime(c + "\n"); });
$("#penUpButton").addEventListener("click", () => sendRealtime(state.settings.penUpCommand + "\n")); $("#penDownButton").addEventListener("click", () => sendRealtime(state.settings.penDownCommand + "\n"));
$("#reloadButton").addEventListener("click", () => { notifyReloadSimulation(); startSending(state.settings.reloadGcode); });
$("#pauseSend").addEventListener("click", pauseSending); $("#resumeSend").addEventListener("click", resumeSending); $("#stopSend").addEventListener("click", stopSending); $("#resetController").addEventListener("click", resetController);
$("#startSend").addEventListener("click", () => {
const payload = selectedSerialPayload();
if (payload.reload && effectiveSerialDestination() === "execute") notifyReloadSimulation(payload.code);
renderSerialTrajectory(payload.code, payload.name);
scrollToSerialTrajectory();
startConfiguredTransfer(payload.code, payload.name);
});
$("#scrollToSerialControls").addEventListener("click", () => $("#serialSendPanel").scrollIntoView({ behavior: "smooth", block: "start" }));
renderSelectedSerialTrajectory();
$("#clearLog").addEventListener("click", () => $("#serialLog").innerHTML = "");
}
async function connectSerial() {
if (!("serial" in navigator)) return toast("このブラウザはWeb Serialに対応していません");
try {
state.port = await navigator.serial.requestPort(); await state.port.open({ baudRate: +$("#serialBaud").value || 115200 }); state.writer = state.port.writable.getWriter();
$("#connectionBadge").textContent = "Serial: 接続済み"; $("#connectionBadge").classList.add("connected"); log(`接続しました / ${activeControllerProfile().label}`, "rx"); readSerial(); startStatusPolling(); updateSerialProfileDisplay();
} catch (e) { log(`接続エラー: ${e.message}`, "rx"); }
}
async function readSerial() {
const decoder = new TextDecoder(); state.reader = state.port.readable.getReader();
try { while (state.port) { const { value, done } = await state.reader.read(); if (done) break; state.readBuffer += decoder.decode(value, { stream:true }); const lines = state.readBuffer.split(/\r?\n/); state.readBuffer = lines.pop(); lines.forEach(handleSerialLine); } }
catch (e) { if (state.port) log(`受信エラー: ${e.message}`, "rx"); }
finally { try { state.reader?.releaseLock(); } catch {} state.reader = null; }
}
function handleSerialLine(line) {
const text = line.trim();
if (!text) return;
state.lastReceivedLine = text;
if (/^<.*>$/.test(text)) { parseControllerStatus(text); return; }
if (text === "[SDLIST:BEGIN]") {
state.sdFiles = [];
state.sdListReceiving = true;
renderSdFileList();
return;
}
const sdFile = text.match(/^\[SDLIST:FILE name=([A-Za-z0-9._-]+) size=(\d+)\]$/);
if (sdFile) {
state.sdFiles.push({ name: sdFile[1], size: Number(sdFile[2]) });
return;
}
const sdListEnd = text.match(/^\[SDLIST:END count=(\d+)\]$/);
if (sdListEnd) {
state.sdListReceiving = false;
renderSdFileList();
return;
}
const sdMode = text.match(/^\[MSG:SDMODE active=([01])\]$/);
if (sdMode) {
state.sdManagementActive = sdMode[1] === "1";
$("#sdManagerStatus").textContent = state.sdManagementActive ? "接続済み・同期できます" : "管理モードを終了しました";
return;
}
if (/^ok\b/i.test(text)) {
state.lastOkAt = Date.now();
state.okWaiters.shift()?.resolve(text);
if (!state.sending) log(text, "rx");
return;
}
if (/^(error|alarm):?/i.test(text)) {
log(text, "rx");
state.okWaiters.shift()?.reject(new Error(text));
return;
}
if (!state.sending || shouldLogPicoPlanarDebug(text)) log(text, "rx");
}
function shouldLogPicoPlanarDebug(text) {
if (state.settings.controllerProfile === "pico2-tmc2209-planar") {
return /^\[MSG:PFDBG(?:\s|\])/i.test(text);
}
if (state.settings.controllerProfile === "pico2-drv8835-planar") {
return /^\[MSG:(?:DRV8835|M980)(?:\s|\])/i.test(text);
}
return state.settings.controllerProfile === "m5stack-drv8835-planar" &&
/^\[MSG:(?:DRV8835|M980|SDUPLOAD|SDMODE|SDFILE)(?:\s|\])/i.test(text);
}
async function disconnectSerial() {
stopStatusPolling();
if (state.writer && state.positionTelemetryEnabled) {
try { await rawWrite("M983 S0\n", false); await sleep(50); }
catch (error) { log(`切断前位置センサ通信停止失敗: ${error.message}`, "rx"); }
}
if (state.writer && state.sdUploading) {
try { await rawWrite("\x18", false); log("SD upload cancel before disconnect (Ctrl-X)", "tx"); await sleep(100); }
catch (error) { log(`切断前SD転送中止失敗: ${error.message}`, "rx"); }
}
if (state.writer && !state.sdUploading && state.settings.stopStrategy === "cancel-pen-up" && (state.sending || state.jogging)) {
try { await state.writer.write(new Uint8Array([0x85])); log("Motion cancel before disconnect (0x85)", "tx"); await sleep(250); }
catch (error) { log(`切断前キャンセル失敗: ${error.message}`, "rx"); }
}
if (state.writer && state.sdManagementActive) {
try { await rawWrite("M22\n", false); await sleep(100); }
catch (error) { log(`切断前SD管理終了失敗: ${error.message}`, "rx"); }
}
const disconnectCommand = String(state.settings.disconnectCommand || "").trim();
if (state.writer && disconnectCommand) {
try { await rawWrite(disconnectCommand + "\n"); await sleep(150); }
catch (error) { log(`切断コマンド失敗: ${error.message}`, "rx"); }
}
state.stopped = true; clearOkWaiters("切断");
try { await state.reader?.cancel(); } catch {} try { state.writer?.releaseLock(); state.writer = null; await state.port?.close(); } catch (e) { log(`切断エラー: ${e.message}`, "rx"); }
state.port = null; state.sdUploading=false; state.sdManagementActive=false; state.sdFiles=[]; state.sdListReceiving=false; $("#m5OperationMode").value="normal"; updateSerialDestinationUi(); state.controllerState="未接続"; state.machinePosition=null; state.workPosition=null; state.workOffset=null; disablePositionTelemetry(false); updateSerialPositionDisplay(); $("#connectionBadge").textContent = "Serial: 未接続"; $("#connectionBadge").classList.remove("connected"); log("切断しました", "rx");
}
async function rawWrite(text, shouldLog = true) { if (!state.writer) throw new Error("Serial未接続です"); await state.writer.write(new TextEncoder().encode(text)); if (shouldLog) log(text.replace(/[\r\n]+$/, "") || "Ctrl-X", "tx"); }
async function sendRealtime(text) {
if (state.sdUploading && text !== "\x18" && text !== "\x85") {
return toast("SD転送中は停止以外の手動コマンドを送信できません");
}
if (state.sdManagementActive && text !== "\x18" && text !== "\x85") {
return toast("SDカード管理中は通常コマンドを送信できません");
}
try { await rawWrite(text); } catch (e) { toast(e.message); }
}
function clearOkWaiters(reason = "キャンセル") {
state.okWaiters.splice(0).forEach(w => w.reject(new Error(reason)));
}
function waitOk(timeout = 15000, meta = {}) {
timeout = Math.max(1000, +(timeout || state.settings.okTimeoutMs) || 15000);
return new Promise((resolve,reject) => {
const item = {
...meta,
startedAt: Date.now(),
resolve: value => { clearTimeout(item.timer); resolve(value); },
reject: e => { clearTimeout(item.timer); reject(e); }
};
item.timer = setTimeout(() => {
const i=state.okWaiters.indexOf(item); if(i>=0) state.okWaiters.splice(i,1);
logOkTimeoutDebug(item, timeout);
reject(new Error("ok応答がタイムアウトしました"));
}, timeout);
state.okWaiters.push(item);
});
}
async function sendLineAndWait(line, trackPosition = true, meta = {}) {
const pending = waitOk(null, { line, ...meta });
state.lastSentLine = line; state.lastSendAt = Date.now();
await rawWrite(line + "\n", false);
await pending;
if (trackPosition) updatePosition(line);
}
function formatSdFileSize(bytes) {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function renderSdFileList() {
const list = $("#sdFileList");
if (!list) return;
list.replaceChildren();
if (state.sdListReceiving) {
const loading = document.createElement("p");
loading.className = "muted";
loading.textContent = "SDカードを読み込み中...";
list.append(loading);
return;
}
if (!state.sdFiles.length) {
const empty = document.createElement("p");
empty.className = "muted";
empty.textContent = state.sdManagementActive ? "対応するG-codeファイルはありません" : "SDカード管理モードを選ぶと一覧を同期します";
list.append(empty);
return;
}
for (const file of state.sdFiles) {
const row = document.createElement("div");
row.className = "sd-file-row";
const name = document.createElement("input");
name.value = file.name;
name.maxLength = 48;
name.inputMode = "latin";
name.spellcheck = false;
name.setAttribute("aria-label", `${file.name}の新しいファイル名`);
const size = document.createElement("span");
size.className = "sd-file-size";
size.textContent = formatSdFileSize(file.size);
const rename = document.createElement("button");
rename.textContent = "名前変更";
rename.addEventListener("click", () => renameSdFile(file.name, name.value));
const remove = document.createElement("button");
remove.className = "danger";
remove.textContent = "削除";
remove.addEventListener("click", () => deleteSdFile(file.name));
row.append(name, size, rename, remove);
list.append(row);
}
}
async function synchronizeSdFileList() {
state.sdListReceiving = true;
state.sdFiles = [];
renderSdFileList();
await sendLineAndWait("M20", false);
state.sdListReceiving = false;
renderSdFileList();
$("#sdManagerStatus").textContent = `${state.sdFiles.length}件を同期しました`;
}
async function enterSdManagement() {
if (!supportsSdManagement()) return toast("このプロファイルはSDカード管理に対応していません");
if (!state.writer) {
$("#m5OperationMode").value = "normal";
updateSerialDestinationUi();
return toast("先にSerial接続してください");
}
if (state.sending || state.jogging) {
$("#m5OperationMode").value = "normal";
updateSerialDestinationUi();