diff --git a/bindings/python/src/lib.rs b/bindings/python/src/lib.rs index 197e494e..8c4038b2 100644 --- a/bindings/python/src/lib.rs +++ b/bindings/python/src/lib.rs @@ -1856,13 +1856,35 @@ struct IntentSession { state: camlib::post_intent::IntentChecker, initial: Vec, } +/// The decoder's reading of each event's blocks (`Line.holds_axes`), a JSON +/// list of boolean lists; omitted when it held none. +fn held_blocks(held_json: Option<&str>) -> PyResult>> { + held_json + .map(serde_json::from_str) + .transpose() + .map_err(|e| PyValueError::new_err(e.to_string())) + .map(Option::unwrap_or_default) +} #[pymethods] impl IntentSession { + /// `held_json`: the decoder's reading of each initialization block, a + /// JSON list of booleans (`Line.holds_axes`); omitted when it held none. #[new] - fn new(header_json: &str, settings_json: &str, lines_json: &str) -> PyResult { - if [header_json.len(), settings_json.len(), lines_json.len()] - .iter() - .any(|n| *n > 512 * 1024) + #[pyo3(signature=(header_json,settings_json,lines_json,held_json=None))] + fn new( + header_json: &str, + settings_json: &str, + lines_json: &str, + held_json: Option<&str>, + ) -> PyResult { + if [ + header_json.len(), + settings_json.len(), + lines_json.len(), + held_json.map_or(0, str::len), + ] + .iter() + .any(|n| *n > 512 * 1024) { return Err(PyValueError::new_err("generic post header byte cap")); } @@ -1872,8 +1894,14 @@ impl IntentSession { .map_err(|e| PyValueError::new_err(e.to_string()))?; let lines: Vec = serde_json::from_str(lines_json).map_err(|e| PyValueError::new_err(e.to_string()))?; - let (state, first) = camlib::post_intent::IntentChecker::begin(&header, settings, &lines) - .map_err(PyValueError::new_err)?; + let held: Vec = held_json + .map(serde_json::from_str) + .transpose() + .map_err(|e| PyValueError::new_err(e.to_string()))? + .unwrap_or_default(); + let (state, first) = + camlib::post_intent::IntentChecker::begin_held(&header, settings, &lines, &held) + .map_err(PyValueError::new_err)?; let initial = serde_json::to_vec(&first).map_err(|e| PyValueError::new_err(e.to_string()))?; Ok(Self { state, initial }) @@ -1985,7 +2013,7 @@ impl IntentSession { let bytes = serde_json::to_vec(&out).map_err(|e| PyValueError::new_err(e.to_string()))?; Ok(PyBytes::new(py, &bytes)) } - #[pyo3(signature=(ranges_json,decoded_json,blocks_json,cancel=None))] + #[pyo3(signature=(ranges_json,decoded_json,blocks_json,cancel=None,held_json=None))] fn check_lowered<'py>( &mut self, py: Python<'py>, @@ -1993,11 +2021,17 @@ impl IntentSession { decoded_json: &str, blocks_json: &str, cancel: Option>, + held_json: Option<&str>, ) -> PyResult> { if !self.initial.is_empty() - || [ranges_json.len(), decoded_json.len(), blocks_json.len()] - .iter() - .any(|n| *n > 512 * 1024) + || [ + ranges_json.len(), + decoded_json.len(), + blocks_json.len(), + held_json.map_or(0, str::len), + ] + .iter() + .any(|n| *n > 512 * 1024) { return Err(PyValueError::new_err( "generic lowered lifecycle/input byte cap", @@ -2009,14 +2043,18 @@ impl IntentSession { serde_json::from_str(decoded_json).map_err(|e| PyValueError::new_err(e.to_string()))?; let blocks: Vec> = serde_json::from_str(blocks_json).map_err(|e| PyValueError::new_err(e.to_string()))?; + let held = held_blocks(held_json)?; let flag = cancel.map(|c| c.flag.clone()).unwrap_or_default(); let out = py - .detach(|| self.state.check_lowered(&ranges, &decoded, &blocks, &*flag)) + .detach(|| { + self.state + .check_lowered_held(&ranges, &decoded, &blocks, &held, &*flag) + }) .map_err(PyValueError::new_err)?; let bytes = serde_json::to_vec(&out).map_err(|e| PyValueError::new_err(e.to_string()))?; Ok(PyBytes::new(py, &bytes)) } - #[pyo3(signature=(events_json,decoded_json,blocks_json,cancel=None))] + #[pyo3(signature=(events_json,decoded_json,blocks_json,cancel=None,held_json=None))] fn consume<'py>( &mut self, py: Python<'py>, @@ -2024,11 +2062,17 @@ impl IntentSession { decoded_json: &str, blocks_json: &str, cancel: Option>, + held_json: Option<&str>, ) -> PyResult> { if !self.initial.is_empty() - || [events_json.len(), decoded_json.len(), blocks_json.len()] - .iter() - .any(|n| *n > 512 * 1024) + || [ + events_json.len(), + decoded_json.len(), + blocks_json.len(), + held_json.map_or(0, str::len), + ] + .iter() + .any(|n| *n > 512 * 1024) { return Err(PyValueError::new_err( "generic post lifecycle/input byte cap", @@ -2040,10 +2084,13 @@ impl IntentSession { serde_json::from_str(decoded_json).map_err(|e| PyValueError::new_err(e.to_string()))?; let blocks: Vec> = serde_json::from_str(blocks_json).map_err(|e| PyValueError::new_err(e.to_string()))?; + let held = held_blocks(held_json)?; let flag = cancel.map(|c| c.flag.clone()).unwrap_or_default(); let bytes = py .detach(|| { - let out = self.state.consume(&events, &decoded, &blocks, &*flag)?; + let out = self + .state + .consume_held(&events, &decoded, &blocks, &held, &*flag)?; serde_json::to_vec(&out).map_err(|e| e.to_string()) }) .map_err(PyValueError::new_err)?; @@ -2143,21 +2190,30 @@ impl IntentSession { (placed[0], placed[1], placed[2]), )) } - #[pyo3(signature=(lines_json,cancel=None))] + #[pyo3(signature=(lines_json,cancel=None,held_json=None))] fn finish<'py>( &mut self, py: Python<'py>, lines_json: &str, cancel: Option>, + held_json: Option<&str>, ) -> PyResult> { - if !self.initial.is_empty() || lines_json.len() > 32768 { + if !self.initial.is_empty() + || lines_json.len() > 32768 + || held_json.is_some_and(|h| h.len() > 32768) + { return Err(PyValueError::new_err("generic finish byte cap")); } let lines: Vec = serde_json::from_str(lines_json).map_err(|e| PyValueError::new_err(e.to_string()))?; + let held: Vec = held_json + .map(serde_json::from_str) + .transpose() + .map_err(|e| PyValueError::new_err(e.to_string()))? + .unwrap_or_default(); let flag = cancel.map(|c| c.flag.clone()).unwrap_or_default(); let out = py - .detach(|| self.state.finish(&lines, &*flag)) + .detach(|| self.state.finish_held(&lines, &held, &*flag)) .map_err(PyValueError::new_err)?; let bytes = serde_json::to_vec(&out).map_err(|e| PyValueError::new_err(e.to_string()))?; Ok(PyBytes::new(py, &bytes)) diff --git a/docs/fanuc-0imb-post.md b/docs/fanuc-0imb-post.md index c5ee33e1..0399afcf 100644 --- a/docs/fanuc-0imb-post.md +++ b/docs/fanuc-0imb-post.md @@ -32,7 +32,9 @@ are retained privately; the manual is not redistributed in the library. G43/H and G49 can cause axis movement. The reference therefore uses explicit G1 compensation blocks whose spindle-axis endpoints preserve the declared tip position. G52 clears only the local shift; a zero G92 shift remains a setup -premise. Units agree with startup offset-table units. Decimal points avoid DPI +premise. G52 moves no axis: the decoder reads its X/Y/Z words as the shift +(`hold_axes`), so the machine check keeps a start pose on the travel limits +exactly there (#369). Units agree with startup offset-table units. Decimal points avoid DPI parameter ambiguity. G61 selects exact-stop mode without asserting zero physical servo error. M-code functions and ATC routes depend on the builder. diff --git a/docs/haas-ngc-post.md b/docs/haas-ngc-post.md index 55343838..008adfda 100644 --- a/docs/haas-ngc-post.md +++ b/docs/haas-ngc-post.md @@ -112,6 +112,9 @@ length geometry+wear, G92 and machine setup remain external measured premises. Initialization: framed `%`/O program, explicit units/G90/G17/G94/G40/G49/G80, G52 X0 Y0 Z0, conditional G50/G69, G100 X0 Y0 Z0, plain G187 reset, G61 exact stop, M5/M9. Decoder requires the closing percent after M30 before file completion. +G52 and G100 set a shift and a mode and move no axis: both decoders read their +X/Y/Z words as parameters (`hold_axes`), so the machine check keeps a start +pose on the travel limits exactly there (#369). G61 supplies the documented nominal stop at every commanded endpoint. No G64, G187 P/E blending model or automatic corner rounding/chamfer words. This proves nominal paths under the declared model, not servo/acceleration/physical accuracy. diff --git a/docs/machine.md b/docs/machine.md index cea117d8..ad42cb8f 100644 --- a/docs/machine.md +++ b/docs/machine.md @@ -115,7 +115,9 @@ start pose or a waypoint set it is still exactly there, at the start of every move and along any move that does not command it. A mill homed on its limits (X 0 of travel [0, 508], say) therefore starts its first moves inside. A block commands an axis by writing its word, even one equal to the current position, -or by moving along it; the exact rule is in +or by moving along it, but not by naming it as a parameter of an offset or +mode setting its decoder reads as moving nothing (the Haas and FANUC header's +`G52 X0 Y0 Z0`); the exact rule is in [the travel rule](python.md#the-travel-rule). A decoded arc whose words leave an endpoint gap is known to that gap either side of its nominal circle. diff --git a/docs/posts.md b/docs/posts.md index 087db3c5..54ea9278 100644 --- a/docs/posts.md +++ b/docs/posts.md @@ -357,6 +357,11 @@ while that axis is still where the controller placed it itself (#367): controller post writes itself (a FANUC `G1 G43 H.. Z..`, a Carvera `G53 G0 Z-3`). A probing cycle leaves every axis written, since its macros move axes their blocks need not name. +- A block that only sets an offset or a mode, naming axis letters as its + parameters (`G52 X0 Y0 Z0`, Haas `G100 X0 Y0 Z0`), writes no axis word: + the decoder reads it as moving no axis (`GCodeDecoder.hold_axes`), and + the post and the machine check both leave the axes it names placed. A + block no decoder classifies so counts every axis it names. An axis word commands the axis to that work coordinate through the controller's *actual* work offset, even at the value it already has. Where diff --git a/docs/python.md b/docs/python.md index e1012393..a7a9ed2a 100644 --- a/docs/python.md +++ b/docs/python.md @@ -249,6 +249,15 @@ and route waypoints. and an absent word is the only way to leave an axis where it is; - a block that writes an axis word and decodes to no move (its words equal the decoded position) commands that axis all the same, for the next move; + - a block the independent decoder reads as setting an offset or a mode + without moving any axis commands none of the axes it names: there the + letters are parameters, not positions. The controller decoders read so + the local-shift reset `G52 X0 Y0 Z0` (Haas NGC, FANUC 0i-MB, Centroid + CNC12 mill, plasma and lathe, LNC), the Haas mirror-image cancel `G100 + X0 Y0 Z0` and the Siemens 808D ISO `G50.1`/`G92.1 X0. Y0. Z0.` resets, + each from its manual. The decoder says so itself + (`GCodeDecoder.hold_axes`, recorded as `holds_axes` on the posted line); + a block no decoder classifies counts every axis it names; - a route waypoint makes the axes it names exact again; an axis it retains stays as it was. diff --git a/examples/centroid_lathe_post.py b/examples/centroid_lathe_post.py index d81f04f4..25e760d3 100644 --- a/examples/centroid_lathe_post.py +++ b/examples/centroid_lathe_post.py @@ -204,6 +204,9 @@ def read_line(self, line, context=None): return [CutterCompensation(self.compensation, 'xz')] if text == 'G52 X0 Z0': self.ready.add('frame_reset') + # 9.17: G52 with zero shifts cancels any local offset; it moves + # no axis, the X/Z words are the shift. + self.hold_axes() return [] words = text.split(' ') if words[0] == d.code('rapid'): diff --git a/examples/centroid_plasma_post.py b/examples/centroid_plasma_post.py index 57e9436d..eef64e14 100644 --- a/examples/centroid_plasma_post.py +++ b/examples/centroid_plasma_post.py @@ -175,6 +175,9 @@ def read_line(self, line, context=None): self.length = None return super().read_line(line, context) if text == 'G52 X0 Y0 Z0': - # Cancels any local offset: the frame reset. + # Cancels any local offset: the frame reset. CNC12 G52 (Mill + # Operator's Manual 12.20, the same CNC12 software) moves no axis: + # the X/Y/Z words are the shift. + self.hold_axes() return super().read_line('G52', context) return super().read_line(line, context) diff --git a/examples/centroid_post.py b/examples/centroid_post.py index 982e02d2..442bb05d 100644 --- a/examples/centroid_post.py +++ b/examples/centroid_post.py @@ -204,6 +204,9 @@ def read_line(self, line, context=None): if set(values) != {'G', 'X', 'Y', 'Z'} or any(values[a] != 0 for a in 'XYZ'): raise ValueError('only an explicit zero XYZ G52 reset is supported') self.ready.add('frame_reset') + # 12.20: G52 shifts the local coordinate system (zero cancels the + # shift); it moves no axis, the X/Y/Z words are the shift. + self.hold_axes() return [] if values.get('G') in (73, 83, 84) and any('.' not in text for w, text in pieces if w == 'Q'): # Parameters 245/246 may reinterpret an undotted Q (implied decimals). diff --git a/examples/fanuc_0imb_post.py b/examples/fanuc_0imb_post.py index 428a868b..1bc60f16 100644 --- a/examples/fanuc_0imb_post.py +++ b/examples/fanuc_0imb_post.py @@ -448,6 +448,10 @@ def read_line(self, line, context=None): if set(values) != {'X', 'Y', 'Z'} or any(values[a] != 0 for a in 'XYZ'): raise ValueError('only explicit all-axis local zero supported') self.ready.add('frame_reset') + # B-63844EN, local coordinate system (printed pp. 79-89): G52 IP_ + # sets the local shift, G52 with zero cancels it; the block moves + # no axis, its X/Y/Z words are the shift. + self.hold_axes() return [] if values.get('M') in (0, 1, int(self.machine.dialect.code('tool_change')[1:])): if self.rpm or self.coolant != 'off': diff --git a/examples/haas_ngc_post.py b/examples/haas_ngc_post.py index ab70d540..01f87c6e 100644 --- a/examples/haas_ngc_post.py +++ b/examples/haas_ngc_post.py @@ -450,6 +450,11 @@ def read_line(self, line, context=None): self.ready.add('frame_reset') else: self.mirror_off = True + # 96-8210 Rev N, G-codes: G52 sets a coordinate shift (zero + # clears it) and G100 cancels mirror image on the axes it names. + # Neither commands motion: the X/Y/Z words are the shift and the + # axes selected, not positions. + self.hold_axes() return [] if g in (50, 69, 187): if set(values) != {'G'} or g in (50, 69) and not self.machine.rotation_scaling: diff --git a/examples/lnc_mill_post.py b/examples/lnc_mill_post.py index b52767d6..13ef975e 100644 --- a/examples/lnc_mill_post.py +++ b/examples/lnc_mill_post.py @@ -385,6 +385,9 @@ def read_line(self, line, context=None): if set(values) != {'X', 'Y', 'Z'} or any(values[a] != 0 for a in 'XYZ'): raise ValueError('only an explicit all-axis G52 zero is supported') self.ready.add('frame_reset') + # p.48: G52 X0 Y0 Z0 clears the local coordinate system; it moves + # no axis, the X/Y/Z words are the shift. + self.hold_axes() return [] tool_change = int(self.machine.dialect.code('tool_change')[1:]) if values.get('M') in (0, 1, tool_change): diff --git a/examples/siemens808d_iso_post.py b/examples/siemens808d_iso_post.py index 045ba5c1..6a474871 100644 --- a/examples/siemens808d_iso_post.py +++ b/examples/siemens808d_iso_post.py @@ -354,6 +354,10 @@ def read_line(self, line, context=None): if self.resets != {50, 69, 50.1}: raise ValueError('cancel transforms before coordinate reset') self.ready.add('frame_reset') + # ISO pp104-113: G50.1 cancels mirroring on the axes it names and + # G92.1 X0. Y0. Z0. resets the G92/G52 shifts of those axes; + # neither moves an axis, the X/Y/Z words select the axes. + self.hold_axes() return [] if (m in (0, 1, 6) or 'T' in values) and (self.rpm or self.coolant != 'off'): raise ValueError('explicit spindle/coolant off required before OEM stop/tool change') diff --git a/python/camlib/postprocessor.py b/python/camlib/postprocessor.py index e0e06f90..a3be8351 100644 --- a/python/camlib/postprocessor.py +++ b/python/camlib/postprocessor.py @@ -1213,7 +1213,7 @@ def _call(self, name, *args, limit=8): raise ValueError(f'{name} emitted no blocks') return self._lines[:] - def _track_placed(self, name): + def _track_placed(self, name, held=()): """Which axes are still where the controller placed them after the blocks the hook ``name`` wrote (``self._lines``). @@ -1222,9 +1222,11 @@ def _track_placed(self, name): change whose declared mode moves axes to machine positions places those axes again, at its change block. Any block that names an axis word commands that axis to a work position, through the - controller's actual work offset, so the axis leaves that state. A - probing cycle's macros move axes their blocks need not name: it - leaves every axis commanded.""" + controller's actual work offset, so the axis leaves that state, + except a block the decoder read as moving no axis (``held``, one + flag per block: ``GCodeDecoder.hold_axes``), whose axis letters are + parameters. A probing cycle's macros move axes their blocks need not + name: it leaves every axis commanded.""" if name == 'on_begin': self._placed = (True, True, True) return @@ -1234,7 +1236,9 @@ def _track_placed(self, name): d = self.machine.dialect placed = list(getattr(self, '_placed', (False, False, False))) places = _TOOL_CHANGE_PLACES.get(self.machine.tool_change_position_mode, ()) - for line in self._lines: + for k, line in enumerate(self._lines): + if k < len(held) and held[k]: + continue if name == 'on_tool_change' and _changes_tool(line, d): for i in places: placed[i] = True @@ -1243,6 +1247,14 @@ def _track_placed(self, name): placed[i] = False self._placed = tuple(placed) + def _hold_placed(self, name, before, held): + """After the decoder read the blocks the last hook ``name`` wrote: + track them again from ``before`` (the state before that hook), + leaving out the blocks it held, as the machine check does.""" + if any(held): + self._placed = before + self._track_placed(name, held) + class GCodePost(PostProcessor): """Default formatter using the machine's declared dialect; normal Python.""" @@ -2016,6 +2028,9 @@ def __init__(self, machine, program): self.cycle_queue = [] self.cycle_initial = None self.compensation = 'off' + # The blocks of the last read() held as moving no axis (hold_axes). + self.held = () + self._holding = False # Beam tools: the spindle words fire and stop their beam. def shape(t): @@ -2049,7 +2064,18 @@ def validate_initialized(self): if not required <= self.ready: raise ValueError('incomplete explicit decoder modal initialization: ' + str(sorted(required - self.ready))) + def hold_axes(self): + """Call from ``read_line`` while reading a block that sets an offset + or a mode and moves no axis, whose axis words are parameters of that + setting (``G52 X0 Y0 Z0``): cite the controller's manual where it is + called. The machine check then leaves the axes the block names where + they were, and the post keeps them placed; any other block that names + an axis commands it. ``held`` gives, after ``read``, one flag per + block (empty when none was held).""" + self._holding = True + def read(self, lines, context=None): + self.held = () if context is not None and 'probe' in context: if self.cycle_queue or self.cycle_active or self.tap_return is not None: raise ValueError('a probing cycle cannot start inside another cycle') @@ -2060,8 +2086,14 @@ def read(self, lines, context=None): raise ValueError('canned cycle moves still pending') result = [] pending = self.tap_return + held = [] for line in lines: + self._holding = False result.extend(self.read_line(line, context)) + held.append(self._holding) + self._holding = False + if any(held): + self.held = tuple(held) if pending is not None: # The block after a tapping cycle is its return: G33.1 returns by # itself; a G84 cycle returns to R and must then be cancelled (G80). @@ -3217,6 +3249,17 @@ def _is_curve(event): ) +def _held_json(held): + """The decoder's held blocks (``GCodeDecoder.held``) for the native + session, or None when it held none.""" + return _json([bool(h) for h in held]) if any(held) else None + + +def _held_blocks_json(held): + """``_held_json`` for each event's blocks.""" + return _json([[bool(h) for h in block] for block in held]) if any(any(b) for b in held) else None + + class PostEngine: """Owns one run, bounded atomic batches and separately owned post/decoder state.""" @@ -3303,7 +3346,9 @@ def begin(self, program, *, run_id=None, cancel=None): scheduling = _settings(m, True) scheduling['policy']['junction_mode'] = 'exact_stop' settings['motion_scheduling'] = scheduling - session = native.IntentSession(_json(replace(program, events=()).to_dict()), _json(settings), _json(lines)) + session = native.IntentSession( + _json(replace(program, events=()).to_dict()), _json(settings), _json(lines), _held_json(decoder.held) + ) session.check_cancel(cancel) first = Chunk(session.take_begin()) data = first.data @@ -3394,6 +3439,7 @@ def _format(self, events, originals, ranges, cancel, renumber=False): blocks = [] actual = [] effects = [] + held = [] fast = self._default_motions(post, decoder) if fast is not None: return self._format_default(fast, post, decoder, events, originals, ranges, cancel, renumber) @@ -3415,21 +3461,27 @@ def _format(self, events, originals, ranges, cancel, renumber=False): post.position_mm = decoder.position post.source_event = _typed(original) if isinstance(original, dict) else original post.source_fraction = interval if kind == 'motion' else None - block = post._call('on_' + ('motion' if kind == 'motion' else kind), typed) + name = 'on_' + ('motion' if kind == 'motion' else kind) + placed = post._placed + block = post._call(name, typed) if post.machine is not self.machine: raise ValueError('hook changed the machine definition') context = _context(event) decoded = decoder.read(block, context) if decoder.ended or decoder.tool_pending: raise ValueError('event ended program or left a partial tool transition') + # The post keeps placed axes as the machine check reads the + # blocks: those the decoder held command no axis. + post._hold_placed(name, placed, decoder.held) if renumber and kind == 'motion' and any(isinstance(e, Motion) for e in decoded): next_id += 1 # Own immutable snapshots before releasing the GIL in native checking. owned = [_typed(e.to_dict()) for e in decoded] blocks.append(block) actual.append([e.to_dict() for e in owned]) + held.append(list(decoder.held)) effects.extend(owned) - return post, decoder, blocks, actual, tuple(effects) + return post, decoder, blocks, actual, tuple(effects), held def _format_default(self, fast, post, decoder, events, originals, ranges, cancel, renumber=False): """As _format, with runs of non-tapping motions formatted and decoded @@ -3437,6 +3489,7 @@ def _format_default(self, fast, post, decoder, events, originals, ranges, cancel blocks = [] actual = [] effects = [] + held = [] next_id = None i = 0 while i < len(events): @@ -3473,6 +3526,7 @@ def _format_default(self, fast, post, decoder, events, originals, ranges, cancel post._placed = tuple(placed) for event, block, words in zip(events[i:j], lines, decoded): blocks.append(block) + held.append([]) if renumber and next_id is None: next_id = event['motion']['id'] if words is None: @@ -3513,21 +3567,25 @@ def _format_default(self, fast, post, decoder, events, originals, ranges, cancel post.position_mm = decoder.position post.source_event = _typed(original) if isinstance(original, dict) else original post.source_fraction = interval if kind == 'motion' else None - block = post._call('on_' + ('motion' if kind == 'motion' else kind), typed) + name = 'on_' + ('motion' if kind == 'motion' else kind) + placed = post._placed + block = post._call(name, typed) if post.machine is not self.machine: raise ValueError('hook changed the machine definition') context = _context(event) decoded = decoder.read(block, context) if decoder.ended or decoder.tool_pending: raise ValueError('event ended program or left a partial tool transition') + post._hold_placed(name, placed, decoder.held) if renumber and kind == 'motion' and any(isinstance(e, Motion) for e in decoded): next_id += 1 owned = [_typed(e.to_dict()) for e in decoded] blocks.append(block) actual.append([e.to_dict() for e in owned]) + held.append(list(decoder.held)) effects.extend(owned) i += 1 - return post, decoder, blocks, actual, tuple(effects) + return post, decoder, blocks, actual, tuple(effects), held @staticmethod def _checked_chunk(raw, blocks, effects): @@ -3606,9 +3664,13 @@ def consume(self, events, *, cancel=None): if self.machine.schedule_post_feeds else source ) - post, decoder, blocks, actual, effects = self._format(prepared, originals, [(0.0, 1.0)] * len(source), cancel) + post, decoder, blocks, actual, effects, held = self._format( + prepared, originals, [(0.0, 1.0)] * len(source), cancel + ) out = self._checked_chunk( - self._session.consume(_json(source), _json(actual), _json(blocks), cancel), blocks, effects + self._session.consume(_json(source), _json(actual), _json(blocks), cancel, _held_blocks_json(held)), + blocks, + effects, ) self.post = post self.decoder = decoder @@ -3698,11 +3760,13 @@ def drain(self, max_segments=64, *, cancel=None): preview = json.loads(self._session.preview(max_segments, cancel)) events = [p['event'] for p in preview] ranges = [p['source_fraction_interval'] for p in preview] - post, decoder, blocks, actual, effects = self._format( + post, decoder, blocks, actual, effects, held = self._format( events, [self._sources[p['source']] for p in preview], ranges, cancel, renumber=True ) out = self._checked_chunk( - self._session.check_lowered(_json(ranges), _json(actual), _json(blocks), cancel), blocks, effects + self._session.check_lowered(_json(ranges), _json(actual), _json(blocks), cancel, _held_blocks_json(held)), + blocks, + effects, ) self.post = post self.decoder = decoder @@ -3850,7 +3914,7 @@ def finish(self, *, cancel=None): for a in actions ): raise ValueError('finish needs stopped spindle/coolant and end; no extra motion/effects') - out = self._checked_chunk(self._session.finish(_json(lines), cancel), [lines], ()) + out = self._checked_chunk(self._session.finish(_json(lines), cancel, _held_json(decoder.held)), [lines], ()) self.post = post self.decoder = decoder self.finished = True diff --git a/python/tests/test_checked_post_controls.py b/python/tests/test_checked_post_controls.py index 86ad107a..db3a938e 100644 --- a/python/tests/test_checked_post_controls.py +++ b/python/tests/test_checked_post_controls.py @@ -144,7 +144,7 @@ def test_native_control_mismatch_rejection_does_not_advance_events_or_lines(self e = PostEngine(m) begin = e.begin(p) source = [v.to_dict() for v in p.events[:2]] - _, _, blocks, actual, _ = e._format(source, p.events[:2], [(0.0, 1.0)] * 2, None) + _, _, blocks, actual, _, _ = e._format(source, p.events[:2], [(0.0, 1.0)] * 2, None) for change in ('tool', 'number', 'length_register', 'position_after_mm'): forged = deepcopy(actual) forged[1][0][change] = {'tool': 'other', 'number': 3, 'length_register': 8, 'position_after_mm': [6, 0, 3]}[ diff --git a/python/tests/test_placed_axes.py b/python/tests/test_placed_axes.py index 26c44e1c..cee1f007 100644 --- a/python/tests/test_placed_axes.py +++ b/python/tests/test_placed_axes.py @@ -25,7 +25,7 @@ from camlib.post import GCodePost, post_job, post_job_input from camlib.verification import StockContactOptions from support.facing import facing_job -from test_rust_post import ROOT, plain +from test_rust_post import ROOT, example, plain from test_tool_change_pose import job as drilling_job, machine as mill, tools as drilling_tools # Work zero in machine coordinates: the mill homes at X 0, Y 0 (its travel @@ -33,8 +33,9 @@ ORIGIN = (250.0, 200.0, -150.0) -def homed_model(tool, register, work_error_mm): - """A mill homed on its limits, the work frame known to +-work_error_mm.""" +def homed_model(tool, register, work_error_mm, z_max_mm=0): + """A mill homed on its limits, the work frame known to +-work_error_mm. + z_max_mm: the Z travel maximum (home is Z 0).""" g = tool.gauge_length_mm return MachineModel( 1, @@ -42,7 +43,7 @@ def homed_model(tool, register, work_error_mm): 'homed-at-limits', '1', 'milling', - (Axis('head', 0, 500), Axis('head', 0, 400), Axis('head', -300, 0)), + (Axis('head', 0, 500), Axis('head', 0, 400), Axis('head', -300, z_max_mm)), 1, WorkFrame(ORIGIN), (-work_error_mm,) * 3, @@ -65,8 +66,10 @@ def homed_model(tool, register, work_error_mm): ) -def facing_from_home(work_error_mm=0.02): - """A Facing whose start is the home pose, and the homed LinuxCNC mill.""" +def facing_from_home(work_error_mm=0.02, tool_change=None): + """A Facing whose start is the home pose, and the homed LinuxCNC mill. + tool_change: the setup's (ToolChangeInPlace unless given), from the + home pose.""" spec = facing_job() tool = spec['tools'][0] home = (-ORIGIN[0], -ORIGIN[1], -ORIGIN[2] - tool.gauge_length_mm) @@ -76,7 +79,7 @@ def facing_from_home(work_error_mm=0.02): tools=spec['tools'], operations=tuple(camlib.OperationNode(op, sources=()) for op in spec['operations']), initial_position_mm=home, - tool_change=ToolChangeInPlace(), + tool_change=ToolChangeInPlace() if tool_change is None else tool_change(tool, home), ) job = camlib.Job('facing-from-home', '1', (setup,)) setting = ToolSetting.for_tool(tool, number=1, length_register=1) @@ -154,6 +157,105 @@ def on_motion(self, motion): self.assertIn('straddles the minimum 0.000000 mm', details) +class OffsetBlockTest(unittest.TestCase): + """#369: Haas and FANUC headers clear the local shift with G52 X0 Y0 Z0 + (Haas also mirror image, G100 X0 Y0 Z0). Those blocks set an offset or + a mode and move no axis; their decoders read them so (hold_axes), and + the machine check keeps the axes they name exactly at home.""" + + def facing(self, controller): + # The FANUC reference declares where M6 leaves the spindle: here the + # table pose of the tool is the home pose the program starts at. + table = controller == 'fanuc_0imb_post' + job, _, home = facing_from_home( + tool_change=(lambda tool, home: camlib.ToolChangeTable({tool.id: home})) if table else None + ) + tool = facing_job()['tools'][0] + declared = dict( + output_units='mm', + decimals=3, + max_feed_mm_min=10000, + max_spindle_rpm=30000, + max_sweep_rad=6.283185307179586, + tool_changes=True, + flood=True, + rapid_mm_min=6000, + tool_change_position_mode='preserve_spindle', + # FANUC activates the length offset with G1 G43 H Z (B-63844EN + # pp. 199-206), which commands Z: there Z is homed below its + # maximum, X and Y still on their minimums. + crash_model=homed_model(tool, 1, 0.02, z_max_mm=50 if table else 0), + ) + setting = ToolSetting.for_tool(tool, number=1, length_register=1) + module = example(controller) + if controller == 'haas_ngc_post': + m = module.define_machine( + 'Haas homed at its limits', + (setting,), + traverse_feed_mm_min=3000, + coordinate_system='fanuc', + h_t_agreement=True, + g92_shift_mm=(0, 0, 0), + rotation_scaling=False, + work_to_machine=WorkFrame(ORIGIN), + **declared, + ) + return job, m, module.HaasNGCPost, module.HaasNGCDecoder + declared['tool_change_position_mode'] = 'table' + m = module.define_machine( + 'FANUC homed at its limits', + (replace(setting, position_after_mm=home),), + startup_units='mm', + startup_standard_modes=True, + g92_shift_mm=(0, 0, 0), + m_codes=dict( + tool_change='M6', spindle_cw='M3', spindle_ccw='M4', spindle_off='M5', coolant_off='M9', flood='M8' + ), + traverse_feed_mm_min=3000, + work_to_machine=WorkFrame(ORIGIN), + **declared, + ) + return job, m, module.Fanuc0iMBPost, module.Fanuc0iMBDecoder + + def test_haas_and_fanuc_headers_leave_the_axes_at_home(self): + for controller, block in (('haas_ngc_post', 'G52 X0 Y0 Z0'), ('fanuc_0imb_post', 'G52 X0. Y0. Z0.')): + with self.subTest(controller): + job, m, post, decoder = self.facing(controller) + released = job.post_nc('top', machine=m, post=post, decoder=decoder) + self.assertIn(block, released.text.splitlines()) + # X and Y are not written before the first traverse; the + # header names them only as G52's (and G100's) parameters. + self.assertEqual(released.machine['status'], 'clear', released.machine) + self.assertTrue(released.machine['complete']) + self.assertEqual(tuple(released.findings), ()) + if controller == 'haas_ngc_post': + self.assertIn('G100 X0 Y0 Z0', released.text.splitlines()) + # The Rust Haas post and decoder release the same program. + rust = post_job(post_job_input(job, 'top', machine=m)) + self.assertTrue(rust['released'], rust.get('refused')) + self.assertEqual(rust['program'], released.text) + self.assertEqual(rust['machine']['status'], 'clear') + + def test_a_block_no_decoder_classifies_still_commands_its_axes(self): + # The same header read by a decoder that does not classify it: the + # axis letters count as words, which command the axes at home + # through the work offset, straddling the minimums by the interval. + for controller in ('haas_ngc_post', 'fanuc_0imb_post'): + with self.subTest(controller): + job, m, post, decoder = self.facing(controller) + + class Unclassified(decoder): + def hold_axes(self): + pass + + with self.assertRaises(ExportRefused) as refused: + job.post_nc('top', machine=m, post=post, decoder=Unclassified) + self.assertEqual(refused.exception.statuses, ('uncertain',)) + posted = job.post_nc('top', machine=m, post=post, decoder=Unclassified, accept={'uncertain'}) + details = ' '.join(f['detail'] for f in posted.machine['findings']) + self.assertIn('straddles the minimum 0.000000 mm of declared [0, 500] machine travel', details) + + class ToolChangeTest(unittest.TestCase): def test_z_home_tool_change_places_z_until_the_program_moves_it(self): m = mill( @@ -209,6 +311,24 @@ def post(mode, **settings): p._call('on_tool_change', ToolChange('drill3', 1, 1, (0, 0, 40))) self.assertEqual(p._placed, (False, False, False)) + def test_a_block_the_decoder_held_leaves_placed_axes_placed(self): + # The post keeps placed axes as the machine check reads the blocks: + # after the decoder held a block, its axis letters are parameters. + p = GCodePost(mill({'drill3': (0.0, 0.0, 40.0)}, mode='preserve_tip')) + p._placed = (True, True, True) + p._lines = ['G52 X0 Y0 Z0', 'G4 P1'] + p._track_placed('on_dwell', (True, False)) + self.assertEqual(p._placed, (True, True, True)) + p._track_placed('on_dwell') + self.assertEqual(p._placed, (False, False, False)) + # _hold_placed tracks the hook's blocks again from the state before + # it, leaving out those held; with none held it changes nothing. + p._lines = ['G52 X0 Y0 Z0', 'G0 Y5'] + p._hold_placed('on_dwell', (True, True, True), (True, False)) + self.assertEqual(p._placed, (True, False, True)) + p._hold_placed('on_dwell', (True, True, True), ()) + self.assertEqual(p._placed, (True, False, True)) + if __name__ == '__main__': unittest.main() diff --git a/python/tests/test_python_lowering.py b/python/tests/test_python_lowering.py index 995a770f..062fb70a 100644 --- a/python/tests/test_python_lowering.py +++ b/python/tests/test_python_lowering.py @@ -179,7 +179,7 @@ def test_preview_caps_pending_lifecycle_and_modified_intervals_are_atomic(self): e.drain(n) events = [i['event'] for i in preview] ranges = [list(i['source_fraction_interval']) for i in preview] - _, _, blocks, actual, _ = e._format(events, [p.events[-1]] * 7, ranges, None) + _, _, blocks, actual, _, _ = e._format(events, [p.events[-1]] * 7, ranges, None) ranges[0][1] += 1e-5 with self.assertRaisesRegex(ValueError, 'interval'): e._session.check_lowered(json.dumps(ranges), json.dumps(actual), json.dumps(blocks)) diff --git a/src/gcode/decode.rs b/src/gcode/decode.rs index 54dfb9b0..9bb4d130 100644 --- a/src/gcode/decode.rs +++ b/src/gcode/decode.rs @@ -187,6 +187,11 @@ pub struct Decoder { rules: Vec<(Code, Effect)>, required: BTreeSet, motions: crate::post_decode::Decoder, + /// Per block of the last `read`: read as setting an offset or a mode + /// without moving any axis, the axis letters it names being parameters + /// (`hold_axes`; `post::Line::holds_axes`). Empty when none was. + pub held: Vec, + holding: bool, } impl Decoder { @@ -274,6 +279,8 @@ impl Decoder { rules, required, motions, + held: vec![], + holding: false, machine: machine.clone(), }) } @@ -299,6 +306,15 @@ impl Decoder { } } + /// Called while reading a block that sets an offset or a mode and + /// moves no axis, whose axis words are parameters of that setting (the + /// controller's manual says so: cite it where it is called). The + /// machine check then leaves the axes the block names where they were; + /// any other block naming an axis commands it. + fn hold_axes(&mut self) { + self.holding = true; + } + fn rule(&self, code: &Code) -> Option<&Effect> { self.rules.iter().find(|(c, _)| c == code).map(|(_, e)| e) } @@ -309,6 +325,7 @@ impl Decoder { lines: &[String], context: Option<&Context>, ) -> Result, String> { + self.held.clear(); if lines.is_empty() && !self.cycle_queue.is_empty() { return Ok(vec![self.cycle_effect(context)?]); } @@ -317,8 +334,14 @@ impl Decoder { } let mut result = vec![]; let pending = self.tap_return; + self.held.clear(); for line in lines { + self.holding = false; result.extend(self.read_line(line, context)?); + self.held.push(self.holding); + } + if !self.held.contains(&true) { + self.held.clear(); } if let Some((start, bottom, feed)) = pending { // The block after a tapping cycle is its return. diff --git a/src/gcode/decode/haas.rs b/src/gcode/decode/haas.rs index ce6ecd9a..851f5678 100644 --- a/src/gcode/decode/haas.rs +++ b/src/gcode/decode/haas.rs @@ -181,6 +181,12 @@ impl Decoder { } else { self.haas.mirror_off = true; } + // Haas 96-8210 Rev N (Mill Operator's Manual, NGC), G-codes: G52 + // sets a coordinate shift (the local system with Setting 33 + // FANUC; zero clears it) and G100 cancels mirror image on the + // axes it names. Neither commands motion: their X/Y/Z words are + // the shift and the axes selected, not positions. + self.hold_axes(); return Ok(vec![]); } if matches!(g, Some(50. | 69. | 187.)) { diff --git a/src/gcode/decode/probe.rs b/src/gcode/decode/probe.rs index dc9d91ee..9a12a535 100644 --- a/src/gcode/decode/probe.rs +++ b/src/gcode/decode/probe.rs @@ -125,6 +125,8 @@ impl Decoder { cycle: &ProbeCycle, covers: u32, ) -> Result, String> { + // A probing cycle's blocks move axes: none is held. + self.held.clear(); if !self.cycle_queue.is_empty() || self.cycle_active || self.tap_return.is_some() { return Err("a probing cycle cannot start inside another cycle".into()); } diff --git a/src/gcode/engine.rs b/src/gcode/engine.rs index 33c3e3dd..dc20c48c 100644 --- a/src/gcode/engine.rs +++ b/src/gcode/engine.rs @@ -22,8 +22,9 @@ pub struct ArcOutput { pub lines_precision: u64, } -/// Each event's written blocks and their decoded events. -type Formatted = (Vec>, Vec>); +/// Each event's written blocks, their decoded events and the blocks the +/// decoder held (`Decoder::held`). +type Formatted = (Vec>, Vec>, Vec>); pub struct Engine { machine: Machine, @@ -164,7 +165,7 @@ impl Engine { lowering: lowering.clone(), motion_scheduling: None, }; - let (session, first) = IntentChecker::begin(header, settings, &lines)?; + let (session, first) = IntentChecker::begin_held(header, settings, &lines, &decoder.held)?; if cancel.is_cancelled() { return Err("post cancelled; batch not committed".into()); } @@ -200,6 +201,7 @@ impl Engine { ) -> Result { let mut blocks = Vec::with_capacity(events.len()); let mut actual = Vec::with_capacity(events.len()); + let mut held = Vec::with_capacity(events.len()); let mut next_id: Option = None; for (event, original) in events.iter().zip(originals) { if cancel.is_cancelled() { @@ -220,6 +222,7 @@ impl Engine { } self.post.position_mm = Some(self.decoder.position); self.post.source_event = Some(original.clone()); + let placed = self.post.placed(); let block = self.post.call(Hook::Event(&typed), 8)?; let decoded = if let Event::Probe { cycle, covers } = &typed { self.decoder.read_probe(&block, cycle, *covers)? @@ -238,10 +241,15 @@ impl Engine { { *id += 1; } + // The post keeps placed axes as the machine check reads the + // blocks: those the decoder held command no axis. + self.post + .hold_placed(Hook::Event(&typed), placed, &self.decoder.held); blocks.push(block); actual.push(decoded); + held.push(self.decoder.held.clone()); } - Ok((blocks, actual)) + Ok((blocks, actual, held)) } /// `PostEngine.consume` (direct mode): at most 64 events, one chunk. @@ -259,8 +267,9 @@ impl Engine { if events.len() > 64 { return Err("post consume accepts at most 64 events".into()); } - let (blocks, actual) = self.format(events, events, false, cancel)?; - self.session.consume(events, &actual, &blocks, cancel) + let (blocks, actual, held) = self.format(events, events, false, cancel)?; + self.session + .consume_held(events, &actual, &blocks, &held, cancel) } /// How a lowered source arc/helix is written (`PostEngine._arc_output`). @@ -332,10 +341,10 @@ impl Engine { .ok_or("lowered segment without its source") }) .collect::>()?; - let (blocks, actual) = self.format(&events, &originals, true, cancel)?; + let (blocks, actual, held) = self.format(&events, &originals, true, cancel)?; let out = self .session - .check_lowered(&ranges, &actual, &blocks, cancel)?; + .check_lowered_held(&ranges, &actual, &blocks, &held, cancel)?; // Sources whose last segment was in this batch are complete. for _ in 0..ranges.iter().filter(|r| r[1] == 1.).count() { self.sources.pop_front(); @@ -477,7 +486,9 @@ impl Engine { "finish needs stopped spindle/coolant and end; no extra motion/effects".into(), ); } - let out = self.session.finish(&lines, cancel)?; + let out = self + .session + .finish_held(&lines, &self.decoder.held, cancel)?; self.finished = true; Ok(out) } diff --git a/src/gcode/post.rs b/src/gcode/post.rs index eef6fc94..ac5e6d54 100644 --- a/src/gcode/post.rs +++ b/src/gcode/post.rs @@ -21,6 +21,33 @@ pub enum Hook<'a> { Finish, } +/// The Python hook a `Hook` calls. +fn hook_name(hook: &Hook<'_>) -> &'static str { + match hook { + Hook::Begin { .. } => "on_begin", + Hook::Finish => "on_finish", + Hook::Event(e) => match e { + Event::Motion { .. } => "on_motion", + Event::ToolChange { .. } => "on_tool_change", + Event::Spindle { .. } => "on_spindle", + Event::Coolant { .. } => "on_coolant", + Event::WorkOffset { .. } => "on_work_offset", + Event::Stop { .. } => "on_stop", + Event::Dwell { .. } => "on_dwell", + Event::Cycle { .. } => "on_cycle", + Event::SpindleOrient { .. } => "on_spindle_orient", + Event::Beam { .. } => "on_beam", + Event::BeamMark { .. } => "on_beam_mark", + Event::BeamStart { .. } => "on_beam_start", + Event::HeightControl { .. } => "on_height_control", + Event::SurfaceSpeed { .. } => "on_surface_speed", + Event::FeedPerRev { .. } => "on_feed_per_rev", + Event::CutterCompensation { .. } => "on_cutter_compensation", + Event::Probe { .. } => "on_probe", + }, + } +} + #[derive(Clone)] pub struct DefaultPost { machine: Machine, @@ -328,29 +355,7 @@ impl DefaultPost { pub fn call(&mut self, hook: Hook<'_>, limit: usize) -> Result, String> { self.lines.clear(); self.limit = limit; - let name = match &hook { - Hook::Begin { .. } => "on_begin", - Hook::Finish => "on_finish", - Hook::Event(e) => match e { - Event::Motion { .. } => "on_motion", - Event::ToolChange { .. } => "on_tool_change", - Event::Spindle { .. } => "on_spindle", - Event::Coolant { .. } => "on_coolant", - Event::WorkOffset { .. } => "on_work_offset", - Event::Stop { .. } => "on_stop", - Event::Dwell { .. } => "on_dwell", - Event::Cycle { .. } => "on_cycle", - Event::SpindleOrient { .. } => "on_spindle_orient", - Event::Beam { .. } => "on_beam", - Event::BeamMark { .. } => "on_beam_mark", - Event::BeamStart { .. } => "on_beam_start", - Event::HeightControl { .. } => "on_height_control", - Event::SurfaceSpeed { .. } => "on_surface_speed", - Event::FeedPerRev { .. } => "on_feed_per_rev", - Event::CutterCompensation { .. } => "on_cutter_compensation", - Event::Probe { .. } => "on_probe", - }, - }; + let name = hook_name(&hook); if self.covered > 0 && self.covered_probe { // A written probing cycle carries all its moves. if name != "on_motion" { @@ -408,7 +413,7 @@ impl DefaultPost { Hook::Finish => self.on_finish()?, Hook::Event(event) => self.on_event(event)?, } - self.track_placed(name); + self.track_placed(name, &[]); if self.lines.is_empty() && name != "on_cycle" && !(name == "on_cutter_compensation" && self.machine.dialect.compensation_with_move) @@ -428,8 +433,10 @@ impl DefaultPost { /// word commands that axis to a work position, through the controller's /// actual work offset, so the axis leaves that state. A probing cycle's /// macros move axes their blocks need not name: it leaves every axis - /// commanded. - fn track_placed(&mut self, name: &str) { + /// commanded. A block the decoder read as moving no axis (`held`, one + /// flag per block, empty for none: `post::Line::holds_axes`) names its + /// axes as parameters, not words that command them. + fn track_placed(&mut self, name: &str, held: &[bool]) { match name { "on_begin" => self.placed = [true; 3], "on_probe" => self.placed = [false; 3], @@ -440,7 +447,10 @@ impl DefaultPost { "table" => &[0, 1, 2], _ => &[], }; - for line in &self.lines { + for (i, line) in self.lines.iter().enumerate() { + if held.get(i).copied().unwrap_or(false) { + continue; + } if name == "on_tool_change" && changes_tool(line, d) { for &i in places { self.placed[i] = true; @@ -456,6 +466,22 @@ impl DefaultPost { } } + /// Which work axes are still where the controller placed them. + pub fn placed(&self) -> [bool; 3] { + self.placed + } + + /// `PostProcessor._hold_placed`: after the decoder read the blocks the + /// last `call` wrote for `hook`, track them again from `before` (the + /// state before that call) leaving out the blocks it held, as the + /// machine check does. + pub fn hold_placed(&mut self, hook: Hook<'_>, before: [bool; 3], held: &[bool]) { + if held.contains(&true) { + self.placed = before; + self.track_placed(hook_name(&hook), held); + } + } + fn on_event(&mut self, event: &Event) -> Result<(), String> { let d = self.machine.dialect.clone(); match event { diff --git a/src/machine/session.rs b/src/machine/session.rs index edb59969..764955bd 100644 --- a/src/machine/session.rs +++ b/src/machine/session.rs @@ -853,6 +853,19 @@ impl Session { } if depth != 0 { [true; 3] } else { words } } + /// The work axes a posted block may command: none for a block the + /// independent decoder read as setting an offset or a mode without + /// moving any axis (`Line::holds_axes`: its axis letters are parameters, + /// such as the shift of `G52 X0 Y0 Z0`), else `axis_words`. Only the + /// decoder's own reading holds a block; any other block that names an + /// axis commands it. + fn line_words(&self, line: &crate::post::Line) -> [bool; 3] { + if line.holds_axes { + [false; 3] + } else { + self.axis_words(&line.text) + } + } /// The machine axes a command of the `work` axes may move: those whose /// row of the rigid work-to-machine frame depends on one of them. fn affected(&self, work: [bool; 3]) -> [bool; 3] { @@ -905,7 +918,9 @@ impl Session { /// block that writes an axis word commands that axis to a work position, /// even one equal to the decoded current position (that block decodes /// to no move, yet the machine goes to the commanded position, which the - /// interval places), so it is held with the interval from then on. + /// interval places), so it is held with the interval from then on. A + /// block the decoder read as moving no axis (`line_words`: `G52 X0 Y0 + /// Z0` and the like) writes no axis word. /// /// For a decoded move: its start is exact on every axis still exact /// before its record's blocks (except the last one, which may be the @@ -937,7 +952,7 @@ impl Session { ([false; 3], [false; 3]) } else { while next < lines.len() && lines[next].number < start { - let words = self.axis_words(&lines[next].text); + let words = self.line_words(&lines[next]); let between = Attribution { event: self.last_event, ..Default::default() @@ -949,7 +964,7 @@ impl Session { let mut complete = true; while next < lines.len() && lines[next].number <= end { complete &= lines[next].number == start + own.len(); - own.push(self.axis_words(&lines[next].text)); + own.push(self.line_words(&lines[next])); next += 1; } if !complete || own.len() != end - start + 1 { @@ -982,7 +997,7 @@ impl Session { } } while next < lines.len() { - let words = self.axis_words(&lines[next].text); + let words = self.line_words(&lines[next]); let between = Attribution { event: self.last_event, ..Default::default() diff --git a/src/post.rs b/src/post.rs index d10de157..2a89cf46 100644 --- a/src/post.rs +++ b/src/post.rs @@ -17,6 +17,14 @@ pub struct Line { pub operation: Option, pub motion_id: Option, pub text: String, + /// The independent decoder read this block as setting an offset or a + /// mode without moving any axis: the axis letters it names are + /// parameters, not positions (Haas and FANUC `G52 X0 Y0 Z0`, Haas + /// `G100 X0 Y0 Z0`). The machine check then leaves the axes it names + /// where they were. Only a decoder sets it; absent, every axis word in + /// the block counts as commanding its axis. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub holds_axes: bool, } #[derive(Debug, Serialize, Deserialize)] pub struct Checked { diff --git a/src/post_intent.rs b/src/post_intent.rs index 83198ea9..bce3fc2c 100644 --- a/src/post_intent.rs +++ b/src/post_intent.rs @@ -208,6 +208,18 @@ impl IntentChecker { header: &Program, settings: Settings, lines: &[String], + ) -> Result<(Self, Output), String> { + Self::begin_held(header, settings, lines, &[]) + } + /// `begin`, with the independent decoder's reading of each + /// initialization block: `held[i]` when it read block `i` as setting an + /// offset or a mode without moving any axis (`Line::holds_axes`). Empty + /// when it held none. + pub fn begin_held( + header: &Program, + settings: Settings, + lines: &[String], + held: &[bool], ) -> Result<(Self, Output), String> { if !header.events.is_empty() || !valid_id(&settings.run_id) @@ -362,7 +374,7 @@ impl IntentChecker { }; state.check_point(header.initial_position_mm, None)?; state.check_point(state.settings.decoded_initial_position_mm, None)?; - let mut chunk = state.chunk(None, lines)?; + let mut chunk = state.chunk(None, lines, held)?; chunk.decoded_initial_position_mm = Some(state.settings.decoded_initial_position_mm); let mut output = state.output(chunk, vec![], vec![]); output.lowering_policy = state.settings.lowering.clone(); @@ -566,9 +578,19 @@ impl IntentChecker { } Ok(Some(checks)) } - fn chunk(&mut self, event: Option<(&Event, usize)>, lines: &[String]) -> Result { + /// `held`: the decoder's reading of each block (`Line::holds_axes`), + /// empty when it held none. + fn chunk( + &mut self, + event: Option<(&Event, usize)>, + lines: &[String], + held: &[bool], + ) -> Result { + if !held.is_empty() && held.len() != lines.len() { + return Err("decoder block classification does not match the written blocks".into()); + } let mut output = vec![]; - for text in lines { + for (i, text) in lines.iter().enumerate() { if text.len() > 1024 || !text.is_ascii() || text.bytes().any(|b| b < 32 && b != b'\t' || b == 127) @@ -589,6 +611,7 @@ impl IntentChecker { operation: motion.map(|m| m.operation.clone()), motion_id: motion.map(|m| m.id), text: text.clone(), + holds_axes: held.get(i).copied().unwrap_or(false), }); } Ok(Chunk { @@ -608,6 +631,7 @@ impl IntentChecker { expected: &Event, actual: &[Event], lines: &[String], + held: &[bool], index: usize, ) -> Result { let start_line = self.line + 1; @@ -677,7 +701,7 @@ impl IntentChecker { self.normal_acceleration = self.checked_normal_acceleration(event, false)?; self.axis_feed = self.checked_axis_feed(event, false)?; } - let mut chunk = self.chunk(Some((expected, index)), lines)?; + let mut chunk = self.chunk(Some((expected, index)), lines, held)?; // Preserve exactly the decoded control effects, including explicit // coolant-off and immaterial stopped-spindle direction. No candidate // record escapes if comparison, quota or cancellation later fails. @@ -983,12 +1007,26 @@ impl IntentChecker { decoded: &[Vec], blocks: &[Vec], cancel: &impl CancelSignal, + ) -> Result { + self.consume_held(source, decoded, blocks, &[], cancel) + } + /// `consume`, with the independent decoder's reading of each event's + /// blocks (`begin_held`): one entry per event, or none when it held no + /// block. + pub fn consume_held( + &mut self, + source: &[Event], + decoded: &[Vec], + blocks: &[Vec], + held: &[Vec], + cancel: &impl CancelSignal, ) -> Result { if self.finished || self.settings.lowering.is_some() || source.len() > 64 || source.len() != decoded.len() || source.len() != blocks.len() + || !held.is_empty() && held.len() != blocks.len() || blocks .iter() .zip(source) @@ -1003,7 +1041,7 @@ impl IntentChecker { let mut next = self.clone(); let first = next.source.summary.events; next.source.consume(source)?; - let mut out = next.chunk(None, &[])?; + let mut out = next.chunk(None, &[], &[])?; let mut mappings = vec![]; let mut records = vec![]; for (i, ((expected, actual), lines)) in source.iter().zip(decoded).zip(blocks).enumerate() { @@ -1024,7 +1062,8 @@ impl IntentChecker { let expected = scheduled.as_ref().map_or(authored, |s| &s.event); next.normal_acceleration = next.checked_normal_acceleration(expected, true)?; next.axis_feed = next.checked_axis_feed(expected, true)?; - let chunk = next.decoded_event(expected, actual, lines, first + i)?; + let held = held.get(i).map_or(&[][..], |h| &h[..]); + let chunk = next.decoded_event(expected, actual, lines, held, first + i)?; let hash = format!( "{:x}", Sha256::digest(serde_json::to_vec(authored).map_err(|e| e.to_string())?) @@ -1255,12 +1294,25 @@ impl IntentChecker { decoded: &[Vec], blocks: &[Vec], cancel: &impl CancelSignal, + ) -> Result { + self.check_lowered_held(ranges, decoded, blocks, &[], cancel) + } + /// `check_lowered`, with the decoder's reading of each segment's blocks + /// (`consume_held`). + pub fn check_lowered_held( + &mut self, + ranges: &[[f64; 2]], + decoded: &[Vec], + blocks: &[Vec], + held: &[Vec], + cancel: &impl CancelSignal, ) -> Result { if self.finished || ranges.is_empty() || ranges.len() > 64 || ranges.len() != decoded.len() || ranges.len() != blocks.len() + || !held.is_empty() && held.len() != blocks.len() || blocks.iter().any(|b| b.len() > PROBE_BLOCK_LINES) || decoded.iter().any(|b| b.len() > 8) { @@ -1279,10 +1331,12 @@ impl IntentChecker { return Err("source interval gap/overlap or modified lowering plan".into()); } let mut next = self.clone(); - let mut out = next.chunk(None, &[])?; + let mut out = next.chunk(None, &[], &[])?; let mut mappings = vec![]; let mut records = vec![]; - for (range, (actual, lines)) in ranges.iter().zip(decoded.iter().zip(blocks)) { + for (i, (range, (actual, lines))) in + ranges.iter().zip(decoded.iter().zip(blocks)).enumerate() + { cancelled(cancel)?; let start = next.decoded.summary.final_position_mm; let p = next @@ -1303,7 +1357,8 @@ impl IntentChecker { if lines.len() > block_lines(&event) { return Err("generic lowering lifecycle/batch/block cap".into()); } - let mut chunk = next.decoded_event(&event, actual, lines, index)?; + let held = held.get(i).map_or(&[][..], |h| &h[..]); + let mut chunk = next.decoded_event(&event, actual, lines, held, index)?; if let Event::Motion { motion } = &original { let decoded = chunk.checked[0].motion.as_ref(); let has_motion = decoded.is_some(); @@ -1391,6 +1446,16 @@ impl IntentChecker { &mut self, lines: &[String], cancel: &impl CancelSignal, + ) -> Result { + self.finish_held(lines, &[], cancel) + } + /// `finish`, with the decoder's reading of each closing block + /// (`begin_held`). + pub fn finish_held( + &mut self, + lines: &[String], + held: &[bool], + cancel: &impl CancelSignal, ) -> Result { if self.finished || !self.pending.is_empty() @@ -1402,7 +1467,7 @@ impl IntentChecker { } cancelled(cancel)?; let mut next = self.clone(); - let chunk = next.chunk(None, lines)?; + let chunk = next.chunk(None, lines, held)?; let output = next.output(chunk, vec![], vec![]); check_chunk_size(&output)?; cancelled(cancel)?; diff --git a/tests/machine.rs b/tests/machine.rs index a1573417..b7c3cdf1 100644 --- a/tests/machine.rs +++ b/tests/machine.rs @@ -565,6 +565,7 @@ fn posted(header: &[&str], blocks: &[Block]) -> (Vec, Vec (Vec, Vec>(), + ) + }; + let (status, found) = findings(true); + assert!(found.is_empty(), "{found:?}"); + assert_eq!(status, Status::Clear); + // The same blocks, unclassified (no decoder held them): every axis they + // name is commanded at the decoded position, which straddles the limits + // by the interval. The conservative rule stays the default. + // The header's finding is at no move (Z, the first axis outside), and + // the traverse then starts from an X known only to the interval. + let (status, found) = findings(false); + assert_eq!(status, Status::Uncertain); + assert!( + found + .iter() + .any(|f| f.bodies[0] == "axis_z" && f.motion_id.is_none()), + "{found:?}" + ); + assert!( + found + .iter() + .any(|f| (f.bodies[0].as_str(), f.motion_id, f.fraction) == ("axis_x", Some(2), 0.)), + "{found:?}" + ); +} + /// Posted by Python's `Job.post_nc` (python/tests/test_placed_axes.py): a /// Facing whose start is the home pose of a LinuxCNC mill homed at X 0, Y 0 /// (its travel minimums) and Z 0 (its maximum), its work frame known to