forked from swarfer/GRBL-Post-Processor
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathOpenbuildsFusion360PostGrbl.cps
2511 lines (2347 loc) · 101 KB
/
OpenbuildsFusion360PostGrbl.cps
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
*/
obversion = 'V1.0.43';
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 2024";
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.
// things for splitting on linecount, aka tapesplitting
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 to 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
cutmode : 0, // M3 or M4
cuttingMode : 'none', // set by onParameter for laser/plasma
haveRapid : false // assume no rapid moves
}
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 topheight 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 = 54;// 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 toTitleCase(str)
{
// function to reformat a string to 'title case'
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();
});
}
function rpm2dial(rpm, op)
{
// translates an RPM for the spindle into a dial value, eg. for the Makita RT0700 and Dewalt 611 routers
// additionally, check that spindle rpm is between minimum and maximum of what our spindle can do
// array which maps spindle speeds to router dial settings,
// according to Makita RT0700 Manual : 1=10000, 2=12000, 3=17000, 4=22000, 5=27000, 6=30000
// according to Dewalt 611 Manual : 1=16000, 2=18200, 3=20400, 4=22600, 5=24800, 6=27000
var wmsg = "";
if (isProbeOperation())
return 1;
if (properties.routerType == "Dewalt")
{
var speeds = [0, 16000, 18200, 20400, 22600, 24800, 27000];
}
else
if (properties.routerType == "Router11")
{
var speeds = [0, 10000, 14000, 18000, 23000, 27000, 32000];
}
else
{
// this is Makita R0701
var speeds = [0, 10000, 12000, 17000, 22000, 27000, 30000];
}
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;
}
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]);
}
}
function myMachineConfig()
{
// 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.
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) + ")");
}
/**
* returns the time as 'machining time 00h00m00s'
*/
function getMachineTime(sec)
{
var machineTimeInSeconds = sec.getCycleTime();
var machineTimeHours = Math.floor(machineTimeInSeconds / 3600);
machineTimeInSeconds = machineTimeInSeconds % 3600;
var machineTimeMinutes = Math.floor(machineTimeInSeconds / 60);
var machineTimeSeconds = Math.floor(machineTimeInSeconds % 60);
var machineTimeText = " Machining time : ";
machineTimeText += subst(localize("%1h:%2m:%3s"), machineTimeHours, machineTimeMinutes, machineTimeSeconds);
return machineTimeText;
}
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));
}
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);
}
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") + " :");
}
for (var i = secID; i < numberOfSections; ++i)
{
var section = getSection(i);
var tool = section.getTool();
var rpm = section.getMaximumSpindleSpeed();
OB.isLaser = OB.isPlasma = false;
switch (tool.type)
{
case TOOL_LASER_CUTTER:
OB.isLaser = true;
break;
case TOOL_WATER_JET:
case TOOL_PLASMA_CUTTER:
OB.isPlasma = true;
break;
default:
OB.isLaser = false;
OB.isPlasma = false;
}
if (section.hasParameter("operation-comment"))
{
writeComment((i + 1) + " : " + section.getParameter("operation-comment"));
var op = section.getParameter("operation-comment")
}
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);
writeComment("howto use this post for plasma https://github.com/OpenBuilds/OpenBuilds-Fusion360-Postprocessor/blob/master/README-plasma.md");
}
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));
}
}
}
if (section.strategy != 'probe')
checkMinFeedrate(section, op);
machineTimeText = getMachineTime(section);
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;
}
}
}
if (OB.isLaser || OB.isPlasma)
{
allowHelicalMoves = false; // laser/plasma not doing this, ever
}
writeln("");
gAbsIncModal.reset();
gFeedModeModal.reset();
gPlaneModal.reset();
writeBlock(gAbsIncModal.format(90), gFeedModeModal.format(94), gPlaneModal.format(17) );
switch (unit)
{
case IN:
writeBlock(gUnitModal.format(20));
break;
case MM:
writeBlock(gUnitModal.format(21));
break;
}
//writeComment("Header end");
writeln("");
if (debugMode)
{
var msg = "debugMode is true";
writeComment(msg);
warning(msg);
writeln("");
}
}
function onOpen()
{
receivedMachineConfiguration = machineConfiguration.isReceived();
if (typeof defineMachine == "function")
{
defineMachine(); // hardcoded machine configuration
}
activateMachine(); // enable the machine optimizations and settings
// 3. moved to top of file
//myMachineConfig();
numberOfSections = getNumberOfSections();
if (properties.splitLines > 0)
{
SPL.tapelines = properties.splitLines;
}
if (debugMode) writeComment("onOpen");
// Number of checks capturing fatal errors
// 2. is RadiusCompensation not set incorrectly ?
onRadiusCompensation();
// 4. checking for duplicate tool numbers with the different geometry.
// check for duplicate tool number
for (var i = 0; i < getNumberOfSections(); ++i)
{
var sectioni = getSection(i);
var tooli = sectioni.getTool();
if (i < (getNumberOfSections() - 1) && (tooli.number != getSection(i + 1).getTool().number))
{
filesToGenerate++;
}
for (var j = i + 1; j < getNumberOfSections(); ++j)
{
var sectionj = getSection(j);
var toolj = sectionj.getTool();
if (tooli.number == toolj.number)
{
if (xyzFormat.areDifferent(tooli.diameter, toolj.diameter) ||
xyzFormat.areDifferent(tooli.cornerRadius, toolj.cornerRadius) ||
abcFormat.areDifferent(tooli.taperAngle, toolj.taperAngle) ||
(tooli.numberOfFlutes != toolj.numberOfFlutes))
{
error( subst(
localize("Using the same tool number for different cutter geometry for operation '%1' and '%2'."),
sectioni.hasParameter("operation-comment") ? sectioni.getParameter("operation-comment") : ("#" + (i + 1)),
sectionj.hasParameter("operation-comment") ? sectionj.getParameter("operation-comment") : ("#" + (j + 1))
) );
return;
}
}
else
{
if (properties.generateMultiple == false)
{
multipleToolError = true;
}
}
}
}
if (multipleToolError)
{
var mte = "WARNING " + "Multiple tools found. This post does not support tool changes. You should repost and select True for Multiple Files in the post properties.";
warning(mte);
writeComment(mte);
}
writeHeader(0);
gMotionModal.reset();
if (properties.plasma_usetouchoff)
properties.UseZ = true; // force it on, we need Z motion, always
if (properties.UseZ)
zOutput.format(1);
else
zOutput.format(0);
//writeComment("onOpen end");
}
function onComment(message)
{
writeComment(message);
}
function forceXYZ()
{
xOutput.reset();
yOutput.reset();
zOutput.reset();
}
function forceAny()
{
forceXYZ();
feedOutput.reset();
gMotionModal.reset();
}
function forceAll()
{
//writeComment("forceAll");
forceAny();
sOutput.reset();
gAbsIncModal.reset();
gFeedModeModal.reset();
gMotionModal.reset();
gPlaneModal.reset();
gUnitModal.reset();