forked from grblHAL/core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcode.c
3045 lines (2481 loc) · 135 KB
/
gcode.c
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
/*
gcode.c - rs274/ngc parser.
Part of grblHAL
Copyright (c) 2017-2022 Terje Io
Copyright (c) 2011-2016 Sungeun K. Jeon for Gnea Research LLC
Copyright (c) 2009-2011 Simen Svale Skogsrud
Grbl is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Grbl is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Grbl. If not, see <http://www.gnu.org/licenses/>.
*/
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "hal.h"
#include "motion_control.h"
#include "protocol.h"
#include "state_machine.h"
#if NGC_EXPRESSIONS_ENABLE
#include "ngc_expr.h"
#include "ngc_params.h"
#endif
// NOTE: Max line number is defined by the g-code standard to be 99999. It seems to be an
// arbitrary value, and some GUIs may require more. So we increased it based on a max safe
// value when converting a float (7.2 digit precision)s to an integer.
#define MAX_LINE_NUMBER 10000000
#ifdef N_TOOLS
#define MAX_TOOL_NUMBER N_TOOLS // Limited by max unsigned 8-bit value
#else
#define MAX_TOOL_NUMBER 4294967294 // Limited by max unsigned 32-bit value - 1
#endif
#define MACH3_SCALING
// Do not change, must be same as axis indices
#define I_VALUE X_AXIS
#define J_VALUE Y_AXIS
#define K_VALUE Z_AXIS
// Define modal groups internal bitfield for checking multiple command violations and tracking the
// type of command that is called in the block. A modal group is a group of g-code commands that are
// mutually exclusive, or cannot exist on the same line, because they each toggle a state or execute
// a unique motion. These are defined in the NIST RS274-NGC v3 g-code standard, available online,
// and are similar/identical to other g-code interpreters by manufacturers (Haas,Fanuc,Mazak,etc).
typedef union {
uint32_t mask;
struct {
uint32_t G0 :1, //!< [G4,G10,G28,G28.1,G30,G30.1,G53,G92,G92.1] Non-modal
G1 :1, //!< [G0,G1,G2,G3,G33,G38.2,G38.3,G38.4,G38.5,G76,G80] Motion
G2 :1, //!< [G17,G18,G19] Plane selection
G3 :1, //!< [G90,G91] Distance mode
G4 :1, //!< [G91.1] Arc IJK distance mode
G5 :1, //!< [G93,G94,G95] Feed rate mode
G6 :1, //!< [G20,G21] Units
G7 :1, //!< [G40] Cutter radius compensation mode. G41/42 NOT SUPPORTED.
G8 :1, //!< [G43,G43.1,G49] Tool length offset
G10 :1, //!< [G98,G99] Return mode in canned cycles
G11 :1, //!< [G50,G51] Scaling
G12 :1, //!< [G54,G55,G56,G57,G58,G59] Coordinate system selection
G13 :1, //!< [G61] Control mode
G14 :1, //!< [G96,G97] Spindle Speed Mode
G15 :1, //!< [G7,G8] Lathe Diameter Mode
M4 :1, //!< [M0,M1,M2,M30] Stopping
M6 :1, //!< [M6] Tool change
M7 :1, //!< [M3,M4,M5] Spindle turning
M8 :1, //!< [M7,M8,M9] Coolant control
M9 :1, //!< [M49,M50,M51,M53,M56] Override control
M10 :1; //!< User defined M commands
};
} modal_groups_t;
typedef enum {
AxisCommand_None = 0,
AxisCommand_NonModal,
AxisCommand_MotionMode,
AxisCommand_ToolLengthOffset,
AxisCommand_Scaling
} axis_command_t;
typedef struct {
parameter_words_t parameter;
modal_groups_t modal_group;
} word_bit_t;
typedef union {
uint_fast8_t mask;
struct {
uint_fast8_t i :1,
j :1,
k :1;
};
} ijk_words_t;
// Declare gc extern struct
parser_state_t gc_state, *saved_state = NULL;
#ifdef N_TOOLS
tool_data_t tool_table[N_TOOLS + 1];
#else
tool_data_t tool_table;
#endif
#define FAIL(status) return(status);
static gc_thread_data thread;
static output_command_t *output_commands = NULL; // Linked list
static scale_factor_t scale_factor = {
.ijk[X_AXIS] = 1.0f,
.ijk[Y_AXIS] = 1.0f,
.ijk[Z_AXIS] = 1.0f
#ifdef A_AXIS
, .ijk[A_AXIS] = 1.0f
#endif
#ifdef B_AXIS
, .ijk[B_AXIS] = 1.0f
#endif
#ifdef C_AXIS
, .ijk[C_AXIS] = 1.0f
#endif
#ifdef U_AXIS
, .ijk[U_AXIS] = 1.0f
#endif
#ifdef V_AXIS
, .ijk[V_AXIS] = 1.0f
#endif
};
// Simple hypotenuse computation function.
inline static float hypot_f (float x, float y)
{
return sqrtf(x * x + y * y);
}
inline static bool motion_is_lasercut (motion_mode_t motion)
{
return motion == MotionMode_Linear || motion == MotionMode_CwArc || motion == MotionMode_CcwArc || motion == MotionMode_CubicSpline;
}
parser_state_t *gc_get_state (void)
{
return &gc_state;
}
static void set_scaling (float factor)
{
uint_fast8_t idx = N_AXIS;
axes_signals_t state = gc_get_g51_state();
do {
scale_factor.ijk[--idx] = factor;
#ifdef MACH3_SCALING
scale_factor.xyz[idx] = 0.0f;
#endif
} while(idx);
gc_state.modal.scaling_active = factor != 1.0f;
if(state.value != gc_get_g51_state().value)
sys.report.scaling = On;
}
float *gc_get_scaling (void)
{
return scale_factor.ijk;
}
axes_signals_t gc_get_g51_state ()
{
uint_fast8_t idx = N_AXIS;
axes_signals_t scaled = {0};
do {
scaled.value <<= 1;
if(scale_factor.ijk[--idx] != 1.0f)
scaled.value |= 0x01;
} while(idx);
return scaled;
}
float gc_get_offset (uint_fast8_t idx)
{
return gc_state.modal.coord_system.xyz[idx] + gc_state.g92_coord_offset[idx] + gc_state.tool_length_offset[idx];
}
inline static float gc_get_block_offset (parser_block_t *gc_block, uint_fast8_t idx)
{
return gc_block->modal.coord_system.xyz[idx] + gc_state.g92_coord_offset[idx] + gc_state.tool_length_offset[idx];
}
void gc_set_tool_offset (tool_offset_mode_t mode, uint_fast8_t idx, int32_t offset)
{
bool tlo_changed = false;
switch(mode) {
case ToolLengthOffset_Cancel:
idx = N_AXIS;
do {
idx--;
tlo_changed |= gc_state.tool_length_offset[idx] != 0.0f;
gc_state.tool_length_offset[idx] = 0.0f;
gc_state.tool->offset[idx] = 0;
} while(idx);
break;
case ToolLengthOffset_EnableDynamic:
{
float new_offset = offset / settings.axis[idx].steps_per_mm;
tlo_changed |= gc_state.tool_length_offset[idx] != new_offset;
gc_state.tool_length_offset[idx] = new_offset;
gc_state.tool->offset[idx] = offset;
}
break;
default:
break;
}
gc_state.modal.tool_offset_mode = mode;
if(tlo_changed) {
sys.report.tool_offset = true;
system_flag_wco_change();
}
}
plane_t *gc_get_plane_data (plane_t *plane, plane_select_t select)
{
switch (select) {
case PlaneSelect_XY:
plane->axis_0 = X_AXIS;
plane->axis_1 = Y_AXIS;
plane->axis_linear = Z_AXIS;
break;
case PlaneSelect_ZX:
plane->axis_0 = Z_AXIS;
plane->axis_1 = X_AXIS;
plane->axis_linear = Y_AXIS;
break;
default: // case PlaneSelect_YZ:
plane->axis_0 = Y_AXIS;
plane->axis_1 = Z_AXIS;
plane->axis_linear = X_AXIS;
}
return plane;
}
void gc_init (void)
{
#if COMPATIBILITY_LEVEL > 1
memset(&gc_state, 0, sizeof(parser_state_t));
#ifdef N_TOOLS
gc_state.tool = &tool_table[0];
#else
memset(&tool_table, 0, sizeof(tool_table));
gc_state.tool = &tool_table;
#endif
#else
if(sys.cold_start) {
memset(&gc_state, 0, sizeof(parser_state_t));
#ifdef N_TOOLS
gc_state.tool = &tool_table[0];
#else
memset(&tool_table, 0, sizeof(tool_table));
gc_state.tool = &tool_table;
#endif
} else {
memset(&gc_state, 0, offsetof(parser_state_t, g92_coord_offset));
gc_state.tool_pending = gc_state.tool->tool;
if(hal.tool.select)
hal.tool.select(gc_state.tool, false);
// TODO: restore offsets, tool offset mode?
}
#endif
// Clear any pending output commands
while(output_commands) {
output_command_t *next = output_commands->next;
free(output_commands);
output_commands = next;
}
// Load default override status
gc_state.modal.override_ctrl = sys.override.control;
gc_state.spindle.css.max_rpm = settings.spindle.rpm_max; // default max speed for CSS mode
set_scaling(1.0f);
// Load default G54 coordinate system.
if (!settings_read_coord_data(gc_state.modal.coord_system.id, &gc_state.modal.coord_system.xyz))
grbl.report.status_message(Status_SettingReadFail);
if (sys.cold_start && !settings.flags.g92_is_volatile && !settings_read_coord_data(CoordinateSystem_G92, &gc_state.g92_coord_offset))
grbl.report.status_message(Status_SettingReadFail);
// if(settings.flags.lathe_mode)
// gc_state.modal.plane_select = PlaneSelect_ZX;
}
// Set dynamic laser power mode to PPI (Pulses Per Inch)
// Returns true if driver uses hardware implementation.
// Driver support for pulsing the laser on signal is required for this to work.
bool gc_laser_ppi_enable (uint_fast16_t ppi, uint_fast16_t pulse_length)
{
gc_state.is_laser_ppi_mode = ppi > 0 && pulse_length > 0;
return grbl.on_laser_ppi_enable && grbl.on_laser_ppi_enable(ppi, pulse_length);
}
void gc_spindle_off (void)
{
gc_state.spindle.rpm = sys.spindle_rpm = 0.0f;
gc_state.modal.spindle.value = 0;
#ifndef GRBL_ESP32
hal.spindle.set_state(gc_state.modal.spindle, 0.0f);
#else
hal.spindle.esp32_off();
#endif
sys.report.spindle = On;
}
void gc_coolant_off (void)
{
gc_state.modal.coolant.value = 0;
hal.coolant.set_state(gc_state.modal.coolant);
sys.report.coolant = On;
}
// Add output command to linked list
static bool add_output_command (output_command_t *command)
{
output_command_t *add_cmd;
if((add_cmd = malloc(sizeof(output_command_t)))) {
memcpy(add_cmd, command, sizeof(output_command_t));
if(output_commands == NULL)
output_commands = add_cmd;
else {
output_command_t *cmd = output_commands;
while(cmd->next)
cmd = cmd->next;
cmd->next = add_cmd;
}
}
return add_cmd != NULL;
}
static status_code_t init_sync_motion (plan_line_data_t *pl_data, float pitch)
{
pl_data->condition.inverse_time = Off;
pl_data->feed_rate = gc_state.distance_per_rev = pitch;
pl_data->condition.is_rpm_pos_adjusted = Off; // Switch off CSS.
pl_data->overrides = sys.override.control; // Use current override flags and
pl_data->overrides.sync = On; // set to sync overrides on execution of motion.
// Disable feed rate and spindle overrides for the duration of the cycle.
pl_data->overrides.spindle_rpm_disable = sys.override.control.spindle_rpm_disable = On;
pl_data->overrides.feed_rate_disable = sys.override.control.feed_rate_disable = On;
sys.override.spindle_rpm = DEFAULT_SPINDLE_RPM_OVERRIDE;
// TODO: need for gc_state.distance_per_rev to be reset on modal change?
float feed_rate = pl_data->feed_rate * hal.spindle.get_data(SpindleData_RPM)->rpm;
if(feed_rate == 0.0f)
FAIL(Status_GcodeSpindleNotRunning); // [Spindle not running]
if(feed_rate > settings.axis[Z_AXIS].max_rate * 0.9f)
FAIL(Status_GcodeMaxFeedRateExceeded); // [Feed rate too high]
return Status_OK;
}
// Remove whitespace, control characters, comments and if block delete is active block delete lines
// else the block delete character. Remaining characters are converted to upper case.
// If the driver handles message comments then the first is extracted and returned in a dynamically
// allocated memory block, the caller must free this after the message has been processed.
char *gc_normalize_block (char *block, char **message)
{
char c, *s1, *s2, *comment = NULL;
// Remove leading whitespace & control characters
while(*block && *block <= ' ')
block++;
if(*block == ';' || (*block == '/' && sys.flags.block_delete_enabled)) {
*block = '\0';
return block;
}
if(*block == '/')
block++;
s1 = s2 = block;
while((c = *s1) != '\0') {
if(c > ' ') switch(c) {
case ';':
if(!comment) {
*s1 = '\0';
continue;
}
break;
case '(':
// TODO: generate error if a left paranthesis is found inside a comment...
comment = s1;
break;
case ')':
if(comment && !hal.driver_cap.no_gcode_message_handling) {
size_t len = s1 - comment - 4;
if(message && *message == NULL && !strncmp(comment, "(MSG,", 5) && (*message = malloc(len))) {
*s1 = '\0';
memcpy(*message, comment + 5, len);
}
}
comment = NULL;
break;
default:
if(comment == NULL)
*s2++ = CAPS(c);
break;
}
if(comment && s1 - comment < 5)
*s1 = CAPS(c);
s1++;
}
*s2 = '\0';
return block;
}
#if NGC_EXPRESSIONS_ENABLE
#define NGC_N_ASSIGN_PARAMETERS_PER_BLOCK 10
static ngc_param_t ngc_params[NGC_N_ASSIGN_PARAMETERS_PER_BLOCK];
static status_code_t read_parameter (char *line, uint_fast8_t *char_counter, float *value)
{
char c = *(line + *char_counter);
status_code_t status = Status_OK;
if(c == '#') {
(*char_counter)++;
if(*(line + *char_counter) == '<') {
(*char_counter)++;
char *pos = line + *char_counter;
while(*line && *line != '>')
line++;
*char_counter += line - pos + 1;
if(*line == '>') {
*line = '\0';
if(!ngc_named_param_get(pos, value))
status = Status_BadNumberFormat;
} else
status = Status_BadNumberFormat;
} else if (read_float(line, char_counter, value)) {
if(!ngc_param_get((ngc_param_id_t)*value, value))
status = Status_BadNumberFormat;
} else
status = Status_BadNumberFormat;
} else if(c == '[')
status = ngc_eval_expression(line, char_counter, value);
else if(!read_float(line, char_counter, value))
*value = NAN;
return status;
}
#endif
// Parses and executes one block (line) of 0-terminated G-Code.
// In this function, all units and positions are converted and exported to internal functions
// in terms of (mm, mm/min) and absolute machine coordinates, respectively.
status_code_t gc_execute_block(char *block)
{
static const parameter_words_t axis_words_mask = {
.x = On,
.y = On,
.z = On
#ifdef A_AXIS
, .a = On
#endif
#ifdef B_AXIS
, .b = On
#endif
#ifdef C_AXIS
, .c = On
#endif
#ifdef U_AXIS
, .u = On
#endif
#ifdef V_AXIS
, .v = On
#endif
};
static const parameter_words_t pq_words = {
.p = On,
.q = On
};
static const parameter_words_t ij_words = {
.i = On,
.j = On
};
static const parameter_words_t positive_only_words = {
.d = On,
.f = On,
.h = On,
.n = On,
.t = On,
.s = On
};
static const modal_groups_t jog_groups = {
.G0 = On,
.G3 = On,
.G6 = On
};
static parser_block_t gc_block;
#if NGC_EXPRESSIONS_ENABLE
uint_fast8_t ngc_param_count = 0;
#endif
char *message = NULL;
block = gc_normalize_block(block, &message);
if(block[0] == '\0') {
if(message) {
report_message(message, Message_Plain);
free(message);
}
return Status_OK;
}
// Determine if the line is a program start/end marker.
// Old comment from protocol.c:
// NOTE: This maybe installed to tell Grbl when a program is running vs manual input,
// where, during a program, the system auto-cycle start will continue to execute
// everything until the next '%' sign. This will help fix resuming issues with certain
// functions that empty the planner buffer to execute its task on-time.
if (block[0] == CMD_PROGRAM_DEMARCATION && block[1] == '\0') {
gc_state.file_run = !gc_state.file_run;
if(message) {
report_message(message, Message_Plain);
free(message);
}
return Status_OK;
}
/* -------------------------------------------------------------------------------------
STEP 1: Initialize parser block struct and copy current g-code state modes. The parser
updates these modes and commands as the block line is parsed and will only be used and
executed after successful error-checking. The parser block struct also contains a block
values struct, word tracking variables, and a non-modal commands tracker for the new
block. This struct contains all of the necessary information to execute the block. */
memset(&gc_block, 0, sizeof(gc_block)); // Initialize the parser block struct.
memcpy(&gc_block.modal, &gc_state.modal, sizeof(gc_state.modal)); // Copy current modes
bool set_tool = false;
axis_command_t axis_command = AxisCommand_None;
uint_fast8_t port_command = 0;
plane_t plane;
// Initialize bitflag tracking variables for axis indices compatible operations.
axes_signals_t axis_words = {0}; // XYZ tracking
ijk_words_t ijk_words = {0}; // IJK tracking
// Initialize command and value words and parser flags variables.
modal_groups_t command_words = {0}; // Bitfield for tracking G and M command words. Also used for modal group violations.
gc_parser_flags_t gc_parser_flags = {0}; // Parser flags for handling special cases.
static parameter_words_t user_words = {0}; // User M-code words "taken"
// Determine if the line is a jogging motion or a normal g-code block.
if (block[0] == '$') { // NOTE: `$J=` already parsed when passed to this function.
// Set G1 and G94 enforced modes to ensure accurate error checks.
gc_parser_flags.jog_motion = On;
gc_block.modal.motion = MotionMode_Linear;
gc_block.modal.feed_mode = FeedMode_UnitsPerMin;
gc_block.modal.spindle_rpm_mode = SpindleSpeedMode_RPM;
gc_block.values.n = JOG_LINE_NUMBER; // Initialize default line number reported during jog.
}
/* -------------------------------------------------------------------------------------
STEP 2: Import all g-code words in the block. A g-code word is a letter followed by
a number, which can either be a 'G'/'M' command or sets/assigns a command value. Also,
perform initial error-checks for command word modal group violations, for any repeated
words, and for negative values set for the value words F, N, P, T, and S. */
uint_fast8_t char_counter = gc_parser_flags.jog_motion ? 3 /* Start parsing after `$J=` */ : 0;
char letter;
float value;
uint32_t int_value = 0;
uint_fast16_t mantissa = 0;
bool is_user_mcode = false;
word_bit_t word_bit = { .parameter = {0}, .modal_group = {0} }; // Bit-value for assigning tracking variables
while ((letter = block[char_counter++]) != '\0') { // Loop until no more g-code words in block.
// Import the next g-code word, expecting a letter followed by a value. Otherwise, error out.
#if NGC_EXPRESSIONS_ENABLE
status_code_t status;
if(letter == '#') {
if(block[char_counter] == '<') {
char *s = &block[++char_counter];
while(*s && *s != '>')
s++;
if(*s && *(s + 1) == '=') {
char *name = &block[char_counter];
*s++ = '\0';
s++;
char_counter += s - name;
if((status = read_parameter(block, &char_counter, &value)) != Status_OK)
FAIL(status); // [Expected parameter value]
if(!ngc_named_param_set(name, value))
FAIL(Status_BadNumberFormat); // [Expected equal sign]
}
} else {
float param;
if (!read_float(block, &char_counter, ¶m))
FAIL(Status_BadNumberFormat); // [Expected parameter number]
if (block[char_counter++] != '=')
FAIL(Status_BadNumberFormat); // [Expected equal sign]
if((status = read_parameter(block, &char_counter, &value)) != Status_OK)
FAIL(status); // [Expected parameter value]
if(ngc_param_count < NGC_N_ASSIGN_PARAMETERS_PER_BLOCK && ngc_param_is_rw((ngc_param_id_t)param)) {
ngc_params[ngc_param_count].id = (ngc_param_id_t)param;
ngc_params[ngc_param_count++].value = value;
} else
FAIL(Status_BadNumberFormat); // [Expected parameter value]
}
continue;
}
if((letter < 'A') || (letter > 'Z'))
FAIL(Status_ExpectedCommandLetter); // [Expected word letter]
if((status = read_parameter(block, &char_counter, &value)) != Status_OK)
return status;
if(!is_user_mcode && isnanf(value))
FAIL(Status_BadNumberFormat); // [Expected word value]
#else
if((letter < 'A') || (letter > 'Z'))
FAIL(Status_ExpectedCommandLetter); // [Expected word letter]
if (!read_float(block, &char_counter, &value)) {
if(is_user_mcode) // Valueless parameters allowed for user defined M-codes.
value = NAN; // Parameter validation deferred to implementation.
else
FAIL(Status_BadNumberFormat); // [Expected word value]
}
#endif
// Convert values to smaller uint8 significand and mantissa values for parsing this word.
// NOTE: Mantissa is multiplied by 100 to catch non-integer command values. This is more
// accurate than the NIST gcode requirement of x10 when used for commands, but not quite
// accurate enough for value words that require integers to within 0.0001. This should be
// a good enough comprimise and catch most all non-integer errors. To make it compliant,
// we would simply need to change the mantissa to int16, but this add compiled flash space.
// Maybe update this later.
if(isnan(value))
mantissa = 0;
else {
int_value = (uint32_t)truncf(value);
mantissa = (uint_fast16_t)roundf(100.0f * (value - int_value));
}
// NOTE: Rounding must be used to catch small floating point errors.
// Check if the g-code word is supported or errors due to modal group violations or has
// been repeated in the g-code block. If ok, update the command or record its value.
switch(letter) {
/* 'G' and 'M' Command Words: Parse commands and check for modal group violations.
NOTE: Modal group numbers are defined in Table 4 of NIST RS274-NGC v3, pg.20 */
case 'G': // Determine 'G' command and its modal group
is_user_mcode = false;
word_bit.modal_group.mask = 0;
switch(int_value) {
case 7: case 8:
if(sys.mode == Mode_Lathe) {
word_bit.modal_group.G15 = On;
gc_block.modal.diameter_mode = int_value == 7; // TODO: find specs for implementation, only affects X calculation? reporting? current position?
} else
FAIL(Status_GcodeUnsupportedCommand); // [G7 & G8 not supported]
break;
case 10: case 28: case 30: case 92:
// Check for G10/28/30/92 being called with G0/1/2/3/38 on same block.
// * G43.1 is also an axis command but is not explicitly defined this way.
if (mantissa == 0) { // Ignore G28.1, G30.1, and G92.1
if (axis_command)
FAIL(Status_GcodeAxisCommandConflict); // [Axis word/command conflict]
axis_command = AxisCommand_NonModal;
}
// No break. Continues to next line.
case 4: case 53:
word_bit.modal_group.G0 = On;
gc_block.non_modal_command = (non_modal_t)int_value;
if ((int_value == 28) || (int_value == 30)) {
if (!((mantissa == 0) || (mantissa == 10)))
FAIL(Status_GcodeUnsupportedCommand);
gc_block.non_modal_command += mantissa;
mantissa = 0; // Set to zero to indicate valid non-integer G command.
} else if (int_value == 92) {
if (!((mantissa == 0) || (mantissa == 10) || (mantissa == 20) || (mantissa == 30)))
FAIL(Status_GcodeUnsupportedCommand);
gc_block.non_modal_command += mantissa;
mantissa = 0; // Set to zero to indicate valid non-integer G command.
}
break;
case 33: case 76:
if(!hal.spindle.get_data)
FAIL(Status_GcodeUnsupportedCommand); // [G33 or G76 not supported]
if (axis_command)
FAIL(Status_GcodeAxisCommandConflict); // [Axis word/command conflict]
axis_command = AxisCommand_MotionMode;
word_bit.modal_group.G1 = On;
gc_block.modal.motion = (motion_mode_t)int_value;
gc_block.modal.canned_cycle_active = false;
break;
case 38:
if(!(hal.probe.get_state && ((mantissa == 20) || (mantissa == 30) || (mantissa == 40) || (mantissa == 50))))
FAIL(Status_GcodeUnsupportedCommand); // [probing not supported by driver or unsupported G38.x command]
int_value += (mantissa / 10) + 100;
mantissa = 0; // Set to zero to indicate valid non-integer G command.
// No break. Continues to next line.
case 0: case 1: case 2: case 3: case 5:
// Check for G0/1/2/3/38 being called with G10/28/30/92 on same block.
// * G43.1 is also an axis command but is not explicitly defined this way.
if (axis_command)
FAIL(Status_GcodeAxisCommandConflict); // [Axis word/command conflict]
axis_command = AxisCommand_MotionMode;
// No break. Continues to next line.
case 80:
word_bit.modal_group.G1 = On;
gc_block.modal.motion = (motion_mode_t)int_value;
gc_block.modal.canned_cycle_active = false;
break;
case 73: case 81: case 82: case 83: case 85: case 86: case 89:
if (axis_command)
FAIL(Status_GcodeAxisCommandConflict); // [Axis word/command conflict]
axis_command = AxisCommand_MotionMode;
word_bit.modal_group.G1 = On;
gc_block.modal.canned_cycle_active = true;
gc_block.modal.motion = (motion_mode_t)int_value;
gc_parser_flags.canned_cycle_change = gc_block.modal.motion != gc_state.modal.motion;
break;
case 17: case 18: case 19:
word_bit.modal_group.G2 = On;
gc_block.modal.plane_select = (plane_select_t)(int_value - 17);
break;
case 90: case 91:
if (mantissa == 0) {
word_bit.modal_group.G3 = On;
gc_block.modal.distance_incremental = int_value == 91;
} else {
word_bit.modal_group.G4 = On;
if ((mantissa != 10) || (int_value == 90))
FAIL(Status_GcodeUnsupportedCommand); // [G90.1 not supported]
mantissa = 0; // Set to zero to indicate valid non-integer G command.
// Otherwise, arc IJK incremental mode is default. G91.1 does nothing.
}
break;
case 93: case 94:
word_bit.modal_group.G5 = On;
gc_block.modal.feed_mode = (feed_mode_t)(94 - int_value);
break;
case 95:
if(hal.spindle.get_data) {
word_bit.modal_group.G5 = On;
gc_block.modal.feed_mode = FeedMode_UnitsPerRev;
} else
FAIL(Status_GcodeUnsupportedCommand); // [G95 not supported]
break;
case 20: case 21:
word_bit.modal_group.G6 = On;
gc_block.modal.units_imperial = int_value == 20;
break;
case 40:
word_bit.modal_group.G7 = On;
// NOTE: Not required since cutter radius compensation is always disabled. Only here
// to support G40 commands that often appear in g-code program headers to setup defaults.
// gc_block.modal.cutter_comp = CUTTER_COMP_DISABLE; // G40
break;
case 43: case 49:
word_bit.modal_group.G8 = On;
// NOTE: The NIST g-code standard vaguely states that when a tool length offset is changed,
// there cannot be any axis motion or coordinate offsets updated. Meaning G43, G43.1, and G49
// all are explicit axis commands, regardless if they require axis words or not.
// NOTE: cannot find the NIST statement referenced above, changed to match LinuxCNC behaviour in build 20210513.
if (int_value == 49) // G49
gc_block.modal.tool_offset_mode = ToolLengthOffset_Cancel;
#ifdef N_TOOLS
else if (mantissa == 0) // G43
gc_block.modal.tool_offset_mode = ToolLengthOffset_Enable;
else if (mantissa == 20) // G43.2
gc_block.modal.tool_offset_mode = ToolLengthOffset_ApplyAdditional;
#endif
else if (mantissa == 10) { // G43.1
if (axis_command)
FAIL(Status_GcodeAxisCommandConflict); // [Axis word/command conflict] }
axis_command = AxisCommand_ToolLengthOffset;
gc_block.modal.tool_offset_mode = ToolLengthOffset_EnableDynamic;
} else
FAIL(Status_GcodeUnsupportedCommand); // [Unsupported G43.x command]
mantissa = 0; // Set to zero to indicate valid non-integer G command.
break;
case 54: case 55: case 56: case 57: case 58: case 59:
word_bit.modal_group.G12 = On;
gc_block.modal.coord_system.id = (coord_system_id_t)(int_value - 54); // Shift to array indexing.
if(int_value == 59 && mantissa > 0) {
if(N_WorkCoordinateSystems == 9 && (mantissa == 10 || mantissa == 20 || mantissa == 30)) {
gc_block.modal.coord_system.id += mantissa / 10;
mantissa = 0;
} else
FAIL(Status_GcodeUnsupportedCommand); // [Unsupported G59.x command]
}
break;
case 61:
word_bit.modal_group.G13 = On;
if (mantissa != 0) // [G61.1 not supported]
FAIL(Status_GcodeUnsupportedCommand);
break;
/*
case 61:
word_bit.modal_group.G13 = On;
if (mantissa != 0 || mantissa != 10)
FAIL(Status_GcodeUnsupportedCommand);
gc_block.modal.control = mantissa == 0 ? ControlMode_ExactPath : ControlMode_ExactStop;
break;
case 64:
word_bit.modal_group.G13 = On;
gc_block.modal.control = ControlMode_PathBlending; // G64
break;
*/
case 96: case 97:
if(sys.mode == Mode_Lathe && hal.spindle.cap.variable) {
word_bit.modal_group.G14 = On;
gc_block.modal.spindle_rpm_mode = (spindle_rpm_mode_t)((int_value - 96) ^ 1);
} else
FAIL(Status_GcodeUnsupportedCommand);
break;
case 98: case 99:
word_bit.modal_group.G10 = On;
gc_block.modal.retract_mode = (cc_retract_mode_t)(int_value - 98);
break;
case 50: case 51:
axis_command = AxisCommand_Scaling;
word_bit.modal_group.G11 = On;
gc_block.modal.scaling_active = int_value == 51;
break;
default: FAIL(Status_GcodeUnsupportedCommand); // [Unsupported G command]
} // end G-value switch
if (mantissa > 0)
FAIL(Status_GcodeCommandValueNotInteger); // [Unsupported or invalid Gxx.x command]
// Check for more than one command per modal group violations in the current block
// NOTE: Variable 'word_bit' is always assigned, if the command is valid.
if (command_words.mask & word_bit.modal_group.mask)
FAIL(Status_GcodeModalGroupViolation);
command_words.mask |= word_bit.modal_group.mask;
break;
case 'M': // Determine 'M' command and its modal group
if (mantissa > 0)
FAIL(Status_GcodeCommandValueNotInteger); // [No Mxx.x commands]
is_user_mcode = false;
word_bit.modal_group.mask = 0;
switch(int_value) {
case 0: case 1: case 2: case 30: case 60:
word_bit.modal_group.M4 = On;
switch(int_value) {
case 0: // M0 - program pause
gc_block.modal.program_flow = ProgramFlow_Paused;
break;
case 1: // M1 - program pause
if(hal.signals_cap.stop_disable ? !hal.control.get_state().stop_disable : !sys.flags.optional_stop_disable)
gc_block.modal.program_flow = ProgramFlow_OptionalStop;
break;
default: // M2, M30, M60 - program end and reset
gc_block.modal.program_flow = (program_flow_t)int_value;
}
break;
case 3: case 4: case 5:
word_bit.modal_group.M7 = On;
gc_block.modal.spindle.on = !(int_value == 5);
gc_block.modal.spindle.ccw = int_value == 4;
sys.flags.delay_overrides = On;
break;
case 6:
if(settings.tool_change.mode != ToolChange_Ignore) {
if(hal.stream.suspend_read || hal.tool.change)
word_bit.modal_group.M6 = On;
else
FAIL(Status_GcodeUnsupportedCommand); // [Unsupported M command]
}
break;
case 7: case 8: case 9:
word_bit.modal_group.M8 = On;
sys.flags.delay_overrides = On;