-
-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathControllerImpl.cpp
More file actions
1257 lines (923 loc) · 36.1 KB
/
ControllerImpl.cpp
File metadata and controls
1257 lines (923 loc) · 36.1 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
/******************************************************************************\
CAMotics is an Open-Source simulation and CAM software.
Copyright (C) 2011-2019 Joseph Coffland <joseph@cauldrondevelopment.com>
This program 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 2 of the License, or
(at your option) any later version.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
\******************************************************************************/
#include "ControllerImpl.h"
#include "Codes.h"
#include <cbang/SStream.h>
#include <cbang/Catch.h>
#include <cbang/log/Logger.h>
#include <limits>
#include <cstring> // For memset()
using namespace std;
using namespace cb;
using namespace GCode;
ControllerImpl::ControllerImpl(MachineInterface &machine,
const ToolTable &tools) :
tools(tools) {
state.units = this->machine.getUnits();
state.plane = XY;
state.cutterRadiusComp = false;
state.toolDiameter = 0;
state.toolOrientation = 0;
state.incrementalDistanceMode = false;
state.feedMode = UNITS_PER_MINUTE;
state.coordSystem = 1;
state.toolLengthComp = false;
state.returnMode = RETURN_TO_R;
state.spinMode = REVOLUTIONS_PER_MINUTE;
state.arcIncrementalDistanceMode = true;
state.latheDiameterMode = true;
state.pathMode = CONTINUOUS_MODE;
state.feed = 0;
state.speed = 0;
state.spindleDir = DIR_OFF;
state.mist = false;
state.flood = false;
state.speedOverride = 0;
state.feedOverride = 0;
state.adaptiveFeed = false;
state.feedHold = false;
state.motionBlendingTolerance = -1;
state.naiveCamTolerance = -1;
state.moveInAbsoluteCoords = false;
this->machine.setNextNode(SmartPointer<MachineInterface>::Phony(&machine));
memset(varValues, 0, sizeof(varValues));
pushScope();
}
double ControllerImpl::getVar(char c) const {
if (c < 'A' || 'Z' < c)
THROW("Invalid var '" << String::escapeC(string(1, c)) << "'");
return varValues[c - 'A'];
}
string ControllerImpl::getVarGroupStr(const char *group) const {
string s;
for (int i = 0; group[i]; i++)
s += SSTR(' ' << group[i] << getVar(group[i]));
return s;
}
Units ControllerImpl::getUnits() const {return machine.getUnits();}
void ControllerImpl::setUnits(Units units) {
if (units == machine.getUnits()) return;
switch (units) {
case Units::NO_UNITS: THROW("Cannot set to NO_UNITS");
case Units::METRIC:
machine.setMetric();
set("_metric", 1, NO_UNITS);
set("_imperial", 0, NO_UNITS);
position = position * 25.4;
break;
case Units::IMPERIAL:
machine.setImperial();
set("_metric", 0, NO_UNITS);
set("_imperial", 1, NO_UNITS);
position = position / 25.4;
break;
}
state.units = units;
}
void ControllerImpl::setFeedMode(feed_mode_t mode) {
state.feedMode = mode;
machine.setFeedMode(mode);
}
void ControllerImpl::setSpindleDir(dir_t dir) {
state.spindleDir = dir;
setSpeed(state.speed);
}
void ControllerImpl::setSpinMode(spin_mode_t mode, double max) {
state.spinMode = mode;
state.spinMax = max;
machine.setSpinMode(mode, max);
}
void ControllerImpl::setMistCoolant(bool enable) {
state.mist = enable;
machine.output(MachineEnum::MIST, enable);
set("_mist", enable, NO_UNITS);
}
void ControllerImpl::setFloodCoolant(bool enable) {
state.flood = enable;
machine.output(MachineEnum::FLOOD, enable);
set("_flood", enable, NO_UNITS);
}
void ControllerImpl::digitalOutput(unsigned index, bool enable,
bool synchronized) {
if (3 < index) {
LOG_WARNING("Invalid digital output " << index);
return;
}
machine.output((port_t)(DIGITAL_OUT_0 + index), enable);
}
void ControllerImpl::input(unsigned index, bool digital, input_mode_t mode,
double timeout) {
if (3 < index) {
LOG_WARNING("Invalid " << (digital ? "digital" : "analog") << " input "
<< index);
return;
}
if (INPUT_LOW < mode) {
LOG_WARNING("Unsupported input mode " << mode);
return;
}
if (!digital && mode != INPUT_IMMEDIATE) {
LOG_WARNING("Analog input mode can only be immediate");
return;
}
if (timeout < 0) {
LOG_WARNING("Invalid timeout " << timeout);
return;
}
syncState = SYNC_INPUT; // Synchronize input result
machine.input((port_t)((digital ? DIGITAL_IN_0 : ANALOG_IN_0) + index),
mode, timeout);
}
void ControllerImpl::setPlane(plane_t plane) {
if (VW < plane) THROW("Invalid plane: " << plane);
state.plane = plane;
set("_plane", plane, NO_UNITS);
}
void ControllerImpl::setPathMode(path_mode_t mode, double motionBlending,
double naiveCAM) {
state.pathMode = mode;
state.motionBlendingTolerance = motionBlending;
state.naiveCamTolerance = naiveCAM;
machine.setPathMode(mode, motionBlending, naiveCAM);
}
void ControllerImpl::setIncrementalDistanceMode(bool enable) {
state.incrementalDistanceMode = enable;
set("_incremental_distance_mode", enable, NO_UNITS);
}
void ControllerImpl::setArcIncrementalDistanceMode(bool enable) {
state.arcIncrementalDistanceMode = enable;
set("_arc_incremental_distance_mode", enable, NO_UNITS);
}
double ControllerImpl::getAxisCSOffset(char axis, unsigned cs) const {
if (!cs) cs = get(CURRENT_COORD_SYSTEM);
return get(COORD_SYSTEM_ADDR(cs, Axes::toIndex(axis)));
}
double ControllerImpl::getAxisToolOffset(char axis) const {
return state.toolLengthComp ? get(TOOL_OFFSET_ADDR(Axes::toIndex(axis))) : 0;
}
double ControllerImpl::getAxisGlobalOffset(char axis) const {
return get(GLOBAL_OFFSETS_ENABLED) ?
get(GLOBAL_OFFSET_ADDR(Axes::toIndex(axis))) : 0;
}
double ControllerImpl::getAxisOffset(char axis) const {
if (absoluteCoords) return 0; // Only set with G0 and G1 moves
return getAxisCSOffset(axis) + getAxisToolOffset(axis) +
getAxisGlobalOffset(axis);
}
double ControllerImpl::getAxisPosition(char axis) const {
return getAxisAbsolutePosition(axis) - getAxisOffset(axis);
}
double ControllerImpl::getAxisAbsolutePosition(char axis) const {
return position.get(axis);
}
void ControllerImpl::setAxisAbsolutePosition(char axis, double abs,
Units units) {
double scale = 1;
if (units == METRIC && getUnits() == IMPERIAL) scale = 1.0 / 25.4;
else if (units == IMPERIAL && getUnits() == METRIC) scale = 25.4;
position.set(axis, abs * scale);
double pos = abs - getAxisOffset(axis);
set(CURRENT_COORD_ADDR(Axes::toIndex(axis)), pos, units);
set("_" + string(1, tolower(axis)), pos, units);
}
Axes ControllerImpl::getAbsolutePosition() const {
Axes pos;
for (const char *axes = Axes::AXES; *axes; axes++)
pos.set(*axes, getAxisAbsolutePosition(*axes));
LOG_INFO(5, "Controller: Current absolute position is " << pos << "mm");
return pos;
}
void ControllerImpl::setAbsolutePosition(const Axes &axes, Units units) {
LOG_INFO(5, "Controller: Set absolute position to " << axes << units);
for (const char *var = Axes::AXES; *var; var++)
if (!isnan(axes.get(*var)))
setAxisAbsolutePosition(*var, axes.get(*var), units);
}
Axes ControllerImpl::getNextAbsolutePosition(int vars, bool incremental) const {
Axes position;
for (const char *axis = Axes::AXES; *axis; axis++)
if (vars & getVarType(*axis)) {
double pos = getVar(*axis);
if (incremental) pos += getAxisAbsolutePosition(*axis);
else pos += getAxisOffset(*axis);
position.set(*axis, pos);
} else position.set(*axis, getAxisAbsolutePosition(*axis));
LOG_INFO(5, "Controller: Next absolute position is " << position << "mm");
return position;
}
bool ControllerImpl::isPositionChanging(int vars, bool incremental) const {
Axes nextPos = getNextAbsolutePosition(vars, state.incrementalDistanceMode);
return nextPos != getAbsolutePosition();
}
void ControllerImpl::move(const Axes &pos, int axes, bool rapid) {
machine.move(pos, axes, rapid, 0);
setAbsolutePosition(pos, getUnits());
}
void ControllerImpl::makeMove(int axes, bool rapid, bool incremental) {
move(getNextAbsolutePosition(axes, incremental), axes, rapid);
}
void ControllerImpl::moveAxis(char axis, double value, bool rapid) {
Axes pos = getAbsolutePosition();
pos.set(axis, value + getAxisOffset(axis));
move(pos, getVarType(axis), rapid);
}
void ControllerImpl::linear(int vars, bool rapid) {
absoluteCoords = state.moveInAbsoluteCoords;
makeMove(vars, rapid, state.incrementalDistanceMode);
absoluteCoords = false;
}
void ControllerImpl::arc(int vars, bool clockwise) {
// TODO Affected by cutter radius compensation
// TODO Make sure this is correct for planes XZ and YZ
const char *axes = getPlane().getAxes();
if (state.plane == XZ) clockwise = !clockwise;
// Compute start and end points
Axes current(getAbsolutePosition());
Axes target(getNextAbsolutePosition(vars, state.incrementalDistanceMode));
Vector2D start(current.get(axes[0]), current.get(axes[1]));
Vector2D finish(target.get(axes[0]), target.get(axes[1]));
Vector2D center;
double radius;
if (VT_R & vars) {
radius = getVar('R');
// If radius is less than half the distance then the arc is impossible
double a = start.distance(finish) / 2;
if (fabs(radius) < a - 0.00001) {
LOG_WARNING("Impossible radius format arc, replacing with line segment, "
"radius=" << fabs(radius) << " distance/2=" << a);
move(target, vars, false);
return;
}
// Compute arc center
Vector2D m((start + finish) / 2);
Vector2D E(start.y() - finish.y(), finish.x() - start.x());
double d = (finish - start).length() / 2;
double l = radius * radius - d * d;
// Handle possible small negative caused by rounding errors
l = l < 0 ? 0 : sqrt(l);
if (!clockwise) l = -l;
if (0 < radius) l = -l;
center = m + E.normalize() * l;
static bool warned = false;
if (!warned) LOG_WARNING("Radius format arcs are discouraged");
warned = true;
} else {
// Get arc center
const char *offsets = getPlane().getOffsets();
Vector2D offset;
if (state.arcIncrementalDistanceMode) {
offset =
Vector2D((vars & getVarType(offsets[0])) ? getVar(offsets[0]) : 0,
(vars & getVarType(offsets[1])) ? getVar(offsets[1]) : 0);
center = start + offset;
} else center = Vector2D(getVar(offsets[0]) - getAxisOffset(axes[0]),
getVar(offsets[1]) - getAxisOffset(axes[1]));
// Check that the radius matches
radius = start.distance(center);
double radiusDiff = fabs(radius - finish.distance(center));
if ((machine.isImperial() && 0.0005 < radiusDiff) ||
(machine.isMetric() && 0.005 < radiusDiff)) {
LOG_WARNING("Arc radiuses differ by " << radiusDiff << "mm");
LOG_DEBUG(1, " center=" << center << " start=" << start
<< " finish=" << finish << " offset=" << offset);
}
}
// Compute angle
double startAngle = (start - center).angleBetween(Vector2D(1, 0));
double finishAngle = (finish - center).angleBetween(Vector2D(1, 0));
double angle = finishAngle - startAngle;
if (0 <= angle) angle -= 2 * Math::PI;
if (!clockwise) angle += 2 * Math::PI;
if (!angle) angle = 2 * Math::PI;
if ((VT_P & vars) && 1 < getVar('P'))
angle += Math::PI * 2 * (getVar('P') - 1) * (angle < 0 ? -1 : 1);
LOG_DEBUG(4, "Arc angle=" << angle << " startAngle=" << startAngle
<< " finishAngle=" << finishAngle << " start=" << start
<< " finish=" << finish << " center=" << center
<< " radius=" << radius);
// Do arc
double deltaZ = target.get(axes[2]) - current.get(axes[2]);
Axes offset;
offset.set(axes[0], center[0] - start[0]);
offset.set(axes[1], center[1] - start[1]);
offset.set(axes[2], deltaZ);
machine.arc(offset.getXYZ(), target.getXYZ(), -angle, state.plane);
setAbsolutePosition(target, getUnits());
LOG_INFO(3, "Controller: Arc");
}
void ControllerImpl::straightProbe(int vars, bool towardWorkpiece,
bool signalError) {
if (!isPositionChanging(vars, state.incrementalDistanceMode))
THROW("Probe target position is same as current position");
syncState = SYNC_PROBE; // Synchronize with found position
machine.seek(PROBE, towardWorkpiece, signalError);
makeMove(vars, false, state.incrementalDistanceMode);
LOG_INFO(3, "Controller: straight probe "
<< (towardWorkpiece ? "toward" : "away from") << " workpiece"
<< (signalError ? " with error signal" : ""));
}
void ControllerImpl::seek(int vars, bool active, bool error) {
port_t port;
if (vars & VT_P) port = (port_t)(unsigned)round(getVar('P'));
else {
char targetAxis = 0;
bool seekMin;
for (const char *axes = Axes::AXES; *axes; axes++)
if (vars & getVarType(*axes)) {
if (targetAxis) THROW("Multiple axes in seek");
targetAxis = *axes;
seekMin = (0 < getVar(*axes)) ^ active;
}
switch (targetAxis) {
case 'X': port = seekMin ? X_MIN : X_MAX; break;
case 'Y': port = seekMin ? Y_MIN : Y_MAX; break;
case 'Z': port = seekMin ? Z_MIN : Z_MAX; break;
case 'A': port = seekMin ? A_MIN : A_MAX; break;
case 'B': port = seekMin ? B_MIN : B_MAX; break;
case 'C': port = seekMin ? C_MIN : C_MAX; break;
case 'U': port = seekMin ? U_MIN : U_MAX; break;
case 'V': port = seekMin ? V_MIN : V_MAX; break;
case 'W': port = seekMin ? W_MIN : W_MAX; break;
default: THROW("Seek requires axis");
}
}
if (!isPositionChanging(vars, true))
THROW("Seek target position is same as current position");
syncState = SYNC_SEEK; // Synchronize with found position
machine.seek(port, active, error);
makeMove(vars, false, true);
}
void ControllerImpl::drill(int vars, bool dwell, bool feedOut,
bool spindleStop) {
Plane plane = getPlane();
unsigned xyVars = vars & (plane.getXVarType() | plane.getYVarType());
unsigned zVar = plane.getZVarType();
double r = getVar('R');
unsigned L = (vars & VT_L) ? (unsigned)getVar('L') : 1;
double zClear = 0;
switch (state.returnMode) {
case RETURN_TO_R: zClear = r; break;
case RETURN_TO_OLD_Z: {
double oldZ = getAxisPosition(plane.getZAxis());
zClear = (r < oldZ) ? oldZ : r;
break;
}
}
for (unsigned i = 0; i < L; i++) {
// Z is below R
double z = getAxisPosition(plane.getZAxis());
if (!i && z < r) moveAxis(plane.getZAxis(), r, true);
// Traverse to XY
makeMove(xyVars, true, state.incrementalDistanceMode);
// Move to Z if above
z = getAxisPosition(plane.getZAxis());
if (z != r) moveAxis(plane.getZAxis(), r, true);
// Drill
makeMove(zVar, false, state.incrementalDistanceMode);
// Dwell
if (dwell) this->dwell(getVar('P'));
// Stop Spindle
dir_t spindleDir = state.spindleDir;
if (spindleStop) setSpindleDir(DIR_OFF);
// Retract
moveAxis(plane.getZAxis(), zClear, !feedOut);
// Restart Spindle
if (spindleStop) setSpindleDir(spindleDir);
}
}
void ControllerImpl::dwell(double seconds) {machine.dwell(seconds);}
void ControllerImpl::pause(pause_t type) {
syncState = SYNC_PAUSE;
machine.pause(type);
}
void ControllerImpl::setTools(int vars, bool relative, bool cs9) {
Tool &tool = getTool(getVar('P'));
for (const char *v = Tool::VARS; *v; v++)
if (vars & getVarType(*v)) {
double offset = getVar(*v);
// G10 L10 & L11
if (relative && (getVarType(*v) & VT_AXIS)) {
unsigned cs = cs9 ? 9 : get(CURRENT_COORD_SYSTEM);
offset = getAxisAbsolutePosition(*v) - getAxisCSOffset(*v, cs) -
(cs9 ? 0 : getAxisGlobalOffset(*v)) - offset;
}
tool.set(*v, offset);
}
LOG_INFO(3, "Controller: Set Tool Table" << getVarGroupStr("PRXYZABCUVWIJQ"));
}
void ControllerImpl::toolChange() {
int tool = get("_selected_tool");
if (tool < 0) THROW("No tool selected");
machine.changeTool(tool);
LOG_INFO(3, "Controller: Tool change " << tool);
}
void ControllerImpl::loadToolOffsets(unsigned number, bool add) {
try {
const Tool &tool = getTool(number);
for (const char *axis = Axes::AXES; *axis; axis++) {
address_t addr = TOOL_OFFSET_ADDR(Axes::toIndex(*axis));
double offset = tool.get(*axis) + (add ? get(addr, getUnits()) : 0);
set(addr, offset, getUnits());
}
state.toolLengthComp = true;
} CATCH_WARNING; // Tool may not exist
}
void ControllerImpl::loadToolVarOffsets(int vars) {
for (const char *axis = Axes::AXES; *axis; axis++)
if (vars & getVarType(*axis)) {
address_t addr = TOOL_OFFSET_ADDR(Axes::toIndex(*axis));
set(addr, getVar(*axis), getUnits());
}
state.toolLengthComp = true;
}
void ControllerImpl::storePredefined(bool first) {
for (const char *axis = Axes::AXES; *axis; axis++)
set(PREDEFINED_ADDR(first, Axes::toIndex(*axis)),
getAxisAbsolutePosition(*axis), getUnits());
}
void ControllerImpl::loadPredefined(bool first, int vars) {
for (const char *axis = Axes::AXES; *axis; axis++)
if (vars & getVarType(*axis)) {
address_t addr = PREDEFINED_ADDR(first, Axes::toIndex(*axis));
setAxisAbsolutePosition(*axis, get(addr), getUnits());
}
}
void ControllerImpl::setCoordSystem(unsigned cs) {
state.coordSystem = cs;
set(CURRENT_COORD_SYSTEM, cs, NO_UNITS);
}
void ControllerImpl::setCoordSystemOffsets(int vars, bool relative) {
unsigned cs = getVar('P');
if (9 < cs) THROW("Invalid coordinate system number " << cs);
if (!cs) cs = get(CURRENT_COORD_SYSTEM);
if (vars & VarTypes::VT_R) {
if (relative) LOG_WARNING("R not allowed in G10 L20");
else {
address_t addr = COORD_SYSTEM_ADDR(cs, COORD_SYSTEM_ROTATION_MEMBER);
set(addr, getVar('R'), NO_UNITS);
}
}
for (const char *axis = Axes::AXES; *axis; axis++)
if (vars & getVarType(*axis)) {
address_t addr = COORD_SYSTEM_ADDR(cs, Axes::toIndex(*axis));
double offset = getVar(*axis);
if (relative)
offset = getAxisPosition(*axis) + getAxisCSOffset(*axis) - offset;
set(addr, offset, getUnits());
}
}
void ControllerImpl::setAxisGlobalOffset(char axis, double offset) {
set(GLOBAL_OFFSET_ADDR(Axes::toIndex(axis)), offset, getUnits());
}
void ControllerImpl::setGlobalOffsets(int vars, bool relative) {
set(GLOBAL_OFFSETS_ENABLED, 1, NO_UNITS);
// Make the current point have the coordinates specified, without motion
for (const char *axis = Axes::AXES; *axis; axis++)
if (getVarType(*axis) & vars) {
double offset = getVar(*axis);
if (relative)
offset = getAxisPosition(*axis) + getAxisGlobalOffset(*axis) - offset;
setAxisGlobalOffset(*axis, offset);
}
}
void ControllerImpl::resetGlobalOffsets(bool clear) {
set(GLOBAL_OFFSETS_ENABLED, 0, NO_UNITS);
if (clear)
for (unsigned axis = 0; axis < 9; axis++)
set(GLOBAL_OFFSET_ADDR(axis), 0, getUnits());
}
void ControllerImpl::restoreGlobalOffsets() {
set(GLOBAL_OFFSETS_ENABLED, 1, NO_UNITS);
}
void ControllerImpl::updateOffsetParams() {
if (!offsetParamChanged) return;
offsetParamChanged = false;
for (const char *axis = Axes::AXES; *axis; axis++) {
string name = "_offset_" + string(1, tolower(*axis));
double offset = getAxisOffset(*axis);
if (!has(name) || offset != get(name)) {
set(name, offset, getUnits());
double position = getAxisPosition(*axis);
address_t addr = CURRENT_COORD_ADDR(Axes::toIndex(*axis));
set(addr, position, getUnits());
set("_" + string(1, tolower(*axis)), position, getUnits());
}
}
// Apply rotation
unsigned cs = get(CURRENT_COORD_SYSTEM);
address_t addr = COORD_SYSTEM_ADDR(cs, COORD_SYSTEM_ROTATION_MEMBER);
double r = get(addr) * Math::PI / 180;
Transform &t = machine.getTransforms().get(XYZ).pull();
t.rotate(r, Vector3D(0, 0, 1), Vector3D(0, 0, 0));
}
void ControllerImpl::setHomed(int vars, bool homed) {
for (const char *axis = Axes::AXES; *axis; axis++)
if (getVarType(*axis) & vars) {
string name = SSTR("_" << (char)tolower(*axis) << "_homed");
set(name, homed, NO_UNITS);
if (homed) {
string name = SSTR("_" << (char)tolower(*axis) << "_home");
set(name, getVar(*axis), getUnits());
setAxisAbsolutePosition(*axis, getVar(*axis), getUnits());
setAxisGlobalOffset(*axis, 0);
}
}
// Notify machine that axis positions have changed
if (homed) machine.setPosition(getAbsolutePosition());
}
void ControllerImpl::setCutterRadiusComp(int vars, bool left, bool dynamic) {
LOG_WARNING("Cutter radius compensation not implemented"); // TODO
if (getCurrentTool() < 0) {
LOG_ERROR("Tool not set, cannot set cutter radius compensation");
return;
}
// NOTE, Fanuc may use ``D`` or ``H`` for the same purpose.
try {
if (dynamic) {
state.toolDiameter = (left ? 1 : -1) * getVar('D');
if (vars & VT_L) state.toolOrientation = getVar('L');
else state.toolOrientation = 0;
} else {
state.toolOrientation = 0;
if (!(vars & VT_D))
state.toolDiameter = getTool(getCurrentTool()).getRadius() * 2;
else if (!getVar('D')) state.toolDiameter = 0;
else state.toolDiameter = getTool(getVar('D')).getRadius() * 2;
}
set(TOOL_DIAMETER, state.toolDiameter, getUnits());
set(TOOL_ORIENTATION, state.toolOrientation, NO_UNITS);
state.cutterRadiusComp = true;
} CATCH_WARNING; // Tool may not exist
}
void ControllerImpl::end() {
// TODO replace this with GCode override
// See http://linuxcnc.org/docs/html/gcode/m-code.html#mcode:m2-m30
// Origin offsets are set to the default (G54)
setCoordSystem(1);
// Selected plane is set to XY plane (G17)
setPlane(XY);
// Distance mode is set to absolute mode (G90)
setIncrementalDistanceMode(false);
// Feed rate mode is set to units per minute (G94)
setFeedMode(UNITS_PER_MINUTE);
// TODO Feed and speed overrides are set to on (M48)
// Cutter compensation is turned off (G40)
state.cutterRadiusComp = false;
// The spindle is stopped (M5)
setSpindleDir(DIR_OFF);
// The current motion mode is set to feed (G1)
setCurrentMotionMode(10);
// Coolant is turned off (M9)
setMistCoolant(false);
setFloodCoolant(false);
// Update offsets after changes above
updateOffsetParams();
throw EndProgram();
}
void ControllerImpl::stop() {
// The spindle is stopped (M5)
setSpindleDir(DIR_OFF);
// Coolant is turned off (M9)
setMistCoolant(false);
setFloodCoolant(false);
}
double ControllerImpl::get(address_t addr, Units units) const {
return machine.get(addr, units);
}
void ControllerImpl::set(address_t addr, double value, Units units) {
machine.set(addr, value, units);
// Check if offsets have changed
if (GLOBAL_OFFSETS_ENABLED <= addr && addr <= CS9_ROTATION)
offsetParamChanged = true;
}
double ControllerImpl::get(const string &name, Units units) const {
return machine.get(name, units);
}
void ControllerImpl::set(const string &name, double value, Units units) {
machine.set(name, value, units);
}
void ControllerImpl::saveModalState(bool autoRestore) {
if (autoRestore && stateStack.size() == 1)
LOG_WARNING("Cannot autorestore modal state from top scope");
state.autoRestore = autoRestore;
stateStack.back() = new state_t(this->state);
}
void ControllerImpl::clearSavedModalState() {stateStack.back().release();}
void ControllerImpl::restoreModalState() {
if (stateStack.back().isNull()) {
LOG_ERROR("Cannot restore modal state when not previously saved at this "
"scope");
return;
}
state = *stateStack.back();
setUnits(state.units);
set(TOOL_DIAMETER, state.toolDiameter, getUnits());
set(TOOL_ORIENTATION, state.toolOrientation, NO_UNITS);
setFeedMode(state.feedMode);
setCoordSystem(state.coordSystem);
setSpinMode(state.spinMode, state.spinMax);
setFeed(state.feed);
setSpeed(state.speed);
setMistCoolant(state.mist);
setFloodCoolant(state.flood);
setPathMode(state.pathMode, state.motionBlendingTolerance,
state.naiveCamTolerance);
}
void ControllerImpl::message(const string &text) {machine.message(text);}
double ControllerImpl::get(address_t addr) const {return get(addr, getUnits());}
void ControllerImpl::set(address_t addr, double value) {
set(addr, value, NO_UNITS);
}
bool ControllerImpl::has(const string &name) const {return machine.has(name);}
double ControllerImpl::get(const string &name) const {
return get(name, getUnits());
}
void ControllerImpl::set(const string &name, double value) {
set(name, value, NO_UNITS);
}
void ControllerImpl::clear(const string &name) {machine.clear(name);}
void ControllerImpl::setVar(char c, double value) {
if (c < 'A' || 'Z' < c)
THROW("Invalid var '" << String::escapeC(string(1, c)) << "'");
varValues[c - 'A'] = value;
}
void ControllerImpl::setCurrentMotionMode(unsigned mode) {
currentMotionMode = mode;
}
void ControllerImpl::synchronize(double result) {
if (syncState == SYNC_NONE) THROW("Not synchronizing");
switch (syncState) {
case SYNC_NONE: break;
case SYNC_SEEK:
case SYNC_PROBE:
// Set PROBE_SUCCESS and probed position in PROBE_RESULT_X to W
set(PROBE_SUCCESS, result, NO_UNITS);
for (const char *axis = Axes::AXES; *axis; axis++)
set(PROBE_RESULT_ADDR(Axes::toIndex(*axis)),
getAxisAbsolutePosition(*axis), getUnits());
break;
case SYNC_INPUT: set(USER_INPUT, result, NO_UNITS); break;
case SYNC_PAUSE: break;
}
syncState = SYNC_NONE;
}
void ControllerImpl::setLocation(const LocationRange &location) {
machine.setLocation(location);
}
void ControllerImpl::setFeed(double feed) {
state.feed = feed;
machine.setFeed(feed);
}
void ControllerImpl::setSpeed(double speed) {
state.speed = speed;
double mspeed;
switch (state.spindleDir) {
case DIR_OFF: mspeed = 0; break;
case DIR_CLOCKWISE: mspeed = speed; break;
case DIR_COUNTERCLOCKWISE: mspeed = -speed; break;
default: THROW("Invalid spindle direction");
}
machine.setSpeed(mspeed);
}
void ControllerImpl::setTool(unsigned tool) {
set("_selected_tool", tool, NO_UNITS);
}
void ControllerImpl::pushScope() {stateStack.push_back(0);}
void ControllerImpl::popScope() {
if (!stateStack.back().isNull() && stateStack.back()->autoRestore)
restoreModalState();
stateStack.pop_back();
}
void ControllerImpl::startBlock() {
if (syncState != SYNC_NONE) {
if (syncState != SYNC_PAUSE) {
LOG_WARNING("Position after synchronized command unknown in simulator.");
synchronize(0);
}
syncState = SYNC_NONE;
}
state.moveInAbsoluteCoords = false;
}
bool ControllerImpl::execute(const Code &code, int vars) {
bool implemented = true;
switch (code.type) {
case 'G':
switch (code.number) {
case 0: linear(vars, true); break;
case 10: linear(vars, false); break;