forked from swarfer/GRBL-Post-Processor
-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathOpenbuildsFusion360PostGrbl.cps
More file actions
3239 lines (3065 loc) · 136 KB
/
OpenbuildsFusion360PostGrbl.cps
File metadata and controls
3239 lines (3065 loc) · 136 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
/*
Custom Post-Processor for GRBL based Openbuilds-style CNC machines, router and laser-cutting
Made possible by
Swarfer https://github.com/swarfer/GRBL-Post-Processor
Sharmstr https://github.com/sharmstr/GRBL-Post-Processor
Strooom https://github.com/Strooom/GRBL-Post-Processor
This post-Processor should work on GRBL-based machines
Changelog
22/Aug/2016 - V01 : Initial version (Stroom)
23/Aug/2016 - V02 : Added Machining Time to Operations overview at file header (Stroom)
24/Aug/2016 - V03 : Added extra user properties - further cleanup of unused variables (Stroom)
07/Sep/2016 - V04 : Added support for INCHES. Added a safe retract at beginning of first section (Stroom)
11/Oct/2016 - V05 : Update (Stroom)
30/Jan/2017 - V06 : Modified capabilities to also allow waterjet, laser-cutting (Stroom)
28 Jan 2018 - V07 : Fix arc errors and add gotoMCSatend option (Swarfer)
16 Feb 2019 - V08 : Ensure X, Y, Z output when linear differences are very small (Swarfer)
27 Feb 2019 - V09 : Correct way to force word output for XYZIJK, see 'force:true' in CreateVariable (Swarfer)
27 Feb 2018 - V10 : Added user properties for router type. Added rounding of dial settings to 1 decimal (Sharmstr)
16 Mar 2019 - V11 : Added rounding of tool length to 2 decimals. Added check for machine config in setup (Sharmstr)
: Changed RPM warning so it includes operation. Added multiple .nc file generation for tool changes (Sharmstr)
: Added check for duplicate tool numbers with different geometry (Sharmstr)
17 Apr 2019 - V12 : Added check for minimum feed rate. Added file names to header when multiple are generated (Sharmstr)
: Added a descriptive title to gotoMCSatend to better explain what it does.
: Moved machine vendor, model and control to user properties (Sharmstr)
15 Aug 2019 - V13 : Grouped properties for clarity (Sharmstr)
05 Jun 2020 - V14 : description and comment changes (Swarfer)
09 Jun 2020 - V15 : remove limitation to MM units - will produce inch output but user must note that machinehomeX/Y/Z values are always MILLIMETERS (Swarfer)
10 Jun 2020 - V1.0.16 : OpenBuilds-Fusion360-Postprocessor, Semantic Versioning, Automatically add router dial if Router type is set (OpenBuilds)
11 Jun 2020 - V1.0.17 : Improved the header comments, code formatting, removed all tab chars, fixed multifile name extensions
21 Jul 2020 - V1.0.18 : Combined with Laser post - will output laser file as if an extra tool.
08 Aug 2020 - V1.0.19 : Fix for spindleondelay missing on subfiles
02 Oct 2020 - V1.0.20 : Fix for long comments and new restrictions
05 Nov 2020 - V1.0.21 : poweron/off for plasma, coolant can be turned on for laser/plasma too
04 Dec 2020 - V1.0.22 : Add Router11 and dial settings
16 Jan 2021 - V1.0.23 : Remove end of file marker '%' from end of output, arcs smaller than toolRadius will be linearized
25 Jan 2021 - V1.0.24 : Improve coolant codes
26 Jan 2021 - V1.0.25 : Plasma pierce height, and probe
29 Aug 2021 - V1.0.26 : Regroup properties for display, Z height check options
03 Sep 2021 - V1.0.27 : Fix arc ramps not changing Z when they should have
12 Nov 2021 - V1.0.28 : Added property group names, fixed default router selection, now uses permittedCommentChars (sharmstr)
24 Nov 2021 - V1.0.28 : Improved coolant selection, tweaked property groups, tweaked G53 generation, links for help in comments.
21 Feb 2022 - V1.0.29 : Fix sideeffects of drill operation having rapids even when in noRapid mode by always resetting haveRapid in onSection
10 May 2022 - V1.0.30 : Change naming convention for first file in multifile output (Sharmstr)
xx Sep 2022 - V1.0.31 : better laser, with pierce option if cutting
06 Dec 2022 - V1.0.32 : fix long comments that were getting extra brackets
22 Dec 2022 - V1.0.33 : refactored file naming and debugging, indented with astyle
10 Mar 2023 - V1.0.34 : move coolant code to the spindle control line to help with restarts
26 Mar 2023 - V1.0.35 : plasma pierce height override, spindle speed change always with an M3, version number display
03 Jun 2023 - V1.0.36 : code to recenter arcs with bad radii
04 Oct 2023 - V1.0.37 : Tape splitting
Nov 2023 - V1.0.38 : Simple probing, each axis on its own, and xy corner, for BB4x with 3D probe, and machine simulation
10 Feb 3024 - V1.0.39 : Add missing drill cycles, missing because probing failed to expand unhandled cycles
13 Mar 2024 - V1.0.40 : force position after plasma probe, fix plasma linearization of small arcs to avoid GRBL bug in arc after probe, fix pierceClearance and pierceHeight, fix plasma kerfWidth
27 Mar 2024 - V1.0.41 : replace 'power' with OB.power (and friends) because postprocessor.power now exists and is readonly
30 Mar 2024 - V1.0.42 : postprocessor.alert() method has disappeared - replaced with warning(msg) and writeComment(msg), moved more stuff into OB. and SPL.
xx Oct 2024 - V1.0.43 : fix plasma pierce/cut height, pierceTime so it uses the tool settings if provided
10 Aug 2025 - V1.0.44 : fix movement ordering and other tweaks, see readme.md
17 Aug 2025 - V1.0.45 : docs, refactored, new speed handling in adaptives, see README for details
25 Dec 2025 - V1.0.46 : wcs handling on sections, plasma arcs, direct moves, linesplit feedrate on reentry, total machining time in header
*/
obversion = 'V1.0.46';
description = "OpenBuilds CNC : GRBL/BlackBox"; // cannot have brackets in comments
longDescription = description + " : Post " + obversion; // adds description to post library dialog box
vendor = "OpenBuilds";
vendorUrl = "https://openbuilds.com";
model = "GRBL";
legal = "Copyright Openbuilds and swarfer 2025";
certificationLevel = 2;
minimumRevision = 45892;
debugMode = false;
extension = "gcode"; // file extension of the gcode file
setCodePage("ascii"); // character set of the gcode file
//setEOL(CRLF); // end-of-line type : use CRLF for windows
var permittedCommentChars = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,=_-*/\\:";
capabilities = CAPABILITY_MILLING | CAPABILITY_JET | CAPABILITY_INSPECTION | CAPABILITY_MACHINE_SIMULATION; // intended for a CNC, so Milling, and waterjet/plasma/laser
tolerance = spatial(0.002, MM);
minimumChordLength = spatial(0.25, MM);
minimumCircularRadius = spatial(0.125, MM);
maximumCircularRadius = spatial(1000, MM);
minimumCircularSweep = toRad(0.1); // was 0.01
maximumCircularSweep = toRad(180);
allowHelicalMoves = true;
allowSpiralMoves = false;
allowedCircularPlanes = (1 << PLANE_XY); // allow only XY plane
// if you need vertical arcs then uncomment the line below
//allowedCircularPlanes = (1 << PLANE_XY) | (1 << PLANE_ZX) | (1 << PLANE_YZ); // allow all planes, recentering arcs solves YZ/XZ arcs
// if you allow vertical arcs then be aware that ObCONTROL will not display the gcode correctly, but it WILL cut correctly.
/**
* @typedef {object} SplittingState
* @property {number} tapelines - The maximum number of G-code lines allowed per file before a split is triggered. A value of 0 disables splitting by line count. This is set from the `splitLines` post-processor property.
* @property {number} linecnt - The current line counter for the active file. It is incremented with each call to `writeBlock`.
* @property {boolean} forceSplit - A flag that, when set to true, forces a file split at the beginning of the next section. This is used to signal that the line count has been exceeded.
*/
/**
* Manages the state for splitting G-code files based on line count ("tape splitting").
* This object holds the configuration and current status for the file splitting logic.
* Note that line counts will not be exact as we try to split at the next rapid movement
* after linecount has been achieved.
* @type {SplittingState}
*/
var SPL =
{
tapelines : 0,
linecnt : 0,
forceSplit : false
}
// user-defined properties : defaults are set, but they can be changed from a dialog box in Fusion when doing a post.
properties =
{
spindleOnOffDelay: 1.8, // time (in seconds) the spindle needs to get up to speed or stop, or laser/plasma pierce delay
spindleTwoDirections : false, // true : spindle can rotate clockwise and counterclockwise, will send M3 and M4. false : spindle can only go clockwise, will only send M3
hasCoolant : false, // true : machine uses the coolant output, M8 M9 will be sent. false : coolant output not connected, so no M8 M9 will be sent
routerType : "other",
generateMultiple: true, // specifies if a file should be generated for each tool change
splitLines: 0, // if > 0 then split on line count (and tool change if that is also set)
machineHomeZ : -10, // absolute machine coordinates where the machine will move to at the end of the job - first retracting Z, then moving home X Y
machineHomeX : -10, // always in millimeters
machineHomeY : -10,
gotoMCSatend : false, // true will do G53 G0 x{machinehomeX} y{machinehomeY}, false will do G0 x{machinehomeX} y{machinehomeY} at end of program
PowerVaporise : 5, // cutting power in percent, to vaporize plastic coatings
PowerThrough : 100, // for through cutting
PowerEtch : 10, // for etching the surface
UseZ : false, // if true then Z will be moved to 0 at beginning and back to 'retract height' at end
UsePierce : false, // if true && islaser && cutting use M3 and honor pierce delays, else use M4
//plasma stuff
plasma_usetouchoff : false, // use probe for touchoff if true
plasma_touchoffOffset : 5.0, // offset from trigger point to real Z0, used in G10 line
plasma_pierceHeightoverride: false, // if true replace all pierce height settings with value below
plasma_pierceHeightValue : toPreciseUnit(10,MM), //mmOrInch(10, 0.375), // not forcing mm, user beware
plasma_postcutdelay : 0, // seconds to delay after the cut stops to allow assist air to bleed off
linearizeSmallArcs: true, // arcs with radius < toolRadius have radius errors, linearize instead?
machineVendor : "OpenBuilds",
modelMachine : "Generic XYZ",
machineControl : "Grbl 1.1 / BlackBox",
checkZ : false, // true for a PS tool height checkmove at start of every file
checkFeed : 200 // always MM/min
//postProcessorDocs : 'https://docs.openbuilds.com/doku.php', // for future use. link to post processor help docs. be sure to uncomment comment as well
};
// user-defined property definitions - note, do not skip any group numbers
groupDefinitions =
{
//postInfo: {title: "OpenBuilds Post Documentation: https://docs.openbuilds.com/doku.php", description: "", order: 0},
spindle: {title: "Spindle/Plasma", description: "Spindle and Plasma Cutter options", order: 1},
safety: {title: "Safety", description: "Safety options", order: 2},
toolChange: {title: "Tool Changes", description: "Tool change options", order: 3},
startEndPos: {title: "Job Start Z and Job End X,Y,Z Coordinates", description: "Set the spindle start and end position", order: 4},
arcs: {title: "Arcs", description: "Arc options", order: 5},
laserPlasma: {title: "Laser / Plasma", description: "Laser / Plasma options", order: 6},
machine: {title: "Machine", description: "Machine options", order: 7}
};
propertyDefinitions =
{
/*
postProcessorDocs: {
group: "postInfo",
title: "Copy and paste linke to docs",
description: "Link to docs",
type: "string",
},
*/
routerType: {
group: "spindle",
title: "SPINDLE Router type",
description: "Select the type of spindle you have.",
type: "enum",
values: [
{title:"Other", id:"other"},
{title: "Router11", id: "Router11"},
{title: "Makita RT0701", id: "Makita"},
{title: "Dewalt 611", id: "Dewalt"}
]
},
spindleTwoDirections: {
group: "spindle",
title: "SPINDLE can rotate clockwise and counterclockwise?",
description: "Yes : spindle can rotate clockwise and counterclockwise, will send M3 and M4. No : spindle can only go clockwise, will only send M3",
type: "boolean",
},
spindleOnOffDelay: {
group: "spindle",
title: "SPINDLE on/off or Plasma Pierce Delay",
description: "Time (in seconds) the spindle needs to get up to speed or stop, also used for plasma pierce delay if > 0, else uses tool.pierceTime",
type: "number",
},
hasCoolant: {
group: "spindle",
title: "SPINDLE Has coolant?",
description: "Yes: machine uses the coolant output, M8 M9 will be sent. No : coolant output not connected, so no M8 M9 will be sent",
type: "boolean",
},
checkFeed: {
group: "safety",
title: "SAFETY: Check tool feedrate",
description: "Feedrate to be used for the tool length check, always millimeters.",
type: "spatial",
},
checkZ: {
group: "safety",
title: "SAFETY: Check tool Z length?",
description: "Insert a safe move and program pause M0 to check for tool length, tool will lower to clearanceHeight set in the Heights tab.",
type: "boolean",
},
generateMultiple: {
group: "toolChange",
title: "TOOL: Generate muliple files for tool changes?",
description: "Generate multiple files. One for each tool change.",
type: "boolean",
},
splitLines: {
group: "toolChange",
title: "Split on line count (0 for none)",
description: "Split files after given number of lines, or 0 for no split on line count.",
type: "number",
},
gotoMCSatend: {
group: "startEndPos",
title: "EndPos: Use Machine Coordinates (G53) at end of job?",
description: "Yes will do G53 G0 x{machinehomeX} y(machinehomeY) (Machine Coordinates), No will do G0 x(machinehomeX) y(machinehomeY) (Work Coordinates) at end of program",
type: "boolean",
},
machineHomeX: {
group: "startEndPos",
title: "EndPos: End of job X position (MM).",
description: "(G53 or G54) X position to move to in Millimeters",
type: "spatial",
},
machineHomeY: {
group: "startEndPos",
title: "EndPos: End of job Y position (MM).",
description: "(G53 or G54) Y position to move to in Millimeters.",
type: "spatial",
},
machineHomeZ: {
group: "startEndPos",
title: "startEndPos: START and End of job Z position (MCS Only) (MM)",
description: "G53 Z position to move to in Millimeters, normally negative. Moves to this distance below Z home.",
type: "spatial",
},
linearizeSmallArcs: {
group: "arcs",
title: "ARCS: Linearize Small Arcs",
description: "Arcs with radius < toolRadius can have mismatched radii, set this to Yes to linearize them. This solves G2/G3 radius mismatch errors.",
type: "boolean",
},
PowerVaporise: {title: "LASER: Power for Vaporizing", description: "Just enough Power to VAPORIZE plastic coating, in percent.", group: "laserPlasma", type: "integer"},
PowerThrough: {title: "LASER: Power for Through Cutting", description: "Normal Through cutting power, in percent.", group: "laserPlasma", type: "integer"},
PowerEtch: {title: "LASER: Power for Etching", description: "Just enough power to Etch the surface, in percent.", group: "laserPlasma", type: "integer"},
UseZ: {title: "P+L: Use Z motions at start and end.", description: "Use True if you have a laser on a router with Z motion, or a PLASMA cutter.", group: "laserPlasma", type: "boolean"},
UsePierce: {title: "LASER: Use pierce delays with M3 motion when cutting.", description: "True will use M3 commands and pierce delays, else use M4 with no delays.", group: "laserPlasma", type: "boolean"},
plasma_usetouchoff: {title: "PLASMA: Use Z touchoff probe routine", description: "Set to true if have a touchoff probe for Plasma.", group: "laserPlasma", type: "boolean"},
plasma_touchoffOffset: {title: "PLASMA: Plasma touch probe offset", description: "Offset in Z at which the probe triggers, always Millimeters, always positive.", group: "laserPlasma", type: "spatial"},
plasma_pierceHeightoverride: {title: "P+L: Override the pierce height", description: "Set to true if want to always use the pierce height Z value.", group: "laserPlasma", type: "boolean"},
plasma_pierceHeightValue : {title: "P+L: Override the pierce height Z value", description: "Offset in Z for the plasma pierce height, always positive. Set to 0 to avoid all piercing.", group: "laserPlasma", type: "spatial"},
plasma_postcutdelay : {title: "PLASMA: Seconds to delay after cut", description: "Seconds to delay after cut stops to allow assist air to bleed off before next pierce.", group: "laserPlasma", type: "number"},
machineVendor: {
group: "machine",
title: "Machine Vendor",
description: "Machine vendor defined here will be displayed in header if machine config not set.",
type: "string",
},
modelMachine: {
group: "machine",
title: "Machine Model",
description: "Machine model defined here will be displayed in header if machine config not set.",
type: "string",
},
machineControl: {
group: "machine",
title: "Machine Control",
description: "Machine control defined here will be displayed in header if machine config not set.",
type: "string",
}
};
// USER ADJUSTMENTS FOR PLASMA
plasma_probedistance = 15; // distance to probe down in Z, always in millimeters
plasma_proberate = 100; // feedrate for probing, in mm/minute
// END OF USER ADJUSTMENTS
// creation of all kinds of G-code formats - controls the amount of decimals used in the generated G-Code
var gFormat = createFormat({prefix: "G", decimals: 0});
var gPFormat = createFormat({prefix: "G", decimals: 1}); // for probing commands
var mFormat = createFormat({prefix: "M", decimals: 0});
var xyzFormat = createFormat({decimals: (unit == MM ? 3 : 4)});
var abcFormat = createFormat({decimals: 3, forceDecimal: true, scale: DEG});
var arcFormat = createFormat({decimals: (unit == MM ? 3 : 4)});
var feedFormat = createFormat({decimals: 0});
var rpmFormat = createFormat({decimals: 0});
var pFormat = createFormat({decimals: 0});
var secFormat = createFormat({decimals: 3, forceDecimal: true}); // seconds
//var taperFormat = createFormat({decimals:1, scale:DEG});
var xOutput = createVariable({prefix: "X", force: false}, xyzFormat);
var yOutput = createVariable({prefix: "Y", force: false}, xyzFormat);
var zOutput = createVariable({prefix: "Z", force: false}, xyzFormat); // dont need Z every time
var feedOutput = createVariable({prefix: "F"}, feedFormat);
var sOutput = createVariable({prefix: "S", force: false}, rpmFormat);
var pWord = createVariable({prefix: "P", force: true}, pFormat);
var mOutput = createVariable({force: false}, mFormat); // only use for M3/4/5
// for arcs
var iOutput = createReferenceVariable({prefix: "I", force: true}, arcFormat);
var jOutput = createReferenceVariable({prefix: "J", force: true}, arcFormat);
var kOutput = createReferenceVariable({prefix: "K", force: true}, arcFormat);
var gMotionModal = createModal({}, gFormat); // modal group 1 // G0-G3, ...
var gProbeModal = createModal({onchange: function () { gMotionModal.reset(); }, force: true }, gPFormat);
var gPlaneModal = createModal({onchange: function ()
{
gMotionModal.reset();
}
}, gFormat); // modal group 2 // G17-19
var gAbsIncModal = createModal({}, gFormat); // modal group 3 // G90-91
var gFeedModeModal = createModal({}, gFormat); // modal group 5 // G93-94
var gUnitModal = createModal({}, gFormat); // modal group 6 // G20-21
var gWCSOutput = createModal({}, gFormat); // for G54 G55 etc
var sequenceNumber = 1; //used for multiple file naming
var multipleToolError = false; //used for alerting during single file generation with multiple tools
var filesToGenerate = 1; //used to figure out how many files will be generated so we can diplay in header
var minimumFeedRate = toPreciseUnit(45, MM); // GRBL lower limit in mm/minute
var fileIndexFormat = createFormat({width: 2, zeropad: true, decimals: 0});
var isNewfile = false; // set true when a new file has just been started
// group our private variables together so Autodesk does not break us when they make something into a property
var OB = {
power : 0, // the setpower value, for S word when laser/plasma cutting
powerOn : false, // is the laser power on? used for laser when haveRapid=false
isLaser : false, // set true for laser/water/
isPlasma : false, // set true for plasma
isMill : false, // set true for mill and not laser and not plasma
cutmode : 0, // M3 or M4
cuttingMode : 'none', // set by onParameter for laser/plasma
haveRapid : false, // assume no rapid moves
movestr : 'unknown', // movement type string for comments
movestrP : 'unknown' // movement type string for comments
}
/**
* @typedef {object} HeightsState
* @property {number} retract - The Z-height to which the tool retracts during linking moves.
* @property {number} clearance - A safe Z-height used for initial positioning and tool checks.
* @property {number} top - The top height of the current operation, often used as a reference for plasma/laser cut heights.
*/
/**
* Manages the various height settings received from Fusion 360 operations.
* @type {HeightsState}
*/
var Heights = {
retract: 1, // will be set by onParameter and used in onLinear to detect rapids
clearance: 10, // will be set by onParameter
top: 1 // set by onParameter
};
/*
Keep track of feedrates, saved here by onParameter
*/
var Feeds = {
cutting: 1, // cutting feedrate
entry : 1, // lead-in feedrate
exit : 1 // lead-out feedrate
}
var plasma = {
pierceHeight : 3.14, // set by onParameter or tool.pierceHeight
pierceTime : 3.14, // plasma pierce delay set by tool if properties.spindleOnOffDelay = 0
leadinRate : 314, // set by onParameter: the lead-in feedrate,plasma : onparameter:movement:lead_in is always metric so convert when needed
cutHeight : 3.14, // tool cut height from onParameter
mode : 1 // mode 1 is the old mode using topHeights as cutheight, mode 2 is new mode, using tool cutheight
};
//var workOffset = 0;
//var retractHeight = 1; // will be set by onParameter and used in onLinear to detect rapids
//var clearanceHeight = 10; // will be set by onParameter
//var topHeight = 1; // set by onParameter
var linmove = 1; // linear move mode
var toolRadius; // for arc linearization
var coolantIsOn = 0; // set when coolant is used to we can do intelligent turn off
var currentworkOffset = 0; // the current WCS in use, so we can retract Z between sections if needed
var clnt = ''; // coolant code to add to spindle line
var PRB = {
feedProbeLink : 1000, // probe linking moves feedrate
feedProbeMeasure : 102, // probing feedrate
probe_output_work_offset : 0 // the WCS to update when probing
}
// Start of machine configuration logic
var compensateToolLength = false; // add the tool length to the pivot distance for nonTCP rotary heads
// internal variables, do not change
var receivedMachineConfiguration;
var operationSupportsTCP;
var multiAxisFeedrate;
function activateMachine() {
// disable unsupported rotary axes output
if (!machineConfiguration.isMachineCoordinate(0) && (typeof aOutput != "undefined")) {
aOutput.disable();
}
if (!machineConfiguration.isMachineCoordinate(1) && (typeof bOutput != "undefined")) {
bOutput.disable();
}
if (!machineConfiguration.isMachineCoordinate(2) && (typeof cOutput != "undefined")) {
cOutput.disable();
//machineConfiguration.setControl(properties.machineControl);
}
// setup usage of multiAxisFeatures
useMultiAxisFeatures = getProperty("useMultiAxisFeatures") != undefined ? getProperty("useMultiAxisFeatures") :
(typeof useMultiAxisFeatures != "undefined" ? useMultiAxisFeatures : false);
useABCPrepositioning = getProperty("useABCPrepositioning") != undefined ? getProperty("useABCPrepositioning") :
(typeof useABCPrepositioning != "undefined" ? useABCPrepositioning : false);
if (!machineConfiguration.isMultiAxisConfiguration()) {
return; // don't need to modify any settings for 3-axis machines
}
// save multi-axis feedrate settings from machine configuration
var mode = machineConfiguration.getMultiAxisFeedrateMode();
var type = mode == FEED_INVERSE_TIME ? machineConfiguration.getMultiAxisFeedrateInverseTimeUnits() :
(mode == FEED_DPM ? machineConfiguration.getMultiAxisFeedrateDPMType() : DPM_STANDARD);
multiAxisFeedrate = {
mode : mode,
maximum : machineConfiguration.getMultiAxisFeedrateMaximum(),
type : type,
tolerance: mode == FEED_DPM ? machineConfiguration.getMultiAxisFeedrateOutputTolerance() : 0,
bpwRatio : mode == FEED_DPM ? machineConfiguration.getMultiAxisFeedrateBpwRatio() : 1
};
// setup of retract/reconfigure TAG: Only needed until post kernel supports these machine config settings
if (receivedMachineConfiguration && machineConfiguration.performRewinds()) {
safeRetractDistance = machineConfiguration.getSafeRetractDistance();
safePlungeFeed = machineConfiguration.getSafePlungeFeedrate();
safeRetractFeed = machineConfiguration.getSafeRetractFeedrate();
}
if (typeof safeRetractDistance == "number" && getProperty("safeRetractDistance") != undefined && getProperty("safeRetractDistance") != 0) {
safeRetractDistance = getProperty("safeRetractDistance");
}
if (machineConfiguration.isHeadConfiguration()) {
compensateToolLength = typeof compensateToolLength == "undefined" ? false : compensateToolLength;
}
if (machineConfiguration.isHeadConfiguration() && compensateToolLength) {
for (var i = 0; i < getNumberOfSections(); ++i) {
var section = getSection(i);
if (section.isMultiAxis()) {
machineConfiguration.setToolLength(getBodyLength(section.getTool())); // define the tool length for head adjustments
section.optimizeMachineAnglesByMachine(machineConfiguration, OPTIMIZE_AXIS);
}
}
} else {
optimizeMachineAngles2(OPTIMIZE_AXIS);
}
}
function getBodyLength(tool) {
for (var i = 0; i < getNumberOfSections(); ++i) {
var section = getSection(i);
if (tool.number == section.getTool().number) {
return section.getParameter("operation:tool_overallLength", tool.bodyLength + tool.holderLength);
}
}
return tool.bodyLength + tool.holderLength;
}
function defineMachine() {
var useTCP = true;
if (false) { // note: setup your machine here
var aAxis = createAxis({coordinate:0, table:true, axis:[1, 0, 0], range:[-120, 120], preference:1, tcp:useTCP});
var cAxis = createAxis({coordinate:2, table:true, axis:[0, 0, 1], range:[-360, 360], preference:0, tcp:useTCP});
machineConfiguration = new MachineConfiguration(aAxis, cAxis);
setMachineConfiguration(machineConfiguration);
if (receivedMachineConfiguration) {
warning(localize("The provided CAM machine configuration is overwritten by the postprocessor."));
receivedMachineConfiguration = false; // CAM provided machine configuration is overwritten
}
}
if (!receivedMachineConfiguration) {
// multiaxis settings
if (machineConfiguration.isHeadConfiguration()) {
machineConfiguration.setVirtualTooltip(false); // translate the pivot point to the virtual tool tip for nonTCP rotary heads
}
// retract / reconfigure
var performRewinds = false; // set to true to enable the rewind/reconfigure logic
if (performRewinds) {
machineConfiguration.enableMachineRewinds(); // enables the retract/reconfigure logic
safeRetractDistance = (unit == IN) ? 1 : 25; // additional distance to retract out of stock, can be overridden with a property
safeRetractFeed = (unit == IN) ? 20 : 500; // retract feed rate
safePlungeFeed = (unit == IN) ? 10 : 250; // plunge feed rate
machineConfiguration.setSafeRetractDistance(safeRetractDistance);
machineConfiguration.setSafeRetractFeedrate(safeRetractFeed);
machineConfiguration.setSafePlungeFeedrate(safePlungeFeed);
var stockExpansion = new Vector(toPreciseUnit(0.1, IN), toPreciseUnit(0.1, IN), toPreciseUnit(0.1, IN)); // expand stock XYZ values
machineConfiguration.setRewindStockExpansion(stockExpansion);
}
// multi-axis feedrates
if (machineConfiguration.isMultiAxisConfiguration()) {
machineConfiguration.setMultiAxisFeedrate(
useTCP ? FEED_FPM : FEED_INVERSE_TIME,
9999.99, // maximum output value for inverse time feed rates
INVERSE_MINUTES, // INVERSE_MINUTES/INVERSE_SECONDS or DPM_COMBINATION/DPM_STANDARD
0.5, // tolerance to determine when the DPM feed has changed
1.0 // ratio of rotary accuracy to linear accuracy for DPM calculations
);
setMachineConfiguration(machineConfiguration);
}
/* home positions */
// machineConfiguration.setHomePositionX(toPreciseUnit(0, IN));
// machineConfiguration.setHomePositionY(toPreciseUnit(0, IN));
// machineConfiguration.setRetractPlane(toPreciseUnit(0, IN));
}
}
// End of machine configuration logic ======================================================================
/**
* function to reformat a string to 'title case'
* @param str the string to casify
* @returns entitled string
*/
function toTitleCase(str)
{
return str.replace( /\w\S*/g, function(txt)
{
// /\w\S*/g keep that format, astyle will put spaces in it
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
}
// ------- use astyle below thisline -----------------
/**
* Translates a spindle RPM into a manual dial setting for specific router models.
*
* This function takes a target RPM and calculates the corresponding dial setting
* (e.g., 1, 2.5, 6) for routers like Makita, Dewalt, and Router11. It uses linear
* interpolation for speeds that fall between the fixed dial settings.
*
* It also validates the requested RPM against the selected router's capabilities.
* If the RPM is out of range, it issues a warning to the user and clamps the
* dial setting to the nearest valid value (minimum or maximum).
*
* The supported router types and their speed mappings are:
* - **Dewalt 611**: [1: 16000, 2: 18200, 3: 20400, 4: 22600, 5: 24800, 6: 27000]
* - **Router11**: [1: 10000, 2: 14000, 3: 18000, 4: 23000, 5: 27000, 6: 32000]
* - **Makita RT0701 (Default)**: [1: 10000, 2: 12000, 3: 17000, 4: 22000, 5: 27000, 6: 30000]
*
* For probe operations, it returns a default dial setting of 1.
*
* @param {number} rpm The target spindle speed in revolutions per minute.
* @param {string} op The name of the current operation, used for logging warning messages.
* @returns {string|number} The calculated dial setting as a string with one decimal place (e.g., "2.5"),
* or an integer for the minimum/maximum settings.
*/
function rpm2dial(rpm, op)
{
var wmsg = "";
if (isProbeOperation())
return 1;
var speeds;
switch (properties.routerType) {
case "Dewalt":
speeds = [0, 16000, 18200, 20400, 22600, 24800, 27000];
break;
case "Router11":
speeds = [0, 10000, 14000, 18000, 23000, 27000, 32000];
break;
case "Makita":
default:
// this is Makita R0701 and default for 'other'
speeds = [0, 10000, 12000, 17000, 22000, 27000, 30000];
break;
}
if (rpm < speeds[1])
{
wmsg = "WARNING " + rpm + " rpm is below minimum spindle RPM of " + speeds[1] + " rpm in the " + op + " operation.";
warning(wmsg);
writeComment(wmsg);
return 1;
}
if (rpm > speeds[speeds.length - 1])
{
wmsg = "WARNING " + rpm + " rpm is above maximum spindle RPM of " + speeds[speeds.length - 1] + " rpm in the " + op + " operation.";
warning(wmsg);
writeComment(wmsg);
return (speeds.length - 1);
}
var i;
for (i = 1; i < (speeds.length - 1); i++)
{
if ((rpm >= speeds[i]) && (rpm <= speeds[i + 1]))
{
return (((rpm - speeds[i]) / (speeds[i + 1] - speeds[i])) + i).toFixed(1);
}
}
error("Fatal Error calculating router speed dial.");
return 0;
}
/**
* Checks various feed rates for a given operation against the GRBL minimum feed rate.
*
* This function retrieves the cutting, retract, entry, exit, ramp, and plunge feed rates
* from the provided section object. It compares each of these against the `minimumFeedRate`
* property (a GRBL controller limitation). If any feed rate is found to be below this
* minimum, it generates a detailed warning message. This message is both displayed to the
* user in the Fusion 360 post-process dialog and written as a comment in the output
* G-code file for on-machine reference.
*
* @param {object} section The Fusion 360 section object for the current operation,
* which contains all toolpath parameters.
* @param {string} op A descriptive name or identifier for the current operation,
* used within the warning message to help the user locate the issue.
* @returns {void} This function does not return a value.
*/
function checkMinFeedrate(section, op)
{
var alertMsg = "";
if (section.getParameter("operation:tool_feedCutting") < minimumFeedRate)
alertMsg = "Cutting\n";
if (section.getParameter("operation:tool_feedRetract") < minimumFeedRate)
alertMsg = alertMsg + "Retract\n";
if (section.getParameter("operation:tool_feedEntry") < minimumFeedRate)
alertMsg = alertMsg + "Entry\n";
if (section.getParameter("operation:tool_feedExit") < minimumFeedRate)
alertMsg = alertMsg + "Exit\n";
if (section.getParameter("operation:tool_feedRamp") < minimumFeedRate)
alertMsg = alertMsg + "Ramp\n";
if (section.getParameter("operation:tool_feedPlunge") < minimumFeedRate)
alertMsg = alertMsg + "Plunge\n";
if (alertMsg != "")
{
var fF = createFormat({decimals: 0, suffix: (unit == MM ? "mm" : "in" )});
var fo = createVariable({}, fF);
var wmsg = "WARNING " + "The following feedrates in " + op + " are set below the minimum feedrate that GRBL supports. The feedrate should be higher than " + fo.format(minimumFeedRate) + " per minute.\n\n" + alertMsg;
warning(wmsg);
writeComment(wmsg);
}
}
/**
* write a block of gcode
* counts lines if tapelines is set
*/
function writeBlock()
{
writeWords(arguments);
if (SPL.tapelines) SPL.linecnt++;
}
/**
* Thanks to nyccnc.com
* Thanks to the Autodesk Knowledge Network for help with this at
* https://knowledge.autodesk.com/support/hsm/learn-explore/caas/sfdcarticles/sfdcarticles/How-to-use-Manual-NC-options-to-manually-add-code-with-Fusion-360-HSM-CAM.html!
*/
function onPassThrough(text)
{
var commands = String(text).split(",");
for (text in commands)
{
writeBlock(commands[text]);
}
}
/**
* 3. here you can set all the properties of your machine if you havent set up a machine config in CAM. These are optional and only used to print in the header.
* rather set up a real machine config
*/
function myMachineConfig()
{
myMachine = getMachineConfiguration();
if (!myMachine.getVendor())
{
// machine config not found so we'll use the info below
myMachine.setWidth(600);
myMachine.setDepth(800);
myMachine.setHeight(130);
myMachine.setMaximumSpindlePower(700);
myMachine.setMaximumSpindleSpeed(30000);
myMachine.setMilling(true);
myMachine.setTurning(false);
myMachine.setToolChanger(false);
myMachine.setNumberOfTools(1);
myMachine.setNumberOfWorkOffsets(6);
myMachine.setVendor(properties.machineVendor);
myMachine.setModel(properties.modelMachine);
myMachine.setControl(properties.machineControl);
}
}
/**
* Remove special characters which could confuse GRBL : $, !, ~, ?, (, )
* In order to make it simple, I replace everything which is not A-Z, 0-9, space, : , .
* Finally put everything between () as this is the way GRBL & UGCS expect comments
*/
function formatComment(text)
{
return ("(" + filterText(String(text), permittedCommentChars) + ")");
}
/**
* return seconds as a h:m:s string
* @param secs seconds of time
*/
function getTimeText(secs)
{
var machineTimeInSeconds = secs;
var machineTimeHours = Math.floor(machineTimeInSeconds / 3600);
machineTimeInSeconds = machineTimeInSeconds % 3600; // remove the hours
var machineTimeMinutes = Math.floor(machineTimeInSeconds / 60);
var machineTimeSeconds = Math.floor(machineTimeInSeconds % 60); // remove the minutes
var machineTimeText = subst(localize("%1h:%2m:%3s"), machineTimeHours, machineTimeMinutes, machineTimeSeconds);
return machineTimeText;
}
/**
* returns the time as 'machining time 00h00m00s'
*/
function getMachineTime(sec)
{
var machineTimeInSeconds = sec.getCycleTime();
var machineTimeText = " Machining time : ";
machineTimeText += getTimeText(machineTimeInSeconds);
return machineTimeText;
}
/**
* Writes a formatted G-code comment to the output file, automatically handling line wrapping.
*
* This function takes a string and formats it as a valid GRBL comment (e.g., "(My Comment)").
* If the input text exceeds 70 characters, it intelligently splits the string at word
* boundaries to create multiple comment lines, each under the length limit. This prevents
* issues with G-code controllers that may not handle very long single-line comments.
*
* @param {string} text The comment string to write. Can be a single line or a long string that needs wrapping.
* @returns {void}
*/
function writeComment(text)
{
// v20 - split the line so no comment is longer than 70 chars
if (text)
if (text.length > 70)
{
//text = String(text).replace( /[^a-zA-Z\d:=,.]+/g, " "); // remove illegal chars
text = filterText(text.trim(), permittedCommentChars);
var bits = text.split(" "); // get all the words
var out = '';
for (i = 0; i < bits.length; i++)
{
out += bits[i] + " "; // additional space after first line
if (out.length > 60) // a long word on the end can take us to 80 chars!
{
writeln(formatComment( out.trim() ) );
out = "";
}
}
if (out.length > 0)
writeln(formatComment( out.trim() ) );
}
else
writeln(formatComment(text));
}
/**
* Writes the header information at the beginning of a G-code file.
*
* This function generates a comprehensive header containing metadata about the job,
* the post-processor, and the machine setup. It includes:
* - Product and post-processor version information.
* - Unit system (mm or inch).
* - Warnings for unsupported features (e.g., multiple tools in a single file).
* - A detailed list of all operations (or a subset for multi-file jobs),
* including tool details, spindle speeds, work coordinates, and estimated machining time.
* - For multi-file jobs, it lists all generated filenames in the header of the first file.
* - It concludes by setting up the initial G-code modal states (G90, G94, G17, G21/G20).
*
* @param {number} secID The starting section (operation) ID. For the first file, this is 0.
* For subsequent files in a multi-file job, this will be the ID of the first
* operation in that new file.
* @returns {void}
*/
function writeHeader(secID)
{
//writeComment("Header start " + secID);
if (multipleToolError)
{
writeComment("Warning: Multiple tools found. This post does not support tool changes. You should repost and select True for Multiple Files in the post properties.");
writeln("");
}
var productName = getProduct();
writeComment("Made in : " + productName);
writeComment("G-Code optimized for " + properties.machineControl + " controller");
writeComment(description);
cpsname = FileSystem.getFilename(getConfigurationPath());
writeComment("Post-Processor : " + cpsname + " " + obversion );
//writeComment("Post processor documentation: " + properties.postProcessorDocs );
var unitstr = (unit == MM) ? 'mm' : 'inch';
writeComment("Units = " + unitstr );
if (isJet())
{
writeComment("Laser UseZ = " + properties.UseZ);
writeComment("Laser UsePierce = " + properties.UsePierce);
}
if (allowedCircularPlanes == 1)
{
writeln("");
writeComment("Arcs are limited to the XY plane: if you want vertical arcs then edit allowedCircularPlanes in the CPS file");
}
else
{
writeln("");
writeComment("Arcs can occur on XY,YZ,ZX planes: CONTROL may not display them correctly but they will cut correctly");
}
writeln("");
if (hasGlobalParameter("document-path"))
{
var path = getGlobalParameter("document-path");
if (path)
{
writeComment("Drawing name : " + path);
}
}
if (programName)
{
writeComment("Program Name : " + programName);
}
if (programComment)
{
writeComment("Program Comments : " + programComment);
}
// output stock size
var xl = getGlobalParameter('stock-lower-x');
var yl = getGlobalParameter('stock-lower-y');
var xu = getGlobalParameter('stock-upper-x');
var yu = getGlobalParameter('stock-upper-y');
var zl = getGlobalParameter('stock-lower-z');
var zu = getGlobalParameter('stock-upper-z');
var xs = xu - xl;
var ys = yu - yl;
var zs = zu - zl;
writeComment("Stock : XxYxZ : " + xs.toPrecision(2) + "x" + ys.toPrecision(2) + "x" + zs.toPrecision(2) )
writeln("");
numberOfSections = getNumberOfSections();
if (properties.generateMultiple && filesToGenerate > 1)
{
if (properties.splitLines > 0)
{
writeComment("Since we are splitting on line count we don't know how many files will be written.");
writeComment("There will be at least " + filesToGenerate + " files, from the number of tools.");
writeComment("Files will be named like programName.01ofMany.nc")
writeComment(numberOfSections + " Operation" + ((numberOfSections == 1) ? "" : "s") );
}
else
{
writeComment(numberOfSections + " Operation" + ((numberOfSections == 1) ? "" : "s") + " in " + filesToGenerate + " files.");
writeComment("File List:");
//writeComment(" " + FileSystem.getFilename(getOutputPath()));
for (var i = 0; i < filesToGenerate; ++i)
{
filename = makeFileName(i + 1);
writeComment(" " + filename);
}
writeln("");
writeComment("This is file: " + sequenceNumber + " of " + filesToGenerate);
}
writeln("");
writeComment("This file contains the following operations: ");
}
else
{
writeComment(numberOfSections + " Operation" + ((numberOfSections == 1) ? "" : "s") + " :");
}
var totalSeconds = 0;
for (var i = secID; i < numberOfSections; ++i)
{
var section = getSection(i);
var tool = section.getTool();
var rpm = section.getMaximumSpindleSpeed();
setOperationType(tool);
if (section.hasParameter("operation-comment"))
{
var op = section.getParameter("operation-comment");
writeComment((i + 1) + " : " + op);
}
else
{
writeComment(i + 1);
var op = i + 1;
}
if (section.workOffset > 0)
{
writeComment(" Work Coordinate System : G" + (section.workOffset + 53));
}
if (OB.isLaser || OB.isPlasma)
{
writeComment(" Tool #" + tool.number + ": " + toTitleCase(getToolTypeName(tool.type)) + " Diam = " + xyzFormat.format(tool.jetDiameter) + unitstr);
if (OB.isPlasma)
writeComment("How to use this post for plasma https://github.com/OpenBuilds/OpenBuilds-Fusion360-Postprocessor/blob/master/README-plasma.md");
if (OB.isLaser)
switch (section.getJetMode() )
{
case JET_MODE_THROUGH:
OB.power = calcPower(properties.PowerThrough);
writeComment(" LASER THROUGH CUTTING " + properties.PowerThrough + "percent = S" + OB.power);
break;
case JET_MODE_ETCHING:
OB.power = calcPower(properties.PowerEtch);
writeComment(" LASER ETCH CUTTING " + properties.PowerEtch + "percent = S" + OB.power);
break;
case JET_MODE_VAPORIZE:
OB.power = calcPower(properties.PowerVaporise);
writeComment(" LASER VAPORIZE CUTTING " + properties.PowerVaporise + "percent = S" + OB.power);
break;
default:
error(localize("Unsupported cutting mode."));
return;
}
}
else
{
if (getToolTypeName( tool.type) == 'probe')
writeComment(" Tool #" + tool.number + ": " + toTitleCase(getToolTypeName(tool.type)) + " Diam = " + xyzFormat.format(tool.diameter) + unitstr + ", Len = " + tool.fluteLength.toFixed(2) + unitstr);
else
{
writeComment(" Tool #" + tool.number + ": " + toTitleCase(getToolTypeName(tool.type)) + " " + tool.numberOfFlutes + " Flutes, Diam = " + xyzFormat.format(tool.diameter) + unitstr + ", Len = " + tool.fluteLength.toFixed(2) + unitstr);
if (isProbeOperation())
{
writeComment('Probing, no dial to set') ;
}
else
if (properties.routerType != "other")
{
writeComment(" Spindle : RPM = " + round(rpm, 0) + ", set " + properties.routerType + " dial to " + rpm2dial(rpm, op));
}
else
{
writeComment(" Spindle : RPM = " + round(rpm, 0) + " " + properties.routerType);
}
}
}
if (section.strategy != 'probe')
checkMinFeedrate(section, op);
machineTimeText = getMachineTime(section);
totalSeconds += section.getCycleTime();
writeComment(machineTimeText);
if (properties.generateMultiple && (i + 1 < numberOfSections))
{
if (tool.number != getSection(i + 1).getTool().number)
{
writeln("");
writeComment("Remaining operations located in additional files.");
break;
}
}
}
machineTimeText = "Total Machining time : " + getTimeText(totalSeconds);
writeComment(machineTimeText);
writeln("");
// Restore the OB state to be correct for the current tool. The loop above
// will have left the state set for the *last* tool in the entire job.
setOperationType(getSection(secID).getTool());
if (OB.isLaser || OB.isPlasma)
{