diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e03839ec..0ff4411a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -126,9 +126,9 @@ jobs: cd "${LINUXCNC_DIR}/src" ./autogen.sh ./configure --with-realtime=uspace \ - --enable-headless \ + --disable-gui \ --disable-build-documentation \ - --disable-build-manpages + --disable-manpages make -j"$(nproc)" - name: Save LinuxCNC build if: steps.linuxcnc-cache.outputs.cache-hit != 'true' diff --git a/.github/workflows/linuxcnc-patches.yml b/.github/workflows/linuxcnc-patches.yml index 6ee3366f..29e72f31 100644 --- a/.github/workflows/linuxcnc-patches.yml +++ b/.github/workflows/linuxcnc-patches.yml @@ -4,10 +4,12 @@ on: push: paths: - "linuxcnc-patches/**" + - "linuxcnc-tests/**" - ".github/workflows/linuxcnc-patches.yml" pull_request: paths: - "linuxcnc-patches/**" + - "linuxcnc-tests/**" - ".github/workflows/linuxcnc-patches.yml" workflow_dispatch: @@ -33,6 +35,8 @@ jobs: label: 2 - shard: 2 label: 3 + - shard: 3 + label: 4 steps: - name: Check out repository @@ -71,7 +75,17 @@ jobs: - name: Install LinuxCNC build and test dependencies working-directory: ${{ runner.temp }}/linuxcnc - run: .github/scripts/install-deps.sh + run: | + set -euo pipefail + + .github/scripts/use-main-ubuntu-mirror.sh + sudo apt-get --quiet update + sudo apt-get install --yes --no-install-recommends build-essential dpkg-dev + export DEB_BUILD_PROFILES="pkg.linuxcnc.headless nodoc" + debian/configure no-docs + sudo env DEB_BUILD_PROFILES="${DEB_BUILD_PROFILES}" \ + apt-get -P "pkg.linuxcnc.headless,nodoc" build-dep --yes \ + --no-install-recommends . - name: Build patched LinuxCNC working-directory: ${{ runner.temp }}/linuxcnc @@ -79,33 +93,14 @@ jobs: mkdir -p "${RUNNER_TEMP}/rtlib-a" "${RUNNER_TEMP}/rtlib-b" .github/scripts/build-rip.sh \ --with-realtime=uspace \ - --with-extra-rtlib-dirs="${RUNNER_TEMP}/rtlib-a:${RUNNER_TEMP}/rtlib-b" + --with-extra-rtlib-dirs="${RUNNER_TEMP}/rtlib-a:${RUNNER_TEMP}/rtlib-b" \ + --disable-gui \ + --disable-build-documentation \ + --disable-manpages - name: Run LinuxCNC regression suite shard working-directory: ${{ runner.temp }}/linuxcnc env: SHARD_COUNT: ${{ strategy.job-total }} SHARD_INDEX: ${{ matrix.shard }} - run: | - set -euo pipefail - - shard_tests=() - while IFS= read -r -d '' test_path; do - if [[ "${test_path}" == tests/resumable-stop/* ]]; then - test_shard=0 - else - checksum="$(printf '%s' "${test_path}" | cksum)" - checksum="${checksum%% *}" - test_shard=$((1 + checksum % (SHARD_COUNT - 1))) - fi - if (( test_shard == SHARD_INDEX )); then - shard_tests+=("${test_path}") - fi - done < <( - find tests \( -name test -o -name test.sh -o -name test.hal \) \ - -print0 | sort -z - ) - - ((${#shard_tests[@]} > 0)) - echo "Running ${#shard_tests[@]} tests in shard $((SHARD_INDEX + 1))/${SHARD_COUNT}" - scripts/rip-environment runtests -p "${shard_tests[@]}" + run: '"${GITHUB_WORKSPACE}/linuxcnc-tests/run.sh" . -p' diff --git a/AGENTS.md b/AGENTS.md index 8697ccce..887b1aa8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,13 @@ # LinuxCNC Ctrl Agent Guidance +## Project scope + +- LinuxCNC's own GUIs and GUI tools, its older remote interfaces, tool database + programs, and RTAI or kernel-module realtime are out of scope (see + `README.md`). Do not + report review findings against them, fix them, test them, extend patches for + them, or write patches to remove them. `halui` is headless and stays in scope. + ## Native formatting and linting - Treat native formatting and linting as part of completing every change under diff --git a/Dockerfile b/Dockerfile index 71e17222..fd466b1c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,9 +42,9 @@ RUN cd /src/linuxcnc/src \ && ./configure \ --prefix=/opt/linuxcnc \ --with-realtime=uspace \ - --enable-headless \ + --disable-gui \ --disable-build-documentation \ - --disable-build-manpages \ + --disable-manpages \ && make -j"${build_jobs}" \ && make DESTDIR=/linuxcnc-root install diff --git a/README.md b/README.md index 7e544607..01e88557 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,24 @@ INI, program, HAL, and scope services over gRPC, plus binary WebSocket streams for position history, selected HAL values, and G-code preview. See the [architecture document](./docs/native-grpc-architecture.md). +## Scope + +LinuxCNC runs here as a headless backend, and clients use the APIs this +repository provides. LinuxCNC's own GUIs and GUI tools (AXIS, Touchy, gmoccapy, +QtDragon, `tooledit` and similar) are out of scope: we do not add features to +them, fix them, test them, or keep patches compatible with them. `halui` is a +headless HAL interface and stays in scope. + +The older remote interfaces (`linuxcncrsh`, `halrmt`, `schedrmt`), tool database +programs (`[EMCIO]DB_PROGRAM`), and RTAI or other kernel-module realtime are out +of scope in the same way: clients use this repository's gRPC APIs, tool data +lives in the file-backed tool table, and LinuxCNC runs with `uspace` realtime, +including on PREEMPT_RT kernels. + +Out of scope means we do not care about these features. It does not mean we +remove them: patches neither fix them nor strip them out, and code a patch +already touches stays as it is unless other work requires a change. + ## Repository layout - `proto/`: canonical versioned protobuf wire contract and its existing license. diff --git a/docs/status-delta-boundaries.md b/docs/status-delta-boundaries.md index e2e95277..f89e2d11 100644 --- a/docs/status-delta-boundaries.md +++ b/docs/status-delta-boundaries.md @@ -45,7 +45,8 @@ LinuxCNCStat | |-- interpreterErrorCode * | |-- taskPaused * | |-- delayLeft * -| `-- queuedMdiCommands * +| |-- queuedMdiCommands * +| `-- holdWait * |-- motion | |-- traj | | |-- linearUnits * diff --git a/linuxcnc-patches/0001-export-spindle-speed-feedback.patch b/linuxcnc-patches/0001-export-spindle-speed-feedback.patch index 36c06597..6d018537 100644 --- a/linuxcnc-patches/0001-export-spindle-speed-feedback.patch +++ b/linuxcnc-patches/0001-export-spindle-speed-feedback.patch @@ -12,10 +12,10 @@ Subject: [PATCH] emc: expose spindle speed feedback in status 5 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index df82c4d0d0..fd5b118fba 100644 +index 3809d6b..299418c 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -1014,6 +1014,7 @@ void EMC_SPINDLE_STAT::update(CMS * cms) +@@ -1018,6 +1018,7 @@ void EMC_SPINDLE_STAT::update(CMS * cms) { EMC_SPINDLE_STAT_MSG::update(cms); cms->update(speed); @@ -24,10 +24,10 @@ index df82c4d0d0..fd5b118fba 100644 cms->update(css_maximum); cms->update(css_factor); diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index afd051e27b..68478559c7 100644 +index d31f9a5..9e1d4d0 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -1118,7 +1118,8 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { +@@ -1160,7 +1160,8 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { // cppcheck-suppress duplInheritedMember void update(CMS * cms); @@ -38,10 +38,10 @@ index afd051e27b..68478559c7 100644 double css_maximum; double css_factor; // CSS Status diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc -index d58c87c637..6373c42f49 100644 +index 2be2c1b..4fd5564 100644 --- a/src/emc/nml_intf/emcops.cc +++ b/src/emc/nml_intf/emcops.cc -@@ -178,6 +178,7 @@ EMC_AUX_STAT::EMC_AUX_STAT() +@@ -195,6 +195,7 @@ EMC_AUX_STAT::EMC_AUX_STAT() EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() : EMC_SPINDLE_STAT_MSG(EMC_SPINDLE_STAT_TYPE, sizeof(EMC_SPINDLE_STAT)), speed(0.0), @@ -50,10 +50,10 @@ index d58c87c637..6373c42f49 100644 css_maximum(0.0), css_factor(1.0), diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index 7aaee75fe7..a37da0ca5f 100644 +index befed5a..4215d22 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -2036,6 +2036,7 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ +@@ -2131,6 +2131,7 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ stat[s].spindle_override_enabled = enables & SS_ENABLED; stat[s].enabled = emcmotStatus.spindle_status[s].speed != 0; stat[s].speed = emcmotStatus.spindle_status[s].speed; @@ -62,10 +62,10 @@ index 7aaee75fe7..a37da0ca5f 100644 stat[s].direction = emcmotStatus.spindle_status[s].direction; stat[s].orient_state = emcmotStatus.spindle_status[s].orient_state; diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index 0ffaae6b7d..73b9efc2c8 100644 +index 0fcf4da..1d2ab2f 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1425,6 +1425,7 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { +@@ -1431,6 +1431,7 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { F(enabled); F2("override_enabled", spindle_override_enabled); F(speed); diff --git a/linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch b/linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch index 6e49fa60..59c632a6 100644 --- a/linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch +++ b/linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch @@ -12,10 +12,10 @@ Subject: [PATCH] emc: expose interpreter coordinate data in status 5 files changed, 88 insertions(+) diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index fd5b118fba..282edd98ec 100644 +index 299418c..ec54d4e 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -1392,8 +1392,14 @@ void EMC_TASK_STAT::update(CMS * cms) +@@ -1417,8 +1417,14 @@ void EMC_TASK_STAT::update(CMS * cms) cms->update(ini_filename, LINELEN); EmcPose_update(cms, &g5x_offset); cms->update(g5x_index); @@ -31,10 +31,10 @@ index fd5b118fba..282edd98ec 100644 cms->update(activeGCodes, ACTIVE_G_CODES); cms->update(activeMCodes, ACTIVE_M_CODES); diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index 68478559c7..38f67b98bd 100644 +index 9e1d4d0..3d8c617 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -1459,8 +1459,12 @@ class EMC_TASK_STAT:public EMC_TASK_STAT_MSG { +@@ -1538,8 +1538,12 @@ class EMC_TASK_STAT:public EMC_TASK_STAT_MSG { char ini_filename[LINELEN]; EmcPose g5x_offset; // in user units, currently active int g5x_index; // index of active g5x system @@ -48,10 +48,10 @@ index 68478559c7..38f67b98bd 100644 int activeGCodes[ACTIVE_G_CODES]; int activeMCodes[ACTIVE_M_CODES]; diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc -index 6373c42f49..6e068c2708 100644 +index 4fd5564..ed6a962 100644 --- a/src/emc/nml_intf/emcops.cc +++ b/src/emc/nml_intf/emcops.cc -@@ -134,8 +134,12 @@ EMC_TASK_STAT::EMC_TASK_STAT() +@@ -150,8 +150,12 @@ EMC_TASK_STAT::EMC_TASK_STAT() ini_filename{}, g5x_offset{}, g5x_index(0), @@ -65,10 +65,10 @@ index 6373c42f49..6e068c2708 100644 activeSettings{}, programUnits(CANON_UNITS_MM), diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index 90fc85d0be..d5c060f669 100644 +index 8ab3f56..7620a30 100644 --- a/src/emc/task/emctask.cc +++ b/src/emc/task/emctask.cc -@@ -738,6 +738,46 @@ int emcTaskUpdate(EMC_TASK_STAT * stat) +@@ -797,6 +797,46 @@ int emcTaskUpdate(EMC_TASK_STAT * stat) //update state of block delete stat->block_delete_state = GET_BLOCK_DELETE(); @@ -116,10 +116,10 @@ index 90fc85d0be..d5c060f669 100644 stat->taskbeat = task_beat; diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index 73b9efc2c8..3345c0a6a0 100644 +index 1d2ab2f..d242bd5 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1261,6 +1261,26 @@ static PyObject *Stat_g5x_offset(pyStatChannel *s, void *) { +@@ -1267,6 +1267,26 @@ static PyObject *Stat_g5x_offset(pyStatChannel *s, void *) { return pose(s->status.task.g5x_offset); } @@ -146,7 +146,7 @@ index 73b9efc2c8..3345c0a6a0 100644 static PyObject *Stat_g92_offset(pyStatChannel *s, void *) { return pose(s->status.task.g92_offset); } -@@ -1543,8 +1563,22 @@ static PyGetSetDef Stat_getsetlist[] = { +@@ -1576,8 +1596,22 @@ static PyGetSetDef Stat_getsetlist[] = { {(char*)"mcodes", (getter)Stat_activemcodes, NULL, NULL, NULL}, {(char*)"misc_error", (getter)Stat_misc_error, NULL, NULL, NULL}, {(char*)"g5x_offset", (getter)Stat_g5x_offset, NULL, NULL, NULL}, diff --git a/linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch b/linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch index 336564cf..eb3a6d2f 100644 --- a/linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch +++ b/linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch @@ -15,16 +15,23 @@ Interp::init(), and preserve _setup.spindle_mode[] across synch() calls. Also update Interp::convert_stop() (M2/M30) to set the interpreter model back to G97 when it already turns CSS off at the canon level. + +Since the original patch, upstream added the interpreter-side +_setup.css_maximum[] (the G96 D word, used by the G33/G76 pitch check) +and reset it in the same synch() loop. It is modal state belonging to +G96, and canon keeps its own CSS limit across synch(), so treat it +exactly like spindle_mode: initialize it in init(), preserve it across +synch(), and clear it in convert_stop() alongside the return to G97. --- - src/emc/rs274ngc/interp_convert.cc | 3 ++- - src/emc/rs274ngc/rs274ngc_pre.cc | 7 +++++-- - 2 files changed, 7 insertions(+), 3 deletions(-) + src/emc/rs274ngc/interp_convert.cc | 4 +++- + src/emc/rs274ngc/rs274ngc_pre.cc | 11 ++++++++--- + 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 779ed70095..be11b73201 100644 +index 35e9d50..450922e 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -5246,8 +5246,9 @@ int Interp::convert_stop(block_pointer block, //!< pointer to a block of RS27 +@@ -5533,8 +5533,10 @@ int Interp::convert_stop(block_pointer block, //!< pointer to a block of RS27 settings->spindle_turning[s] = CANON_STOPPED; settings->speed_override[s] = true; @@ -32,31 +39,36 @@ index 779ed70095..be11b73201 100644 + /* turn off CSS (G96) and return to G97 */ SET_SPINDLE_MODE(s, 0); + settings->spindle_mode[s] = SPINDLE_MODE::CONSTANT_RPM; ++ settings->css_maximum[s] = 0.0; } /*8*/ settings->motion_mode = G_1; diff --git a/src/emc/rs274ngc/rs274ngc_pre.cc b/src/emc/rs274ngc/rs274ngc_pre.cc -index f843fc8298..2ea4bf5550 100644 +index f594b4d..ac70436 100644 --- a/src/emc/rs274ngc/rs274ngc_pre.cc +++ b/src/emc/rs274ngc/rs274ngc_pre.cc -@@ -1207,7 +1207,9 @@ int Interp::init() +@@ -1232,7 +1232,10 @@ int Interp::init() _setup.sequence_number = 0; /*DOES THIS NEED TO BE AT TOP? */ //_setup.speed set in Interp::synch _setup.speed_feed_mode = CANON_INDEPENDENT; -// setup.spindle_mode set in interp_synch; + for (int s = 0; s < EMCMOT_MAX_SPINDLES; s++) { + _setup.spindle_mode[s] = SPINDLE_MODE::CONSTANT_RPM; ++ _setup.css_maximum[s] = 0.0; + } //_setup.speed_override set in Interp::synch //_setup.spindle_turning set in Interp::synch //_setup.stack does not need initialization -@@ -2061,7 +2063,8 @@ int Interp::synch() +@@ -2137,8 +2140,10 @@ int Interp::synch() _setup.speed[s] = GET_EXTERNAL_SPEED(s); _setup.spindle_turning[s] = GET_EXTERNAL_SPINDLE(s); _setup.speed_override[s] = GET_EXTERNAL_SPINDLE_OVERRIDE_ENABLE(s); - _setup.spindle_mode[s] = SPINDLE_MODE::CONSTANT_RPM; -+ // _setup.spindle_mode is modal; preserve it across synch() so that -+ // G96/G97 survives task-mode switches and MDI command boundaries. +- _setup.css_maximum[s] = 0.0; ++ // _setup.spindle_mode and _setup.css_maximum (the G96 D word) are ++ // modal; preserve them across synch() so that G96/G97 survives ++ // task-mode switches and MDI command boundaries. Canon keeps its own ++ // CSS limit across synch() too, so the two models stay in step. } GET_EXTERNAL_PARAMETER_FILE_NAME(file_name, (LINELEN - 1)); save_parameters(((file_name[0] == diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index bff1a70b..54bdb67f 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -4,101 +4,74 @@ Date: Wed, 1 Jul 2026 00:57:53 +0200 Subject: [PATCH] emc: add resumable Stop for active AUTO programs Add a dedicated task and trajectory Stop operation that preserves interpreter and motion queues. Stop safely completes position-synchronized motion, snapshots spindle and coolant outputs, and restores them before resuming queued motion, while still waiting for interrupted orientation to complete. Expose the command and Stop state through Python and HALUI; Node bindings are maintained in the consumer repository. + +Ported to v2.10.0-pre2. Differences from the patch on the old base: + +- Upstream M5 arms motion's next-feed at-speed barrier and EMCMOT_SPINDLE_OFF now overwrites atspeed_next_feed. Stop turns spindles off with EMCMOT_SPINDLE_AT_SPEED_PRESERVE, which SPINDLE_OFF now honours as SPINDLE_ON already did, so a barrier armed before Stop still holds the next feed after Resume. +- Stop is accepted while task waits for a queued G28.2 homing cycle (motion is dipped into FREE, so task.mode reads MANUAL). The homing cycle runs to completion before Stop reaches STOPPED. +- The trajectory planner judged rest from emcmotStatus->current_vel after tpUpdateInitialStatus() had zeroed it, so STOPPED was reported, and spindle and coolant switched off, while a feed was still decelerating. It now uses the segment velocities. +- motion-logger logs EMCMOT_STOP. +- Stop turns spindles off and on with a PRESERVE request whose at-speed field and state no longer stay behind in the shared motion command, so a later S-word change still arms the next feed's at-speed wait and cannot switch on another spindle. +- While stopping, the planner does not start a held segment from rest. Starting it consumed a pending at-speed wait, or began a G33 index search, while Stop had the spindle off; the feed then resumed without waiting, or the thread locked on during coast-down and the axis raced to catch up after Resume. +- Stop lets the whole run of position-synchronized segments that share one spindle synchronization finish, not only the segment active when it arrived, including a segment that is at the head of the queue but not active yet. Halting at the start of the next G33 left the axis behind the turning spindle and Resume lunged to catch up. The run is tracked by a flag (stop_sync_run), not by a pointer into the segment queue. A blend arc at the end of such a run is finished as well. +- When Stop comes to rest it clears the spindle synchronization, so a G33 that follows velocity-synchronized motion waits for a fresh index pulse after Resume instead of making up the revolutions turned meanwhile. +- Resume or Run during a Stop always leaves single-step mode entered by an earlier Step. +- EMCMOT_ABORT ends a Stop in every motion mode. +- motion-logger logs EMCMOT_STOP. +- tests/resumable-stop gains the scenarios dwell-atspeed, homing, homing-interrupted, speed-change-atspeed, queued-feed-atspeed, g33-chain, g95-between-g33, spindle-state and step-resume-stopping, fails if STOPPED is reported while moving, re-runs four scenarios under the trapezoidal planner, and its checkresult now fails when the scenario count is wrong. --- - docs/src/config/ini-config.adoc | 1 - - docs/src/config/python-interface.adoc | 10 + + docs/src/config/python-interface.adoc | 20 + docs/src/gui/halui.adoc | 3 +- docs/src/man/man1/halui.1.adoc | 5 +- - src/emc/motion/command.c | 21 +- - src/emc/motion/control.c | 13 + + src/emc/motion-logger/motion-logger.c | 4 + + src/emc/motion/command.c | 45 +- + src/emc/motion/control.c | 21 + src/emc/motion/motion.c | 1 + - src/emc/motion/motion.h | 3 + - src/emc/nml_intf/emc.cc | 24 + - src/emc/nml_intf/emc.hh | 10 + - src/emc/nml_intf/emc_nml.hh | 22 + - src/emc/nml_intf/emcops.cc | 4 + - src/emc/task/emctaskmain.cc | 337 +++++++- - src/emc/task/taskintf.cc | 11 + - src/emc/tp/tp.c | 68 +- - src/emc/tp/tp_types.h | 7 + - src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + + src/emc/motion/motion.h | 7 + + src/emc/nml_intf/emc.cc | 25 + + src/emc/nml_intf/emc.hh | 23 + + src/emc/nml_intf/emc_nml.hh | 24 + + src/emc/nml_intf/emcops.cc | 5 + + src/emc/task/emctaskmain.cc | 468 +++++++++++++++++- + src/emc/task/taskintf.cc | 67 ++- + src/emc/tp/tp.c | 144 +++++- + src/emc/tp/tp_types.h | 12 + + src/emc/usr_intf/axis/extensions/emcmodule.cc | 19 + src/emc/usr_intf/halui.cc | 9 +- - tests/resumable-stop/README | 10 + - tests/resumable-stop/after-abort.ngc | 4 + - tests/resumable-stop/checkresult | 3 + - tests/resumable-stop/core_sim.hal | 42 + - tests/resumable-stop/css.ngc | 6 + - tests/resumable-stop/dwell.ngc | 5 + - tests/resumable-stop/fperrev.ngc | 7 + - tests/resumable-stop/g76.ngc | 7 + - tests/resumable-stop/multi-spindle.ngc | 4 + - tests/resumable-stop/orient.ngc | 6 + - tests/resumable-stop/pause.ngc | 7 + - tests/resumable-stop/rapid-then-feed.ngc | 7 + - tests/resumable-stop/single-step.ngc | 10 + - tests/resumable-stop/tap.ngc | 7 + - tests/resumable-stop/test-ui.py | 772 ++++++++++++++++++ - tests/resumable-stop/test.ini | 95 +++ - tests/resumable-stop/test.ngc | 9 + - tests/resumable-stop/test.sh | 42 + - tests/resumable-stop/thread.ngc | 7 + - tests/resumable-stop/tool.tbl | 1 + - 38 files changed, 1597 insertions(+), 17 deletions(-) - create mode 100644 tests/resumable-stop/README - create mode 100644 tests/resumable-stop/after-abort.ngc - create mode 100755 tests/resumable-stop/checkresult - create mode 100644 tests/resumable-stop/core_sim.hal - create mode 100644 tests/resumable-stop/css.ngc - create mode 100644 tests/resumable-stop/dwell.ngc - create mode 100644 tests/resumable-stop/fperrev.ngc - create mode 100644 tests/resumable-stop/g76.ngc - create mode 100644 tests/resumable-stop/multi-spindle.ngc - create mode 100644 tests/resumable-stop/orient.ngc - create mode 100644 tests/resumable-stop/pause.ngc - create mode 100644 tests/resumable-stop/rapid-then-feed.ngc - create mode 100644 tests/resumable-stop/single-step.ngc - create mode 100644 tests/resumable-stop/tap.ngc - create mode 100755 tests/resumable-stop/test-ui.py - create mode 100644 tests/resumable-stop/test.ini - create mode 100644 tests/resumable-stop/test.ngc - create mode 100755 tests/resumable-stop/test.sh - create mode 100644 tests/resumable-stop/thread.ngc - create mode 100644 tests/resumable-stop/tool.tbl + 18 files changed, 877 insertions(+), 25 deletions(-) -diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc -index 8cb14ddb65..aa8e86d3b5 100644 ---- a/docs/src/config/ini-config.adoc -+++ b/docs/src/config/ini-config.adoc -@@ -704,7 +704,6 @@ For more information on the motion controller see the <> sect - This parameter affects the polling interval when waiting for motion to complete, when executing a pause instruction, and when accepting a command from a user interface. - There is usually no need to change this number. - Defaults to 0.100 if omitted. -- - [[sub:ini:sec:hal]] - === [HAL] section(((INI File,Sections,[HAL] Section))) - diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc -index 219a873d24..0278680c8e 100644 +index 25d5762..5153f11 100644 --- a/docs/src/config/python-interface.adoc +++ b/docs/src/config/python-interface.adoc -@@ -209,6 +209,10 @@ see <> for an example. +@@ -209,6 +209,18 @@ see <> for an example. current state of RS274NGC interpreter. One of INTERP_IDLE, INTERP_READING, INTERP_PAUSED, INTERP_WAITING. +*stop_state*:: '(returns integer)' - + current resumable Stop state. One of `STOP_IDLE`, `STOP_STOPPING`, + `STOP_STOPPED`, `STOP_STARTING`. ++ ++*hold_wait*:: '(returns integer)' - ++ while a Stop is `STOP_STOPPING` or the program is paused, the operation the ++ hold waits for before the machine holds. An operation already handed to ++ another subsystem runs to its end first, and Abort is the way out. One of ++ `HOLD_WAIT_NONE`, `HOLD_WAIT_HOMING` (a queued `G28.2`), `HOLD_WAIT_IO` (a ++ tool change or other I/O command), `HOLD_WAIT_SYSTEM_COMMAND` (a user ++ `M100`-`M199` program). + *interpreter_errcode*:: '(returns integer)' - current RS274NGC interpreter return code. One of INTERP_OK, INTERP_EXIT, INTERP_EXECUTE_FINISH, INTERP_ENDFILE, -@@ -640,6 +644,12 @@ c.tool_offset(toolno, z_offset, x_offset, diameter, frontangle, backangle, orie +@@ -640,6 +652,14 @@ c.tool_offset(toolno, z_offset, x_offset, diameter, frontangle, backangle, orie `abort()`:: send EMC_TASK_ABORT message. +`program_stop()`:: + stop an active AUTO program without clearing its interpreter or motion + queues. The program can be continued with Run, Resume, or Single Step. ++ Position-synchronized motion (`G33`, `G33.1`) and a queued `G28.2` homing ++ cycle run to completion before the program holds. + The command is rejected when no AUTO program is active; use `abort()` when + execution must be terminated. + @@ -106,7 +79,7 @@ index 219a873d24..0278680c8e 100644 run, step, pause or resume a program. diff --git a/docs/src/gui/halui.adoc b/docs/src/gui/halui.adoc -index 37d92b8ff7..633a65fc00 100644 +index 37d92b8..633a65f 100644 --- a/docs/src/gui/halui.adoc +++ b/docs/src/gui/halui.adoc @@ -268,7 +268,8 @@ _L_ = axis letter (xyzabcuvw) @@ -120,7 +93,7 @@ index 37d92b8ff7..633a65fc00 100644 === Rapid Override diff --git a/docs/src/man/man1/halui.1.adoc b/docs/src/man/man1/halui.1.adoc -index 6e84da6e5f..c172f579cd 100644 +index 6e84da6..c172f57 100644 --- a/docs/src/man/man1/halui.1.adoc +++ b/docs/src/man/man1/halui.1.adoc @@ -137,8 +137,9 @@ contact) connect the physical button to a HAL debounce filter first. @@ -135,28 +108,50 @@ index 6e84da6e5f..c172f579cd 100644 === Mode +diff --git a/src/emc/motion-logger/motion-logger.c b/src/emc/motion-logger/motion-logger.c +index 36b77e5..24d0fea 100644 +--- a/src/emc/motion-logger/motion-logger.c ++++ b/src/emc/motion-logger/motion-logger.c +@@ -364,6 +364,10 @@ int main(int argc, char* argv[]) { + log_print("PAUSE\n"); + break; + ++ case EMCMOT_STOP: ++ log_print("STOP\n"); ++ break; ++ + case EMCMOT_RESUME: + log_print("RESUME\n"); + break; diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index fa7beb3c72..efe02af73d 100644 +index e2ecb07..35cf0db 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -507,6 +507,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -536,6 +536,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + rtapi_print_msg(RTAPI_MSG_DBG, "ABORT"); + /* the override release is queued behind the cycle, drop it here */ + emcmotStatus->enables_new &= ~SS_LOCKED; ++ /* End a resumable Stop in every mode: one issued during a queued ++ G28.2 is aborted while motion is in FREE, and would otherwise ++ hold the next coordinated program. In COORD, tpAbort() below ++ pauses the planner again for its own deceleration. */ ++ if (emcmotInternal->coord_tp.stopping) { ++ emcmotInternal->coord_tp.pausing = 0; ++ } ++ emcmotInternal->coord_tp.stopping = 0; ++ emcmotInternal->coord_tp.stop_sync_run = 0; ++ emcmotStatus->stopped = 0; + /* check for coord or free space motion active */ if (GET_MOTION_TELEOP_FLAG()) { axis_jog_abort_all(0); - } else if (GET_MOTION_COORD_FLAG()) { -+ emcmotInternal->coord_tp.stopping = 0; -+ emcmotInternal->coord_tp.stop_tc = 0; -+ emcmotStatus->stopped = 0; - tpAbort(&emcmotInternal->coord_tp); - } else { - for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -1221,6 +1224,15 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1323,6 +1333,15 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) emcmotStatus->paused = 1; break; + case EMCMOT_STOP: + rtapi_print_msg(RTAPI_MSG_DBG, "STOP"); + emcmotInternal->coord_tp.stopping = 1; -+ emcmotInternal->coord_tp.stop_tc = 0; ++ emcmotInternal->coord_tp.stop_sync_run = 0; + tpPause(&emcmotInternal->coord_tp); + emcmotStatus->paused = 1; + emcmotStatus->stopped = 0; @@ -165,48 +160,88 @@ index fa7beb3c72..efe02af73d 100644 case EMCMOT_REVERSE: /* run motion in reverse*/ /* only allowed during a pause */ -@@ -1240,8 +1252,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1342,8 +1361,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) /* can happen at any time */ rtapi_print_msg(RTAPI_MSG_DBG, "RESUME"); emcmotStatus->stepping = 0; + emcmotInternal->coord_tp.stopping = 0; -+ emcmotInternal->coord_tp.stop_tc = 0; ++ emcmotInternal->coord_tp.stop_sync_run = 0; tpResume(&emcmotInternal->coord_tp); emcmotStatus->paused = 0; + emcmotStatus->stopped = 0; break; case EMCMOT_STEP: -@@ -1665,7 +1680,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1799,8 +1821,19 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + emcmotStatus->spindle_status[n].brake = 0; //disengage brake } apply_spindle_limits(&emcmotStatus->spindle_status[n]); ++ if (emcmotCommand->wait_for_spindle_at_speed == ++ EMCMOT_SPINDLE_AT_SPEED_PRESERVE && emcmotCommand->state) { ++ /* A resumable Stop restoring this spindle: task waits for ++ an at-speed sampled after this point. */ ++ emcmotStatus->spindle_status[n].stop_restore_seq++; ++ emcmotStatus->spindle_status[n].stop_restore_atspeed_dropped = 0; ++ } ++ } ++ if (emcmotCommand->wait_for_spindle_at_speed != ++ EMCMOT_SPINDLE_AT_SPEED_PRESERVE) { ++ emcmotStatus->atspeed_next_feed = ++ emcmotCommand->wait_for_spindle_at_speed; + } +- emcmotStatus->atspeed_next_feed = emcmotCommand->wait_for_spindle_at_speed; + + // check whether it's passed correctly + if (!emcmotStatus->atspeed_next_feed){ +@@ -1839,8 +1872,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) } + /* Optionally make the spindle stop an at-speed barrier: the next feed + move waits until at-speed reflects the stopped state. Safe when +- unwired since at-speed defaults to 1 (see motion.c). */ - emcmotStatus->atspeed_next_feed = emcmotCommand->wait_for_spindle_at_speed; ++ unwired since at-speed defaults to 1 (see motion.c). A resumable ++ Stop turns the spindle off with EMCMOT_SPINDLE_AT_SPEED_PRESERVE so ++ that a barrier the program already armed survives the Stop. */ + if (emcmotCommand->wait_for_spindle_at_speed != + EMCMOT_SPINDLE_AT_SPEED_PRESERVE) { + emcmotStatus->atspeed_next_feed = + emcmotCommand->wait_for_spindle_at_speed; + } + break; - // check whether it's passed correctly - if (!emcmotStatus->atspeed_next_feed){ + case EMCMOT_SPINDLE_ORIENT: diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 9e23ea480a..0a5d550480 100644 +index 17fb96b..ccd0f34 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1990,6 +1990,19 @@ static void output_to_hal(void) - *(emcmot_hal_data->requested_vel) = 0.0; +@@ -417,6 +417,14 @@ static void process_inputs(void) + hal_get_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_in); + emcmotStatus->spindle_status[spindle_num].at_speed = + hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_is_atspeed); ++ /* Sampled every servo period for resumable Stop: a short false ++ between a Stop restore and at-speed would be missed by task. */ ++ if (!emcmotStatus->spindle_status[spindle_num].at_speed) { ++ emcmotStatus->spindle_status[spindle_num].stop_restore_atspeed_dropped = 1; ++ if (emcmotStatus->spindle_status[spindle_num].state) { ++ emcmotStatus->spindle_status[spindle_num].atspeed_feedback = 1; ++ } ++ } + } + /* compute net feed and spindle scale factors */ + if ( emcmotStatus->motion_state == EMCMOT_MOTION_COORD ) { +@@ -2071,6 +2079,19 @@ static void output_to_hal(void) + hal_set_real(emcmot_hal_data->requested_vel, 0.0); } + /* + * Alternate trajectory planners only provide the established tpPause() + * interface. Treat a completed fallback pause as a completed Stop. The -+ * default planner sets stop_tc while an active position-synchronized -+ * segment must finish, so do not complete Stop at an intermediate zero -+ * velocity in that case. ++ * default planner sets stop_sync_run while a position-synchronized run ++ * must finish, so do not complete Stop at an intermediate zero velocity ++ * in that case, such as an exact-stop boundary between two G33 moves. + */ + if (emcmotInternal->coord_tp.stopping && -+ !emcmotInternal->coord_tp.stop_tc && ++ !emcmotInternal->coord_tp.stop_sync_run && + fabs(emcmotStatus->current_vel) < TP_VEL_EPSILON) { + emcmotStatus->stopped = 1; + } @@ -215,10 +250,10 @@ index 9e23ea480a..0a5d550480 100644 /* Change the following lines to assign the variable you want to observe to one of the debug parameters. You can also comment out these lines diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c -index 6b4f01a50f..7f81108901 100644 +index 30ce42a..067711a 100644 --- a/src/emc/motion/motion.c +++ b/src/emc/motion/motion.c -@@ -906,6 +906,7 @@ static int init_comm_buffers(void) +@@ -909,6 +909,7 @@ static int init_comm_buffers(void) emcmotStatus->depth = 0; emcmotStatus->activeDepth = 0; emcmotStatus->paused = 0; @@ -227,7 +262,7 @@ index 6b4f01a50f..7f81108901 100644 SET_MOTION_INPOS_FLAG(1); SET_MOTION_ENABLE_FLAG(0); diff --git a/src/emc/motion/motion.h b/src/emc/motion/motion.h -index 9c62af046c..84ab8eb6ce 100644 +index b98bfc0..1915616 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -81,6 +81,7 @@ to another. @@ -246,7 +281,18 @@ index 9c62af046c..84ab8eb6ce 100644 EMCMOT_REVERSE, /* run reverse motion */ EMCMOT_FORWARD, /* run reverse motion */ EMCMOT_RESUME, /* resume motion */ -@@ -637,6 +639,7 @@ Suggestion: Split this in to an Error and a Status flag register.. +@@ -547,6 +549,10 @@ Suggestion: Split this in to an Error and a Status flag register.. + double spindleRevs; /* position of spindle in revolutions */ + double spindleSpeedIn; /* velocity of spindle in revolutions per minute */ + int at_speed; ++ /* Resumable Stop's at-speed wait (see process_inputs()). */ ++ int atspeed_feedback; /* at-speed has read false while the spindle was on */ ++ unsigned int stop_restore_seq; /* Stop restores (preserving spindle-ons) handled */ ++ int stop_restore_atspeed_dropped; /* at-speed read false since the last restore */ + int fault; /* amplifier fault */ + double max_pos_speed; /* spindle speed limits */ + double min_pos_speed; /* signed values, so max_neg = 0 */ +@@ -645,6 +651,7 @@ Suggestion: Split this in to an Error and a Status flag register.. int activeDepth; /* depth of active blend elements */ int queueFull; /* Flag to indicate the tc queue is full */ int paused; /* Flag to signal motion paused */ @@ -255,10 +301,10 @@ index 9c62af046c..84ab8eb6ce 100644 /* 1 << (joint-num*2) = ignore neg limit */ /* 2 << (joint-num*2) = ignore pos limit */ diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index 282edd98ec..4665d2fe6c 100644 +index ec54d4e..27f5172 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -181,6 +181,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) +@@ -179,6 +179,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) case EMC_TASK_ABORT_TYPE: ((EMC_TASK_ABORT *) buffer)->update(cms); break; @@ -268,7 +314,7 @@ index 282edd98ec..4665d2fe6c 100644 case EMC_TASK_PLAN_CLOSE_TYPE: ((EMC_TASK_PLAN_CLOSE *) buffer)->update(cms); break; -@@ -277,6 +280,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) +@@ -275,6 +278,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) case EMC_TRAJ_PAUSE_TYPE: ((EMC_TRAJ_PAUSE *) buffer)->update(cms); break; @@ -278,7 +324,7 @@ index 282edd98ec..4665d2fe6c 100644 case EMC_TRAJ_PROBE_TYPE: ((EMC_TRAJ_PROBE *) buffer)->update(cms); break; -@@ -444,6 +450,8 @@ const char *emc_symbol_lookup(uint32_t type) +@@ -445,6 +451,8 @@ const char *emc_symbol_lookup(uint32_t type) return "EMC_STAT"; case EMC_TASK_ABORT_TYPE: return "EMC_TASK_ABORT"; @@ -287,7 +333,7 @@ index 282edd98ec..4665d2fe6c 100644 case EMC_TASK_PLAN_CLOSE_TYPE: return "EMC_TASK_PLAN_CLOSE"; case EMC_TASK_PLAN_END_TYPE: -@@ -506,6 +514,8 @@ const char *emc_symbol_lookup(uint32_t type) +@@ -507,6 +515,8 @@ const char *emc_symbol_lookup(uint32_t type) return "EMC_TRAJ_LINEAR_MOVE"; case EMC_TRAJ_PAUSE_TYPE: return "EMC_TRAJ_PAUSE"; @@ -296,7 +342,7 @@ index 282edd98ec..4665d2fe6c 100644 case EMC_TRAJ_PROBE_TYPE: return "EMC_TRAJ_PROBE"; case EMC_AUX_INPUT_WAIT_TYPE: -@@ -839,6 +849,11 @@ void EMC_TASK_ABORT::update(CMS * cms) +@@ -843,6 +853,11 @@ void EMC_TASK_ABORT::update(CMS * cms) EMC_TASK_CMD_MSG::update(cms); } @@ -308,7 +354,7 @@ index 282edd98ec..4665d2fe6c 100644 /* * NML/CMS Update function for EMC_TASK_PLAN_INIT * Automatically generated by NML CodeGen Java Applet. -@@ -1018,6 +1033,7 @@ void EMC_SPINDLE_STAT::update(CMS * cms) +@@ -1022,6 +1037,7 @@ void EMC_SPINDLE_STAT::update(CMS * cms) cms->update(spindle_scale); cms->update(css_maximum); cms->update(css_factor); @@ -316,7 +362,7 @@ index 282edd98ec..4665d2fe6c 100644 cms->update(state); cms->update(direction); cms->update(brake); -@@ -1026,6 +1042,7 @@ void EMC_SPINDLE_STAT::update(CMS * cms) +@@ -1030,6 +1046,7 @@ void EMC_SPINDLE_STAT::update(CMS * cms) cms->update(orient_state); cms->update(orient_fault); cms->update(spindle_override_enabled); @@ -324,15 +370,16 @@ index 282edd98ec..4665d2fe6c 100644 cms->update(homed); } -@@ -1380,6 +1397,7 @@ void EMC_TASK_STAT::update(CMS * cms) +@@ -1388,6 +1405,8 @@ void EMC_TASK_STAT::update(CMS * cms) cms->update((int *) &state, 1); cms->update((int *) &execState, 1); cms->update((int *) &interpState, 1); + cms->update((int *) &stopState, 1); ++ cms->update((int *) &holdWait, 1); cms->update(callLevel); - cms->update(motionLine); - cms->update(currentLine); -@@ -1711,6 +1729,7 @@ void EMC_TRAJ_STAT::update(CMS * cms) + // Send only the frames that are in use. With the program in the main file + // that is none, instead of EMC_MAX_CALL_STACK empty frames every cycle. +@@ -1743,6 +1762,7 @@ void EMC_TRAJ_STAT::update(CMS * cms) cms->update(queueFull); cms->update(id); cms->update(paused); @@ -340,7 +387,7 @@ index 282edd98ec..4665d2fe6c 100644 cms->update(single_stepping); cms->update(scale); cms->update(rapid_scale); -@@ -1868,6 +1887,11 @@ void EMC_TRAJ_PAUSE::update(CMS * cms) +@@ -1905,6 +1925,11 @@ void EMC_TRAJ_PAUSE::update(CMS * cms) EMC_TRAJ_CMD_MSG::update(cms); } @@ -353,7 +400,7 @@ index 282edd98ec..4665d2fe6c 100644 * NML/CMS Update function for EMC_AUX_STAT_MSG * Automatically generated by NML CodeGen Java Applet. diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index 20bb4bba56..eadd123b99 100644 +index c2f4d1b..d8b6a4b 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -93,6 +93,7 @@ struct PM_CARTESIAN; @@ -364,7 +411,7 @@ index 20bb4bba56..eadd123b99 100644 #define EMC_TRAJ_RESUME_TYPE ((NMLTYPE) 218) #define EMC_TRAJ_DELAY_TYPE ((NMLTYPE) 219) #define EMC_TRAJ_LINEAR_MOVE_TYPE ((NMLTYPE) 220) -@@ -124,6 +125,7 @@ struct PM_CARTESIAN; +@@ -125,6 +126,7 @@ struct PM_CARTESIAN; // NML for EMC_TASK @@ -372,7 +419,7 @@ index 20bb4bba56..eadd123b99 100644 #define EMC_TASK_ABORT_TYPE ((NMLTYPE) 503) #define EMC_TASK_SET_MODE_TYPE ((NMLTYPE) 504) #define EMC_TASK_SET_STATE_TYPE ((NMLTYPE) 505) -@@ -225,6 +227,13 @@ enum class EMC_TASK_INTERP { +@@ -228,6 +230,22 @@ enum class EMC_TASK_INTERP { WAITING = 4 }; @@ -382,11 +429,20 @@ index 20bb4bba56..eadd123b99 100644 + STOPPED = 2, + STARTING = 3 +}; ++ ++// What a Stop or Pause is waiting for before the machine holds: an ++// operation already handed to another subsystem runs to its end first. ++enum class EMC_TASK_HOLD_WAIT { ++ NONE = 0, ++ HOMING = 1, // a queued G28.2 homing cycle ++ IO = 2, // a tool change or other I/O controller command ++ SYSTEM_COMMAND = 3 // a user M100-M199 program ++}; + // types for motion control enum class EMC_TRAJ_MODE { FREE = 1, // independent-axis motion, -@@ -364,6 +373,7 @@ extern int emcTrajEnable(); +@@ -369,6 +387,7 @@ extern int emcTrajEnable(); extern int emcTrajDisable(); extern int emcTrajAbort(); extern int emcTrajPause(); @@ -394,11 +450,22 @@ index 20bb4bba56..eadd123b99 100644 extern int emcTrajReverse(); extern int emcTrajForward(); extern int emcTrajStep(); +@@ -436,6 +455,10 @@ extern int emcSpindleSpeed(int spindle, double speed, double factor, double xoff + extern int emcSpindleOn(int spindle, double speed, double factor, double xoffset,int wait_for_atspeed = 1); + extern int emcSpindleOrient(int spindle, double orientation, int direction); + extern int emcSpindleOff(int spindle, int wait_for_atspeed = 0); ++// Resumable Stop: count of Stop spindle restores motion has handled, and ++// whether the spindle reported at-speed after the restore with that count. ++extern unsigned int emcSpindleStopRestoreSeq(int spindle); ++extern bool emcSpindleStopRestoreAtSpeed(int spindle, unsigned int seq); + extern int emcSpindleIncrease(int spindle); + extern int emcSpindleDecrease(int spindle); + extern int emcSpindleConstant(int spindle); diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index 38f67b98bd..6b94fa62f0 100644 +index 3d8c617..239d812 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -699,6 +699,15 @@ class EMC_TRAJ_PAUSE:public EMC_TRAJ_CMD_MSG { +@@ -704,6 +704,15 @@ class EMC_TRAJ_PAUSE:public EMC_TRAJ_CMD_MSG { void update(CMS * cms); }; @@ -414,7 +481,7 @@ index 38f67b98bd..6b94fa62f0 100644 class EMC_TRAJ_RESUME:public EMC_TRAJ_CMD_MSG { public: EMC_TRAJ_RESUME() -@@ -988,6 +997,7 @@ class EMC_TRAJ_STAT:public EMC_TRAJ_STAT_MSG { +@@ -1022,6 +1031,7 @@ class EMC_TRAJ_STAT:public EMC_TRAJ_STAT_MSG { bool queueFull; // non-zero means can't accept another motion int id; // id of the currently executing motion bool paused; // non-zero means motion paused @@ -422,7 +489,7 @@ index 38f67b98bd..6b94fa62f0 100644 bool single_stepping; // non-zero means motion stepping single block double scale; // velocity scale factor double rapid_scale; // rapid scale factor -@@ -1123,6 +1133,7 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { +@@ -1165,6 +1175,7 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { double spindle_scale; // spindle over-ride double css_maximum; double css_factor; // CSS Status @@ -430,7 +497,7 @@ index 38f67b98bd..6b94fa62f0 100644 int state; int direction; // 0 stopped, 1 forward, -1 reverse int brake; // 0 released, 1 engaged -@@ -1131,6 +1142,7 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { +@@ -1173,6 +1184,7 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { int orient_state; int orient_fault; bool spindle_override_enabled; @@ -438,7 +505,7 @@ index 38f67b98bd..6b94fa62f0 100644 bool homed; }; -@@ -1176,6 +1188,15 @@ class EMC_TASK_CMD_MSG:public RCS_CMD_MSG { +@@ -1225,6 +1237,15 @@ class EMC_TASK_CMD_MSG:public RCS_CMD_MSG { void update(CMS * cms); }; @@ -454,19 +521,21 @@ index 38f67b98bd..6b94fa62f0 100644 class EMC_TASK_ABORT:public EMC_TASK_CMD_MSG { public: EMC_TASK_ABORT() -@@ -1447,6 +1468,7 @@ class EMC_TASK_STAT:public EMC_TASK_STAT_MSG { +@@ -1516,6 +1537,9 @@ class EMC_TASK_STAT:public EMC_TASK_STAT_MSG { EMC_TASK_EXEC execState; // EMC_DONE,WAITING_FOR_MOTION, etc. EMC_TASK_INTERP interpState; // EMC_IDLE,READING,PAUSED,WAITING + EMC_TASK_STOP_STATE stopState; - int callLevel; // current subroutine level - 0 if not in a subroutine, > 0 otherwise - int motionLine; // line motion is executing-- may lag - int currentLine; // line currently executing ++ // While STOPPING or paused: the operation the hold waits for. ++ EMC_TASK_HOLD_WAIT holdWait; + // Subroutine depth of the move motion is executing -- 0 if not in a + // subroutine. Like motionLine, this lags the interpreter, which reads ahead. + int callLevel; diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc -index 6e068c2708..734079d3af 100644 +index ed6a962..6010ecb 100644 --- a/src/emc/nml_intf/emcops.cc +++ b/src/emc/nml_intf/emcops.cc -@@ -70,6 +70,7 @@ EMC_TRAJ_STAT::EMC_TRAJ_STAT() +@@ -78,6 +78,7 @@ EMC_TRAJ_STAT::EMC_TRAJ_STAT() queueFull(OFF), id(0), paused(OFF), @@ -474,15 +543,16 @@ index 6e068c2708..734079d3af 100644 single_stepping(false), scale(0.0), rapid_scale(0.0), -@@ -122,6 +123,7 @@ EMC_TASK_STAT::EMC_TASK_STAT() +@@ -137,6 +138,8 @@ EMC_TASK_STAT::EMC_TASK_STAT() state(EMC_TASK_STATE::ESTOP), execState(EMC_TASK_EXEC::DONE), interpState(EMC_TASK_INTERP::IDLE), + stopState(EMC_TASK_STOP_STATE::IDLE), ++ holdWait(EMC_TASK_HOLD_WAIT::NONE), callLevel(0), + callStack{}, motionLine(0), - currentLine(0), -@@ -186,6 +188,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() +@@ -203,6 +206,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() spindle_scale(1.0), css_maximum(0.0), css_factor(1.0), @@ -490,7 +560,7 @@ index 6e068c2708..734079d3af 100644 state(0), direction(0), brake(1), -@@ -194,6 +197,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() +@@ -211,6 +215,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() orient_state(0), orient_fault(0), spindle_override_enabled(OFF), @@ -499,10 +569,10 @@ index 6e068c2708..734079d3af 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 3bf13a702d..2810757914 100644 +index a3b5256..3e73c7b 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -124,6 +124,37 @@ static int emcTaskEager = 0; +@@ -124,6 +124,39 @@ static int emcTaskEager = 0; static int no_force_homing = 0; // forces the user to home first before allowing MDI and Program run //can be overridden by [TRAJ]NO_FORCE_HOMING=1 @@ -516,6 +586,9 @@ index 3bf13a702d..2810757914 100644 + int orient_mode; + double orient_timeout; + double orient_deadline; ++ // STARTING waits for at-speed after the restore motion counts as seq. ++ bool restore_wait_at_speed; ++ unsigned int restore_seq; +}; + +struct SpindleOrientRequest { @@ -528,7 +601,6 @@ index 3bf13a702d..2810757914 100644 +static SpindleOrientRequest active_spindle_orient_requests[EMCMOT_MAX_SPINDLES] = {}; +static bool stop_mist = false; +static bool stop_flood = false; -+static bool stop_resume_latched = false; +static bool stop_single_step = false; +static bool stop_outputs_saved = false; +static double taskExecDelayStopTime = 0.0; @@ -540,7 +612,18 @@ index 3bf13a702d..2810757914 100644 // delay counter static double taskExecDelayTimeout = 0.0; -@@ -487,6 +518,9 @@ extern int emcTaskMopup(); +@@ -414,6 +447,10 @@ static double homingIssueTime = 0.0; // etime() when issued, for the start-t + // vary widely in duration, same as a GUI just watching .homing/.homed). + static const double HOMING_START_TIMEOUT = 2.0; + static EMC_TRAJ_MODE homingPriorMode = EMC_TRAJ_MODE::FREE; // mode to restore on success ++// Task mode in effect when the queued home was issued. While motion is dipped ++// into FREE, determineMode() reports MANUAL, so resumable Stop uses this to ++// recognise a G28.2 that belongs to an AUTO program. ++static EMC_TASK_MODE homingPriorTaskMode = EMC_TASK_MODE::MANUAL; + // True only while emcTaskExecute() is issuing a command taken off the + // interp_list. emcTaskIssueCommand() serves both that queued path and the + // immediate commands emcTaskPlan() sends straight through (the GUI's Home +@@ -522,6 +559,9 @@ extern int emcTaskMopup(); void readahead_reading(void) { @@ -550,7 +633,7 @@ index 3bf13a702d..2810757914 100644 int readRetval; int execRetval; -@@ -701,6 +735,9 @@ static void mdi_execute_hook(void) +@@ -737,6 +777,9 @@ static void mdi_execute_hook(void) void readahead_waiting(void) { @@ -560,10 +643,50 @@ index 3bf13a702d..2810757914 100644 // now handle call logic // check for subsystems done if (interp_list.len() == 0 && -@@ -745,6 +782,188 @@ static bool allow_while_idle_type() { +@@ -781,6 +824,294 @@ static bool allow_while_idle_type() { return 0; } ++/* ++ * While Stop is in progress, queued commands that only add to the coordinated ++ * motion queue may still be issued: the planner holds whatever Stop does not ++ * let finish, and a synchronized run or a latched G76 pass may need its ++ * remaining segments. Every other command (spindle, coolant, I/O, dwell, tool ++ * change, homing, program end, a G76 pass-group fence ...) waits until after ++ * Resume, so that it neither runs behind the output state Stop records and ++ * restores nor runs out of program order. ++ */ ++static bool emcTaskStopAllowsIssue(const NMLmsg *cmd) ++{ ++ switch (emcStatus->task.stopState) { ++ case EMC_TASK_STOP_STATE::IDLE: ++ return true; ++ case EMC_TASK_STOP_STATE::STOPPING: ++ break; ++ default: ++ return false; ++ } ++ switch (cmd->_type) { ++ case EMC_TRAJ_LINEAR_MOVE_TYPE: ++ case EMC_TRAJ_CIRCULAR_MOVE_TYPE: ++ case EMC_TRAJ_SET_VELOCITY_TYPE: ++ case EMC_TRAJ_SET_ACCELERATION_TYPE: ++ case EMC_TRAJ_SET_TERM_COND_TYPE: ++ case EMC_TRAJ_SET_SPINDLESYNC_TYPE: ++ case EMC_TRAJ_SET_FO_ENABLE_TYPE: ++ case EMC_TRAJ_SET_FH_ENABLE_TYPE: ++ case EMC_TRAJ_SET_SO_ENABLE_TYPE: ++ return true; ++ case EMC_MOTION_SET_DOUT_TYPE: ++ // Synchronized outputs travel with the next queued move. ++ return !reinterpret_cast(cmd)->now; ++ case EMC_MOTION_SET_AOUT_TYPE: ++ return !reinterpret_cast(cmd)->now; ++ default: ++ return false; ++ } ++} ++ +static void emcTaskResumeInterpreter() +{ + if (emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED) { @@ -579,7 +702,10 @@ index 3bf13a702d..2810757914 100644 + emcStatus->motion.traj.single_stepping = 1; + stepping = 1; + steppingWait = 0; -+ if (emcStatus->motion.traj.queue == 0) { ++ // Only a Pause saved interpResumeState; a Stop leaves the interpreter ++ // reading, and restoring a stale state could mark the program finished. ++ if (emcStatus->motion.traj.queue == 0 && ++ emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED) { + emcStatus->task.interpState = interpResumeState; + } + emcStatus->task.task_paused = 1; @@ -589,7 +715,6 @@ index 3bf13a702d..2810757914 100644 +{ + bool was_active = emcStatus && + emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE; -+ stop_resume_latched = false; + stop_single_step = false; + stop_outputs_saved = false; + taskExecDelayStopTime = 0.0; @@ -609,7 +734,7 @@ index 3bf13a702d..2810757914 100644 + for (int s = 0; s < emcStatus->motion.traj.spindles; ++s) { + if (stop_spindles[s].running || + stop_spindles[s].orienting) { -+ emcSpindleOff(s); ++ emcSpindleOff(s, EMCMOT_SPINDLE_AT_SPEED_PRESERVE); + } + } + if (stop_mist) { @@ -620,9 +745,22 @@ index 3bf13a702d..2810757914 100644 + } +} + ++/* ++ * A second Stop, or a Pause, while Resume is pending cancels it: STARTING ++ * returns to STOPPED with the outputs Resume switched back on off again. The ++ * program stays stopped until the next Resume, Run or Single Step. ++ */ ++static void emcTaskStopCancelResume() ++{ ++ stop_single_step = false; ++ if (emcStatus->task.stopState == EMC_TASK_STOP_STATE::STARTING) { ++ emcTaskStopDisableSavedOutputs(); ++ emcStatus->task.stopState = EMC_TASK_STOP_STATE::STOPPED; ++ } ++} ++ +static void emcTaskStopResume() +{ -+ stop_resume_latched = false; + if (!stop_outputs_saved) { + return; + } @@ -634,11 +772,17 @@ index 3bf13a702d..2810757914 100644 + emcCoolantFloodOn(); + } + for (int s = 0; s < emcStatus->motion.traj.spindles; ++s) { ++ stop_spindles[s].restore_wait_at_speed = false; + if (stop_spindles[s].running) { -+ emcSpindleOn(s, stop_spindles[s].speed, ++ stop_spindles[s].restore_seq = emcSpindleStopRestoreSeq(s); ++ // A spindle restored at commanded speed 0 (M3 S0) does not spin ++ // up, and an at-speed comparator need not drop for it. ++ stop_spindles[s].restore_wait_at_speed = ++ emcSpindleOn(s, stop_spindles[s].speed, + stop_spindles[s].css_factor, + stop_spindles[s].css_xoffset, -+ EMCMOT_SPINDLE_AT_SPEED_PRESERVE); ++ EMCMOT_SPINDLE_AT_SPEED_PRESERVE) == 0 && ++ stop_spindles[s].speed != 0.0; + } + if (stop_spindles[s].orienting) { + emcSpindleOrient(s, stop_spindles[s].orientation, @@ -652,11 +796,41 @@ index 3bf13a702d..2810757914 100644 + emcStatus->task.stopState = EMC_TASK_STOP_STATE::STARTING; +} + ++/* ++ * What a Stop or Pause waits for. An operation task has already handed to ++ * another subsystem runs to its end before the machine holds, as an M ++ * function runs to its completion signal on other controls, and only then ++ * does Stop switch spindle and coolant off. None of these waits has a ++ * timeout of its own; Abort, E-stop and Machine Off end them. ++ * ++ * A queued G28.2 homing cycle cannot be paused and resumed part way. Motion ++ * is dipped into FREE meanwhile and may report a stopped coordinated planner ++ * long before homing ends. Test the exec state, not homingWaiting: Abort, ++ * E-stop, machine off and mode changes leave that flag set when they end the ++ * wait. ++ */ ++static EMC_TASK_HOLD_WAIT emcTaskHoldWait() ++{ ++ if (emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_HOMING) { ++ return EMC_TASK_HOLD_WAIT::HOMING; ++ } ++ if (emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_SYSTEM_CMD) { ++ return EMC_TASK_HOLD_WAIT::SYSTEM_COMMAND; ++ } ++ if (emcStatus->io.status == RCS_STATUS::EXEC) { ++ return EMC_TASK_HOLD_WAIT::IO; ++ } ++ return EMC_TASK_HOLD_WAIT::NONE; ++} ++ +static void emcTaskStopProgress() +{ + switch (emcStatus->task.stopState) { + case EMC_TASK_STOP_STATE::STOPPING: { -+ if (!emcStatus->motion.traj.stopped) { ++ // Like position-synchronized motion, an operation already under way ++ // runs to its end before Stop is reached. ++ if (emcTaskHoldWait() != EMC_TASK_HOLD_WAIT::NONE || ++ !emcStatus->motion.traj.stopped) { + return; + } + @@ -688,7 +862,7 @@ index 3bf13a702d..2810757914 100644 + } + if (spindle_running || + status.orient_state == EMCMOT_ORIENT_IN_PROGRESS) { -+ emcSpindleOff(s); ++ emcSpindleOff(s, EMCMOT_SPINDLE_AT_SPEED_PRESERVE); + spindle_output_active = true; + } + } @@ -705,9 +879,6 @@ index 3bf13a702d..2810757914 100644 + return; + } + emcStatus->task.stopState = EMC_TASK_STOP_STATE::STOPPED; -+ if (stop_resume_latched) { -+ emcTaskStopResume(); -+ } + return; + } + @@ -730,7 +901,25 @@ index 3bf13a702d..2810757914 100644 + } + } + } -+ if (stop_single_step) { ++ /* ++ * Motion continues only once every spindle Stop switched off and ++ * Resume switched back on is at speed again, so an interrupted feed ++ * does not restart cutting while the spindle spins up. Like ++ * upstream's own at-speed waits this has no timeout; Stop, Abort, ++ * E-stop and machine off leave STARTING. See ++ * emcSpindleStopRestoreAtSpeed() for why a stale at-speed does not ++ * count. ++ */ ++ for (int s = 0; s < emcStatus->motion.traj.spindles; ++s) { ++ if (stop_spindles[s].restore_wait_at_speed && ++ !emcSpindleStopRestoreAtSpeed(s, ++ stop_spindles[s].restore_seq)) { ++ return; ++ } ++ } ++ // Motion refuses a Step with nothing queued (Stop between moves); ++ // resume it instead, and the interpreter steps the next line. ++ if (stop_single_step && emcStatus->motion.traj.queue > 0) { + emcTrajStep(); + } else { + emcTrajResume(); @@ -749,7 +938,7 @@ index 3bf13a702d..2810757914 100644 /* emcTaskPlan() -@@ -773,6 +992,28 @@ static int emcTaskPlan(void) +@@ -809,6 +1140,33 @@ static int emcTaskPlan(void) return retval; } @@ -761,15 +950,20 @@ index 3bf13a702d..2810757914 100644 + (type == EMC_TASK_PLAN_RUN_TYPE || + type == EMC_TASK_PLAN_RESUME_TYPE || + type == EMC_TASK_PLAN_STEP_TYPE)) { ++ if (emcStatus->task.stopState == EMC_TASK_STOP_STATE::STOPPING) { ++ // Not remembered for later: the operator resumes once the ++ // machine has stopped, knowing it is safe to. ++ emcOperatorError(_("Can't resume while the program is stopping; wait until it has stopped")); ++ return -1; ++ } + stop_single_step = type == EMC_TASK_PLAN_STEP_TYPE; + if (stop_single_step) { + emcTaskStepInterpreter(); -+ } else if (emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED) { ++ } else { ++ // Also leaves single-step mode entered by an earlier Step. + emcTaskResumeInterpreter(); + } -+ if (emcStatus->task.stopState == EMC_TASK_STOP_STATE::STOPPING) { -+ stop_resume_latched = true; -+ } else if (emcStatus->task.stopState == EMC_TASK_STOP_STATE::STOPPED) { ++ if (emcStatus->task.stopState == EMC_TASK_STOP_STATE::STOPPED) { + emcTaskStopResume(); + } + return 0; @@ -778,7 +972,15 @@ index 3bf13a702d..2810757914 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1843,6 +2084,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1734,6 +2092,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + // found to have been rejected), invisibly to the task-level + // MDI/AUTO/MANUAL state. + homingPriorMode = emcStatus->motion.traj.mode; ++ homingPriorTaskMode = emcStatus->task.mode; + if (homingPriorMode != EMC_TRAJ_MODE::FREE) { + emcTrajSetMode(EMC_TRAJ_MODE::FREE); + } +@@ -1937,6 +2296,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcTrajPause(); break; @@ -790,7 +992,7 @@ index 3bf13a702d..2810757914 100644 case EMC_TRAJ_RESUME_TYPE: emcStatus->task.task_paused = 0; retval = emcTrajResume(); -@@ -1923,6 +2169,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2039,6 +2403,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE: wait_spindle_orient_complete_msg = reinterpret_cast(cmd); @@ -802,7 +1004,7 @@ index 3bf13a702d..2810757914 100644 taskExecDelayTimeout = etime() + wait_spindle_orient_complete_msg->timeout; break; -@@ -1983,6 +2234,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2099,6 +2468,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_ORIENT_TYPE: spindle_orient_msg = reinterpret_cast(cmd); @@ -817,19 +1019,23 @@ index 3bf13a702d..2810757914 100644 retval = emcSpindleOrient(spindle_orient_msg->spindle, spindle_orient_msg->orientation, spindle_orient_msg->mode); break; -@@ -2075,7 +2334,46 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2191,7 +2568,47 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // task commands + case EMC_TASK_PLAN_STOP_TYPE: { ++ // Only a program: an availability change or tool table edit in ++ // AUTO also keeps task busy, but has no program to resume. + bool active_auto_program = -+ emcStatus->task.interpState != EMC_TASK_INTERP::IDLE || -+ emcStatus->task.execState != EMC_TASK_EXEC::DONE || -+ emcStatus->motion.traj.queue > 0 || -+ interp_list.len() > 0 || -+ emcTaskCommand != nullptr; ++ emcStatus->task.interpState != EMC_TASK_INTERP::IDLE; ++ // During a queued G28.2 motion is dipped into FREE and task.mode ++ // reads MANUAL; the program that issued the home still owns task. ++ EMC_TASK_MODE program_mode = ++ emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_HOMING ++ ? homingPriorTaskMode ++ : emcStatus->task.mode; + if (emcStatus->task.state != EMC_TASK_STATE::ON || -+ emcStatus->task.mode != EMC_TASK_MODE::AUTO || ++ program_mode != EMC_TASK_MODE::AUTO || + !active_auto_program) { + emcOperatorError(_("Can't stop program when no AUTO program is active")); + retval = -1; @@ -838,18 +1044,15 @@ index 3bf13a702d..2810757914 100644 + + switch (emcStatus->task.stopState) { + case EMC_TASK_STOP_STATE::IDLE: -+ stop_resume_latched = false; + stop_single_step = false; + stop_outputs_saved = false; + emcStatus->task.stopState = EMC_TASK_STOP_STATE::STOPPING; + emcStatus->task.task_paused = 1; + retval = emcTrajStop(); + break; ++ case EMC_TASK_STOP_STATE::STOPPING: + case EMC_TASK_STOP_STATE::STARTING: -+ emcTaskStopDisableSavedOutputs(); -+ emcStatus->task.stopState = EMC_TASK_STOP_STATE::STOPPED; -+ stop_resume_latched = false; -+ stop_single_step = false; ++ emcTaskStopCancelResume(); + retval = 0; + break; + default: @@ -864,17 +1067,20 @@ index 3bf13a702d..2810757914 100644 // abort everything emcTaskAbort(); // KLUDGE call motion abort before state restore to make absolutely sure no -@@ -2099,6 +2397,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2215,6 +2632,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) mode_msg->mode != EMC_TASK_MODE::AUTO) { emcOperatorError(_("Can't switch mode while mode is AUTO and interpreter is not IDLE")); } else { // we can honour the modeswitch -+ if (mode_msg->mode != emcStatus->task.mode) { ++ // emcTaskSetMode() aborts the program for AUTO and MDI even when ++ // the mode does not change, so the Stop state goes with it. ++ if (mode_msg->mode != emcStatus->task.mode || ++ mode_msg->mode != EMC_TASK_MODE::MANUAL) { + emcTaskStopClear(); + } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { // leaving auto or mdi mode for manual -@@ -2143,6 +2444,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2259,6 +2682,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_SET_STATE_TYPE: state_msg = reinterpret_cast(cmd); @@ -884,7 +1090,15 @@ index 3bf13a702d..2810757914 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2368,11 +2672,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2451,6 +2877,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + break; + + case EMC_TASK_PLAN_PAUSE_TYPE: ++ emcTaskStopCancelResume(); + emcTrajPause(); + if (emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED) { + interpResumeState = emcStatus->task.interpState; +@@ -2484,11 +2911,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -897,7 +1111,7 @@ index 3bf13a702d..2810757914 100644 retval = 0; break; -@@ -2569,6 +2870,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3125,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -905,7 +1119,7 @@ index 3bf13a702d..2810757914 100644 /*! \todo FIXME-- duplicate code for abort, also near end of main, when aborting on subordinate errors, -@@ -2614,7 +2916,9 @@ static int emcTaskExecute(void) +@@ -2746,7 +3171,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -913,10 +1127,19 @@ index 3bf13a702d..2810757914 100644 + emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED && + emcStatus->task.stopState != EMC_TASK_STOP_STATE::STOPPED && + emcStatus->task.stopState != EMC_TASK_STOP_STATE::STARTING) { - if (0 == emcTaskCommand) { + if (NULL == emcTaskCommand) { // need a new command emcTaskCommand = interp_list.get(); -@@ -2739,6 +3043,18 @@ static int emcTaskExecute(void) +@@ -2767,7 +3194,7 @@ static int emcTaskExecute(void) + emcStatus->task.execState = emcTaskCheckPreconditions(emcTaskCommand.get()); + } + } +- } else { ++ } else if (emcTaskStopAllowsIssue(emcTaskCommand.get())) { + // have an outstanding command + // This is the one emcTaskIssueCommand() call site followed by + // emcTaskCheckPostconditions(), i.e. the only one whose commands +@@ -3040,6 +3467,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -935,7 +1158,7 @@ index 3bf13a702d..2810757914 100644 // check if delay has passed emcStatus->task.delayLeft = taskExecDelayTimeout - etime(); if (etime() >= taskExecDelayTimeout) { -@@ -3325,6 +3641,7 @@ int main(int argc, char *argv[]) +@@ -3626,6 +4065,7 @@ int main(int argc, char *argv[]) prev_traj_enabled = emcStatus->motion.traj.enabled; // synchronize subordinate states if (emcStatus->io.aux.estop) { @@ -943,7 +1166,7 @@ index 3bf13a702d..2810757914 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3406,6 +3723,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4147,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -951,7 +1174,7 @@ index 3bf13a702d..2810757914 100644 // abort everything emcTaskAbort(); emcIoAbort(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); -@@ -3441,6 +3759,12 @@ int main(int argc, char *argv[]) +@@ -3742,6 +4183,18 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -960,11 +1183,17 @@ index 3bf13a702d..2810757914 100644 + } else { + emcTaskStopProgress(); + } ++ emcStatus->task.holdWait = ++ emcStatus->task.state == EMC_TASK_STATE::ON && ++ (emcStatus->task.stopState == EMC_TASK_STOP_STATE::STOPPING || ++ (emcStatus->task.stopState == EMC_TASK_STOP_STATE::IDLE && ++ emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED)) ++ ? emcTaskHoldWait() : EMC_TASK_HOLD_WAIT::NONE; + // update task-specific status emcTaskUpdate(&emcStatus->task); -@@ -3461,6 +3785,9 @@ int main(int argc, char *argv[]) +@@ -3762,6 +4215,9 @@ int main(int argc, char *argv[]) emcStatus->io.status == RCS_STATUS::ERROR) { emcStatus->status = RCS_STATUS::ERROR; emcStatus->task.status = RCS_STATUS::ERROR; @@ -975,10 +1204,10 @@ index 3bf13a702d..2810757914 100644 emcStatus->task.execState == EMC_TASK_EXEC::DONE && emcStatus->motion.status == RCS_STATUS::DONE && diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index a37da0ca5f..86fdd15940 100644 +index 4215d22..3f66a0b 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -1421,6 +1421,13 @@ int emcTrajPause() +@@ -1497,6 +1497,13 @@ int emcTrajPause() return usrmotWriteEmcmotCommand(&emcmotCommand); } @@ -992,7 +1221,7 @@ index a37da0ca5f..86fdd15940 100644 int emcTrajReverse() { emcmotCommand.command = EMCMOT_REVERSE; -@@ -1676,6 +1683,7 @@ int emcTrajUpdate(EMC_TRAJ_STAT * stat) +@@ -1756,6 +1763,7 @@ int emcTrajUpdate(EMC_TRAJ_STAT * stat) } stat->paused = emcmotStatus.paused; @@ -1000,7 +1229,83 @@ index a37da0ca5f..86fdd15940 100644 stat->scale = emcmotStatus.feed_scale; stat->rapid_scale = emcmotStatus.rapid_scale; -@@ -2042,6 +2050,9 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ +@@ -2065,25 +2073,69 @@ int emcSpindleOrient(int spindle, double orientation, int mode) + } + + ++/* ++ * emcSpindleSpeed() sends EMCMOT_SPINDLE_ON with whatever on/off state and ++ * at-speed request the last spindle command left in emcmotCommand. A ++ * resumable Stop's spindle commands (EMCMOT_SPINDLE_AT_SPEED_PRESERVE) must ++ * leave both as they were: otherwise a later S-word change would leave the ++ * next feed's at-speed wait unarmed, or switch on a spindle stopped by M5. ++ */ ++static int writeSpindleCommand(int state, int wait_for_at_speed) ++{ ++ int previous_state = emcmotCommand.state; ++ unsigned char previous_wait = emcmotCommand.wait_for_spindle_at_speed; ++ emcmotCommand.state = state; ++ emcmotCommand.wait_for_spindle_at_speed = wait_for_at_speed; ++ int retval = usrmotWriteEmcmotCommand(&emcmotCommand); ++ if (wait_for_at_speed == EMCMOT_SPINDLE_AT_SPEED_PRESERVE) { ++ emcmotCommand.state = previous_state; ++ emcmotCommand.wait_for_spindle_at_speed = previous_wait; ++ } ++ return retval; ++} ++ + int emcSpindleOn(int spindle, double speed, double css_factor, double offset, int wait_for_at_speed) + { + emcmotCommand.command = EMCMOT_SPINDLE_ON; + emcmotCommand.spindle = spindle; +- emcmotCommand.state = 1; + emcmotCommand.vel = speed; + emcmotCommand.ini_maxvel = css_factor; + emcmotCommand.acc = offset; +- emcmotCommand.wait_for_spindle_at_speed = wait_for_at_speed; +- return usrmotWriteEmcmotCommand(&emcmotCommand); ++ return writeSpindleCommand(1, wait_for_at_speed); + } + + int emcSpindleOff(int spindle, int wait_for_at_speed) + { + emcmotCommand.command = EMCMOT_SPINDLE_OFF; +- emcmotCommand.state = 0; + emcmotCommand.spindle = spindle; +- emcmotCommand.wait_for_spindle_at_speed = wait_for_at_speed; +- return usrmotWriteEmcmotCommand(&emcmotCommand); ++ return writeSpindleCommand(0, wait_for_at_speed); ++} ++ ++unsigned int emcSpindleStopRestoreSeq(int spindle) ++{ ++ if (spindle < 0 || spindle >= EMCMOT_MAX_SPINDLES) { ++ return 0; ++ } ++ return emcmotStatus.spindle_status[spindle].stop_restore_seq; ++} ++ ++/* ++ * True once motion has handled the restore that followed seq and has since ++ * read spindle.N.at-speed true, with that true not left over from before the ++ * restore: motion must also have read at-speed false at some servo period ++ * after the restore (the first sample after it still reflects the stopped ++ * spindle). That false is not required while at-speed has never read false ++ * with the spindle on (unconnected, or tied true, as in a simulation or a ++ * machine without feedback): there is nothing to wait for. ++ */ ++bool emcSpindleStopRestoreAtSpeed(int spindle, unsigned int seq) ++{ ++ if (spindle < 0 || spindle >= EMCMOT_MAX_SPINDLES) { ++ return true; ++ } ++ const auto &status = emcmotStatus.spindle_status[spindle]; ++ return status.stop_restore_seq != seq && status.at_speed && ++ (status.stop_restore_atspeed_dropped || !status.atspeed_feedback); + } + + int emcSpindleBrakeRelease(int spindle) +@@ -2137,6 +2189,9 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ stat[s].orient_state = emcmotStatus.spindle_status[s].orient_state; stat[s].orient_fault = emcmotStatus.spindle_status[s].orient_fault; stat[s].spindle_scale = emcmotStatus.spindle_status[s].scale; @@ -1011,10 +1316,42 @@ index a37da0ca5f..86fdd15940 100644 return 0; } diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index e5667b3f29..e48127c5a9 100644 +index c75c795..e481a43 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c -@@ -250,7 +250,11 @@ STATIC double tpGetFeedScale(TP_STRUCT const * const tp, +@@ -229,6 +229,31 @@ STATIC int tpGetMachineActiveLimit(double * const act_limit, PmCartesian const * + } + + ++/** ++ * Check whether a resumable Stop holds a segment at feed scale 0. ++ * While stop_sync_run is set, Stop lets a position-synchronized run finish: ++ * the segment that was synchronized when Stop arrived (also while it still ++ * waits for its index pulse) and the position-synchronized segments after it ++ * that continue the same spindle synchronization without a new index pulse. ++ * Stopping part way along that run would leave the axis behind the spindle. ++ * A rigid tap stays exempt in its final unsynchronized placement, and so ++ * does a blend arc that the trapezoidal planner inserts at the end of the ++ * run: it carries the run's last stretch into the following move. Every ++ * other segment is held. ++ */ ++STATIC bool tpStopHolds(TP_STRUCT const * const tp, ++ TC_STRUCT const * const tc) { ++ if (!tp->stopping) { ++ return false; ++ } ++ bool synchronized = tc->synchronized == TC_SYNC_POSITION || ++ tc->motion_type == TC_RIGIDTAP || ++ tc->motion_type == TC_SPHERICAL; ++ return !(tp->stop_sync_run && synchronized && ++ (tc->active || emcmotStatus->spindleSync)); ++} ++ ++ + /** + * Get a segment's feed scale based on the current planner state and emcmotStatus. + * @note depends on emcmotStatus for system information. +@@ -239,7 +264,11 @@ STATIC double tpGetFeedScale(TP_STRUCT const * const tp, return 0.0; } //All reasons to disable feed override go here @@ -1023,20 +1360,20 @@ index e5667b3f29..e48127c5a9 100644 + (tp->pausing && + (tc->synchronized == TC_SYNC_NONE || + tc->synchronized == TC_SYNC_VELOCITY)) || -+ (tp->stopping && tc != tp->stop_tc); ++ tpStopHolds(tp, tc); bool aborting = tp->aborting; if (pausing) { tc_debug_print("pausing\n"); -@@ -490,6 +494,8 @@ int tpClear(TP_STRUCT * const tp) +@@ -455,6 +484,8 @@ int tpClear(TP_STRUCT * const tp) tp->depth = tp->activeDepth = 0; tp->aborting = 0; tp->pausing = 0; + tp->stopping = 0; -+ tp->stop_tc = 0; ++ tp->stop_sync_run = 0; tp->reverse_run = 0; tp->synchronized = 0; tp->uu_per_rev = 0.0; -@@ -2830,12 +2836,24 @@ int tpCalculateSCurveAccel(TP_STRUCT const * const tp, TC_STRUCT * const tc, TC_ +@@ -2816,12 +2847,24 @@ int tpCalculateSCurveAccel(TP_STRUCT const * const tp, TC_STRUCT * const tc, TC_ } // Check pause/abort state @@ -1045,7 +1382,7 @@ index e5667b3f29..e48127c5a9 100644 + (tp->pausing && + (tc->synchronized == TC_SYNC_NONE || + tc->synchronized == TC_SYNC_VELOCITY)) || -+ (tp->stopping && tc != tp->stop_tc); ++ tpStopHolds(tp, tc); bool is_aborting = tp->aborting; - // Check if feed_override = 0 (not pause/abort, but velocity limited to 0) @@ -1064,7 +1401,7 @@ index e5667b3f29..e48127c5a9 100644 // Normal operation parameters double effective_max_vel = tc_target_vel; double effective_target_vel = tc_finalvel; -@@ -3301,7 +3319,9 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) +@@ -3327,7 +3370,9 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) tpUpdateMovementStatus(tp, NULL); @@ -1075,23 +1412,35 @@ index e5667b3f29..e48127c5a9 100644 } /** Wrapper function to unlock rotary axes */ -@@ -3711,6 +3731,9 @@ STATIC int tpUpdateCycle(TP_STRUCT * const tp, +@@ -3812,6 +3857,20 @@ STATIC int tpUpdateCycle(TP_STRUCT * const tp, int planner_type = GET_TRAJ_PLANNER_TYPE(); if(mode == NULL) planner_type = 0; ++ /* ++ * Spindle-synchronized threading (G33, G33.1, G76) and rigid tapping run ++ * on the trapezoidal planner even when PLANNER_TYPE selects the S-curve ++ * one. Their speed limit follows spindle feedback and drops to zero while ++ * the spindle restarts after a resumable Stop or while a thread waits for ++ * its index; the S-curve (Ruckig) planner rejects a zero maximum speed. ++ * Velocity-synchronized motion handles this in velocity control (see ++ * above); position-synchronized motion was moved to the trapezoidal ++ * planner instead. Known limitation, revisit with the Stop rework: such ++ * moves start and reverse without jerk limiting. ++ */ + if (tc->synchronized == TC_SYNC_POSITION || tc->motion_type == TC_RIGIDTAP) { + planner_type = 0; + } if(planner_type != 1){ // If the slowdown is not too great, use velocity ramping instead of trapezoidal velocity -@@ -4118,10 +4141,28 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4253,10 +4312,48 @@ int tpRunCycle(TP_STRUCT * const tp, long period) //If we have a NULL pointer, then the queue must be empty, so we're done. if(!tc) { + if (tp->stopping) { + tpHandleEmptyQueue(tp); + if (tp->stopping) { ++ tp->stop_sync_run = 0; + tp->pausing = 1; + emcmotStatus->stopped = 1; + } @@ -1101,20 +1450,58 @@ index e5667b3f29..e48127c5a9 100644 return TP_ERR_WAITING; } -+ if (tp->stopping && tc != tp->stop_tc) { ++ if (tpStopHolds(tp, tc)) { + tp->pausing = 1; ++ // Any synchronized run Stop was finishing is over. ++ tp->stop_sync_run = 0; + } + ++ /* ++ * tpUpdateInitialStatus() has already zeroed emcmotStatus->current_vel for ++ * this cycle, so judge rest from the velocities the segments reached in ++ * the previous cycle, as tpHandleAbort() does. ++ */ + if (((tp->pausing && tc->synchronized != TC_SYNC_POSITION) || -+ (tp->stopping && tc != tp->stop_tc)) && -+ fabs(emcmotStatus->current_vel) < TP_VEL_EPSILON) { ++ tpStopHolds(tp, tc)) && ++ fabs(tc->currentvel) < TP_VEL_EPSILON && ++ (!nexttc || fabs(nexttc->currentvel) < TP_VEL_EPSILON)) { + emcmotStatus->stopped = 1; ++ /* ++ * Stop holds this segment, so any synchronized run is over and task ++ * is about to switch the spindle off. Forget the spindle ++ * synchronization so that the next position-synchronized move waits ++ * for a fresh index pulse after Resume instead of chasing every ++ * revolution turned while stopped (a G33 after G95 motion would ++ * otherwise continue the earlier G33's synchronization). ++ */ ++ if (tp->stopping) { ++ emcmotStatus->spindleSync = 0; ++ } + } + tc_debug_print("-------------------\n"); -@@ -4227,7 +4268,19 @@ int tpPause(TP_STRUCT * const tp) +@@ -4270,6 +4367,18 @@ int tpRunCycle(TP_STRUCT * const tp, long period) + return TP_ERR_STOPPED; + } + ++ /* ++ * Do not start a segment from rest while Stop holds it. Activation would ++ * consume a pending spindle at-speed wait, or start a position-synchronized ++ * move's index search, while Stop has the spindle switched off. A segment ++ * entered with velocity from the previous one is still activated so that ++ * it can decelerate. ++ */ ++ if (tpStopHolds(tp, tc) && !tc->active && ++ fabs(tc->currentvel) < TP_VEL_EPSILON) { ++ return TP_ERR_WAITING; ++ } ++ + //Return early if we have a reason to wait (i.e. not ready for motion) + if (tpCheckAtSpeed(tp, tc) != TP_ERR_OK){ + return TP_ERR_WAITING; +@@ -4365,7 +4474,27 @@ int tpPause(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -1122,11 +1509,19 @@ index e5667b3f29..e48127c5a9 100644 + + if (tp->stopping) { + TC_STRUCT *tc = tcqItem(&tp->queue, 0); -+ if (tc && tc->active && tc->synchronized == TC_SYNC_POSITION) { -+ tp->stop_tc = tc; ++ /* ++ * A position-synchronized head is let finish when it is active, and ++ * also when it is not yet active but continues a synchronization ++ * already in effect: tpRunCycle() activates the next chained G33 one ++ * servo period after the previous one is popped, and a Stop handled ++ * in that period must not halt the thread. ++ */ ++ if (tc && tc->synchronized == TC_SYNC_POSITION && ++ (tc->active || emcmotStatus->spindleSync)) { ++ tp->stop_sync_run = 1; + tp->pausing = 0; + } else { -+ tp->stop_tc = 0; ++ tp->stop_sync_run = 0; + tp->pausing = 1; + } + } else { @@ -1135,21 +1530,21 @@ index e5667b3f29..e48127c5a9 100644 return TP_ERR_OK; } -@@ -4237,6 +4290,9 @@ int tpResume(TP_STRUCT * const tp) +@@ -4375,6 +4504,9 @@ int tpResume(TP_STRUCT * const tp) return TP_ERR_FAIL; } tp->pausing = 0; + tp->stopping = 0; -+ tp->stop_tc = 0; ++ tp->stop_sync_run = 0; + emcmotStatus->stopped = 0; return TP_ERR_OK; } diff --git a/src/emc/tp/tp_types.h b/src/emc/tp/tp_types.h -index 6687ef3a2d..8d8aa3a362 100644 +index 0e9ab84..d11e695 100644 --- a/src/emc/tp/tp_types.h +++ b/src/emc/tp/tp_types.h -@@ -136,6 +136,13 @@ typedef struct { +@@ -149,6 +149,18 @@ typedef struct { syncdio_t syncdio; //record tpSetDout's here @@ -1158,24 +1553,30 @@ index 6687ef3a2d..8d8aa3a362 100644 + * planners retain the offsets of every member in the established ABI. + */ + int stopping; -+ TC_STRUCT *stop_tc; ++ /* ++ * Set while Stop lets a position-synchronized run (a G33 chain or a ++ * rigid tap) finish; cleared once a held segment reaches the head of the ++ * queue or the queue empties. ++ */ ++ int stop_sync_run; + } TP_STRUCT; diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index 3345c0a6a0..750663187b 100644 +index d242bd5..9261f61 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1132,6 +1132,7 @@ static PyMemberDef Stat_members[] = { +@@ -1138,6 +1138,8 @@ static PyMemberDef Stat_members[] = { }, { "exec_state", T_INT, O(task.execState), READONLY, NULL}, { "interp_state", T_INT, O(task.interpState), READONLY, NULL}, + { "stop_state", T_INT, O(task.stopState), READONLY, NULL}, ++ { "hold_wait", T_INT, O(task.holdWait), READONLY, NULL}, { "call_level", T_INT, O(task.callLevel), READONLY, NULL}, { "read_line", T_INT, O(task.readLine), READONLY, NULL}, { "motion_line", T_INT, O(task.motionLine), READONLY, NULL}, -@@ -1959,6 +1960,13 @@ static PyObject *emcabort(pyCommandChannel *s, PyObject * /*o*/) { +@@ -2003,6 +2005,13 @@ static PyObject *emcabort(pyCommandChannel *s, PyObject * /*o*/) { return Py_None; } @@ -1189,7 +1590,7 @@ index 3345c0a6a0..750663187b 100644 static PyObject *override_limits(pyCommandChannel *s, PyObject * /*o*/) { EMC_JOINT_OVERRIDE_LIMITS m; m.joint = 0; // same number for all -@@ -2361,6 +2369,7 @@ static PyMethodDef Command_methods[] = { +@@ -2405,6 +2414,7 @@ static PyMethodDef Command_methods[] = { {"brake", (PyCFunction)brake, METH_VARARGS, NULL}, {"load_tool_table", (PyCFunction)load_tool_table, METH_NOARGS, NULL}, {"abort", (PyCFunction)emcabort, METH_NOARGS, NULL}, @@ -1197,11 +1598,15 @@ index 3345c0a6a0..750663187b 100644 {"task_plan_synch", (PyCFunction)task_plan_synch, METH_NOARGS, NULL}, {"override_limits", (PyCFunction)override_limits, METH_NOARGS, NULL}, {"home", (PyCFunction)home, METH_VARARGS, -@@ -3402,6 +3411,11 @@ PyMODINIT_FUNC PyInit_linuxcnc(void) +@@ -3383,6 +3393,15 @@ PyMODINIT_FUNC PyInit_linuxcnc(void) PyModule_AddIntConstant(m, "INTERP_PAUSED", (int)EMC_TASK_INTERP::PAUSED); PyModule_AddIntConstant(m, "INTERP_WAITING", (int)EMC_TASK_INTERP::WAITING); + PyModule_AddIntConstant(m, "STOP_IDLE", (int)EMC_TASK_STOP_STATE::IDLE); ++ PyModule_AddIntConstant(m, "HOLD_WAIT_NONE", (int)EMC_TASK_HOLD_WAIT::NONE); ++ PyModule_AddIntConstant(m, "HOLD_WAIT_HOMING", (int)EMC_TASK_HOLD_WAIT::HOMING); ++ PyModule_AddIntConstant(m, "HOLD_WAIT_IO", (int)EMC_TASK_HOLD_WAIT::IO); ++ PyModule_AddIntConstant(m, "HOLD_WAIT_SYSTEM_COMMAND", (int)EMC_TASK_HOLD_WAIT::SYSTEM_COMMAND); + PyModule_AddIntConstant(m, "STOP_STOPPING", (int)EMC_TASK_STOP_STATE::STOPPING); + PyModule_AddIntConstant(m, "STOP_STOPPED", (int)EMC_TASK_STOP_STATE::STOPPED); + PyModule_AddIntConstant(m, "STOP_STARTING", (int)EMC_TASK_STOP_STATE::STARTING); @@ -1210,10 +1615,10 @@ index 3345c0a6a0..750663187b 100644 PyModule_AddIntConstant(m, "MODE_MANUAL", (int)EMC_TASK_MODE::MANUAL); PyModule_AddIntConstant(m, "MODE_AUTO", (int)EMC_TASK_MODE::AUTO); diff --git a/src/emc/usr_intf/halui.cc b/src/emc/usr_intf/halui.cc -index 6e7c462197..bcb62bf9f9 100644 +index 1d0cb6e..65b890a 100644 --- a/src/emc/usr_intf/halui.cc +++ b/src/emc/usr_intf/halui.cc -@@ -1238,6 +1238,13 @@ static int sendAbort() +@@ -1077,6 +1077,13 @@ static int sendAbort() return emcCommandSend(task_abort_msg); } @@ -1227,7 +1632,7 @@ index 6e7c462197..bcb62bf9f9 100644 static void sendJogStop(int ja, int jjogmode) { -@@ -1684,7 +1691,7 @@ static void check_hal_changes() +@@ -1531,7 +1538,7 @@ static void check_hal_changes() sendProgramStep(); if (check_bit_changed(new_halui_data.program_stop, old_halui_data.program_stop) != 0) @@ -1236,1174 +1641,3 @@ index 6e7c462197..bcb62bf9f9 100644 //max-velocity stuff counts = new_halui_data.mv_counts; -diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -new file mode 100644 -index 0000000000..e457195324 ---- /dev/null -+++ b/tests/resumable-stop/README -@@ -0,0 +1,10 @@ -+Verify resumable Stop preserves an active AUTO program and resumes or -+single-steps it. -+ -+This regression test exercises the task-level Stop operation directly through -+the Python command API. It checks that an active feed move stops without -+aborting queued AUTO state, that spindle and coolant outputs are disabled -+while stopped, and that Resume restores them before continuing the same -+program to completion. The G95 scenario enables the jerk-limited trajectory -+planner and rejects zero-limit Ruckig fallback errors while spindle feedback -+recovers after Resume. -diff --git a/tests/resumable-stop/after-abort.ngc b/tests/resumable-stop/after-abort.ngc -new file mode 100644 -index 0000000000..df711f6b3d ---- /dev/null -+++ b/tests/resumable-stop/after-abort.ngc -@@ -0,0 +1,4 @@ -+G21 G90 -+F600 -+G1 X6 -+M2 -diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -new file mode 100755 -index 0000000000..c491888fc8 ---- /dev/null -+++ b/tests/resumable-stop/checkresult -@@ -0,0 +1,3 @@ -+#!/bin/sh -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 15 -+grep -q '^resumable stop scenarios complete$' "$1" -diff --git a/tests/resumable-stop/core_sim.hal b/tests/resumable-stop/core_sim.hal -new file mode 100644 -index 0000000000..bbc7166567 ---- /dev/null -+++ b/tests/resumable-stop/core_sim.hal -@@ -0,0 +1,42 @@ -+# core HAL config file for simulation -+ -+loadrt [KINS]KINEMATICS -+loadrt [EMCMOT]EMCMOT base_period_nsec=[EMCMOT]BASE_PERIOD servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS num_spindles=[TRAJ]SPINDLES -+loadrt encoder names=encoder_0 -+loadrt sim_encoder names=sim_encoder_0 -+ -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+ -+net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net Ypos joint.1.motor-pos-cmd => joint.1.motor-pos-fb -+net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb -+ -+net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in -+ -+net tool-prepare <= iocontrol.0.tool-prepare -+net tool-prepared => iocontrol.0.tool-prepared -+ -+net tool-change <= iocontrol.0.tool-change -+net tool-changed => iocontrol.0.tool-changed -+ -+net spindle-speed-cmd spindle.0.speed-out => sim_encoder_0.speed -+setp sim_encoder_0.ppr 12 -+setp sim_encoder_0.scale 60 -+ -+net spindle-phase-A sim_encoder_0.phase-A => encoder_0.phase-A -+net spindle-phase-B sim_encoder_0.phase-B => encoder_0.phase-B -+net spindle-phase-Z sim_encoder_0.phase-Z => encoder_0.phase-Z -+setp encoder_0.position-scale 48 -+ -+net spindle-index-enable spindle.0.index-enable <=> encoder_0.index-enable -+net spindle-pos encoder_0.position => spindle.0.revs -+net spindle-rps encoder_0.velocity => spindle.0.speed-in -+ -+addf encoder.capture-position servo-thread -+addf sim-encoder.update-speed servo-thread -+addf sim-encoder.make-pulses servo-thread -+addf encoder.update-counters servo-thread -+ -+setp spindle.0.at-speed true -+setp spindle.1.at-speed true -diff --git a/tests/resumable-stop/css.ngc b/tests/resumable-stop/css.ngc -new file mode 100644 -index 0000000000..382aaffcec ---- /dev/null -+++ b/tests/resumable-stop/css.ngc -@@ -0,0 +1,6 @@ -+G21 G18 G90 -+G0 X20 Z0 -+G96 D1000 S60 M3 -+G1 X10 F60 -+M5 -+M2 -diff --git a/tests/resumable-stop/dwell.ngc b/tests/resumable-stop/dwell.ngc -new file mode 100644 -index 0000000000..f7a54f80d5 ---- /dev/null -+++ b/tests/resumable-stop/dwell.ngc -@@ -0,0 +1,5 @@ -+G21 G90 -+G0 X0 -+G4 P3 -+G1 X5 F600 -+M2 -diff --git a/tests/resumable-stop/fperrev.ngc b/tests/resumable-stop/fperrev.ngc -new file mode 100644 -index 0000000000..92dbe87412 ---- /dev/null -+++ b/tests/resumable-stop/fperrev.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+G0 X0 -+S60 M3 -+G95 -+G1 X10 F1 -+M5 -+M2 -diff --git a/tests/resumable-stop/g76.ngc b/tests/resumable-stop/g76.ngc -new file mode 100644 -index 0000000000..1c6a3ea852 ---- /dev/null -+++ b/tests/resumable-stop/g76.ngc -@@ -0,0 +1,7 @@ -+G21 G18 G90 -+G0 X10 Z0 -+S60 M3 -+G76 P1 Z-5 I-1 J0.2 K0.6 R1 -+G1 X20 F600 -+M5 -+M2 -diff --git a/tests/resumable-stop/multi-spindle.ngc b/tests/resumable-stop/multi-spindle.ngc -new file mode 100644 -index 0000000000..ba2e66f6da ---- /dev/null -+++ b/tests/resumable-stop/multi-spindle.ngc -@@ -0,0 +1,4 @@ -+G21 G90 -+G0 X0 -+G1 X10 F60 -+M2 -diff --git a/tests/resumable-stop/orient.ngc b/tests/resumable-stop/orient.ngc -new file mode 100644 -index 0000000000..bb08db3994 ---- /dev/null -+++ b/tests/resumable-stop/orient.ngc -@@ -0,0 +1,6 @@ -+G21 G90 -+G0 X0 -+M19 R90 P1 Q30 -+M19 R180 P0 Q1 -+G1 X20 F60 -+M2 -diff --git a/tests/resumable-stop/pause.ngc b/tests/resumable-stop/pause.ngc -new file mode 100644 -index 0000000000..6fe71e34bc ---- /dev/null -+++ b/tests/resumable-stop/pause.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+G0 X0 -+F600 -+G1 X5 -+M0 -+G1 X10 -+M2 -diff --git a/tests/resumable-stop/rapid-then-feed.ngc b/tests/resumable-stop/rapid-then-feed.ngc -new file mode 100644 -index 0000000000..c562a572dc ---- /dev/null -+++ b/tests/resumable-stop/rapid-then-feed.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+F60 -+S300 M3 -+G0 X80 -+G1 X90 -+M5 -+M2 -diff --git a/tests/resumable-stop/single-step.ngc b/tests/resumable-stop/single-step.ngc -new file mode 100644 -index 0000000000..8955e51e55 ---- /dev/null -+++ b/tests/resumable-stop/single-step.ngc -@@ -0,0 +1,10 @@ -+G21 G90 -+G0 X0 -+F600 -+S300 M3 -+M8 -+G1 X10 -+G1 X20 -+M9 -+M5 -+M2 -diff --git a/tests/resumable-stop/tap.ngc b/tests/resumable-stop/tap.ngc -new file mode 100644 -index 0000000000..3060ac429e ---- /dev/null -+++ b/tests/resumable-stop/tap.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+G0 X0 Z0 -+S6 M3 -+G33.1 Z-5 K10 -+G1 X10 F60 -+M5 -+M2 -diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -new file mode 100755 -index 0000000000..d3c9646b11 ---- /dev/null -+++ b/tests/resumable-stop/test-ui.py -@@ -0,0 +1,772 @@ -+#!/usr/bin/env python3 -+ -+import math -+import os -+import sys -+import time -+ -+import hal -+import linuxcnc -+ -+ -+ORIENT_IN_PROGRESS = 2 -+ -+ -+def fail(message): -+ print(message) -+ sys.exit(1) -+ -+ -+def wait_for(predicate, message, timeout=10.0): -+ start = time.time() -+ while time.time() - start < timeout: -+ s.poll() -+ if predicate(): -+ return -+ time.sleep(0.02) -+ fail(message) -+ -+ -+def wait_complete(message, timeout=10.0): -+ if c.wait_complete(timeout) != linuxcnc.RCS_DONE: -+ fail(message) -+ s.poll() -+ -+ -+c = linuxcnc.command() -+s = linuxcnc.stat() -+e = linuxcnc.error_channel() -+comp = hal.component("resumable-stop-test") -+ -+wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP, "LinuxCNC did not initialize") -+ -+c.state(linuxcnc.STATE_ESTOP_RESET) -+c.state(linuxcnc.STATE_ON) -+wait_complete("machine did not turn on") -+ -+ -+def open_auto_program(path): -+ c.mode(linuxcnc.MODE_AUTO) -+ wait_complete("machine did not enter AUTO") -+ c.program_open(path) -+ wait_complete("%s did not open" % path) -+ -+ -+def wait_for_program_complete(expected_x, expected_z=0.0, timeout=15.0): -+ wait_for( -+ lambda: s.interp_state == linuxcnc.INTERP_IDLE -+ and s.exec_state == linuxcnc.EXEC_DONE -+ and s.queue == 0 -+ and math.isclose(s.position[0], expected_x, abs_tol=0.01) -+ and math.isclose(s.position[2], expected_z, abs_tol=0.01), -+ "program did not complete at expected position", -+ timeout=timeout, -+ ) -+ -+ -+def assert_outputs_stopped_after_program(): -+ if abs(hal.get_value("spindle.0.speed-out")) > 0.001: -+ fail("spindle was not stopped by program completion") -+ -+ if hal.get_value("iocontrol.0.coolant-flood"): -+ fail("flood coolant was not stopped by program completion") -+ -+ -+def run_idle_program_stop_rejected_test(): -+ c.mode(linuxcnc.MODE_AUTO) -+ wait_complete("machine did not enter AUTO") -+ -+ c.program_stop() -+ if c.wait_complete(10.0) != linuxcnc.RCS_ERROR: -+ fail("program Stop was not rejected without an active AUTO program") -+ -+ s.poll() -+ if s.stop_state != linuxcnc.STOP_IDLE: -+ fail("rejected program Stop changed Stop state") -+ -+ -+def resume_and_wait_for_x_motion(stopped_x): -+ c.auto(linuxcnc.AUTO_RESUME) -+ -+ saw_restored_spindle = False -+ saw_restored_coolant = False -+ start = time.time() -+ while time.time() - start < 10.0: -+ s.poll() -+ if hal.get_value("spindle.0.speed-out") > 0.0: -+ saw_restored_spindle = True -+ if hal.get_value("iocontrol.0.coolant-flood"): -+ saw_restored_coolant = True -+ if s.position[0] > stopped_x + 0.05: -+ break -+ time.sleep(0.02) -+ -+ if not saw_restored_spindle: -+ fail("resume did not restore spindle") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.position[0] > stopped_x + 0.05, -+ "program did not resume motion from stopped position", -+ ) -+ -+ return saw_restored_coolant -+ -+ -+def run_ordinary_stop_resume_test(): -+ open_auto_program("test.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.task_mode == linuxcnc.MODE_AUTO -+ and s.interp_state != linuxcnc.INTERP_IDLE -+ and s.queue > 0 -+ and s.position[0] > 0.05 -+ and s.position[0] < 9.0 -+ and hal.get_value("spindle.0.speed-out") > 0.0 -+ and hal.get_value("iocontrol.0.coolant-flood"), -+ "program did not reach active motion with spindle and coolant on", -+ ) -+ -+ line_before_stop = s.read_line -+ queue_before_stop = s.queue -+ -+ c.program_stop() -+ wait_complete("stop command did not complete") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED state", -+ ) -+ -+ stopped_x = s.position[0] -+ stopped_read_line = s.read_line -+ stopped_queue = s.queue -+ -+ time.sleep(0.25) -+ s.poll() -+ -+ if abs(s.position[0] - stopped_x) > 0.001: -+ fail("position changed while stopped: %.6f -> %.6f" % (stopped_x, s.position[0])) -+ -+ if stopped_read_line < line_before_stop: -+ fail("read line regressed across stop: %d -> %d" % (line_before_stop, stopped_read_line)) -+ -+ if stopped_queue <= 0 or stopped_queue > queue_before_stop: -+ fail("queue was not preserved across stop: before=%d stopped=%d" % (queue_before_stop, stopped_queue)) -+ -+ if abs(hal.get_value("spindle.0.speed-out")) > 0.001: -+ fail("spindle speed-out was not disabled while stopped") -+ -+ if hal.get_value("iocontrol.0.coolant-flood"): -+ fail("flood coolant was not disabled while stopped") -+ -+ if not resume_and_wait_for_x_motion(stopped_x): -+ fail("resume did not restore coolant") -+ -+ wait_for_program_complete(10.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_stop_single_step_test(): -+ open_auto_program("single-step.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ wait_for( -+ lambda: s.queue > 0 -+ and s.position[0] > 0.05 -+ and s.position[0] < 9.0 -+ and hal.get_value("spindle.0.speed-out") > 0.0, -+ "program did not reach active motion before single-step test", -+ ) -+ -+ c.program_stop() -+ wait_complete("single-step stop command did not complete") -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED before single-step", -+ ) -+ -+ stopped_x = s.position[0] -+ c.auto(linuxcnc.AUTO_STEP) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.task_paused -+ and s.position[0] > stopped_x + 0.05 -+ and abs(s.current_vel) < 0.001, -+ "single-step did not execute one queued motion and pause", -+ timeout=15.0, -+ ) -+ -+ stepped_x = s.position[0] -+ time.sleep(0.25) -+ s.poll() -+ if abs(s.position[0] - stepped_x) > 0.001: -+ fail("program continued after stop-to-single-step") -+ -+ if abs(hal.get_value("spindle.0.speed-out")) < 0.001: -+ fail("single-step did not restore spindle") -+ if not hal.get_value("iocontrol.0.coolant-flood"): -+ fail("single-step did not restore coolant") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(20.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_rapid_resume_without_at_speed_test(): -+ hal.set_p("spindle.0.at-speed", "false") -+ open_auto_program("rapid-then-feed.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.task_mode == linuxcnc.MODE_AUTO -+ and s.position[0] > 1.0 -+ and s.position[0] < 70.0 -+ and hal.get_value("spindle.0.speed-out") > 0.0, -+ "program did not enter active rapid with spindle at-speed false", -+ ) -+ -+ c.program_stop() -+ wait_complete("rapid stop command did not complete") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not stop during active rapid", -+ ) -+ -+ stopped_x = s.position[0] -+ c.auto(linuxcnc.AUTO_RESUME) -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.position[0] > stopped_x + 0.05, -+ "rapid resume incorrectly waited for spindle at-speed", -+ ) -+ -+ wait_for( -+ lambda: math.isclose(s.position[0], 80.0, abs_tol=0.05) -+ and abs(s.current_vel) < 0.001 -+ and s.queue > 0, -+ "rapid did not complete and wait at following feed with at-speed false", -+ ) -+ -+ time.sleep(0.25) -+ s.poll() -+ if not math.isclose(s.position[0], 80.0, abs_tol=0.05): -+ fail("following feed moved before spindle at-speed became true") -+ -+ hal.set_p("spindle.0.at-speed", "true") -+ wait_for_program_complete(90.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_stop_while_program_paused_test(restart_with_run): -+ open_auto_program("pause.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.interp_state == linuxcnc.INTERP_PAUSED -+ and s.task_paused -+ and math.isclose(s.position[0], 5.0, abs_tol=0.01), -+ "program did not reach M0 pause", -+ ) -+ -+ c.program_stop() -+ wait_complete("stop command did not complete from M0 pause") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED from M0 pause", -+ ) -+ -+ if restart_with_run: -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ else: -+ c.auto(linuxcnc.AUTO_RESUME) -+ -+ wait_for_program_complete(10.0) -+ -+ -+def run_abort_from_empty_stopped_queue_test(): -+ open_auto_program("pause.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.interp_state == linuxcnc.INTERP_PAUSED -+ and s.task_paused -+ and math.isclose(s.position[0], 5.0, abs_tol=0.01), -+ "program did not reach M0 pause before abort test", -+ ) -+ -+ c.program_stop() -+ wait_complete("stop command did not complete from M0 pause before abort") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED from M0 pause before abort", -+ ) -+ -+ c.abort() -+ wait_complete("abort command did not complete from empty stopped queue") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and not s.task_paused -+ and s.interp_state == linuxcnc.INTERP_IDLE -+ and s.exec_state == linuxcnc.EXEC_DONE -+ and s.queue == 0, -+ "abort did not clear empty STOPPED state", -+ ) -+ -+ open_auto_program("after-abort.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.position[0] > 5.05, -+ "motion did not start after aborting empty STOPPED queue", -+ ) -+ -+ wait_for_program_complete(6.0) -+ -+ -+def stop_during_sync_motion(program, active_predicate, complete_predicate, message, expected_z): -+ open_auto_program(program) -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ start = time.time() -+ while time.time() - start < 15.0: -+ s.poll() -+ if ( -+ s.task_mode == linuxcnc.MODE_AUTO -+ and hal.get_value("spindle.0.speed-out") > 0.0 -+ and active_predicate() -+ ): -+ break -+ time.sleep(0.02) -+ else: -+ err = e.poll() -+ fail( -+ "%s did not enter synchronized motion: X=%.6f Z=%.6f " -+ "interp=%d exec=%d queue=%d spindle=%.3f error=%s" -+ % ( -+ message, -+ s.position[0], -+ s.position[2], -+ s.interp_state, -+ s.exec_state, -+ s.queue, -+ hal.get_value("spindle.0.speed-out"), -+ err, -+ ) -+ ) -+ -+ c.program_stop() -+ wait_complete("%s stop command did not complete" % message) -+ -+ start = time.time() -+ while time.time() - start < 15.0: -+ s.poll() -+ if s.stop_state == linuxcnc.STOP_STOPPED: -+ break -+ if not complete_predicate() and s.stop_state == linuxcnc.STOP_STOPPED: -+ fail("%s stopped before synchronized motion completed" % message) -+ time.sleep(0.02) -+ -+ if s.stop_state != linuxcnc.STOP_STOPPED: -+ fail("%s did not enter STOPPED state" % message) -+ -+ if not complete_predicate(): -+ fail( -+ "%s STOPPED before synchronized motion endpoint/cycle completion: " -+ "X=%.6f Z=%.6f" -+ % (message, s.position[0], s.position[2]) -+ ) -+ -+ if s.position[0] > 0.05: -+ fail("%s allowed following X move to start before STOPPED: X=%.6f" % (message, s.position[0])) -+ -+ if abs(hal.get_value("spindle.0.speed-out")) > 0.001: -+ fail("%s spindle speed-out was not disabled while stopped" % message) -+ -+ stopped_x = s.position[0] -+ resume_and_wait_for_x_motion(stopped_x) -+ wait_for_program_complete(10.0, expected_z=expected_z) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_threading_stop_resume_test(): -+ stop_during_sync_motion( -+ "thread.ngc", -+ lambda: s.position[2] < -0.5 and s.position[2] > -4.5, -+ lambda: s.position[2] <= -4.90, -+ "G33 threading", -+ expected_z=-5.0, -+ ) -+ -+ -+def run_fperrev_stop_resume_test(): -+ open_auto_program("fperrev.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.task_mode == linuxcnc.MODE_AUTO -+ and s.position[0] > 0.5 -+ and s.position[0] < 9.0 -+ and hal.get_value("spindle.0.speed-out") > 0.0, -+ "G95 G1 did not enter feed-per-revolution motion", -+ timeout=15.0, -+ ) -+ -+ c.program_stop() -+ wait_complete("G95 G1 stop command did not complete") -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not stop during G95 G1 motion", -+ ) -+ -+ stopped_x = s.position[0] -+ time.sleep(0.25) -+ s.poll() -+ if not math.isclose(s.position[0], stopped_x, abs_tol=0.001): -+ fail("G95 G1 moved while stopped") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.position[0] > stopped_x + 0.05 -+ and hal.get_value("spindle.0.speed-out") > 0.0, -+ "G95 G1 did not resume with the spindle active", -+ ) -+ -+ wait_for_program_complete(10.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_g76_stop_resume_test(): -+ open_auto_program("g76.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.task_mode == linuxcnc.MODE_AUTO -+ and s.position[0] < 9.5 -+ and s.position[2] < -0.5 -+ and s.position[2] > -4.5, -+ "G76 did not enter its first synchronized pass", -+ timeout=15.0, -+ ) -+ -+ c.program_stop() -+ wait_complete("G76 stop command did not complete") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not stop after the active G76 threading TC", -+ timeout=15.0, -+ ) -+ -+ if s.position[2] > -4.90: -+ fail("G76 stopped before its active threading TC completed") -+ -+ if s.position[0] >= 9.5: -+ fail( -+ "G76 executed its retract or a later pass before STOPPED: X=%.6f" -+ % s.position[0] -+ ) -+ -+ stopped_x = s.position[0] -+ stopped_z = s.position[2] -+ time.sleep(0.25) -+ s.poll() -+ if ( -+ not math.isclose(s.position[0], stopped_x, abs_tol=0.001) -+ or not math.isclose(s.position[2], stopped_z, abs_tol=0.001) -+ ): -+ fail("G76 moved while stopped") -+ -+ resume_and_wait_for_x_motion(stopped_x) -+ wait_for_program_complete(20.0, expected_z=-5.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_queued_threading_stop_resume_test(): -+ hal.set_p("spindle.0.at-speed", "false") -+ open_auto_program("thread.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.task_mode == linuxcnc.MODE_AUTO -+ and s.interp_state != linuxcnc.INTERP_IDLE -+ and s.queue > 0 -+ and math.isclose(s.position[0], 0.0, abs_tol=0.001) -+ and math.isclose(s.position[2], 0.0, abs_tol=0.001) -+ and abs(s.current_vel) < 0.001 -+ and hal.get_value("spindle.0.speed-out") > 0.0, -+ "G33 did not queue while waiting for spindle at-speed", -+ ) -+ -+ # Let the stationary queue state persist so the G0 before G33 is gone. -+ time.sleep(0.25) -+ s.poll() -+ if s.queue <= 0 or abs(s.current_vel) >= 0.001: -+ fail("G33 did not remain queued while spindle at-speed was false") -+ -+ c.program_stop() -+ wait_complete("queued G33 stop command did not complete") -+ -+ # Simulate the delayed prerequisite arriving after Stop. The queued G33 -+ # must remain inactive and preserved for Resume. -+ time.sleep(0.05) -+ hal.set_p("spindle.0.at-speed", "true") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not stop with an inactive G33 queued", -+ ) -+ -+ if not math.isclose(s.position[2], 0.0, abs_tol=0.001): -+ fail("queued G33 started after Stop: Z=%.6f" % s.position[2]) -+ -+ time.sleep(0.25) -+ s.poll() -+ if not math.isclose(s.position[2], 0.0, abs_tol=0.001): -+ fail("queued G33 moved while stopped: Z=%.6f" % s.position[2]) -+ -+ resume_and_wait_for_x_motion(s.position[0]) -+ wait_for_program_complete(10.0, expected_z=-5.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_rigid_tap_stop_resume_test(): -+ saw_downstroke = False -+ -+ def active_predicate(): -+ nonlocal saw_downstroke -+ if s.position[2] < -0.5: -+ saw_downstroke = True -+ return True -+ return False -+ -+ def complete_predicate(): -+ return saw_downstroke and s.position[2] >= -0.05 -+ -+ stop_during_sync_motion( -+ "tap.ngc", -+ active_predicate, -+ complete_predicate, -+ "G33.1 rigid tapping", -+ expected_z=0.0, -+ ) -+ -+ -+def run_spindle_orientation_stop_test(): -+ hal.set_p("spindle.0.is-oriented", "false") -+ open_auto_program("orient.ngc") -+ -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: hal.get_value("spindle.0.orient") -+ and s.spindle[0]["orient_state"] == ORIENT_IN_PROGRESS, -+ "M19 did not start spindle orientation", -+ ) -+ -+ x_before_stop = s.position[0] -+ c.program_stop() -+ wait_complete("M19 stop command did not complete") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED during M19", -+ ) -+ -+ if hal.get_value("spindle.0.orient"): -+ fail("task reported STOPPED while spindle orientation remained active") -+ -+ if s.spindle[0]["orient_state"] == ORIENT_IN_PROGRESS: -+ fail("task reported STOPPED while spindle orientation was in progress") -+ -+ if not math.isclose(s.position[0], x_before_stop, abs_tol=0.001): -+ fail("following motion started while stopping M19") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ -+ wait_for( -+ lambda: hal.get_value("spindle.0.orient") -+ and s.spindle[0]["orient_state"] == ORIENT_IN_PROGRESS, -+ "resume did not restore spindle orientation", -+ ) -+ -+ if not math.isclose( -+ hal.get_value("spindle.0.orient-angle"), 90.0, abs_tol=0.001 -+ ): -+ fail("resume did not restore the requested spindle orientation angle") -+ -+ if hal.get_value("spindle.0.orient-mode") != 1: -+ fail("resume did not restore the requested spindle orientation mode") -+ -+ time.sleep(0.25) -+ s.poll() -+ if not math.isclose(s.position[0], x_before_stop, abs_tol=0.001): -+ fail("following motion started before spindle orientation completed") -+ -+ hal.set_p("spindle.0.is-oriented", "true") -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.position[0] > x_before_stop + 0.05, -+ "program did not continue after spindle orientation completed", -+ ) -+ -+ wait_for_program_complete(20.0, timeout=25.0) -+ -+ -+def run_dwell_stop_resume_test(): -+ open_auto_program("dwell.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY -+ and s.delay_left > 2.0, -+ "G4 did not enter its dwell", -+ ) -+ -+ c.program_stop() -+ wait_complete("G4 stop command did not complete") -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED during G4", -+ ) -+ -+ stopped_delay = s.delay_left -+ time.sleep(0.5) -+ s.poll() -+ if not math.isclose(s.position[0], 0.0, abs_tol=0.001): -+ fail("motion started while G4 was stopped") -+ if s.delay_left < stopped_delay - 0.1: -+ fail("G4 delay elapsed while stopped") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ time.sleep(0.5) -+ s.poll() -+ if not math.isclose(s.position[0], 0.0, abs_tol=0.001): -+ fail("motion started before the restored G4 delay elapsed") -+ -+ wait_for_program_complete(5.0) -+ -+ -+def run_multi_spindle_stop_resume_test(): -+ open_auto_program("multi-spindle.ngc") -+ c.spindle(linuxcnc.SPINDLE_FORWARD, 120.0, 0) -+ wait_complete("primary spindle command did not complete") -+ c.spindle(linuxcnc.SPINDLE_REVERSE, 180.0, 1) -+ wait_complete("secondary spindle command did not complete") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.position[0] > 0.05 -+ and s.position[0] < 9.0 -+ and s.spindle[0]["direction"] == 1 -+ and s.spindle[1]["direction"] == -1 -+ and hal.get_value("spindle.0.on") -+ and hal.get_value("spindle.1.on"), -+ "both spindles did not remain active during motion", -+ ) -+ -+ c.program_stop() -+ wait_complete("multi-spindle stop command did not complete") -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED with two spindles", -+ ) -+ if hal.get_value("spindle.0.on") or hal.get_value("spindle.1.on"): -+ fail("a spindle remained enabled while stopped") -+ -+ stopped_x = s.position[0] -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.position[0] > stopped_x + 0.05 -+ and s.spindle[0]["direction"] == 1 -+ and s.spindle[1]["direction"] == -1 -+ and hal.get_value("spindle.0.on") -+ and hal.get_value("spindle.1.on"), -+ "resume did not restore both spindles", -+ ) -+ -+ wait_for_program_complete(10.0) -+ if hal.get_value("spindle.0.on") or hal.get_value("spindle.1.on"): -+ fail("a spindle remained enabled after program completion") -+ -+ -+def run_css_stop_resume_test(): -+ open_auto_program("css.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.position[0] < 18.0 -+ and s.position[0] > 12.0 -+ and hal.get_value("spindle.0.speed-out") > 0.0, -+ "G96 did not enter active CSS motion", -+ ) -+ speed_before_stop = hal.get_value("spindle.0.speed-out") -+ -+ c.program_stop() -+ wait_complete("G96 stop command did not complete") -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not enter STOPPED during G96", -+ ) -+ if abs(hal.get_value("spindle.0.speed-out")) > 0.001: -+ fail("CSS spindle remained active while stopped") -+ -+ stopped_x = s.position[0] -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.position[0] < stopped_x - 0.05 -+ and hal.get_value("spindle.0.speed-out") > 0.0, -+ "G96 motion did not resume with the spindle active", -+ ) -+ wait_for( -+ lambda: hal.get_value("spindle.0.speed-out") > speed_before_stop * 1.02, -+ "G96 spindle speed did not continue tracking diameter after Resume", -+ ) -+ -+ wait_for_program_complete(10.0) -+ assert_outputs_stopped_after_program() -+ -+ -+SCENARIOS = { -+ "idle-rejected": run_idle_program_stop_rejected_test, -+ "ordinary": run_ordinary_stop_resume_test, -+ "single-step": run_stop_single_step_test, -+ "rapid-no-atspeed": run_rapid_resume_without_at_speed_test, -+ "paused-resume": lambda: run_stop_while_program_paused_test(False), -+ "paused-run": lambda: run_stop_while_program_paused_test(True), -+ "abort-empty": run_abort_from_empty_stopped_queue_test, -+ "queued-g33": run_queued_threading_stop_resume_test, -+ "g33": run_threading_stop_resume_test, -+ "fperrev": run_fperrev_stop_resume_test, -+ "g76": run_g76_stop_resume_test, -+ "rigid-tap": run_rigid_tap_stop_resume_test, -+ "orientation": run_spindle_orientation_stop_test, -+ "dwell": run_dwell_stop_resume_test, -+ "multi-spindle": run_multi_spindle_stop_resume_test, -+ "css": run_css_stop_resume_test, -+} -+ -+scenario = os.environ.get("RESUMABLE_STOP_SCENARIO") -+if scenario not in SCENARIOS: -+ fail("unknown resumable-stop scenario: %s" % scenario) -+ -+SCENARIOS[scenario]() -+print("resumable stop scenario ok: %s" % scenario) -+sys.exit(0) -diff --git a/tests/resumable-stop/test.ini b/tests/resumable-stop/test.ini -new file mode 100644 -index 0000000000..b73c0956b5 ---- /dev/null -+++ b/tests/resumable-stop/test.ini -@@ -0,0 +1,95 @@ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0x0 -+ -+[DISPLAY] -+DISPLAY = ./test-ui.py -+ -+[RS274NGC] -+PARAMETER_FILE = sim.var -+ -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4.0 -+BASE_PERIOD = 0 -+SERVO_PERIOD = 1000000 -+ -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 -+ -+[HAL] -+HALFILE = core_sim.hal -+ -+[TRAJ] -+NO_FORCE_HOMING = 1 -+AXES = 3 -+COORDINATES = X Y Z -+SPINDLES = 2 -+LINEAR_UNITS = mm -+ANGULAR_UNITS = degree -+PLANNER_TYPE = 1 -+DEFAULT_LINEAR_VELOCITY = 10 -+MAX_LINEAR_VELOCITY = 50 -+MAX_LINEAR_JERK = 5000 -+ -+[EMCIO] -+TOOL_TABLE = tool.tbl -+ -+[KINS] -+KINEMATICS = trivkins -+JOINTS = 3 -+ -+[AXIS_X] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MAX_JERK = 5000 -+ -+[JOINT_0] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MAX_JERK = 5000 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+ -+[AXIS_Y] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MAX_JERK = 5000 -+ -+[JOINT_1] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MAX_JERK = 5000 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+ -+[AXIS_Z] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MAX_JERK = 5000 -+ -+[JOINT_2] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MAX_JERK = 5000 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -diff --git a/tests/resumable-stop/test.ngc b/tests/resumable-stop/test.ngc -new file mode 100644 -index 0000000000..416044b08c ---- /dev/null -+++ b/tests/resumable-stop/test.ngc -@@ -0,0 +1,9 @@ -+G21 G90 -+G0 X0 -+F60 -+S300 M3 -+M8 -+G1 X10 -+M9 -+M5 -+M2 -diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh -new file mode 100755 -index 0000000000..7a9a863436 ---- /dev/null -+++ b/tests/resumable-stop/test.sh -@@ -0,0 +1,42 @@ -+#!/bin/bash -e -+ -+set -o pipefail -+ -+if nm -D -u "$EMC2_HOME/rtlib/motmod.so" | grep -q '[[:space:]]tpStop$'; then -+ echo "motmod unexpectedly requires the nonstandard tpStop symbol" >&2 -+ exit 1 -+fi -+ -+scenarios=( -+ idle-rejected -+ ordinary -+ single-step -+ rapid-no-atspeed -+ paused-resume -+ paused-run -+ abort-empty -+ queued-g33 -+ g33 -+ fperrev -+ g76 -+ rigid-tap -+ orientation -+ dwell -+ multi-spindle -+ css -+) -+ -+scenario_log=$(mktemp) -+trap 'rm -f "$scenario_log"' EXIT -+ -+for scenario in "${scenarios[@]}"; do -+ echo "Running resumable-stop scenario: $scenario" -+ : > "$scenario_log" -+ RESUMABLE_STOP_SCENARIO="$scenario" linuxcnc -r test.ini 2>&1 | -+ tee "$scenario_log" -+ if grep -Eq 'ruckig_plan_(position|velocity): invalid limits|Ruckig (velocity control )?planning failed' "$scenario_log"; then -+ echo "$scenario emitted a Ruckig invalid-limit or planning failure" >&2 -+ exit 1 -+ fi -+done -+echo "resumable stop scenarios complete" -diff --git a/tests/resumable-stop/thread.ngc b/tests/resumable-stop/thread.ngc -new file mode 100644 -index 0000000000..5976979e44 ---- /dev/null -+++ b/tests/resumable-stop/thread.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+G0 X0 Z0 -+S6 M3 -+G33 Z-5 K10 -+G1 X10 F60 -+M5 -+M2 -diff --git a/tests/resumable-stop/tool.tbl b/tests/resumable-stop/tool.tbl -new file mode 100644 -index 0000000000..68840ea75c ---- /dev/null -+++ b/tests/resumable-stop/tool.tbl -@@ -0,0 +1 @@ -+T1 P1 Z0 D0 diff --git a/linuxcnc-patches/0005-headless-build-option.patch b/linuxcnc-patches/0005-headless-build-option.patch index 35443936..473948df 100644 --- a/linuxcnc-patches/0005-headless-build-option.patch +++ b/linuxcnc-patches/0005-headless-build-option.patch @@ -1,50 +1,80 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: linuxcnc-node maintainers Date: Tue, 21 Jul 2026 20:00:00 +0200 -Subject: [PATCH] Add headless and manpage-free build options +Subject: [PATCH] Complete headless backend-only builds on top of --disable-gui -Add an explicit backend-only build mode and make manpage generation -independently optional. Keep the default GUI and documentation behaviour -unchanged, while allowing minimal images to build without graphical stacks or -Asciidoctor. +Upstream's --disable-gui and --disable-manpages configure options provide +the headless build itself. Fill in what a backend-only installation +still needs on top of them: + +- Without a GUI, Tcl is optional instead of skipped: when tclConfig.sh is + found, the Tcl HAL and LinuxCNC bindings (tcl/hal.so, tcl/linuxcnc.so, + built without Tk and Xinerama) and the Tcl runtime used by haltcl, .tcl + HAL files and [HAL]TWOPASS are built and installed. Tk, X11 and the GUI + runtime checks are still never needed. +- The desktop menu entries, which start GUI programs, are not installed. +- The launcher requires an explicit INI path instead of starting the + graphical configuration picker, keeps its output on stdout and stderr + when not attached to a terminal, and never runs wish, while still + executing an external [DISPLAY] DISPLAY command. +- The Debian build profile pkg.linuxcnc.headless configures with + --disable-gui, uses a backend-only package manifest and drops the GUI + build and runtime dependencies; the nodoc profile configures with + --disable-build-documentation --disable-manpages, skips manpage + installation and no longer needs asciidoctor. + +Builds without these options or profiles are unchanged. --- - debian/configure | 19 ++++- - debian/control.main-pkg.in | 24 +----- - debian/control.top.in | 63 +++++++-------- - debian/linuxcnc-headless.install.in | 3 + - debian/rules.in | 14 ++++ - scripts/linuxcnc.in | 16 ++-- - src/Makefile | 70 ++++++++++++++++- - src/Makefile.inc.in | 3 +- - src/configure.ac | 76 ++++++++++++++++--- - src/emc/usr_intf/Submakefile | 4 +- - src/emc/usr_intf/axis/Submakefile | 12 ++- - src/emc/usr_intf/axis/extensions/emcmodule.cc | 9 +++ - src/emc/usr_intf/emcsh.cc | 7 +- - src/hal/components/Submakefile | 2 + - src/hal/user_comps/Submakefile | 5 ++ - 15 files changed, 250 insertions(+), 77 deletions(-) + debian/.gitignore | 1 + + debian/configure | 19 ++++++- + debian/control.main-pkg.in | 22 +------- + debian/control.top.in | 67 ++++++++++++----------- + debian/linuxcnc-headless.install.in | 16 ++++++ + debian/linuxcnc-headless.not-installed.in | 4 ++ + debian/rules.in | 29 ++++++++++ + scripts/linuxcnc.in | 18 ++++-- + src/Makefile | 20 +++++-- + src/Makefile.inc.in | 1 + + src/configure.ac | 54 +++++++++++------- + src/emc/usr_intf/Submakefile | 10 +++- + src/emc/usr_intf/emcsh.cc | 8 +++ + src/hal/utils/Submakefile | 4 +- + 14 files changed, 187 insertions(+), 86 deletions(-) create mode 100644 debian/linuxcnc-headless.install.in + create mode 100644 debian/linuxcnc-headless.not-installed.in +diff --git a/debian/.gitignore b/debian/.gitignore +index 7654817..0f88137 100644 +--- a/debian/.gitignore ++++ b/debian/.gitignore +@@ -13,6 +13,7 @@ linuxcnc-doc-*/ + # generated from `.in` by debian/configure + linuxcnc-uspace.install + linuxcnc-uspace.manpages ++not-installed + + *.debhelper + shlibs.local diff --git a/debian/configure b/debian/configure -index 096b3f4a5e..7eed1f95eb 100755 +index 096b3f4..da87935 100755 --- a/debian/configure +++ b/debian/configure -@@ -122,6 +122,13 @@ TCLTK_VERSION=8.6 +@@ -122,6 +122,14 @@ TCLTK_VERSION=8.6 PYTHON_IMAGING=python3-pil PYTHON_IMAGING_TK=python3-pil.imagetk QTVCP_DEPENDS="python3-qtpy,\n python3-pyqt5,\n python3-pyqt5.qsci,\n python3-pyqt5.qtsvg,\n python3-pyqt5.qtopengl,\n python3-opencv,\n python3-dbus,\n python3-espeak,\n python3-dbus.mainloop.pyqt5,\n python3-pyqt5.qtwebengine,\n espeak-ng,\n pyqt5-dev-tools,\n gstreamer1.0-tools,\n espeak,\n sound-theme-freedesktop" ++# Runtime packages that only LinuxCNC's GUIs need. The pkg.linuxcnc.headless ++# build profile (configure --disable-gui) does not depend on them. +GUI_RUNTIME_DEPENDS="blt,\n mesa-utils,\n python3-tk,\n python3-cairo,\n python3-gi-cairo,\n python3-opengl,\n python3-configobj,\n python3-xlib,\n libgtksourceview-4-dev,\n tk@TCLTK_VERSION@,\n bwidget (>= 1.7),\n tclx,\n $QTVCP_DEPENDS" -+GUI_RUNTIME_RECOMMENDS="Recommends:\n linuxcnc-doc-en | linuxcnc-doc,\n librsvg2-dev,\n x11-xserver-utils,\n $EXTRA_RECOMMENDS,\n $PYTHON_IMAGING,\n $PYTHON_IMAGING_TK" ++GUI_RUNTIME_RECOMMENDS="linuxcnc-doc-en | linuxcnc-doc,\n librsvg2-dev,\n x11-xserver-utils,\n $PYTHON_IMAGING,\n $PYTHON_IMAGING_TK" +if [[ " ${DEB_BUILD_PROFILES:-} " == *" pkg.linuxcnc.headless "* ]]; then + GUI_RUNTIME_DEPENDS='' + GUI_RUNTIME_RECOMMENDS='' -+ PYTHON_IMAGING='' +fi YAPPS_RUNTIME="python3-yapps" DEBHELPER="debhelper (>= 12)" COMPAT="12" -@@ -172,6 +179,8 @@ sed \ +@@ -172,6 +180,8 @@ sed \ -e "s#@DOC_DEPENDS@#$DOC_DEPENDS#g" \ -e "s#@EXTRA_BUILD@#$EXTRA_BUILD#g" \ -e "s#@EXTRA_RECOMMENDS@#$EXTRA_RECOMMENDS#g" \ @@ -53,31 +83,27 @@ index 096b3f4a5e..7eed1f95eb 100755 -e "s#@KERNEL_DEPENDS@#$KERNEL_DEPENDS#g" \ -e "s#@KERNEL_DEPENDS_BUILD@#$KERNEL_DEPENDS_BUILD#g" \ -e "s#@KERNEL_HEADERS@#$KERNEL_HEADERS#g" \ -@@ -208,10 +217,18 @@ subst control.top.in > control - +@@ -209,7 +219,14 @@ subst control.top.in > control echo >> control subst control.main-pkg.in >> control -+printf '\n' >> control - subst linuxcnc.install.in > ${MAIN_PACKAGE_NAME}.install - subst linuxcnc.lintian-overrides.in > ${MAIN_PACKAGE_NAME}.lintian-overrides --subst linuxcnc.manpages.in > ${MAIN_PACKAGE_NAME}.manpages +-subst linuxcnc.install.in > ${MAIN_PACKAGE_NAME}.install +if [[ " ${DEB_BUILD_PROFILES:-} " == *" pkg.linuxcnc.headless "* ]]; then + subst linuxcnc-headless.install.in > ${MAIN_PACKAGE_NAME}.install -+fi -+if [[ " ${DEB_BUILD_PROFILES:-} " != *" nodoc "* ]]; then -+ subst linuxcnc.manpages.in > ${MAIN_PACKAGE_NAME}.manpages ++ # GUI assets the build still installs but the headless package omits ++ subst linuxcnc-headless.not-installed.in > not-installed +else -+ rm -f ${MAIN_PACKAGE_NAME}.manpages ++ subst linuxcnc.install.in > ${MAIN_PACKAGE_NAME}.install ++ rm -f not-installed +fi + subst linuxcnc.lintian-overrides.in > ${MAIN_PACKAGE_NAME}.lintian-overrides + subst linuxcnc.manpages.in > ${MAIN_PACKAGE_NAME}.manpages - subst rules.in > rules - chmod +x rules diff --git a/debian/control.main-pkg.in b/debian/control.main-pkg.in -index 56653dc082..9b0f41b9f7 100644 +index e964cbb..7017e20 100644 --- a/debian/control.main-pkg.in +++ b/debian/control.main-pkg.in -@@ -13,32 +13,13 @@ Depends: +@@ -13,32 +13,16 @@ Depends: ${shlibs:Depends}, @KERNEL_DEPENDS@, @MODUTILS_DEPENDS@, @@ -100,28 +126,24 @@ index 56653dc082..9b0f41b9f7 100644 - @QTVCP_DEPENDS@, procps, psmisc, udev --Recommends: + Recommends: - linuxcnc-doc-en | linuxcnc-doc, - librsvg2-dev, - x11-xserver-utils, ++ @GUI_RUNTIME_RECOMMENDS@, + python3-paho-mqtt, - @EXTRA_RECOMMENDS@, - @PYTHON_IMAGING@, - @PYTHON_IMAGING_TK@ --Suggests: -+@GUI_RUNTIME_RECOMMENDS@Suggests: ++ @EXTRA_RECOMMENDS@ + Suggests: mesaflash, python3-poppler-qt5, - onboard -@@ -88,4 +69,3 @@ Description: motion controller for CNC machines and robots - has been used for numerous other applications. - . - This package provides the main package for LinuxCNC. -- diff --git a/debian/control.top.in b/debian/control.top.in -index 0adf912110..eb42b5f3ca 100644 +index f08b047..64b4665 100644 --- a/debian/control.top.in +++ b/debian/control.top.in -@@ -14,57 +14,58 @@ Build-Depends: +@@ -14,63 +14,64 @@ Build-Depends: @EXTRA_BUILD@, groff-base , imagemagick , @@ -160,15 +182,25 @@ index 0adf912110..eb42b5f3ca 100644 psmisc, python3, python3-dev, + python3-pybind11, - python3-tk, - python3-xlib, + python3-tk , + python3-xlib , + tcl, tcl@TCLTK_VERSION@-dev, - tclx, - tk@TCLTK_VERSION@-dev, - xvfb , - x11-xserver-utils , +- x11-utils , ++ tclx , ++ tk@TCLTK_VERSION@-dev , ++ xvfb , ++ x11-xserver-utils , ++ x11-utils , + gdb , +- imagemagick , - python3-opengl , - python3-pyqt5 , - python3-pyqt5.qsci , @@ -179,15 +211,7 @@ index 0adf912110..eb42b5f3ca 100644 - python3-dbus , - python3-dbus.mainloop.pyqt5 , - python3-qtpy , -- python3-cairo , -- python3-gi , -- python3-gi-cairo , -- gir1.2-gtk-3.0 , -- gir1.2-gtksource-4 , -+ tclx , -+ tk@TCLTK_VERSION@-dev , -+ xvfb , -+ x11-xserver-utils , ++ imagemagick , + python3-opengl , + python3-pyqt5 , + python3-pyqt5.qsci , @@ -198,6 +222,12 @@ index 0adf912110..eb42b5f3ca 100644 + python3-dbus , + python3-dbus.mainloop.pyqt5 , + python3-qtpy , + python3-zmq , +- python3-cairo , +- python3-gi , +- python3-gi-cairo , +- gir1.2-gtk-3.0 , +- gir1.2-gtksource-4 , + python3-cairo , + python3-gi , + python3-gi-cairo , @@ -213,129 +243,169 @@ index 0adf912110..eb42b5f3ca 100644 @DOC_DEPENDS@, diff --git a/debian/linuxcnc-headless.install.in b/debian/linuxcnc-headless.install.in new file mode 100644 -index 0000000000..2660b6ba4a +index 0000000..1491d02 --- /dev/null +++ b/debian/linuxcnc-headless.install.in -@@ -0,0 +1,3 @@ +@@ -0,0 +1,16 @@ ++etc ++ +usr/bin -+usr/lib -+usr/share/linuxcnc ++usr/lib/lib*.so.* ++usr/lib/linuxcnc ++usr/lib/python3 ++usr/share/tcltk ++ ++usr/share/linuxcnc/hallib/ ++usr/share/linuxcnc/linuxcnc_big.nml ++usr/share/linuxcnc/linuxcnc.nml ++usr/share/linuxcnc/ncfiles/ ++ ++usr/share/locale/*/LC_MESSAGES/linuxcnc.mo ++ ++debian/extras/lib /usr +diff --git a/debian/linuxcnc-headless.not-installed.in b/debian/linuxcnc-headless.not-installed.in +new file mode 100644 +index 0000000..c1d5866 +--- /dev/null ++++ b/debian/linuxcnc-headless.not-installed.in +@@ -0,0 +1,4 @@ ++usr/share/linuxcnc/linuxcnc-wizard.gif ++usr/share/linuxcnc/linuxcnc.gif ++usr/share/linuxcnc/linuxcncicon.png ++usr/share/locale/*/LC_MESSAGES/gmoccapy.mo diff --git a/debian/rules.in b/debian/rules.in -index 50b52e8ff6..467ec47631 100644 +index a7cf564..dee33e7 100644 --- a/debian/rules.in +++ b/debian/rules.in -@@ -32,6 +32,12 @@ export TIME:=$(shell LANG=C date --date='@$(TIMESTAMP)' '+%T') +@@ -32,6 +32,15 @@ export TIME:=$(shell LANG=C date --date='@$(TIMESTAMP)' '+%T') kernel_version = @KERNEL_VERSION@ configure_realtime_arg = @CONFIGURE_REALTIME_ARG@ ++# Build profiles: pkg.linuxcnc.headless builds without LinuxCNC's GUIs (run ++# debian/configure with the same DEB_BUILD_PROFILES so the package manifest ++# and dependencies match); nodoc builds neither documentation nor manpages. +ifneq (,$(filter pkg.linuxcnc.headless,$(DEB_BUILD_PROFILES))) -+enable_headless = --enable-headless ++configure_profile_args += --disable-gui +endif +ifneq (,$(filter nodoc,$(DEB_BUILD_PROFILES))) -+disable_docs = --disable-build-documentation --disable-build-manpages ++configure_profile_args += --disable-build-documentation --disable-manpages +endif ifeq (,$(filter nodocs,$(DEB_BUILD_OPTIONS))) enable_build_documentation = @ENABLE_BUILD_DOCUMENTATION@ \ --enable-build-documentation-translation -@@ -51,6 +57,8 @@ override_dh_auto_configure: - --prefix=/usr --sysconfdir=/etc \ +@@ -52,6 +61,7 @@ override_dh_auto_configure: --mandir=/usr/share/man \ $(configure_realtime_arg) \ -+ $(enable_headless) \ -+ $(disable_docs) \ $(enable_build_documentation) \ ++ $(configure_profile_args) \ --disable-check-runtime-deps -@@ -83,12 +91,15 @@ override_dh_auto_install-arch: + override_dh_auto_build-arch: +@@ -83,7 +93,9 @@ override_dh_auto_install-arch: DESTDIR=$(DESTDIR) $(MAKE) -C src install-software py3clean . +ifeq (,$(filter pkg.linuxcnc.headless,$(DEB_BUILD_PROFILES))) desktop-file-validate $(shell find debian/extras/ share/applications/ -name *.desktop); ++endif # some clean-up rm -f $(DESTDIR)/usr/share/doc/@MAIN_PACKAGE_NAME@/examples/sample-configs/*/*position*.txt -+endif - - override_dh_installdocs-arch: -+ifeq (,$(filter pkg.linuxcnc.headless,$(DEB_BUILD_PROFILES))) - # Sample configs are runtime data read by the launcher, not documentation, - # so they must be installed unconditionally (i.e. regardless of - # DEB_BUILD_OPTIONS=nodocs). They go in `usr/share/doc/linuxcnc` (not -@@ -99,6 +110,9 @@ override_dh_installdocs-arch: +@@ -96,7 +108,12 @@ override_dh_installdocs-arch: + # script looks for them, and that's inconvenient to change. + dh_installdocs --doc-main-package=@MAIN_PACKAGE_NAME@ --package=@MAIN_PACKAGE_NAME@ + mkdir -p debian/@MAIN_PACKAGE_NAME@/usr/share/doc/linuxcnc ++ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES))) mv debian/@MAIN_PACKAGE_NAME@/usr/share/doc/@MAIN_PACKAGE_NAME@/examples debian/@MAIN_PACKAGE_NAME@/usr/share/doc/linuxcnc ++else ++ # dh_installdocs installs no .docs entries under the nodoc build profile. ++ cp -a $(DESTDIR)/usr/share/doc/linuxcnc/examples debian/@MAIN_PACKAGE_NAME@/usr/share/doc/linuxcnc ++endif dh_installdocs --doc-main-package=@MAIN_PACKAGE_NAME@ --package=@MAIN_PACKAGE_NAME@-dev -+else -+ dh_installdocs --doc-main-package=@MAIN_PACKAGE_NAME@ --package=@MAIN_PACKAGE_NAME@-dev + +@@ -139,6 +156,18 @@ else + $(RM) -fr debian/tmp/usr/share/doc/ + endif + ++override_dh_install: ++ dh_install ++ifneq (,$(filter pkg.linuxcnc.headless,$(DEB_BUILD_PROFILES))) ++ # The headless manifest installs all of usr/bin; halcompile belongs to -dev. ++ rm -f debian/@MAIN_PACKAGE_NAME@/usr/bin/halcompile +endif ++ ++override_dh_installman: ++ifeq (,$(filter nodoc,$(DEB_BUILD_PROFILES))) ++ dh_installman ++endif ++ + override_dh_compress: + dh_compress -X.pdf -X.txt -X.hal -X.ini -X.clp -X.var -X.nml -X.tbl -X.xml -Xsample-configs - override_dh_auto_install-indep: - ifeq (,$(filter nodocs,$(DEB_BUILD_OPTIONS))) diff --git a/scripts/linuxcnc.in b/scripts/linuxcnc.in -index 789b9de0ec..3eaca77e7b 100644 +index 3ab645d..027e3b3 100644 --- a/scripts/linuxcnc.in +++ b/scripts/linuxcnc.in -@@ -27,7 +27,8 @@ fi - # Force pyopengl (python3-opengl) to use its GLX backend, even - # if we're running on Wayland where it would normally use EGL. - # Similar for the Gtk and Qt backends. --if [[ ! -v LINUXCNC_OPENGL_PLATFORM || "${LINUXCNC_OPENGL_PLATFORM}" == "glx" ]]; then -+BUILD_HEADLESS=@BUILD_HEADLESS@ -+if [ "$BUILD_HEADLESS" != yes ] && { [[ ! -v LINUXCNC_OPENGL_PLATFORM ]] || [[ "${LINUXCNC_OPENGL_PLATFORM}" == "glx" ]]; }; then - export PYOPENGL_PLATFORM="x11" - export GDK_BACKEND="x11" - export QT_QPA_PLATFORM="xcb" -@@ -127,7 +128,7 @@ Usage: +@@ -47,6 +47,8 @@ PS=@PS@ + AWK=@AWK@ + GREP=@GREP@ + KILL=@KILL@ ++# "no" in a build configured with --disable-gui ++BUILD_GUI=@BUILD_GUI@ + + LINUXCNC_HOME=@EMC2_HOME@; export LINUXCNC_HOME + +@@ -127,7 +129,7 @@ Usage: This help $ $P [Options] - Choose the configuration INI file graphically -+ Choose the configuration INI file graphically (non-headless builds only) ++ Choose the configuration INI file graphically (not in builds without a GUI) $ $P [Options] path/to/your_ini_file Name the configuration INI file using its path -@@ -235,7 +236,7 @@ EOF +@@ -235,7 +237,9 @@ EOF fi esac -if [ -z "$RUNTESTS" ]; then -+if [ -z "$RUNTESTS" ] && [ "$BUILD_HEADLESS" != yes ]; then ++# Without a GUI there is no error dialog to show the logs, so output always ++# goes to stdout/stderr (e.g. a service manager or container log). ++if [ -z "$RUNTESTS" ] && [ "$BUILD_GUI" = yes ]; then if ! tty -s; then exec 2>> "$DEBUG_FILE" exec >> "$PRINT_FILE" -@@ -246,7 +247,7 @@ fi +@@ -246,12 +250,12 @@ fi # shellcheck disable=SC2317,SC2329 function ErrorCheck () { result=$? - if [ -n "$DISPLAY" ]; then -+ if [ "$BUILD_HEADLESS" != yes ] && [ -n "$DISPLAY" ]; then ++ if [ "$BUILD_GUI" = yes ] && [ -n "$DISPLAY" ]; then echo "catch {send -async popimage destroy .}; destroy ." | @WISH@ fi -@@ -344,6 +345,11 @@ if [ -n "$USE_LAST_INIFILE" ]; then + if [ "$result" -ne 0 ]; then +- if tty -s || [ -z "$DISPLAY" ] ; then ++ if tty -s || [ -z "$DISPLAY" ] || [ "$BUILD_GUI" != yes ]; then + if [ -f "$DEBUG_FILE" ]; then + cp "$DEBUG_FILE" "$HOME/linuxcnc_debug.txt" + else +@@ -343,6 +347,12 @@ if [ -n "$USE_LAST_INIFILE" ]; then + echo "Using previous INI file: $INIFILE" >> "$PRINT_FILE" fi ++if [ -z "$INIFILE" ] && [ "$BUILD_GUI" != yes ]; then ++ echo "LinuxCNC was built without a GUI and needs an explicit INI file path." >&2 ++ usage >&2 ++ exit 2 ++fi ++ if [ -z "$INIFILE" ] ; then -+ if [ "$BUILD_HEADLESS" = yes ]; then -+ echo "A headless LinuxCNC build requires an explicit INI file path." >&2 -+ usage >&2 -+ exit 2 -+ fi # nothing specified, get from the user # it returns either a path, or nothing at all - INIFILE=$($PICKCONFIG) -@@ -771,7 +777,7 @@ imgtime=$($INIVAR -ini "$INIFILE" -var INTRO_TIME -sec DISPLAY 2>> "$DEBUG_FILE" - if [ "$imgtime" = "" ] ; then - imgtime=5 - fi --if [ "$img" != "" ] ; then -+if [ "$BUILD_HEADLESS" != yes ] && [ "$img" != "" ] ; then - if [ -e "$img" ]; then - true - elif [ -e "$INI_DIR/$img" ]; then diff --git a/src/Makefile b/src/Makefile -index 482d453198..35c77b38ac 100644 +index 927b122..af616fb 100644 --- a/src/Makefile +++ b/src/Makefile @@ -24,7 +24,7 @@ default: build-software @@ -343,7 +413,7 @@ index 482d453198..35c77b38ac 100644 install: install-software install-docs -install-software: install-kernel-dep install-kernel-indep install-menu -+install-software: ++install-software: install-kernel-dep install-kernel-indep ifeq ($(origin KERNELRELEASE), undefined) #MAKEFLAGS += --warn-undefined-variables @@ -351,219 +421,116 @@ index 482d453198..35c77b38ac 100644 $(error Makefile.inc must specify RTPREFIX and other variables) endif -+ifeq ($(BUILD_HEADLESS),yes) -+install-software: install-kernel-dep install-headless -+else -+install-software: install-kernel-dep install-kernel-indep install-menu ++# The desktop menu entries launch GUI programs, so a build without a GUI ++# does not install them. ++ifeq ($(BUILD_GUI),yes) ++install-software: install-menu +endif + ifeq ($(TOOL_NML),yes) TOOL_NML_FLAG := -DTOOL_NML $(info TOOL_NML_FLAG =$(TOOL_NML_FLAG)) -@@ -201,6 +207,15 @@ SUBDIRS := \ - \ - ../tests \ - -+ifeq ($(BUILD_HEADLESS),yes) -+# Keep backend and language bindings but omit bundled visual frontends. -+SUBDIRS := $(filter-out \ -+ hal/user_comps/vismach hal/classicladder \ -+ emc/usr_intf/touchy emc/usr_intf/stepconf emc/usr_intf/pncconf \ -+ emc/usr_intf/gremlin emc/usr_intf/gscreen emc/usr_intf/pyui \ -+ emc/usr_intf/qtvcp emc/usr_intf/gmoccapy emc/usr_intf/qtplasmac \ -+ emc/usr_intf/mdro,$(SUBDIRS)) -+endif - - - ULAPISRCS := rtapi/$(RTPREFIX)_ulapi.c -@@ -226,6 +241,14 @@ TOOBJSDEPS = $(call TOOBJS,$(1)) $(call TODEPS, $(1)) $(patsubst %.cpp,%.ii,$(pa - SUBMAKEFILES := $(patsubst %,%/Submakefile,$(SUBDIRS)) - -include $(wildcard $(SUBMAKEFILES)) - -+ifeq ($(BUILD_MANPAGES),no) -+TARGETS := $(filter-out manpages ../docs/man/%,$(TARGETS)) -+GENERATED_MANPAGES := -+endif -+ifeq ($(BUILD_HEADLESS),yes) -+TARGETS := $(filter-out %/gmoccapy.mo,$(TARGETS)) -+endif -+ - # This checks that all the things listed in USERSRCS are either C files - # or C++ files - ASSERT_EMPTY = $(if $(1), $(error "Should be empty but is not: $(1)")) -@@ -441,8 +464,9 @@ TARGETS += headers - - # Add converting of %.po files - TARGETS += $(patsubst po/%.po, ../share/locale/%/LC_MESSAGES/linuxcnc.mo, $(wildcard po/*.po)) --TARGETS += $(patsubst po/gmoccapy/%.po, ../share/locale/%/LC_MESSAGES/gmoccapy.mo, $(wildcard po/gmoccapy/*.po)) - TARGETS += $(patsubst po/%.po, objects/%.msg, $(wildcard po/*.po)) -+ifneq ($(BUILD_HEADLESS),yes) -+TARGETS += $(patsubst po/gmoccapy/%.po, ../share/locale/%/LC_MESSAGES/gmoccapy.mo, $(wildcard po/gmoccapy/*.po)) - - # tooledit as standalone app: - TARGETS += ../bin/tooledit -@@ -487,6 +511,7 @@ TARGETS += ../bin/halshow - $(Q)(echo "#!$(TCLSH)")>|$@ - $(Q)(echo "source $(EMC2_TCL_LIB_DIR)/bin/halshow.tcl")>>$@ - $(Q)chmod +x $@ -+endif - - # And make userspace depend on $(TARGETS) - userspace: $(TARGETS) -@@ -678,10 +703,51 @@ install-dirs: - $(DESTDIR)$(datadir)/linuxcnc/pncconf/pncconf-help \ - $(DESTDIR)$(datadir)/linuxcnc/hallib - -+ifeq ($(BUILD_HEADLESS),yes) -+# An explicit allowlist prevents newly-added GUI assets or samples from -+# accidentally entering the backend package. -+install-headless-dirs: -+ $(DIR) $(DESTDIR)$(EMC2_RTLIB_DIR) $(DESTDIR)$(sysconfdir)/linuxcnc \ -+ $(DESTDIR)$(bindir) $(DESTDIR)$(libdir) $(DESTDIR)/$(libdir)/linuxcnc \ -+ $(DESTDIR)$(includedir)/linuxcnc $(DESTDIR)$(tcldir) \ -+ $(DESTDIR)$(tcldir)/msgs $(DESTDIR)$(datadir)/linuxcnc/hallib \ -+ $(DESTDIR)$(mandir)/man1 $(DESTDIR)$(mandir)/man3 $(DESTDIR)$(mandir)/man9 -+ -+install-headless: install-headless-dirs -+ $(FILE) objects/*.msg $(DESTDIR)$(tcldir)/msgs -+ $(EXE) ../scripts/realtime $(DESTDIR)$(prefix)/lib/linuxcnc -+ $(EXE) ../scripts/halrun ../scripts/halcmd_twopass ../scripts/haltcl $(DESTDIR)$(bindir) -+ $(FILE) ../lib/hallib/* $(DESTDIR)$(datadir)/linuxcnc/hallib -+ $(EXE) $(filter-out ../bin/rtapi_app ../bin/linuxcnc_module_helper ../bin/pci_write ../bin/pci_read ../bin/test_rtapi_vsnprintf, $(filter ../bin/%,$(TARGETS))) $(DESTDIR)$(bindir) -+ $(EXE) ../scripts/linuxcnc ../scripts/linuxcnc_info ../scripts/linuxcnc_var $(DESTDIR)$(bindir) -+ $(EXE) ../bin/linuxcnc_check_ini $(DESTDIR)$(bindir) -+ $(FILE) $(filter ../lib/%.a ../lib/%.so.0 ../lib/%.so.1,$(TARGETS)) $(DESTDIR)$(libdir) -+ cp --no-dereference $(wildcard ../lib/*.so) $(DESTDIR)$(libdir) -+ $(FILE) ../lib/linuxcnc/canterp.so $(DESTDIR)$(libdir)/linuxcnc/ -+ $(FILE) $(HEADERS) $(DESTDIR)$(includedir)/linuxcnc/ -+ $(FILE) Makefile.modinc $(DESTDIR)$(datadir)/linuxcnc -+ $(FILE) ../tcl/hal.so ../tcl/linuxcnc.so ../tcl/linuxcnc.tcl \ -+ ../tcl/pkgIndex.tcl ../tcl/twopass.tcl $(DESTDIR)$(tcldir) -+ $(FILE) ../configs/common/linuxcnc.nml ../configs/common/linuxcnc_big.nml $(DESTDIR)$(datadir)/linuxcnc -+ $(FILE) ../src/hal/drivers/mesa-hostmot2/modbus/*.tmpl $(DESTDIR)$(datadir)/linuxcnc/ -+ $(DIR) $(DESTDIR)$(SITEPY) $(DESTDIR)$(SITEPY)/rs274 -+ $(FILE) ../lib/python/linuxcnc.so ../lib/python/_hal.so ../lib/python/gcode.so \ -+ ../lib/python/hal.py ../lib/python/linuxcnc_util.py ../lib/python/nf.py \ -+ ../lib/python/pyhal.py ../lib/python/raster.py ../lib/python/tooldb.py $(DESTDIR)$(SITEPY) -+ $(FILE) ../lib/python/rs274/*.py $(DESTDIR)$(SITEPY)/rs274 -+ifneq ($(BUILD_MANPAGES),no) -+ $(FILE) ../docs/man/man1/*.1 $(DESTDIR)$(mandir)/man1 -+ $(FILE) $(wildcard ../docs/man/man3/*.3) $(DESTDIR)$(mandir)/man3 -+ $(FILE) $(wildcard ../docs/man/man9/*.9) $(DESTDIR)$(mandir)/man9 -+endif -+endif -+ - install-kernel-indep: install-dirs -+ifneq ($(BUILD_MANPAGES),no) - $(FILE) ../docs/man/man1/*.1 $(DESTDIR)$(mandir)/man1 - $(FILE) $(wildcard ../docs/man/man3/*.3) $(DESTDIR)$(mandir)/man3 - $(FILE) $(wildcard ../docs/man/man9/*.9) $(DESTDIR)$(mandir)/man9 -+endif +@@ -705,7 +711,7 @@ ifeq ($(BUILD_MANPAGES),yes) + $(FILE) $(wildcard ../docs/build/man/man3/*.3) $(DESTDIR)$(mandir)/man3 + $(FILE) $(wildcard ../docs/build/man/man9/*.9) $(DESTDIR)$(mandir)/man9 + endif +-ifeq ($(BUILD_GUI),yes) ++ifeq ($(BUILD_TCL),yes) $(FILE) objects/*.msg $(DESTDIR)$(tcldir)/msgs + endif $(EXE) ../scripts/realtime $(DESTDIR)$(prefix)/lib/linuxcnc - $(EXE) ../scripts/halrun $(DESTDIR)$(bindir) +@@ -753,12 +759,16 @@ endif + ifeq ($(BUILD_GUI),yes) + $(EXE) $(TCL) $(DESTDIR)$(tcldir) + $(FILE) ../tcl/TkLinuxCNC $(DESTDIR)/etc/X11/app-defaults +- $(FILE) ../tcl/hal.so $(DESTDIR)$(tcldir) +- $(FILE) ../tcl/linuxcnc.so $(DESTDIR)$(tcldir) +- $(FILE) ../tcl/pkgIndex.tcl $(DESTDIR)$(tcldir) + $(EXE) $(TCL_BIN) $(DESTDIR)$(tcldir)/bin + $(FILE) ../tcl/scripts/balloon.tcl ../tcl/scripts/emchelp.tcl $(DESTDIR)$(tcldir)/scripts + $(EXE) ../tcl/scripts/Set_Coordinates.tcl $(DESTDIR)$(tcldir)/scripts ++else ifeq ($(BUILD_TCL),yes) ++ # Without a GUI only the Tcl runtime that haltcl, .tcl HAL files and ++ # [HAL]TWOPASS use is installed. ++ $(EXE) ../tcl/linuxcnc.tcl ../tcl/twopass.tcl $(DESTDIR)$(tcldir) ++endif ++ifeq ($(BUILD_TCL),yes) ++ $(FILE) ../tcl/hal.so ../tcl/linuxcnc.so ../tcl/pkgIndex.tcl $(DESTDIR)$(tcldir) + endif + ifeq ($(BUILD_GUI),yes) + $(FILE) ../share/linuxcnc/*.glade $(DESTDIR)$(prefix)/share/linuxcnc diff --git a/src/Makefile.inc.in b/src/Makefile.inc.in -index 848adcbd28..b88d758f19 100644 +index ffaaa80..3e21a48 100644 --- a/src/Makefile.inc.in +++ b/src/Makefile.inc.in -@@ -80,6 +80,8 @@ RTFLAGS := -I. -I@RTDIR@/include $(RTFLAGS) -DRTAPI -D_GNU_SOURCE -Drealtime - ULFLAGS = -Wall -g -I. -I@RTDIR@/include -DULAPI -D_GNU_SOURCE -O2 -DLOCALE_DIR=\"$(localedir)\" -DPACKAGE=\"$(package)\" +@@ -81,6 +81,7 @@ ULFLAGS = -Wall -g -I. -I@RTDIR@/include -DULAPI -D_GNU_SOURCE -O2 -DLOCALE_DIR= MODULE_EXT = @MODEXT@ BUILD_SYS = @BUILD_SYS@ -+BUILD_HEADLESS = @BUILD_HEADLESS@ -+BUILD_MANPAGES = @BUILD_MANPAGES@ + BUILD_GUI = @BUILD_GUI@ ++BUILD_TCL = @BUILD_TCL@ CC = @CC@ MANDB = @MANDB@ HIDRAW_H_USABLE = @HIDRAW_H_USABLE@ -@@ -250,4 +252,3 @@ PYTHON_LIBS=@PYTHON_LIBS@ - SITEPY=@SITEPY@ - YAPPS=@YAPPS@ - #### END CONFIG #### -- diff --git a/src/configure.ac b/src/configure.ac -index eceb78329b..c1289732f6 100644 +index 88d7959..901de31 100644 --- a/src/configure.ac +++ b/src/configure.ac -@@ -802,6 +802,19 @@ else +@@ -817,7 +817,7 @@ fi + + + AC_ARG_ENABLE(gui, +- AS_HELP_STRING([--disable-gui], [Disable building graphical user interfaces (Tk, Tcl, X11, Xinerama, GTK)]), ++ AS_HELP_STRING([--disable-gui], [Disable building graphical user interfaces (Tk, X11, Xinerama, GTK); the Tcl bindings are still built if Tcl is found]), + [BUILD_GUI=$enableval], + [BUILD_GUI=yes]) + AC_SUBST([BUILD_GUI]) +@@ -1383,8 +1383,13 @@ AH_BOTTOM(#endif + # Test for tcl/tk headers fails if they are not in /usr/include # + # so testing is done by finding tclConfig.sh and tkConfig.sh # + # if the search fails the traditional check is done # ++# # ++# Tcl is required with a GUI. Without one (--disable-gui) Tk, X11 and the # ++# GUI runtime checks are skipped, and Tcl is optional: when tclConfig.sh is # ++# found, the Tcl HAL and LinuxCNC bindings and the Tcl runtime that haltcl, # ++# .tcl HAL files and [HAL]TWOPASS need are still built (BUILD_TCL). # + ############################################################################## +-if test "$BUILD_GUI" = "yes"; then ++BUILD_TCL=no + + AC_MSG_CHECKING([for tcl]) + +@@ -1408,10 +1413,15 @@ if (test "x$TCLCONFIG" = "x"); then fi + if (test "x$TCLCONFIG" = "x"); then ++ if test "$BUILD_GUI" = "yes"; then + AC_MSG_RESULT([tclConfig.sh not found, trying tcl.h and libs. + If it doesn't work try running ./configure --with-tclConfig=]) + AC_CHECK_HEADERS([tcl.h]) + AC_SEARCH_LIBS(Tcl_Init,[tcl tcl8.7 tcl8.6],[],[AC_MSG_ERROR([tcl lib not found])]) ++ BUILD_TCL=yes ++ else ++ AC_MSG_RESULT([tclConfig.sh not found, building without the Tcl bindings]) ++ fi + else + # tclConfig.sh found, + # extracting vars +@@ -1419,8 +1429,31 @@ else + . "$TCLCONFIG" + TCL_CFLAGS="$TCL_INCLUDE_SPEC -DUSE_TCL_STUBS" + TCL_LIBS="$TCL_STUB_LIB_SPEC" ++ BUILD_TCL=yes + fi -+AC_ARG_ENABLE(headless, -+ AS_HELP_STRING( -+ [--enable-headless], -+ [Build the LinuxCNC backend without bundled graphical interfaces, tools, or assets.] -+ ), -+ [BUILD_HEADLESS=$enableval], -+ [BUILD_HEADLESS=no]) -+ -+case "$BUILD_HEADLESS" in -+ yes|no) ;; -+ *) AC_MSG_ERROR([--enable-headless accepts only yes or no]) ;; -+esac -+ - AC_ARG_ENABLE(gtk, - AS_HELP_STRING( - [--disable-gtk], -@@ -817,6 +830,15 @@ AC_ARG_ENABLE(gtk, - ], - [BUILD_GTK=yes]) - -+if test "$BUILD_HEADLESS" = yes && test "$BUILD_GTK" = yes; then -+ if test "${enable_gtk+set}" = set; then -+ AC_MSG_ERROR([--enable-headless conflicts with --enable-gtk]) -+ fi -+ BUILD_GTK=no ++if test "$BUILD_TCL" = "yes"; then ++if test -z "$TCL_MAJOR_VERSION" || test -z "$TCL_MINOR_VERSION" ; then ++ AC_MSG_ERROR([tclConfig was not found or did not export TCL_MAJOR_VERSION/TCL_MINOR_VERSION. Cannot determine exact Tcl version.]) +fi + -+AC_SUBST(BUILD_HEADLESS) -+ - if test "$BUILD_GTK" = "yes"; then - AC_MSG_CHECKING([for GTK 3.22.4 or above]) - if pkg-config gtk+-3.0 --atleast-version 3.22.4 >/dev/null 2>&1; then -@@ -1061,19 +1083,37 @@ AC_ARG_ENABLE(build-documentation, - AC_MSG_RESULT([no]) - ]) - -+AC_MSG_CHECKING([whether to build manpages]) -+AC_ARG_ENABLE(build-manpages, -+ AS_HELP_STRING( -+ [--disable-build-manpages], -+ [Do not generate or install manpages.] -+ ), -+ [BUILD_MANPAGES=$enableval], -+ [BUILD_MANPAGES=yes]) -+case "$BUILD_MANPAGES" in -+ yes|no) AC_MSG_RESULT([$BUILD_MANPAGES]) ;; -+ *) AC_MSG_ERROR([--enable-build-manpages accepts only yes or no]) ;; -+esac -+ - # Programs required for building documentation. Missing PDF-only - # tools or an invalid CJK font are a hard error whenever PDF was - # requested (BUILD_DOCS_PDF=yes -- i.e. anything except - # --enable-build-documentation=html). =html itself warn-and-disables - # only the missing PDF tools; users who want PDF best-effort can pass - # =html and rebuild after installing the missing tools. --# halcompile manpages need asciidoctor regardless of BUILD_DOCS. -+# halcompile manpages need asciidoctor when manpages are enabled. -+if test "$BUILD_DOCS" = yes || test "$BUILD_MANPAGES" = yes; then - AC_PATH_PROG(ASCIIDOCTOR,asciidoctor,"none") --if ( test "none" = "$ASCIIDOCTOR" ) ; then -+if test "none" = "$ASCIIDOCTOR"; then - AC_MSG_ERROR([no asciidoctor, manpages cannot be built - install with "sudo apt-get install asciidoctor" on Debian / Ubuntu, - "sudo dnf install rubygem-asciidoctor" on Fedora, or "gem install asciidoctor"]) - fi -+else -+ ASCIIDOCTOR=none ++if test "(" "$TCL_MAJOR_VERSION" -lt 8 ")" -o "(" "(" "$TCL_MAJOR_VERSION" -eq 8 ")" -a "(" "$TCL_MINOR_VERSION" -lt 4 ")" ")" ; then ++ AC_MSG_ERROR([Tcl version must be 8.4 or better. Your Tcl version ${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION} is too old.]) +fi -+AC_SUBST(BUILD_MANPAGES) - - if ( test "$BUILD_DOCS" = "yes" ) ; then - if ( test "$BUILD_DOCS" = "yes" ) ; then -@@ -1399,6 +1439,15 @@ else - TCL_LIBS="$TCL_STUB_LIB_SPEC" - fi - ++ +if test -f $TCL_EXEC_PREFIX/bin/tclsh$TCL_VERSION; then + TCLSH=$TCL_EXEC_PREFIX/bin/tclsh$TCL_VERSION +elif test -f $TCL_EXEC_PREFIX/bin/tclsh; then @@ -571,12 +538,31 @@ index eceb78329b..c1289732f6 100644 +else + TCLSH=tclsh +fi ++else ++ TCLSH=tclsh ++fi ++AC_SUBST([BUILD_TCL]) + -+if test "$BUILD_HEADLESS" != yes; then ++if test "$BUILD_GUI" = "yes"; then AC_MSG_CHECKING([for tk]) AC_ARG_WITH(tkConfig, -@@ -1461,14 +1510,6 @@ else +@@ -1467,14 +1500,6 @@ Tcl $TCL_VERSION and Tk $TK_VERSION. You can use --with-tkConfig= and --with-tc + to override the autodetected versions.]) + fi + +-if test -z "$TCL_MAJOR_VERSION" || test -z "$TCL_MINOR_VERSION" ; then +- AC_MSG_ERROR([tclConfig was not found or did not export TCL_MAJOR_VERSION/TCL_MINOR_VERSION. Cannot determine exact Tcl version.]) +-fi +- +-if test "(" "$TCL_MAJOR_VERSION" -lt 8 ")" -o "(" "(" "$TCL_MAJOR_VERSION" -eq 8 ")" -a "(" "$TCL_MINOR_VERSION" -lt 4 ")" ")" ; then +- AC_MSG_ERROR([Tcl version must be 8.4 or better. Your Tcl version ${TCL_MAJOR_VERSION}.${TCL_MINOR_VERSION} is too old.]) +-fi +- + if test -f $TCL_EXEC_PREFIX/bin/wish$TCL_VERSION; then + WISH=$TCL_EXEC_PREFIX/bin/wish$TCL_VERSION + elif test -f $TCL_EXEC_PREFIX/bin/wish; then +@@ -1483,14 +1508,6 @@ else WISH=wish fi @@ -591,185 +577,40 @@ index eceb78329b..c1289732f6 100644 AC_ARG_ENABLE(check-runtime-deps, AS_HELP_STRING( [--disable-check-runtime-deps], -@@ -1519,6 +1560,12 @@ if test "$RUNTIME_CHECK" = "yes"; then - install with "sudo apt-get install python3-gi"]) - fi +@@ -1543,7 +1560,6 @@ install with "sudo apt-get install python3-gi"]) fi -+else -+ TK_CFLAGS= -+ TK_LIBS= -+ WISH=false -+ RUNTIME_CHECK=no -+fi - AC_SUBST([TCL_DBGX]) - AC_SUBST([TK_DBGX]) -@@ -1539,6 +1586,7 @@ AC_SUBST([TCLSH]) - # provides DATE in order to output it to the generated files - DATE=$(date) - AC_SUBST([DATE]) -+if test "$BUILD_HEADLESS" != yes; then - AC_PATH_XTRA - #X_CFLAGS gets set - #X_LIBS and X_EXTRA_LIBS likewise -@@ -1557,6 +1605,10 @@ AC_CHECK_LIB(Xinerama, XineramaQueryExtension, - if test "x$HAVE_XINERAMA" = "xno"; then - AC_MSG_ERROR([Xinerama library or headers not found]) - fi -+else -+ X_LIBS= -+ X_CFLAGS= -+fi - - #clean out LIBS - temp_LIBS=$LIBS -@@ -1659,6 +1711,7 @@ then - fi - AC_MSG_RESULT(OK) - -+if test "$BUILD_HEADLESS" != yes; then - AC_MSG_CHECKING([match between tk and Tkinter versions]) - if $PYTHON -c 'import sys;raise SystemExit(sys.hexversion<0x3040000)' - then -@@ -1683,11 +1736,13 @@ if test "$PYTHON_TK_VERSION" != "$TK_VERSION"; then - AC_MSG_ERROR(["Python requires use of Tk $TK_VERSION. Install this version and specify --with-tkConfig if necessary"]) + else +- TCLSH=tclsh + WISH=wish fi - AC_MSG_RESULT([$PYTHON_TK_VERSION]) -+fi - - AC_MSG_CHECKING(for site-package location) - SITEPY=`$PYTHON -c "import sysconfig; s=sysconfig.get_scheme_names(); print(sysconfig.get_path('platlib', 'deb_system' if 'deb_system' in s else 'rpm_prefix' if 'rpm_prefix' in s else sysconfig.get_default_scheme()))"` - AC_MSG_RESULT($SITEPY) - -+if test "$BUILD_HEADLESS" != yes; then - AC_MSG_CHECKING(for working GLU quadrics) - AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ - #include -@@ -1699,6 +1754,7 @@ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ - AC_MSG_CHECKING(for Xmu headers) - AC_CHECK_HEADERS(X11/Xmu/Xmu.h,[],[AC_MSG_ERROR([Required Xmu header missing. Install it, or specify --disable-python to skip the parts of LinuxCNC that depend on Python])]) -+fi - - AC_SUBST([LIBPYTHON]) - AC_SUBST([SITEPY]) diff --git a/src/emc/usr_intf/Submakefile b/src/emc/usr_intf/Submakefile -index b914e30ffe..9927bf5837 100644 +index cb99070..5437969 100644 --- a/src/emc/usr_intf/Submakefile +++ b/src/emc/usr_intf/Submakefile -@@ -18,11 +18,11 @@ HALUISRCS := emc/usr_intf/halui.cc \ +@@ -18,12 +18,16 @@ HALUISRCS := emc/usr_intf/halui.cc \ USERSRCS += $(EMCSHSRCS) $(EMCRSHSRCS) $(EMCSCHEDSRCS) $(EMCLCDSRCS) $(USRMOTSRCS) $(HALUISRCS) -$(call TOOBJSDEPS, $(EMCSHSRCS)) : EXTRAFLAGS = $(ULFLAGS) $(TCL_CFLAGS) -fPIC -+$(call TOOBJSDEPS, $(EMCSHSRCS)) : EXTRAFLAGS = $(ULFLAGS) $(TCL_CFLAGS) -fPIC $(if $(filter yes,$(BUILD_HEADLESS)),-DLINUXCNC_HEADLESS,) ++# Without a GUI the Tcl binding is built without Tk and Xinerama (no ++# "multihead" command) whenever Tcl itself was found. ++$(call TOOBJSDEPS, $(EMCSHSRCS)) : EXTRAFLAGS = $(ULFLAGS) $(TCL_CFLAGS) -fPIC \ ++ $(if $(filter yes,$(BUILD_GUI)),,-DLINUXCNC_HEADLESS) ../tcl/linuxcnc.so: $(call TOOBJS, $(EMCSHSRCS)) ../lib/liblinuxcnc.a ../lib/liblinuxcncini.so.1 ../lib/libnml.so.0 $(ECHO) Linking $(notdir $@) - $(Q)$(CXX) -shared $(LDFLAGS) -o $@ $(ULFLAGS) $(TCL_CFLAGS) $^ $(TCL_LIBS) -lXinerama -+ $(Q)$(CXX) -shared $(LDFLAGS) -o $@ $(ULFLAGS) $(TCL_CFLAGS) $^ $(TCL_LIBS) $(if $(filter yes,$(BUILD_HEADLESS)),,-lXinerama) +-ifeq ($(BUILD_GUI),yes) ++ $(Q)$(CXX) -shared $(LDFLAGS) -o $@ $(ULFLAGS) $(TCL_CFLAGS) $^ $(TCL_LIBS) \ ++ $(if $(filter yes,$(BUILD_GUI)),-lXinerama) ++ifeq ($(BUILD_TCL),yes) TARGETS += ../tcl/linuxcnc.so + endif - ../bin/linuxcncrsh: $(call TOOBJS, $(EMCRSHSRCS)) ../lib/liblinuxcnchal.so.0 ../lib/liblinuxcnc.a ../lib/libnml.so.0 ../lib/liblinuxcncini.so.1 -diff --git a/src/emc/usr_intf/axis/Submakefile b/src/emc/usr_intf/axis/Submakefile -index 3b294a2c91..b69062529a 100644 ---- a/src/emc/usr_intf/axis/Submakefile -+++ b/src/emc/usr_intf/axis/Submakefile -@@ -1,8 +1,13 @@ - - EMCMODULESRCS := emc/usr_intf/axis/extensions/emcmodule.cc -+ifeq ($(BUILD_HEADLESS),yes) -+PYSRCS += $(EMCMODULESRCS) -+$(call TOOBJSDEPS, $(EMCMODULESRCS)) : EXTRAFLAGS += -DLINUXCNC_HEADLESS -+else - TOGLMODULESRCS := emc/usr_intf/axis/extensions/_toglmodule.c - TKDARMODULESRCS := emc/usr_intf/axis/extensions/tkdarmodule.c - PYSRCS += $(EMCMODULESRCS) $(TOGLMODULESRCS) $(TKDARMODULESRCS) -+endif - - EMCMODULE := ../lib/python/linuxcnc.so - TOGLMODULE := ../lib/python/_togl.so -@@ -17,7 +22,7 @@ $(call TOOBJSDEPS, $(TKDARMODULESRCS)) : EXTRAFLAGS = $(TCL_CFLAGS) - $(EMCMODULE): $(call TOOBJS, $(EMCMODULESRCS)) ../lib/liblinuxcnc.a ../lib/libnml.so.0 \ - ../lib/liblinuxcncini.so ../lib/libtooldata.so.0 - $(ECHO) Linking python module $(notdir $@) -- $(Q)$(CXX) $(LDFLAGS) -shared -o $@ $^ -L/usr/X11R6/lib -lm -lepoxy -+ $(Q)$(CXX) $(LDFLAGS) -shared -o $@ $^ -lm $(if $(filter yes,$(BUILD_HEADLESS)),,-lepoxy) - - $(TOGLMODULE): $(call TOOBJS, $(TOGLMODULESRCS)) - $(ECHO) Linking python module $(notdir $@) -@@ -27,7 +32,9 @@ $(TKDARMODULE): $(call TOOBJS, $(TKDARMODULESRCS)) - $(ECHO) Linking python module $(notdir $@) - $(Q)$(CC) $(LDFLAGS) -shared -o $@ $(TCL_CFLAGS) $^ -lX11 $(TCL_LIBS) - --PYTARGETS += $(EMCMODULE) $(TOGLMODULE) $(TKDARMODULE) -+PYTARGETS += $(EMCMODULE) -+ifneq ($(BUILD_HEADLESS),yes) -+PYTARGETS += $(TOGLMODULE) $(TKDARMODULE) - - PYSCRIPTS := axis.py axis-remote.py linuxcnctop.py hal_manualtoolchange.py \ - mdi.py image-to-gcode.py lintini.py debuglevel.py teach-in.py tracking-test.py -@@ -44,3 +51,4 @@ $(PYBIN): ../bin/%: emc/usr_intf/axis/scripts/%.py - PYI18NSRCS += $(addprefix emc/usr_intf/axis/scripts/, $(PYSCRIPTS)) \ - ../lib/python/propertywindow.py \ - ../share/axis/tcl/axis.tcl -+endif -diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index 750663187b..5f47d78ec1 100644 ---- a/src/emc/usr_intf/axis/extensions/emcmodule.cc -+++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -39,8 +39,10 @@ - - #include - -+#ifndef LINUXCNC_HEADLESS - #include - #include -+#endif - #include - - using namespace linuxcnc; -@@ -2597,6 +2599,7 @@ static PyTypeObject Error_Type = { - #define AXIS_MASK_A 0x08 - #define AXIS_MASK_B 0x10 - #define AXIS_MASK_C 0x20 -+#ifndef LINUXCNC_HEADLESS - static struct rotation_offsets { - double x; - double y; -@@ -3332,14 +3335,18 @@ static PyTypeObject PositionLoggerType = { - #endif - }; - -+#endif -+ - static PyMethodDef emc_methods[] = { - #define METH(name, doc) { #name, (PyCFunction) py##name, METH_VARARGS, doc } -+#ifndef LINUXCNC_HEADLESS - METH(draw_lines, "Draw a bunch of lines in the 'rs274.glcanon' format"), - METH(draw_dwells, "Draw a bunch of dwell positions in the 'rs274.glcanon' format"), - METH(line9, "Draw a single line in the 'rs274.glcanon' format; assumes glBegin(GL_LINES)"), - METH(vertex9, "Get the 3d location for a 9d point"), - METH(gui_rot_offsets, "Set x,y,z offsets for A,B,C rotations"), - METH(gui_respect_offsets, "Enable rotations about g5x,g92 offsets"), -+#endif - {} - #undef METH - }; -@@ -3384,9 +3391,11 @@ PyMODINIT_FUNC PyInit_linuxcnc(void) - PyModule_AddObject(m, "ini", (PyObject*)&Ini_Type); - PyModule_AddObject(m, "error", error); - -+#ifndef LINUXCNC_HEADLESS - PyType_Ready(&PositionLoggerType); - PyModule_AddObject(m, "positionlogger", (PyObject*)&PositionLoggerType); - pthread_mutex_init(&mutex, NULL); -+#endif - - PyModule_AddStringConstant(m, "PREFIX", EMC2_HOME); - PyModule_AddStringConstant(m, "SHARE", EMC2_HOME "/share"); diff --git a/src/emc/usr_intf/emcsh.cc b/src/emc/usr_intf/emcsh.cc -index 7664041959..9112dce1de 100644 +index b040345..8e71c3f 100644 --- a/src/emc/usr_intf/emcsh.cc +++ b/src/emc/usr_intf/emcsh.cc @@ -20,7 +20,9 @@ @@ -780,9 +621,24 @@ index 7664041959..9112dce1de 100644 #include +#endif - #include #include -@@ -3582,6 +3584,7 @@ static int localround(ClientData /*clientdata*/, + #include // PM_POSE, TO_RAD +@@ -3543,12 +3545,14 @@ static int localint(ClientData /*clientdata*/, + return TCL_OK; + } + ++#ifndef LINUXCNC_HEADLESS + static const char *one_head(int x0, int y0, int x1, int y1) + { + static char buf[100]; + snprintf(buf, sizeof(buf), "%d %d %d %d", x0, y0, x1, y1); + return buf; + } ++#endif + + // "round", as in "round 3.9" which returns 4 + static int localround(ClientData /*clientdata*/, +@@ -3581,6 +3585,7 @@ static int localround(ClientData /*clientdata*/, return TCL_OK; } @@ -790,7 +646,7 @@ index 7664041959..9112dce1de 100644 #include static int multihead(ClientData /*clientdata*/, -@@ -3621,6 +3624,7 @@ static int multihead(ClientData /*clientdata*/, +@@ -3620,6 +3625,7 @@ static int multihead(ClientData /*clientdata*/, } return TCL_OK; } @@ -798,7 +654,7 @@ index 7664041959..9112dce1de 100644 static void sigQuit(int /*sig*/) { -@@ -3996,8 +4000,10 @@ int Linuxcnc_Init(Tcl_Interp * interp) +@@ -3995,8 +4001,10 @@ int Linuxcnc_Init(Tcl_Interp * interp) Tcl_CreateObjCommand(interp, "round", localround, (ClientData) NULL, (Tcl_CmdDeleteProc *) NULL); @@ -809,44 +665,25 @@ index 7664041959..9112dce1de 100644 /* * Specify a user-specific startup file to invoke if the application -@@ -4016,4 +4022,3 @@ int Linuxcnc_Init(Tcl_Interp * interp) - - return TCL_OK; - } -- -diff --git a/src/hal/components/Submakefile b/src/hal/components/Submakefile -index 2c37b2043f..2ee769da8b 100644 ---- a/src/hal/components/Submakefile -+++ b/src/hal/components/Submakefile -@@ -42,9 +42,11 @@ else - COMP_DRIVERS := $(wildcard hal/drivers/*.comp) +diff --git a/src/hal/utils/Submakefile b/src/hal/utils/Submakefile +index b3dcdcf..a356d8a 100644 +--- a/src/hal/utils/Submakefile ++++ b/src/hal/utils/Submakefile +@@ -13,7 +13,7 @@ HALSHSRCS := \ + ifneq ($(READLINE_LIBS),) + HALCMDSRCS += hal/utils/halcmd_completion.c + endif +-ifeq ($(BUILD_GUI),yes) ++ifeq ($(BUILD_TCL),yes) + USERSRCS += $(sort $(HALCMDSRCS) $(HALSHSRCS)) + else + USERSRCS += $(sort $(HALCMDSRCS)) +@@ -24,7 +24,7 @@ $(call TOOBJSDEPS, hal/utils/halsh.c) : EXTRAFLAGS += $(TCL_CFLAGS) + ../tcl/hal.so: $(call TOOBJS, $(HALSHSRCS)) ../lib/liblinuxcncini.so.1 ../lib/liblinuxcnchal.so.0 + $(ECHO) Linking $(notdir $@) + $(Q)$(CXX) $(LDFLAGS) -shared $^ $(TCL_LIBS) -o $@ -lfmt +-ifeq ($(BUILD_GUI),yes) ++ifeq ($(BUILD_TCL),yes) + TARGETS += ../tcl/hal.so endif - COMP_DRIVER_MANPAGES := $(patsubst hal/drivers/%.comp, ../docs/man/man9/%.9, $(COMP_DRIVERS)) -+ifneq ($(BUILD_MANPAGES),no) - TARGETS += manpages - GENERATED_MANPAGES += $(COMP_MANPAGES) - GENERATED_MANPAGES += $(COMP_DRIVER_MANPAGES) -+endif - .PHONY: manpages - ifeq ($(TRIVIAL_BUILD),no) - -include $(patsubst %.comp, objects/%.mak, $(COMPS) $(COMP_DRIVERS)) -diff --git a/src/hal/user_comps/Submakefile b/src/hal/user_comps/Submakefile -index 42a52579ce..ce1db76a68 100644 ---- a/src/hal/user_comps/Submakefile -+++ b/src/hal/user_comps/Submakefile -@@ -1,10 +1,15 @@ - USER_COMP_PY = pyvcp hal_input gladevcp scorbot-er-3 mitsub_vfd pmx485 sim-torch z_level_compensation mqtt-publisher hal_bridge -+ifeq ($(BUILD_HEADLESS),yes) -+USER_COMP_PY := $(filter-out pyvcp hal_input gladevcp hal_bridge,$(USER_COMP_PY)) -+endif - - USER_COMPS := $(sort $(wildcard hal/user_comps/*.comp)) - USER_COMP_BINS := $(patsubst hal/user_comps/%.comp, ../bin/%, $(USER_COMPS)) - USER_COMP_MANPAGES := $(patsubst hal/user_comps/%.comp, ../docs/man/man1/%.1, $(USER_COMPS)) - USER_COMP_SRCS := $(patsubst %.comp, objects/%.c, $(USER_COMPS)) -+ifneq ($(BUILD_MANPAGES),no) - GENERATED_MANPAGES += $(USER_COMP_MANPAGES) -+endif - USERSRCS += $(USER_COMP_SRCS) - $(patsubst %, ../bin/%, $(USER_COMP_PY)) : ../bin/%: hal/user_comps/%.py diff --git a/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch b/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch index 7ea89140..7c6d4c3c 100644 --- a/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch +++ b/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch @@ -8,33 +8,25 @@ Subject: [PATCH] hal: add ordered trusted realtime component search path scripts/halrun.in | 3 + scripts/linuxcnc.in | 3 + src/configure.ac | 20 +++ - src/hal/utils/Submakefile | 6 +- + src/hal/utils/Submakefile | 8 +- src/hal/utils/halcmd_commands.cc | 35 ++---- - src/hal/utils/halcmd_completion.c | 49 ++++++-- - src/hal/utils/halrmt.c | 43 +++---- + src/hal/utils/halcmd_completion.c | 48 ++++++-- + src/hal/utils/halrmt.cc | 26 ++-- src/module_helper/Submakefile | 3 +- src/module_helper/module_helper.c | 11 +- src/rtapi/Submakefile | 1 + src/rtapi/rtmod_path.c | 195 ++++++++++++++++++++++++++++++ src/rtapi/rtmod_path.h | 34 ++++++ - src/rtapi/uspace_rtapi_main.cc | 36 ++++-- - tests/rtmod-path/expected | 1 + - tests/rtmod-path/load.hal | 2 + - tests/rtmod-path/test.c | 73 +++++++++++ - tests/rtmod-path/test.sh | 8 ++ - 18 files changed, 470 insertions(+), 75 deletions(-) + src/rtapi/uspace_rtapi_main.cc | 42 +++++-- + 14 files changed, 393 insertions(+), 58 deletions(-) create mode 100644 src/rtapi/rtmod_path.c create mode 100644 src/rtapi/rtmod_path.h - create mode 100644 tests/rtmod-path/expected - create mode 100644 tests/rtmod-path/load.hal - create mode 100644 tests/rtmod-path/test.c - create mode 100755 tests/rtmod-path/test.sh diff --git a/docs/src/man/man1/halcmd.1.adoc b/docs/src/man/man1/halcmd.1.adoc -index 6c6b19b528..4d010eeca1 100644 +index 1538013..34bcc9d 100644 --- a/docs/src/man/man1/halcmd.1.adoc +++ b/docs/src/man/man1/halcmd.1.adoc -@@ -300,6 +300,28 @@ variable substitution take place. +@@ -294,6 +294,28 @@ variable substitution take place. === Environment Variables @@ -64,7 +56,7 @@ index 6c6b19b528..4d010eeca1 100644 - *$ENVVAR* followed by end-of-line or whitespace diff --git a/scripts/halrun.in b/scripts/halrun.in -index a406dd17ad..53d9405f55 100644 +index a406dd1..53d9405 100644 --- a/scripts/halrun.in +++ b/scripts/halrun.in @@ -5,6 +5,9 @@ REALTIME=@REALTIME@ @@ -78,10 +70,10 @@ index a406dd17ad..53d9405f55 100644 help () { halcmd -h diff --git a/scripts/linuxcnc.in b/scripts/linuxcnc.in -index 3eaca77e7b..e373fbbf5a 100644 +index 027e3b3..ef68216 100644 --- a/scripts/linuxcnc.in +++ b/scripts/linuxcnc.in -@@ -819,6 +819,9 @@ fi +@@ -823,6 +823,9 @@ fi # 4.3.3. export the location of the HAL realtime modules so that # "halcmd loadrt" can find them HAL_RTMOD_DIR=$LINUXCNC_RTLIB_DIR; export HAL_RTMOD_DIR @@ -92,7 +84,7 @@ index 3eaca77e7b..e373fbbf5a 100644 # The HALCMD variable must be split because it may contain options. # shellcheck disable=SC2086 diff --git a/src/configure.ac b/src/configure.ac -index c1289732f6..7f05e1dc96 100644 +index 901de31..c7039b9 100644 --- a/src/configure.ac +++ b/src/configure.ac @@ -685,6 +685,26 @@ AC_SUBST([TOOL_NML]) @@ -123,39 +115,49 @@ index c1289732f6..7f05e1dc96 100644 # Subsection 3.4 - define default dirs, these get used in a lot of places # # we decide based on RIP or install where stuff goes # diff --git a/src/hal/utils/Submakefile b/src/hal/utils/Submakefile -index 12d60b7b9d..b4c100e2e2 100644 +index a356d8a..d68df7e 100644 --- a/src/hal/utils/Submakefile +++ b/src/hal/utils/Submakefile -@@ -1,5 +1,5 @@ --HALCMDSRCS := hal/utils/halcmd.c hal/utils/halcmd_commands.cc hal/utils/halcmd_main.c --HALSHSRCS := hal/utils/halcmd.c hal/utils/halcmd_commands.cc hal/utils/halsh.c -+HALCMDSRCS := hal/utils/halcmd.c hal/utils/halcmd_commands.cc hal/utils/halcmd_main.c rtapi/rtmod_path.c -+HALSHSRCS := hal/utils/halcmd.c hal/utils/halcmd_commands.cc hal/utils/halsh.c rtapi/rtmod_path.c +@@ -2,13 +2,15 @@ HALCMDSRCS := \ + hal/utils/halcmd.c \ + hal/utils/halcmd_commands.cc \ + hal/utils/halcmd_main.c \ +- hal/setps_util.c ++ hal/setps_util.c \ ++ rtapi/rtmod_path.c + + HALSHSRCS := \ + hal/utils/halcmd.c \ + hal/utils/halcmd_commands.cc \ + hal/utils/halsh.c \ +- hal/setps_util.c ++ hal/setps_util.c \ ++ rtapi/rtmod_path.c ifneq ($(READLINE_LIBS),) HALCMDSRCS += hal/utils/halcmd_completion.c -@@ -18,7 +18,7 @@ TARGETS += ../tcl/hal.so - $(Q)$(CXX) $(LDFLAGS) -o $@ $^ $(READLINE_LIBS) +@@ -33,7 +35,7 @@ endif + $(Q)$(CXX) $(LDFLAGS) -o $@ $^ $(READLINE_LIBS) -lfmt TARGETS += ../bin/halcmd --HALRMTSRCS := hal/utils/halrmt.c -+HALRMTSRCS := hal/utils/halrmt.c rtapi/rtmod_path.c +-HALRMTSRCS := hal/utils/halrmt.cc hal/setps_util.c ++HALRMTSRCS := hal/utils/halrmt.cc hal/setps_util.c rtapi/rtmod_path.c USERSRCS += $(HALRMTSRCS) - ../bin/halrmt: $(call TOOBJS, $(HALRMTSRCS)) ../lib/liblinuxcnchal.so.0 + ../bin/halrmt: $(call TOOBJS, $(HALRMTSRCS)) ../lib/liblinuxcnchal.so.0 ../lib/liblinuxcncini.so.1 diff --git a/src/hal/utils/halcmd_commands.cc b/src/hal/utils/halcmd_commands.cc -index 5a7eb70f9f..78b34ff978 100644 +index 4132335..9af90be 100644 --- a/src/hal/utils/halcmd_commands.cc +++ b/src/hal/utils/halcmd_commands.cc @@ -42,6 +42,7 @@ + #include // RTAPI realtime OS API #include // HAL public API decls - #include "../hal_priv.h" // private HAL decls #include "halcmd_commands.h" +#include "rtapi/rtmod_path.h" - #include #include // rtapi_strlcpy -@@ -1168,39 +1169,25 @@ int do_loadrt_cmd(char *mod_name, char *args[]) + #include +@@ -935,39 +936,25 @@ int do_loadrt_cmd(const char *mod_name, const char *args[]) argv[m++] = NULL; retval = do_loadusr_cmd(argv); #else @@ -206,10 +208,10 @@ index 5a7eb70f9f..78b34ff978 100644 argv[0] = EMC2_BIN_DIR "/linuxcnc_module_helper"; argv[1] = "insert"; diff --git a/src/hal/utils/halcmd_completion.c b/src/hal/utils/halcmd_completion.c -index 65c304c2bf..c26c6ecad1 100644 +index 69e854e..ae5a356 100644 --- a/src/hal/utils/halcmd_completion.c +++ b/src/hal/utils/halcmd_completion.c -@@ -38,6 +38,7 @@ +@@ -38,12 +38,14 @@ */ #include "halcmd_completion.h" @@ -217,23 +219,14 @@ index 65c304c2bf..c26c6ecad1 100644 #include "config.h" #include /* RTAPI realtime OS API */ #include /* HAL public API decls */ -@@ -45,6 +46,7 @@ - #include #include #include + #include +#include static int argno; -@@ -484,6 +486,7 @@ static char *pin_generator(const char *text, int state) { - } - - #include -+#include - - static int startswith(const char *string, const char *stem) { - return strncmp(string, stem, strlen(stem)) == 0; -@@ -528,26 +531,55 @@ static char *loadusr_generator(const char *text, int state) { +@@ -637,26 +639,55 @@ static char *loadusr_generator(const char *text, int state) { static char *loadrt_generator(const char *text, int state) { static int len; static DIR *d; @@ -297,106 +290,69 @@ index 65c304c2bf..c26c6ecad1 100644 } return NULL; } -@@ -747,4 +779,3 @@ void halcmd_init_readline() { +@@ -845,4 +876,3 @@ void halcmd_init_readline() { rl_readline_name = "halcmd"; rl_attempted_completion_function = rlcompleter; } - -diff --git a/src/hal/utils/halrmt.c b/src/hal/utils/halrmt.c -index 4d20d98e3b..30dc912580 100644 ---- a/src/hal/utils/halrmt.c -+++ b/src/hal/utils/halrmt.c -@@ -274,6 +274,7 @@ - ****************************************************************************/ +diff --git a/src/hal/utils/halrmt.cc b/src/hal/utils/halrmt.cc +index 4689640..42ed0c3 100644 +--- a/src/hal/utils/halrmt.cc ++++ b/src/hal/utils/halrmt.cc +@@ -45,6 +45,7 @@ + #include + #include + #include ++#include - #include "config.h" + #include + #include +@@ -56,6 +57,7 @@ + #include + + #include "hal/setps_util.h" +#include "rtapi/rtmod_path.h" + #include "hal/halqrec.hh" - #define _REENTRANT - -@@ -1127,11 +1128,10 @@ static int doLoadRt(char *mod_name, char *args[], connectionRecType *context) - hal_comp_t *comp; - char *cp1; - const char *nakStr = "SET LOADRT NAK"; -+ int m=0; -+ char *argv[MAX_TOK+4]; - - #if defined(RTAPI_USPACE) --#if 0 -- argv[m++] = "-Wn"; -- argv[m++] = mod_name; - argv[m++] = EMC2_BIN_DIR "/rtapi_app"; - argv[m++] = "load"; - argv[m++] = mod_name; -@@ -1140,13 +1140,10 @@ static int doLoadRt(char *mod_name, char *args[], connectionRecType *context) - argv[m++] = args[n++]; - } - argv[m++] = NULL; --// retval = do_loadusr_cmd(argv); --#endif -+ retval = hal_systemv(argv, context); + using namespace linuxcnc; +@@ -1067,19 +1069,27 @@ static int doLoadRt(connectionRecType &ctx, const std::vector &args + + return 0; #else -- int m=0; -- char *argv[MAX_TOK+3]; -- static char *rtmod_dir = EMC2_RTLIB_DIR; +- // Make full module name '/.o' +- std::string mod_path = fmt::format("{}/{}{}", EMC2_RTLIB_DIR, mod_name, MODULE_EXT); +- +- // Does the module exist? - struct stat stat_buf; +- if (stat(mod_path.c_str(), &stat_buf) != 0 ) { +- errornl(ctx, fmt::format("LoadRt: Can't find module '{}' in '{}'", mod_name, EMC2_RTLIB_DIR)); ++ // Resolve '/' along HAL_RTMOD_PATH; the first match is final + rtmod_path_t rtmod_path; -+ char path_error[MAX_CMD_LEN+1]; - char mod_path[MAX_CMD_LEN+1]; - - if (hal_get_lock()&HAL_LOCK_LOAD) { -@@ -1154,24 +1151,14 @@ static int doLoadRt(char *mod_name, char *args[], connectionRecType *context) - sockWriteError(nakStr, context); - return -EPERM; - } -- if ( (strlen(rtmod_dir)+strlen(mod_name)+5) > MAX_CMD_LEN ) { -- snprintf(errorStr, sizeof(errorStr), "Module path too long"); -+ if (rtmod_path_init(&rtmod_path, getenv("HAL_RTMOD_PATH"), path_error, sizeof(path_error)) || -+ rtmod_path_resolve(&rtmod_path, mod_name, 0, mod_path, sizeof(mod_path), path_error, sizeof(path_error))) { -+ snprintf(errorStr, sizeof(errorStr), "%s", path_error); - sockWriteError(nakStr, context); -- return -1; -- } -- -- /* make full module name '/.o' */ -- rtapi_strxcpy (mod_path, rtmod_dir); -- rtapi_strxcat (mod_path, "/"); -- rtapi_strxcat (mod_path, mod_name); -- rtapi_strxcat (mod_path, MODULE_EXT); -- /* is there a file with that name? */ -- if ( stat(mod_path, &stat_buf) != 0 ) { -- /* can't find it */ -- snprintf(errorStr, sizeof(errorStr), "Can't find module '%s' in %s", mod_name, rtmod_dir); -- sockWriteError(nakStr, context); -- return -1; -+ rtmod_path_free(&rtmod_path); -+ return -1; ++ char path_error[1024]; ++ char mod_path[PATH_MAX]; ++ if (rtmod_path_init(&rtmod_path, getenv("HAL_RTMOD_PATH"), path_error, sizeof(path_error))) { ++ errornl(ctx, fmt::format("LoadRt: {}", path_error)); ++ return -EINVAL; ++ } ++ if (rtmod_path_resolve(&rtmod_path, mod_name.c_str(), 0, mod_path, sizeof(mod_path), ++ path_error, sizeof(path_error))) { ++ rtmod_path_free(&rtmod_path); ++ errornl(ctx, fmt::format("LoadRt: {}", path_error)); + return -ENOENT; } + rtmod_path_free(&rtmod_path); - - // TODO - FIXME - remove test after 2.2.x when blocks isn't functional anymore - if (strncmp(mod_name, "blocks", 6) == 0) { -@@ -1381,8 +1368,13 @@ static int unloadrt_comp(char *mod_name) - } - if ( pid == 0 ) { - /* this is the child process - prepare to exec() rmmod */ -+#if defined(RTAPI_USPACE) -+ argv[0] = EMC2_BIN_DIR "/rtapi_app"; -+ argv[1] = "unload"; -+#else - argv[0] = EMC2_BIN_DIR "/linuxcnc_module_helper"; - argv[1] = "remove"; -+#endif - argv[2] = mod_name; - /* add a NULL to terminate the argv array */ - argv[3] = NULL; -@@ -3625,4 +3617,3 @@ int main(int argc, char **argv) - return 0; + ++ // The module helper inserts by path, followed by the module arguments + argv.push_back(EMC2_BIN_DIR "/linuxcnc_module_helper"); + argv.push_back("insert"); +- for(unsigned i = 0; i < args.size(); i++) { ++ argv.push_back(mod_path); ++ for(unsigned i = 1; i < args.size(); i++) { + argv.push_back(args[i].c_str()); } - } -- + argv.push_back(NULL); diff --git a/src/module_helper/Submakefile b/src/module_helper/Submakefile -index c378790c8f..66f47b4ff6 100644 +index c378790..66f47b4 100644 --- a/src/module_helper/Submakefile +++ b/src/module_helper/Submakefile @@ -1,6 +1,7 @@ @@ -409,7 +365,7 @@ index c378790c8f..66f47b4ff6 100644 ifneq ($(rip_moduledir),) diff --git a/src/module_helper/module_helper.c b/src/module_helper/module_helper.c -index f22c651ba5..83f94cc6da 100644 +index 694c57e..e7e957c 100644 --- a/src/module_helper/module_helper.c +++ b/src/module_helper/module_helper.c @@ -36,6 +36,7 @@ think of a better way. @@ -455,10 +411,10 @@ index f22c651ba5..83f94cc6da 100644 char buf[NAME_MAX + 1]; snprintf(buf, NAME_MAX, "%s%s", mod, MODULE_EXT); diff --git a/src/rtapi/Submakefile b/src/rtapi/Submakefile -index 0ca738d01a..1798fd9491 100644 +index bb36cc3..b3ac70f 100644 --- a/src/rtapi/Submakefile +++ b/src/rtapi/Submakefile -@@ -32,6 +32,7 @@ $(patsubst ./rtapi/%,../include/%,$(RTAPIINCS)): ../include/%.h: ./rtapi/%.h +@@ -2,6 +2,7 @@ ifeq ($(BUILD_SYS),uspace) RTAPI_APP_SRCS := \ @@ -468,7 +424,7 @@ index 0ca738d01a..1798fd9491 100644 rtapi/uspace_rtapi_parport.cc \ diff --git a/src/rtapi/rtmod_path.c b/src/rtapi/rtmod_path.c new file mode 100644 -index 0000000000..763fe5f9b3 +index 0000000..763fe5f --- /dev/null +++ b/src/rtapi/rtmod_path.c @@ -0,0 +1,195 @@ @@ -669,7 +625,7 @@ index 0000000000..763fe5f9b3 +} diff --git a/src/rtapi/rtmod_path.h b/src/rtapi/rtmod_path.h new file mode 100644 -index 0000000000..7d35c26538 +index 0000000..7d35c26 --- /dev/null +++ b/src/rtapi/rtmod_path.h @@ -0,0 +1,34 @@ @@ -708,10 +664,10 @@ index 0000000000..7d35c26538 +#endif +#endif diff --git a/src/rtapi/uspace_rtapi_main.cc b/src/rtapi/uspace_rtapi_main.cc -index e04bf25545..7186ab0854 100644 +index 32c5ddd..95dc8ac 100644 --- a/src/rtapi/uspace_rtapi_main.cc +++ b/src/rtapi/uspace_rtapi_main.cc -@@ -26,6 +26,7 @@ +@@ -25,6 +25,7 @@ #include #include #include @@ -719,9 +675,14 @@ index e04bf25545..7186ab0854 100644 #include #include #include -@@ -59,6 +60,20 @@ - #include - #include "hal/hal_priv.h" +@@ -52,11 +53,24 @@ + #include + #endif + +-#include + #include + + #include "rtapi.h" #include "uspace_common.h" +#include "rtmod_path.h" + @@ -740,7 +701,7 @@ index e04bf25545..7186ab0854 100644 static RtapiApp &App(); -@@ -221,18 +236,19 @@ static int do_comp_args(void *module, const std::vector &args) { +@@ -562,18 +576,24 @@ static int do_comp_args(void *module, const std::vector &args) { static int do_load_cmd(const std::string &name, const std::vector &args) { void *w = modules[name]; if (w == NULL) { @@ -755,126 +716,23 @@ index e04bf25545..7186ab0854 100644 + capture_component_path(); + if (!component_path_ready) { + rtapi_print_msg(RTAPI_MSG_ERR, "rtapi_app: %s\n", component_path_error.c_str()); ++ modules.erase(name); + return -1; + } ++ // rtapi and hal_lib always come from the standard module directory + int core_module = name == "rtapi" || name == "hal_lib"; + if (rtmod_path_resolve(&component_path, name.c_str(), core_module, + what, sizeof(what), error, sizeof(error))) { + rtapi_print_msg(RTAPI_MSG_ERR, "%s\n", error); ++ modules.erase(name); return -1; } - std::string what; - what = fmt::format("{}/{}.so", EMC2_RTLIB_DIR, name); - void *module = modules[name] = dlopen(what.c_str(), RTLD_GLOBAL | RTLD_NOW); ++ // The first regular-file match is final: a failing dlopen is ++ // reported below without falling through to a later directory. + void *module = modules[name] = dlopen(what, RTLD_GLOBAL | RTLD_NOW); if (!module) { rtapi_print_msg(RTAPI_MSG_ERR, "%s: dlopen: %s\n", name.c_str(), dlerror()); modules.erase(name); -diff --git a/tests/rtmod-path/expected b/tests/rtmod-path/expected -new file mode 100644 -index 0000000000..55233dce38 ---- /dev/null -+++ b/tests/rtmod-path/expected -@@ -0,0 +1 @@ -+rtmod-path: all tests passed -diff --git a/tests/rtmod-path/load.hal b/tests/rtmod-path/load.hal -new file mode 100644 -index 0000000000..b44392754d ---- /dev/null -+++ b/tests/rtmod-path/load.hal -@@ -0,0 +1,2 @@ -+loadrt and2 count=1 -+unloadrt all -diff --git a/tests/rtmod-path/test.c b/tests/rtmod-path/test.c -new file mode 100644 -index 0000000000..3bc258f2fe ---- /dev/null -+++ b/tests/rtmod-path/test.c -@@ -0,0 +1,73 @@ -+#include "config.h" -+#include "rtapi/rtmod_path.h" -+ -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+#include -+ -+static void touch_file(const char *path, const char *value) { -+ int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600); -+ assert(fd >= 0); -+ assert(write(fd, value, strlen(value)) == (ssize_t)strlen(value)); -+ close(fd); -+} -+ -+int main(void) { -+ rtmod_path_t path = {0}; -+ char extras[PATH_MAX * 2], *a, *b, *colon; -+ char ordered[PATH_MAX * 2], result[PATH_MAX], error[1024]; -+ char fa[PATH_MAX], fb[PATH_MAX], escaped[PATH_MAX], outside[PATH_MAX]; -+ const char *name = "rtmod_path_fixture"; -+ -+ assert(rtmod_path_init(&path, NULL, error, sizeof(error)) == 0); -+ assert(path.count == 1 && !strcmp(path.dirs[0], EMC2_RTLIB_DIR)); -+ rtmod_path_free(&path); -+ assert(rtmod_path_init(&path, "", error, sizeof(error)) < 0); -+ assert(rtmod_path_init(&path, "relative", error, sizeof(error)) < 0); -+ assert(rtmod_path_init(&path, "/tmp::/var", error, sizeof(error)) < 0); -+ assert(rtmod_path_init(&path, "/definitely/not/trusted", error, sizeof(error)) < 0); -+ assert(!rtmod_name_valid("../bad") && !rtmod_name_valid("bad/name")); -+ -+ strcpy(extras, EMC2_EXTRA_RTLIB_DIRS); -+ colon = strchr(extras, ':'); -+ if (!colon) { -+ puts("rtmod-path: configure with two extra rtlib directories for ordered lookup tests"); -+ return 0; -+ } -+ *colon = 0; a = extras; b = colon + 1; -+ assert(*a && *b && !strchr(b, ':')); -+ mkdir(a, 0700); mkdir(b, 0700); -+ snprintf(fa, sizeof(fa), "%s/%s%s", a, name, MODULE_EXT); -+ snprintf(fb, sizeof(fb), "%s/%s%s", b, name, MODULE_EXT); -+ touch_file(fa, "first-broken-copy"); touch_file(fb, "second-copy"); -+ -+ snprintf(ordered, sizeof(ordered), "%s:%s:%s", a, a, b); -+ assert(rtmod_path_init(&path, ordered, error, sizeof(error)) == 0 && path.count == 2); -+ assert(rtmod_path_resolve(&path, name, 0, result, sizeof(result), error, sizeof(error)) == 0); -+ assert(!strcmp(result, fa)); /* selection is final; loaders must not fall through */ -+ rtmod_path_free(&path); -+ -+ snprintf(ordered, sizeof(ordered), "%s:%s", b, a); -+ assert(rtmod_path_init(&path, ordered, error, sizeof(error)) == 0); -+ assert(rtmod_path_resolve(&path, name, 0, result, sizeof(result), error, sizeof(error)) == 0); -+ assert(!strcmp(result, fb)); -+ assert(rtmod_path_resolve(&path, "missing_fixture", 0, result, sizeof(result), error, sizeof(error)) < 0); -+ assert(strstr(error, a) && strstr(error, b)); -+ -+ snprintf(outside, sizeof(outside), "/tmp/rtmod-path-outside-%ld%s", (long)getpid(), MODULE_EXT); -+ touch_file(outside, "outside"); -+ snprintf(escaped, sizeof(escaped), "%s/rtmod_path_escape%s", a, MODULE_EXT); -+ unlink(escaped); assert(symlink(outside, escaped) == 0); -+ assert(rtmod_path_resolve(&path, "rtmod_path_escape", 0, result, sizeof(result), error, sizeof(error)) < 0); -+ assert(strstr(error, "escapes trusted directory")); -+ rtmod_path_free(&path); -+ -+ unlink(fa); unlink(fb); unlink(escaped); unlink(outside); -+ puts("rtmod-path: all tests passed"); -+ return 0; -+} -diff --git a/tests/rtmod-path/test.sh b/tests/rtmod-path/test.sh -new file mode 100755 -index 0000000000..d4e8e6777f ---- /dev/null -+++ b/tests/rtmod-path/test.sh -@@ -0,0 +1,8 @@ -+#!/bin/sh -+set -eu -+ -+cc -std=c11 -D_GNU_SOURCE -Wall -Wextra -Wno-format-truncation \ -+ -I../../src -I../../src/rtapi \ -+ ../../src/rtapi/rtmod_path.c test.c -o test_rtmod_path -+./test_rtmod_path -+rm -f test_rtmod_path diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index e2c860f2..d6cc1cda 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -3,84 +3,123 @@ From: Dariusz Majnert Date: Fri, 14 Aug 2026 18:32:49 +0200 Subject: [PATCH] native automatic tool wear +Ported to v2.10.0-pre2. Differences from the patch on the old base: +upstream 7180d28698 made #5401-#5409 the loaded tool's stored offset +again and added #5081-#5089 for the applied offset, so #5401-#5409 now +hold stored geometry (refreshed by M6, M61, startup and G10 L1/L3/L10/ +L11), #5430-#5438 stored wear, and #5081-#5089 the applied geometry plus +wear written by the automatic M6/M61 activation, G43, G43 H, G43.1, +G43.2 and G43.4 and zeroed by G49. G43.4 shares G43's path and so also +applies geometry plus wear; the automatic activation re-applies as G43.4 +while the offset in effect is G43.4's, so a later G49 still undoes its +kinematics switch (upstream's RETAIN_G43, extended for G43.4, is still +removed). Wear edits and composition use upstream's per-axis A-W unit +conversion. The pybind11 gcode module accepts 23-item tool entries +(geometry plus wear, as linuxcnc.stat.tool_table now returns) besides +the 14-item ones, so the preview applies the same offset as the machine; +before, a full entry failed the parse. The preview's lathe tool shape +reads diameter, angles and orientation by position, not as the last +four fields. The tool-table default moves into upstream's +CANON_TOOL_TABLE_INIT, and the deleted EMC_TOOL_STAT::operator= is not +restored. tests/tool-wear-task covers the task path on a lathe, the +db-g10-offset test covers G10 L3 notifying a v2.2 db program, and a +renderer test covers wear in the preview. + +Fixes from review of the port: + +- The tool and its automatic offset take effect together. Canon attaches + an offset commanded right behind a tool change (the automatic + activation, or a G43/G49/G43.2 in the same block) to that + EMC_TOOL_LOAD or EMC_TOOL_SET_NUMBER, and task applies it to motion + and to stat.tool_offset in the cycle the tool takes effect; an aborted + change drops it. CHANGE_TOOL_NUMBER flushes buffered motion first. + emcTaskAbort() and the error paths that clear the interpreter list + reset canon's offset from task status, and Interp::synch() reads the + interpreter's offset back from canon. Before, an abort or E-stop + around a pending change could leave the offset of one tool applied + with another tool loaded. +- M61 with cutter radius compensation on is refused before any state + changes, as M6 is. +- A tool line may hold at most 510 characters before its newline. + Loading a table, reading an entry, reading a database reply, + formatting, saving and notifying a database program refuse a longer + line with an error instead of cutting a number short; the formatter no + longer overruns its buffer. A table loaded with refused lines is not + saved over until it is reloaded without them. +- A tool edit whose save or database notification fails is rolled back + in memory. +- GET_EXTERNAL_TOOL_TABLE returns an initialized entry for an + out-of-range index. +- The preview clears its stored tool offset between parses. +- New tests: tool-wear-abort, tool-wear-restart, interp/tool-line-length + and tooldb/db-line-length, with more cases in the existing ones. The + G-code documentation states that G10 L10/L11 set geometry without + regard to stored wear and that nothing is applied after a restart + until G43, M6 or M61. --- configs/sim/gmoccapy/gmoccapy_tool_sensor.ini | 1 - docs/src/config/ini-config.adoc | 4 - docs/src/config/python-interface.adoc | 6 +- - docs/src/gcode/g-code.adoc | 40 ++++- - docs/src/gcode/m-code.adoc | 12 +- - docs/src/gcode/overview.adoc | 2 + - docs/src/gcode/tool-compensation.adoc | 21 ++- - docs/src/tooldatabase/tooldatabase.adoc | 6 +- + docs/src/gcode/g-code.adoc | 69 +++++-- + docs/src/gcode/m-code.adoc | 13 +- + docs/src/gcode/overview.adoc | 15 +- + docs/src/gcode/tool-compensation.adoc | 28 ++- + docs/src/tooldatabase/tooldatabase.adoc | 7 +- + lib/python/rs274/glcanon_scene.py | 4 +- lib/python/tooldb.py | 2 +- src/emc/ini/linuxcnc_check_ini.py | 1 - src/emc/ini/update_ini.py | 1 - - src/emc/nml_intf/canon.hh | 3 +- - src/emc/nml_intf/emc.cc | 3 + - src/emc/nml_intf/emc.hh | 6 +- - src/emc/nml_intf/emc_nml.hh | 4 + - src/emc/nml_intf/emcops.cc | 1 + - src/emc/nml_intf/emctool.h | 3 +- - src/emc/rs274ngc/gcodemodule.cc | 7 +- + src/emc/nml_intf/canon.hh | 8 +- + src/emc/nml_intf/emc.cc | 7 + + src/emc/nml_intf/emc.hh | 13 +- + src/emc/nml_intf/emc_nml.hh | 23 ++- + src/emc/nml_intf/emctool.h | 12 +- + src/emc/nml_intf/interpl.cc | 10 + + src/emc/nml_intf/interpl.hh | 3 + + src/emc/rs274ngc/gcodemodule.cc | 27 ++- src/emc/rs274ngc/interp_array.cc | 1 + src/emc/rs274ngc/interp_check.cc | 4 +- - src/emc/rs274ngc/interp_convert.cc | 145 ++++++++++++------ + src/emc/rs274ngc/interp_convert.cc | 175 +++++++++++------ src/emc/rs274ngc/interp_internal.hh | 2 - - src/emc/rs274ngc/interp_parameter_def.hh | 10 ++ + src/emc/rs274ngc/interp_parameter_def.hh | 10 + src/emc/rs274ngc/pyemctypes.cc | 2 + - src/emc/rs274ngc/rs274ngc_pre.cc | 30 +++- + src/emc/rs274ngc/rs274ngc_interp.hh | 1 + + src/emc/rs274ngc/rs274ngc_pre.cc | 37 +++- src/emc/sai/saicanon.cc | 5 +- - src/emc/task/emccanon.cc | 6 +- - src/emc/task/emctaskmain.cc | 2 + - src/emc/task/taskclass.cc | 20 ++- - src/emc/task/taskclass.hh | 5 +- - src/emc/tooldata/tooldata_common.cc | 31 +++- - src/emc/tooldata/tooldata_db.cc | 2 +- - src/emc/usr_intf/axis/extensions/emcmodule.cc | 29 +++- + src/emc/task/emccanon.cc | 61 ++++-- + src/emc/task/emctask.cc | 4 + + src/emc/task/emctaskmain.cc | 31 ++- + src/emc/task/taskclass.cc | 113 ++++++++--- + src/emc/task/taskclass.hh | 7 +- + src/emc/tooldata/tooldata.hh | 4 +- + src/emc/tooldata/tooldata_common.cc | 184 +++++++++++++----- + src/emc/tooldata/tooldata_db.cc | 77 +++++--- + src/emc/usr_intf/axis/extensions/emcmodule.cc | 29 ++- tests/ccomp/lathe-comp/expected | 4 + tests/ccomp/mill-g90g91g92/expected | 1 + tests/ccomp/mill-line-arc-entry/expected | 1 + + tests/gcode-renderer/canon.py | 3 +- + tests/gcode-renderer/test_renderer.py | 79 ++++++++ tests/interp/cam-nisley/expected | 1 + tests/interp/compile/use-rs274.cc | 3 +- - tests/interp/g10/g10-l1-l10/expected | 9 +- - tests/interp/g10/g10-l1-l10/test.ngc | 4 +- - tests/interp/g10/g10-l11/expected | 2 + + tests/interp/g10/g10-l1-l10/expected | 4 + + tests/interp/g10/g10-l11/expected | 10 +- tests/interp/g72-facing/expected | 1 + tests/interp/g72-missing-iteration/expected | 1 + tests/interp/g76/expected | 1 + - tests/interp/tool-wear/expected | 60 ++++++++ - tests/interp/tool-wear/invalid-i.ngc | 3 + - tests/interp/tool-wear/invalid-j.ngc | 3 + - .../interp/tool-wear/invalid-missing-tool.ngc | 3 + - tests/interp/tool-wear/invalid-q.ngc | 3 + - tests/interp/tool-wear/invalid-r.ngc | 3 + - tests/interp/tool-wear/invalid-zero-tool.ngc | 3 + - tests/interp/tool-wear/test.ngc | 36 +++++ - tests/interp/tool-wear/test.sh | 13 ++ - tests/interp/tool-wear/test.tbl | 3 + tests/remap/introspect/expected | 25 +-- tests/remap/oword-pycall/expected | 25 +-- - tests/t0/nonrandom/expected-gcode-output | 8 +- - tests/t0/random-with-t0/expected-gcode-output | 4 +- - .../random-without-t0/expected-gcode-output | 4 +- + tests/t0/nonrandom/expected-gcode-output | 4 +- + tests/t0/random-with-t0/expected-gcode-output | 2 +- + .../random-without-t0/expected-gcode-output | 2 +- tests/tlo/test-ui.py | 7 +- - tests/toolchanger/m61/test-ui.py | 30 ++-- - .../nonrandom/expected-gcode-output | 24 +-- - .../random/expected-gcode-output | 24 +-- - 63 files changed, 537 insertions(+), 189 deletions(-) - create mode 100644 tests/interp/tool-wear/expected - create mode 100644 tests/interp/tool-wear/invalid-i.ngc - create mode 100644 tests/interp/tool-wear/invalid-j.ngc - create mode 100644 tests/interp/tool-wear/invalid-missing-tool.ngc - create mode 100644 tests/interp/tool-wear/invalid-q.ngc - create mode 100644 tests/interp/tool-wear/invalid-r.ngc - create mode 100644 tests/interp/tool-wear/invalid-zero-tool.ngc - create mode 100644 tests/interp/tool-wear/test.ngc - create mode 100755 tests/interp/tool-wear/test.sh - create mode 100644 tests/interp/tool-wear/test.tbl + tests/toolchanger/m61/test-ui.py | 28 ++- + .../nonrandom/expected-gcode-output | 12 +- + .../random/expected-gcode-output | 12 +- + 59 files changed, 941 insertions(+), 286 deletions(-) diff --git a/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini b/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini -index 37daf10754..bbcdfc2a93 100644 +index 37daf10..bbcdfc2 100644 --- a/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini +++ b/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini @@ -61,7 +61,6 @@ SUBROUTINE_PATH = macros @@ -92,10 +131,10 @@ index 37daf10754..bbcdfc2a93 100644 # INI_VARS 0x00000004 # HAL_PIN_VARS 0x00000008 diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc -index aa8e86d3b5..de598c529d 100644 +index a99a87e..2d7a99e 100644 --- a/docs/src/config/ini-config.adoc +++ b/docs/src/config/ini-config.adoc -@@ -624,9 +624,6 @@ The maximum number of `USER_M_PATH` directories is defined at compile time (typ: +@@ -626,9 +626,6 @@ The maximum number of `USER_M_PATH` directories is defined at compile time (typ: Allows G-code programs to read the values of HAL pins using the format #<_hal[HAL item]>. Variable access is read-only. See <> for more details and an important caveat. @@ -105,7 +144,7 @@ index aa8e86d3b5..de598c529d 100644 * `OWORD_NARGS = 0` (Default: 0) + If this feature is enabled then a called subroutine can determine the number of actual positional parameters passed by inspecting the +#+ parameter. * `NO_DOWNCASE_OWORD = 0` (Default: 0) + -@@ -650,7 +647,6 @@ The above six options were controlled by the `FEATURES` bitmask in versions of L +@@ -652,7 +649,6 @@ The above six options were controlled by the `FEATURES` bitmask in versions of L This INI tag will no longer work. + For reference: ---- @@ -114,10 +153,10 @@ index aa8e86d3b5..de598c529d 100644 FEATURES & 0x4 -> INI_VARS FEATURES & 0x8 -> HAL_PIN_VARS diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc -index 0278680c8e..1a61affaff 100644 +index 5153f11..1c871cf 100644 --- a/docs/src/config/python-interface.adoc +++ b/docs/src/config/python-interface.adoc -@@ -368,7 +368,8 @@ see <> for an example. +@@ -376,7 +376,8 @@ see <> for an example. *tool_table*:: '(returns tuple of tool_results)' - list of tool entries. Each entry is a sequence of the following fields: id, xoffset, yoffset, zoffset, aoffset, boffset, coffset, uoffset, voffset, @@ -127,7 +166,7 @@ index 0278680c8e..1a61affaff 100644 are integers and the rest are floats. [source,python] ---- -@@ -389,7 +390,8 @@ else: +@@ -397,7 +398,8 @@ else: _toolno_ must be greater than zero and less than or equal to the highest tool number in use. Dictionary items include all tooldata items: 'toolno', 'pocketno', 'diameter','frontangle','backangle','orientation', @@ -138,7 +177,7 @@ index 0278680c8e..1a61affaff 100644 [source,python] ---- diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index 66f1a2b776..fa46049723 100644 +index 8162e52..f8f9d01 100644 --- a/docs/src/gcode/g-code.adoc +++ b/docs/src/gcode/g-code.adoc @@ -66,6 +66,7 @@ as the 'L number', and so on for any other letter. @@ -149,17 +188,16 @@ index 66f1a2b776..fa46049723 100644 |<> |Set Tool Table, Calculated, Workpiece |<> |Set Tool Table, Calculated, Fixture |<> |Coordinate System Origin Setting -@@ -702,7 +703,8 @@ current tool loaded in spindle. +@@ -705,7 +706,7 @@ current tool loaded in spindle. [NOTE] -When using G10 L0, tool parameters (#5401-#5413) will be -+When using G10 L0, stored tool parameters (#5400, #5410-#5413 and -+#5430-#5438) will be ++When using G10 L0, tool parameters (#5401-#5413 and #5430-#5438) will be updated immediately and any altered tool diameters will be used for subsequent G41,42 cutter radius compensation commands. Existing G43 tool length compensation values will -@@ -745,6 +747,27 @@ It is an error if: +@@ -748,6 +749,29 @@ It is an error if: For more information on cutter orientation used by the 'Q' word, see the <> diagram. @@ -181,23 +219,55 @@ index 66f1a2b776..fa46049723 100644 +G10 L3 P7 X0.050 Z-0.010 +---- + -+The tool table is persisted, but an active motion offset is not changed -+until G43 is executed or the tool is changed again. ++The tool table is persisted and the stored wear parameters '5430-5438' ++are refreshed when P is the loaded tool, but an active motion offset ++(and so '5081-5089') is not changed until G43 is executed or the tool is ++changed again. + [[gcode:g10-l2]] == G10 L2 Set Coordinate System(((G10 L2 Coordinate System))) -@@ -1404,7 +1427,8 @@ G43 +@@ -857,6 +881,14 @@ the given axes will become the given values. The axes that are not + specified in the G10 L10 command will not be changed. This could be + useful with a probe move as described in the <> section. + ++G10 L10 (and G10 L11) set the geometry offset only, computed from the ++position without the applied tool offset; the tool's stored wear ++(<>) is left as it is and is not taken into account. ++With non-zero wear, the next G43 applies geometry plus wear, so the ++touched-off axis then reads the given value minus that wear. Clear the ++wear first (for example `G10 L3 P1 X0 Z0`) if the touch-off should hold ++exactly. ++ + .G10 L10 Example + [source,ngc] + ---- +@@ -1607,12 +1639,19 @@ G43 'G43' without an H word uses the currently loaded tool from the last 'T__n__ M6'. -'G43 H__n__' uses the offset for tool _n_. +'G43 H__n__' uses the sum of the geometry and wear offsets for tool _n_ +on all nine axes. Repeating G43 replaces the active value and is idempotent. ++ ++The tool length compensation values actually applied to motion, geometry ++plus wear, are stored in the numbered parameters '5081-5089'. + +-The tool length compensation values actually applied to motion are stored +-in the numbered parameters '5081-5089'. The numbered parameters +-'5401-5409' instead hold the loaded tool's stored offset, refreshed on tool +-change ('M6') and 'G10 L1'/'L10'/'L11'. ++When LinuxCNC starts with a tool already in the spindle (a random ++toolchanger keeps it across a restart), that tool's offset is not ++applied: '5401-5409' and '5430-5438' hold its stored geometry and wear, ++but '5081-5089' are 0 until 'G43', 'M6' or 'M61'. The numbered ++parameters '5401-5409' instead hold the loaded tool's stored geometry ++offset and '5430-5438' its stored wear, refreshed on tool change ('M6', ++'M61') and 'G10 L1'/'L3'/'L10'/'L11'. - The active tool length compensation values are stored in the numbered - parameters '5401-5409'. -@@ -1473,7 +1497,7 @@ G43.2 H- or axes- + [NOTE] + 'G43 H0' is a little special. Its behavior is different on random +@@ -1678,7 +1717,7 @@ G43.2 H- or axes- * 'H' - tool number @@ -206,7 +276,7 @@ index 66f1a2b776..fa46049723 100644 * 'G43.2 axes' - applies an additional simultaneous tool offset to subsequent motions by adding the value(s) of any axis words. -@@ -1497,10 +1521,8 @@ G43.2 X0.01 Z0.02 (also add 0.01 to the x tool offset and 0.02 to the z tool off +@@ -1702,10 +1741,8 @@ G43.2 X0.01 Z0.02 (also add 0.01 to the x tool offset and 0.02 to the z tool off M2 (end program) ---- @@ -219,7 +289,20 @@ index 66f1a2b776..fa46049723 100644 Like the other G43 commands, G43.2 does not cause any motion. The next time a compensated axis is moved, that axis's endpoint is the compensated location. -@@ -1516,7 +1538,9 @@ NOTE: G43.2 does not write to the tool table. +@@ -1737,8 +1774,10 @@ offset and switches back to identity kinematics, as long as the offset + in effect is still 'G43.4''s and no 'G12.1' or 'G13.1' has selected a + kinematics since. + +-The H word, the offset itself and the parameters it lands in are +-'G43''s. Which kinematics is the working one is declared by the module ++The H word, the offset itself (geometry plus wear) and the parameters it ++lands in are 'G43''s. While the offset in effect is 'G43.4''s, the ++automatic activation of a built-in 'M6' or 'M61' re-applies it as ++'G43.4', so a later 'G49' still undoes the switch. Which kinematics is the working one is declared by the module + (KINSTYPE_PRIMARY, see the <> chapter), the number is not the answer; a module that + declares none rejects 'G43.4' at read time. +@@ -1763,7 +1802,9 @@ It is an error if: [[gcode:g49]] == G49 Cancel Tool Length Compensation(((G49 Cancel Tool Length Offset))) @@ -228,13 +311,13 @@ index 66f1a2b776..fa46049723 100644 + changing stored geometry or wear. It remains cancelled until G43 or a + subsequent built-in tool change. - It is OK to program using the same offset already in use. It is also - OK to program using no tool length offset if none is currently being + 'G49' also switches a switchable kinematics module back to its identity + kinematics when it cancels a 'G43.4', undoing the switch that made. It diff --git a/docs/src/gcode/m-code.adoc b/docs/src/gcode/m-code.adoc -index 253358f25f..1cb15521ad 100644 +index afa69cc..e74ef24 100644 --- a/docs/src/gcode/m-code.adoc +++ b/docs/src/gcode/m-code.adoc -@@ -176,6 +176,7 @@ When the tool change is complete: +@@ -178,6 +178,7 @@ When the tool change is complete: * If configured in the INI file some axis positions may move when a M6 is issued. See the <> for more information on tool change options. @@ -242,7 +325,7 @@ index 253358f25f..1cb15521ad 100644 * No other changes will be made. For example, coolant will continue to flow during the tool change unless it has been turned off by an 'M9'. -@@ -183,9 +184,9 @@ When the tool change is complete: +@@ -185,9 +186,9 @@ When the tool change is complete: The 'T-' word is an integer number designating the tool pocket number in the carousel (not its index). @@ -255,7 +338,7 @@ index 253358f25f..1cb15521ad 100644 The tool change may include axis motion. It is OK (but not useful) to program a change to the tool already in the spindle. -@@ -351,9 +352,8 @@ cutters and wire spark eroders but it is not limited to such applications. +@@ -420,13 +421,13 @@ cutters and wire spark eroders but it is not limited to such applications. currently in the spindle you can set that tool number without doing a tool change. @@ -267,21 +350,53 @@ index 253358f25f..1cb15521ad 100644 It is an error if: + * Q- is not 0 or greater ++* Cutter radius compensation is on, as for 'M6'; this includes 'M61 Q0' + + [[mcode:m62-m65]] + == M62 - M65 Digital Output Control diff --git a/docs/src/gcode/overview.adoc b/docs/src/gcode/overview.adoc -index 3a201f1c11..6be6e716b6 100644 +index 90f9a06..777efc6 100644 --- a/docs/src/gcode/overview.adoc +++ b/docs/src/gcode/overview.adoc -@@ -337,6 +337,8 @@ example '##2' means the value of the parameter whose index is the +@@ -306,9 +306,11 @@ example '##2' means the value of the parameter whose index is the + failed to close. Used with G38.3 and G38.5. Volatile. + * '5081-5089' - Tool length offset currently applied to motion for X, Y, + Z, A, B, C, U, V & W, in the current program units. Set by +- `G43`/`G43.1`/`G43.2`, and 0 when `G49` is in effect. These report the ++ `G43`/`G43.1`/`G43.2`/`G43.4` and by the automatic activation of a ++ built-in `M6` or `M61`, and 0 when `G49` is in effect. A tool offset ++ taken from the tool table is its geometry plus wear. These report the + offset actually in effect, which differs from the loaded tool's stored +- offset in '5401-5409'. Volatile. ++ geometry in '5401-5409' and wear in '5430-5438'. Volatile. + * '5161-5169' - "G28" Home for X, Y, Z, A, B, C, U, V & W. Persistent. + * '5181-5189' - "G30" Home for X, Y, Z, A, B, C, U, V & W. Persistent. + * '5210' - 1 if "G52" or "G92" offset is currently applied, 0 +@@ -340,15 +342,18 @@ example '##2' means the value of the parameter whose index is the + Persistent. + * '5399' - Result of M66 - Check or wait for input. Volatile. + * '5400' - Tool Number. Volatile. +-* '5401-5409' - The loaded tool's stored offset for X, Y, Z, A, B, C, U, V +- & W. Refreshed from the tool table on tool change (`M6`), at startup, and +- by `G10 L1`/`L10`/`L11`. These are not affected by `G43`/`G43.1`/`G43.2` ++* '5401-5409' - The loaded tool's stored (geometry) offset for X, Y, Z, A, ++ B, C, U, V & W, without wear. Refreshed from the tool table on tool ++ change (`M6`, `M61`), at startup, and by `G10 L1`/`L3`/`L10`/`L11`. These are not affected by `G43`/`G43.1`/`G43.2` + or `G49`; for the offset actually applied to motion see '5081-5089'. + Volatile. + * '5410' - Tool Diameter. Volatile. * '5411' - Tool Front Angle. Volatile. * '5412' - Tool Back Angle. Volatile. * '5413' - Tool Orientation. Volatile. +* '5430-5438' - Stored wear offset for the loaded tool for X, Y, Z, A, B, -+ C, U, V & W. These remain populated while G49 is active. Volatile. ++ C, U, V & W. Refreshed like '5401-5409', and like them not affected by ++ `G43`-family codes or `G49`. Volatile. * '5420-5428' - Current relative position in the active coordinate system including all offsets and in the current program units for X, Y, Z, A, B, C, U, V & W, volatile. diff --git a/docs/src/gcode/tool-compensation.adoc b/docs/src/gcode/tool-compensation.adoc -index 1a64946d36..08dce373da 100644 +index 1a64946..4959eda 100644 --- a/docs/src/gcode/tool-compensation.adoc +++ b/docs/src/gcode/tool-compensation.adoc @@ -46,7 +46,7 @@ The 'Tool Table' is a text file that contains information about each tool. @@ -301,7 +416,17 @@ index 1a64946d36..08dce373da 100644 - D - tool diameter - floating-point, absolute value - I - front angle (lathe only) - floating-point - J - back angle (lathe only) - floating-point -@@ -83,6 +84,17 @@ Lines beginning with a semicolon are ignored. +@@ -80,9 +81,27 @@ In general, the tool table line format is: + + Tool numbers should be unique. + Lines beginning with a semicolon are ignored. ++A line may be at most 510 characters long, not counting its newline (a ++carriage return before it counts as a character); a longer line is refused ++with an error and its tool is not loaded. While a table loaded with refused ++lines is in use, LinuxCNC refuses to save it, since that would delete those ++lines: shorten them and reload the table. A tool whose line would be too ++long to write is refused the same way. A refused save keeps the file as it ++was, and the change that needed it is not kept either. The units used for the length, diameter, etc., are in machine units. @@ -319,7 +444,7 @@ index 1a64946d36..08dce373da 100644 You will probably want to keep the tool entries in ascending order, especially if you are going to be using a randomizing tool changer. Although the tool table does allow for tool numbers in any order. -@@ -114,6 +126,11 @@ This number will be used if tool length offsets are being used and this tool is +@@ -114,6 +133,11 @@ This number will be used if tool length offsets are being used and this tool is These numbers can be positive, zero, or negative, and are in fact completely optional. Although you will probably want to make at least one entry here, otherwise there would be little point in making an entry in the tool table to begin with. @@ -331,7 +456,7 @@ index 1a64946d36..08dce373da 100644 In a typical mill, you probably want an entry for Z (tool length offset). In a typical lathe, you probably want an entry for X (X tool offset) and Z (Z tool offset). In a typical mill using cutter diameter compensation (cutter comp), you probably also want to add an entry for D (cutter diameter). -@@ -223,7 +240,7 @@ so you can use P for any bookkeeping number you want. +@@ -223,7 +247,7 @@ so you can use P for any bookkeeping number you want. When using `[EMCIO]RANDOM_TOOLCHANGER = 0` (the default), the 'P' pocket number is a parameter of the tooldata that is retrieved from the tooldata source (`[EMCIO]TOOL_TABLE` or `[EMCIO]DB_PROGRAM`). In many applications it is fixed but it may be changed by edits to the `[EMCIO]TOOL_TABLE` or programmatically when the `[EMCIO]DB_PROGRAM` is used. @@ -341,10 +466,10 @@ index 1a64946d36..08dce373da 100644 .Random Location Tool Changers diff --git a/docs/src/tooldatabase/tooldatabase.adoc b/docs/src/tooldatabase/tooldatabase.adoc -index 0fab0191b2..8528da146e 100644 +index 0fab019..04d7c54 100644 --- a/docs/src/tooldatabase/tooldatabase.adoc +++ b/docs/src/tooldatabase/tooldatabase.adoc -@@ -32,12 +32,12 @@ The *db_program* may be implemented in any language currently supported in Linux +@@ -32,15 +32,16 @@ The *db_program* may be implemented in any language currently supported in Linux as long as it conforms to the interface messages received on stdin and replied on stdout. A *db_program* could manage data from a flat file, a relational database (SQLite for example), or other data sources. @@ -359,7 +484,11 @@ index 0fab0191b2..8528da146e 100644 No tools will be available if the version is not compatible with the LinuxCNC database interface version. . Upon a successful acknowledgement, LinuxCNC issues a 'g' (*get*) command to request all tools. The *db_program* must respond with a sequence of replies to identify each available tool. -@@ -56,7 +56,7 @@ The "'NAK'" message signifies a lack of synchronization between the *db_program* ++ Each reply line may be at most 510 characters long, not counting its newline; a longer reply is refused and that tool is left out of the tool data. + The textual reply format is identical to the text line format used in conventional tool table files. + A final response of "FINI" terminates the reply. + . The *db_program* then enters an event wait loop to receive commands that indicate that tool data has been changed by LinuxCNC. +@@ -56,7 +57,7 @@ The "'NAK'" message signifies a lack of synchronization between the *db_program* The commands issued for tool data changes are: @@ -368,8 +497,23 @@ index 0fab0191b2..8528da146e 100644 * "l" spindle_load (T__n__M6). The tool data line includes only the 'T' and 'P' items identifying the relevant tool number and pocket number. * "u" spindle_unload (T0M6). The tool data line includes only the 'T' and 'P' items identifying the relevant tool number and pocket number. +diff --git a/lib/python/rs274/glcanon_scene.py b/lib/python/rs274/glcanon_scene.py +index 72c5160..4db7b53 100644 +--- a/lib/python/rs274/glcanon_scene.py ++++ b/lib/python/rs274/glcanon_scene.py +@@ -1894,7 +1894,9 @@ class ToolPart(Part): + + def _draw_lathetool_geometry(self, ctx: FrameContext, + current_tool: Any) -> None: +- diameter, frontangle, backangle, orientation = current_tool[-4:] ++ # Fixed positions: a tool_table entry carries nine wear fields after ++ # orientation, so the last four are not the shape fields. ++ diameter, frontangle, backangle, orientation = current_tool[10:14] + w = 3/8. + radius = ctx.to_internal_linear_unit(diameter) / 2. + mvp = ctx.mv.mvp() diff --git a/lib/python/tooldb.py b/lib/python/tooldb.py -index 8ce720aadc..55a5dfe977 100644 +index 8ce720a..55a5dfe 100644 --- a/lib/python/tooldb.py +++ b/lib/python/tooldb.py @@ -8,7 +8,7 @@ import traceback @@ -382,7 +526,7 @@ index 8ce720aadc..55a5dfe977 100644 #----------------------------------------------------------- # functions for import by user diff --git a/src/emc/ini/linuxcnc_check_ini.py b/src/emc/ini/linuxcnc_check_ini.py -index 79acb0b873..d780715b90 100755 +index 79acb0b..d780715 100755 --- a/src/emc/ini/linuxcnc_check_ini.py +++ b/src/emc/ini/linuxcnc_check_ini.py @@ -231,7 +231,6 @@ def check_bools(): @@ -394,7 +538,7 @@ index 79acb0b873..d780715b90 100755 ("RS274NGC", "NO_DOWNCASE_OWORD"), ("RS274NGC", "OWORD_WARN_ONLY"), diff --git a/src/emc/ini/update_ini.py b/src/emc/ini/update_ini.py -index 5ddc9ec220..f6e34a12d1 100755 +index 5ddc9ec..f6e34a1 100755 --- a/src/emc/ini/update_ini.py +++ b/src/emc/ini/update_ini.py @@ -223,7 +223,6 @@ if version == "$Revision$" or version < "1.0": @@ -406,10 +550,22 @@ index 5ddc9ec220..f6e34a12d1 100755 section += ("HAL_PIN_VARS = %s\n" % ("1" if features & 0x8 else "0")) if features & 0x2: section += ("OWORD_NARGS = 1\n" ) diff --git a/src/emc/nml_intf/canon.hh b/src/emc/nml_intf/canon.hh -index 79b64caf03..23ef06ec5f 100644 +index 96e558d..68cf5d4 100644 --- a/src/emc/nml_intf/canon.hh +++ b/src/emc/nml_intf/canon.hh -@@ -652,7 +652,8 @@ extern void USE_SPINDLE_FORCE(); +@@ -261,6 +261,11 @@ extern void CANON_UPDATE_END_POINT(double x, double y, double z, + /* Called from emctask to update the canon position during skipping through + programs started with start-from-line > 0. */ + ++extern void CANON_RESYNC_TOOL_OFFSET(); ++/* Called from emctask on abort: queued commands are discarded, so canon's ++ tool offset, which USE_TOOL_LENGTH_OFFSET sets at read-ahead time, goes ++ back to the offset motion was actually given. */ ++ + extern void USE_LENGTH_UNITS(CANON_UNITS u); + + /* Use the specified units for length. Conceptually, the units must +@@ -663,7 +668,8 @@ extern void USE_SPINDLE_FORCE(); extern void USE_NO_SPINDLE_FORCE(); /* Tool Functions */ @@ -420,10 +576,19 @@ index 79b64caf03..23ef06ec5f 100644 extern void USE_TOOL_LENGTH_OFFSET(const EmcPose& offset); diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index 4665d2fe6c..5e69fbb997 100644 +index 27f5172..7a02127 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -1000,6 +1000,8 @@ void EMC_TOOL_SET_OFFSET::update(CMS * cms) +@@ -780,6 +780,8 @@ void EMC_COOLANT_CMD_MSG::update(CMS * /*cms*/) + void EMC_TOOL_LOAD::update(CMS * cms) + { + EMC_TOOL_CMD_MSG::update(cms); ++ cms->update(apply_offset); ++ EmcPose_update(cms, &offset); + } + + /* +@@ -1004,6 +1006,8 @@ void EMC_TOOL_SET_OFFSET::update(CMS * cms) cms->update(pocket); cms->update(toolno); EmcPose_update(cms, &offset); @@ -432,7 +597,16 @@ index 4665d2fe6c..5e69fbb997 100644 cms->update(diameter); cms->update(frontangle); cms->update(backangle); -@@ -1241,6 +1243,7 @@ void CANON_TOOL_TABLE_update(CMS * cms, CANON_TOOL_TABLE * x) +@@ -1021,6 +1025,8 @@ void EMC_TOOL_SET_NUMBER::update(CMS * cms) + { + EMC_TOOL_CMD_MSG::update(cms); + cms->update(tool); ++ cms->update(apply_offset); ++ EmcPose_update(cms, &offset); + } + + /* +@@ -1249,6 +1255,7 @@ void CANON_TOOL_TABLE_update(CMS * cms, CANON_TOOL_TABLE * x) { cms->update(x->toolno); EmcPose_update(cms, &x->offset); @@ -441,10 +615,10 @@ index 4665d2fe6c..5e69fbb997 100644 cms->update(x->frontangle); cms->update(x->backangle); diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index eadd123b99..a98ae39f20 100644 +index d8b6a4b..fb1faa8 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh -@@ -418,8 +418,10 @@ extern int emcToolPrepare(int tool); +@@ -439,9 +439,18 @@ extern int emcToolPrepare(int tool); extern int emcToolLoad(); extern int emcToolUnload(); extern int emcToolLoadToolTable(const char *file); @@ -455,13 +629,45 @@ index eadd123b99..a98ae39f20 100644 + double diameter, double frontangle, double backangle, + int orientation); extern int emcToolSetNumber(int number); ++// a built-in M6's tool offset: applied when the following emcToolLoad() ++// completes the change, dropped if the change is aborted ++extern void emcToolSetChangeOffset(bool apply, const EmcPose& offset); ++// apply a tool offset now: to motion and to emcStatus->task.toolOffset ++extern int emcToolApplyOffset(const EmcPose& offset); ++// how the IO side applies a completed change's offset (milltask) ++extern void emcToolRegisterApplyOffset(int (*fn)(const EmcPose&)); // implementation functions for EMC_AUX types + diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index 6b94fa62f0..92e21f800b 100644 +index 239d812..b41c212 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -1601,6 +1601,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { +@@ -1639,13 +1639,22 @@ class EMC_TOOL_PREPARE:public EMC_TOOL_CMD_MSG { + class EMC_TOOL_LOAD:public EMC_TOOL_CMD_MSG { + public: + EMC_TOOL_LOAD() +- : EMC_TOOL_CMD_MSG(EMC_TOOL_LOAD_TYPE, sizeof(EMC_TOOL_LOAD)) ++ : EMC_TOOL_CMD_MSG(EMC_TOOL_LOAD_TYPE, sizeof(EMC_TOOL_LOAD)), ++ apply_offset(false), ++ offset{} + {}; + + // For internal NML/CMS use only. + // Sub-class update() calls base-class update() + // cppcheck-suppress duplInheritedMember + void update(CMS * cms); ++ ++ // tool length offset (external units) that takes effect together with ++ // the tool, when the change completes: set by canon when the offset ++ // is commanded right behind the change (built-in M6, or G43/G49 in the ++ // same block) ++ bool apply_offset; ++ EmcPose offset; + }; + + class EMC_TOOL_UNLOAD:public EMC_TOOL_CMD_MSG { +@@ -1682,6 +1691,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { pocket(0), toolno(0), offset{}, @@ -470,7 +676,7 @@ index 6b94fa62f0..92e21f800b 100644 diameter(0.0), frontangle(0.0), backangle(0.0), -@@ -1615,6 +1617,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { +@@ -1696,6 +1707,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { int pocket; int toolno; EmcPose offset; @@ -479,28 +685,42 @@ index 6b94fa62f0..92e21f800b 100644 double diameter; double frontangle; double backangle; -diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc -index 734079d3af..6d91ef1bd0 100644 ---- a/src/emc/nml_intf/emcops.cc -+++ b/src/emc/nml_intf/emcops.cc -@@ -222,6 +222,7 @@ EMC_TOOL_STAT& EMC_TOOL_STAT::operator =(const EMC_TOOL_STAT& s) - toolTable[idx].toolno = s.toolTable[idx].toolno; - toolTable[idx].pocketno = s.toolTable[idx].pocketno; - toolTable[idx].offset = s.toolTable[idx].offset; -+ toolTable[idx].wear_offset = s.toolTable[idx].wear_offset; - toolTable[idx].diameter = s.toolTable[idx].diameter; - toolTable[idx].frontangle = s.toolTable[idx].frontangle; - toolTable[idx].backangle = s.toolTable[idx].backangle; +@@ -1706,7 +1719,9 @@ class EMC_TOOL_SET_NUMBER:public EMC_TOOL_CMD_MSG { + public: + EMC_TOOL_SET_NUMBER() + : EMC_TOOL_CMD_MSG(EMC_TOOL_SET_NUMBER_TYPE, sizeof(EMC_TOOL_SET_NUMBER)), +- tool(0) ++ tool(0), ++ apply_offset(false), ++ offset{} + {}; + + // For internal NML/CMS use only. +@@ -1715,6 +1730,10 @@ class EMC_TOOL_SET_NUMBER:public EMC_TOOL_CMD_MSG { + void update(CMS * cms); + + int tool; //number to use for currently loaded tool ++ // tool length offset taking effect together with the tool number (as ++ // EMC_TOOL_LOAD) ++ bool apply_offset; ++ EmcPose offset; + }; + + // EMC_TOOL status base class diff --git a/src/emc/nml_intf/emctool.h b/src/emc/nml_intf/emctool.h -index b8775910fe..12879116a4 100644 +index 3935368..ea18394 100644 --- a/src/emc/nml_intf/emctool.h +++ b/src/emc/nml_intf/emctool.h -@@ -23,13 +23,14 @@ +@@ -23,13 +23,18 @@ ** toolno: no restrictions (0: notool) */ #define CANON_POCKETS_MAX 1001 // max size of carousel handled -#define CANON_TOOL_ENTRY_LEN 256 // how long each file line can be +#define CANON_TOOL_ENTRY_LEN 512 // how long each file line can be ++// A tool line holds at most this many characters before its newline, so the ++// line, its newline and the terminating NUL fit CANON_TOOL_ENTRY_LEN. Longer ++// lines are refused, never cut. ++#define CANON_TOOL_LINE_MAX (CANON_TOOL_ENTRY_LEN - 2) #define CANON_TOOL_COMMENT_SIZE 40 // max comment string (include trailing null) struct CANON_TOOL_TABLE { @@ -511,12 +731,59 @@ index b8775910fe..12879116a4 100644 double diameter; double frontangle; double backangle; +@@ -37,8 +42,9 @@ struct CANON_TOOL_TABLE { + char comment[CANON_TOOL_COMMENT_SIZE]; + }; + +-/* default state of an entry: no tool, no pocket, zero geometry */ ++/* default state of an entry: no tool, no pocket, zero geometry and wear */ + #define CANON_TOOL_TABLE_INIT \ +- { -1, -1, { { 0, 0, 0 }, 0, 0, 0, 0, 0, 0 }, 0, 0, 0, 0, { 0 } } ++ { -1, -1, { { 0, 0, 0 }, 0, 0, 0, 0, 0, 0 }, \ ++ { { 0, 0, 0 }, 0, 0, 0, 0, 0, 0 }, 0, 0, 0, 0, { 0 } } + + #endif +diff --git a/src/emc/nml_intf/interpl.cc b/src/emc/nml_intf/interpl.cc +index 80fd26f..2385cec 100644 +--- a/src/emc/nml_intf/interpl.cc ++++ b/src/emc/nml_intf/interpl.cc +@@ -109,6 +109,16 @@ void NML_INTERP_LIST::print() + rcs_print("\n"); + } + ++NMLmsg *NML_INTERP_LIST::back(int skip_type) ++{ ++ for (auto i = linked_list.rbegin(); i != linked_list.rend(); ++i) { ++ if (i->command->_type != skip_type) { ++ return i->command.get(); ++ } ++ } ++ return nullptr; ++} ++ + int NML_INTERP_LIST::len() + { + return ((int)linked_list.size()); +diff --git a/src/emc/nml_intf/interpl.hh b/src/emc/nml_intf/interpl.hh +index b5ef165..e68f0f1 100644 +--- a/src/emc/nml_intf/interpl.hh ++++ b/src/emc/nml_intf/interpl.hh +@@ -41,6 +41,9 @@ public: + void clear(); + void print(); + int len(); ++ // the most recently appended command still on the list whose type is ++ // not skip_type, or nullptr ++ NMLmsg *back(int skip_type); + + private: + std::deque linked_list; diff --git a/src/emc/rs274ngc/gcodemodule.cc b/src/emc/rs274ngc/gcodemodule.cc -index 61c8f5fead..32aeed560b 100644 +index cb3d7ab..91d4b7b 100644 --- a/src/emc/rs274ngc/gcodemodule.cc +++ b/src/emc/rs274ngc/gcodemodule.cc -@@ -517,7 +517,8 @@ void COMMENT(const char *comment) { - Py_XDECREF(result); +@@ -603,7 +603,8 @@ void COMMENT(const char *comment) { + parse_state.canon->comment(comment); } -void SET_TOOL_TABLE_ENTRY(int /*pocket*/, int /*toolno*/, const EmcPose& /*offset*/, double /*diameter*/, @@ -525,22 +792,58 @@ index 61c8f5fead..32aeed560b 100644 double /*frontangle*/, double /*backangle*/, int /*orientation*/) { } -@@ -680,7 +681,9 @@ void GET_EXTERNAL_PARAMETER_FILE_NAME(char *name, int max_size) { +@@ -758,11 +759,15 @@ void GET_EXTERNAL_PARAMETER_FILE_NAME(char *name, int max_size) { } CANON_UNITS GET_EXTERNAL_LENGTH_UNIT_TYPE() { return CANON_UNITS_INCHES; } CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int pocket) { - CANON_TOOL_TABLE tdata = {-1,-1,{{0,0,0},0,0,0,0,0,0},0,0,0,0,{}}; -+ CANON_TOOL_TABLE tdata{}; -+ tdata.toolno = -1; -+ tdata.pocketno = -1; - if(interp_error) return tdata; - PyObject *result = - callmethod(callback, "get_tool", "i", pocket); ++ CANON_TOOL_TABLE tdata = CANON_TOOL_TABLE_INIT; + canon_guard([&]{ + py::object result = py::handle(parse_state.callback).attr("get_tool")(pocket); +- if(!PyTuple_Check(result.ptr()) || PyTuple_GET_SIZE(result.ptr()) != 14) +- throw py::type_error("get_tool: expected a tuple of 14 items"); ++ // 14 items is the geometry-only entry older callers return; 23 is ++ // a full linuxcnc.stat tool_table entry, whose last nine are wear. ++ const Py_ssize_t size = ++ PyTuple_Check(result.ptr()) ? PyTuple_GET_SIZE(result.ptr()) : -1; ++ if(size != 14 && size != 23) ++ throw py::type_error("get_tool: expected a tuple of 14 or 23 items"); + py::tuple t = py::reinterpret_borrow(result); + // Filled only once every field parsed, so a bad entry leaves the + // caller the same all-defaults table PyArg_ParseTuple used to. +@@ -781,6 +786,17 @@ CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int pocket) { + got.frontangle = py::cast(t[11]); + got.backangle = py::cast(t[12]); + got.orientation = py::cast(t[13]); ++ if(size == 23) { ++ got.wear_offset.tran.x = py::cast(t[14]); ++ got.wear_offset.tran.y = py::cast(t[15]); ++ got.wear_offset.tran.z = py::cast(t[16]); ++ got.wear_offset.a = py::cast(t[17]); ++ got.wear_offset.b = py::cast(t[18]); ++ got.wear_offset.c = py::cast(t[19]); ++ got.wear_offset.u = py::cast(t[20]); ++ got.wear_offset.v = py::cast(t[21]); ++ got.wear_offset.w = py::cast(t[22]); ++ } + tdata = got; + }); + return tdata; +@@ -990,6 +1006,9 @@ static py::object parse_file(const char *f, py::handle canon, + parse_state.last_sequence_number = -1; + + parse_state.pos = {}; ++ // the interpreter takes its applied tool offset from here when init() ++ // synchronises it: a parse starts with none, not the previous parse's ++ parse_state.tool_offset = {}; + + parse_state.pinterp->init(); + parse_state.pinterp->open(f); diff --git a/src/emc/rs274ngc/interp_array.cc b/src/emc/rs274ngc/interp_array.cc -index ba233a1d88..ba393b5b9f 100644 +index 6eb4e1c..a900d33 100644 --- a/src/emc/rs274ngc/interp_array.cc +++ b/src/emc/rs274ngc/interp_array.cc -@@ -243,6 +243,7 @@ const int Interp::readonly_parameters[] = { +@@ -244,6 +244,7 @@ const int Interp::readonly_parameters[] = { 5412, // tool backangle 5413, // tool orientation 5420, 5421, 5422, 5423, 5424, 5425, 5426, 5427, 5428, // current X Y ... W @@ -549,7 +852,7 @@ index ba233a1d88..ba393b5b9f 100644 const int Interp::n_readonly_parameters = sizeof(readonly_parameters) / sizeof(int); diff --git a/src/emc/rs274ngc/interp_check.cc b/src/emc/rs274ngc/interp_check.cc -index b5c9749c54..cf3b8050c9 100644 +index fc5ae57..c65a3b2 100644 --- a/src/emc/rs274ngc/interp_check.cc +++ b/src/emc/rs274ngc/interp_check.cc @@ -89,10 +89,10 @@ int Interp::check_g_codes(block_pointer block, //!< pointer to a block to be c @@ -566,15 +869,11 @@ index b5c9749c54..cf3b8050c9 100644 } else if (mode0 == G_30) { } else if (mode0 == G_5_3) { diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index be11b73201..99f9e6fdb8 100644 +index 450922e..ab502ad 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -3817,9 +3817,11 @@ convert_stop). - */ - - int Interp::convert_m(block_pointer block, //!< pointer to a block of RS274/NGC instructions -- setup_pointer settings) //!< pointer to machine settings -+ setup_pointer settings) //!< pointer to machine settings +@@ -4013,6 +4013,8 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 + setup_pointer settings) //!< pointer to machine settings { int type; + bool builtin_tool_change = false; @@ -582,42 +881,52 @@ index be11b73201..99f9e6fdb8 100644 double timeout; // timeout for M66 /* The M62-65 commands are used for DIO */ -@@ -3954,7 +3956,9 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 - // the code was used in its very remap procedure - +@@ -4148,6 +4150,12 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 // the 'recursion case'; record the fact CONTROLLING_BLOCK(*settings).builtin_used = !remapped_in_block; -- CHP(convert_tool_change(settings)); -+ CHP(convert_tool_change(settings)); -+ builtin_tool_change = true; -+ changed_toolno = settings->selected_tool; + CHP(convert_tool_change(settings)); ++ builtin_tool_change = true; ++ // The tool just loaded, from its pocket: selected_tool is not ++ // resynchronised after an abort, the pocket is (upstream ++ // RETAIN_G43 also decides on the pocket). ++ changed_toolno = settings->current_pocket > 0 ++ ? settings->tool_table[settings->current_pocket].toolno : 0; } break; -@@ -3974,8 +3978,10 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 - CHP((find_tool_index(settings, toolno, &idx))); - settings->current_pocket = idx; +@@ -4160,6 +4168,10 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 + toolno = round_to_int(block->q_number); + // now also accept M61 Q0 - unload tool + CHKS((toolno < 0), (_("Need non-negative Q-word to specify tool number with M61"))); ++ // M61 applies the new tool's offset like M6, so it is refused ++ // under cutter compensation like M6, before anything changes ++ CHKS((settings->cutter_comp_side != CUTTER_COMP::OFF), ++ (_("Cannot change tools with cutter radius compensation on"))); + + int idx; + +@@ -4169,6 +4181,8 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 settings->toolchange_flag = true; -- CHANGE_TOOL_NUMBER(settings->current_pocket); -- set_tool_parameters(); -+ CHANGE_TOOL_NUMBER(settings->current_pocket); -+ set_tool_parameters(); -+ builtin_tool_change = true; -+ changed_toolno = toolno; + CHANGE_TOOL_NUMBER(settings->current_pocket); + set_tool_parameters(); ++ builtin_tool_change = true; ++ changed_toolno = toolno; } break; -@@ -3987,21 +3993,28 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 +@@ -4180,22 +4194,31 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 } } - if (FEATURE(RETAIN_G43)) { - -- if ((settings->active_g_codes[9] == G_43) && ONCE(STEP_RETAIN_G43)) { +- if (((settings->active_g_codes[9] == G_43) || +- (settings->active_g_codes[9] == G_43_4)) && ONCE(STEP_RETAIN_G43)) { - if(settings->selected_pocket > 0) { - struct block_struct g43; - init_block(&g43); -- block->g_modes[gees[G_43]] = G_43; -- CHP(convert_tool_length_offset(G_43, &g43, settings)); +- block->g_modes[gees[settings->active_g_codes[9]]] = settings->active_g_codes[9]; +- CHP(convert_tool_length_offset(settings->active_g_codes[9], &g43, settings)); - } else { - struct block_struct g49; - init_block(&g49); @@ -645,12 +954,15 @@ index be11b73201..99f9e6fdb8 100644 + settings->parameters[5437] = loaded_tool.wear_offset.v; + settings->parameters[5438] = loaded_tool.wear_offset.w; + } -+ const int tlo_code = no_tool ? G_49 : G_43; ++ // Re-apply as G43.4 while the offset in effect is still G43.4's, so a ++ // later G49 still undoes its kinematics switch; otherwise plain G43. ++ const int tlo_code = no_tool ? G_49 : ++ settings->kins_by_g43_4 ? G_43_4 : G_43; + CHP(convert_tool_length_offset(tlo_code, &automatic_tlo, settings)); } if (is_user_defined_m_code(block, settings, 7) && ONCE_M(7)) { -@@ -4276,7 +4289,7 @@ int Interp::convert_modal_0(int code, //!< G-code, must be from group 0 +@@ -4464,7 +4487,7 @@ int Interp::convert_modal_0(int code, //!< G-code, must be from group 0 { if (code == G_10) { @@ -659,7 +971,7 @@ index be11b73201..99f9e6fdb8 100644 CHP(convert_setup_tool(block, settings)); else if (block->l_number == 0) { int tno = settings->tool_table[0].toolno; -@@ -4531,7 +4544,8 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { +@@ -4731,7 +4754,8 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { int idx = -1, toolno; int q; double tx, ty, tz, ta, tb, tc, tu, tv, tw; @@ -669,17 +981,17 @@ index be11b73201..99f9e6fdb8 100644 is_near_int(&toolno, block->p_number); -@@ -4542,9 +4556,31 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { +@@ -4742,9 +4766,31 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { block->u_flag || block->v_flag || block->w_flag || block->r_flag || block->q_flag || block->i_flag || block->j_flag), - _("G10 L1 without offsets has no effect")); + _("G10 tool update without offsets has no effect")); - -- if(direct) { ++ + CHKS((wear && (block->r_flag || block->i_flag || block->j_flag || block->q_flag)), + _("G10 L3 does not allow R, I, J, or Q words")); -+ + +- if(direct) { + if (wear) { + if(block->x_flag) + settings->tool_table[idx].wear_offset.tran.x = PROGRAM_TO_USER_LEN(block->x_number); @@ -688,23 +1000,23 @@ index be11b73201..99f9e6fdb8 100644 + if(block->z_flag) + settings->tool_table[idx].wear_offset.tran.z = PROGRAM_TO_USER_LEN(block->z_number); + if(block->a_flag) -+ settings->tool_table[idx].wear_offset.a = PROGRAM_TO_USER_ANG(block->a_number); ++ settings->tool_table[idx].wear_offset.a = PROGRAM_TO_USER_AX(AXIS_A, block->a_number); + if(block->b_flag) -+ settings->tool_table[idx].wear_offset.b = PROGRAM_TO_USER_ANG(block->b_number); ++ settings->tool_table[idx].wear_offset.b = PROGRAM_TO_USER_AX(AXIS_B, block->b_number); + if(block->c_flag) -+ settings->tool_table[idx].wear_offset.c = PROGRAM_TO_USER_ANG(block->c_number); ++ settings->tool_table[idx].wear_offset.c = PROGRAM_TO_USER_AX(AXIS_C, block->c_number); + if(block->u_flag) -+ settings->tool_table[idx].wear_offset.u = PROGRAM_TO_USER_LEN(block->u_number); ++ settings->tool_table[idx].wear_offset.u = PROGRAM_TO_USER_AX(AXIS_U, block->u_number); + if(block->v_flag) -+ settings->tool_table[idx].wear_offset.v = PROGRAM_TO_USER_LEN(block->v_number); ++ settings->tool_table[idx].wear_offset.v = PROGRAM_TO_USER_AX(AXIS_V, block->v_number); + if(block->w_flag) -+ settings->tool_table[idx].wear_offset.w = PROGRAM_TO_USER_LEN(block->w_number); ++ settings->tool_table[idx].wear_offset.w = PROGRAM_TO_USER_AX(AXIS_W, block->w_number); + } else if(direct) { if(block->x_flag) settings->tool_table[idx].offset.tran.x = PROGRAM_TO_USER_LEN(block->x_number); if(block->y_flag) -@@ -4644,10 +4680,10 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { - settings->tool_table[idx].offset.w = PROGRAM_TO_USER_LEN(tw - block->w_number); +@@ -4844,10 +4890,10 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { + settings->tool_table[idx].offset.w = PROGRAM_TO_USER_AX(AXIS_W, tw - block->w_number); } - if(block->r_flag) settings->tool_table[idx].diameter = PROGRAM_TO_USER_LEN(block->r_number) * 2.; @@ -718,7 +1030,7 @@ index be11b73201..99f9e6fdb8 100644 CHKS((!is_near_int(&q, block->q_number)), _("Q number in G10 is not an integer")); CHKS((q > 9), _("Invalid tool orientation")); settings->tool_table[idx].orientation = q; -@@ -4656,6 +4692,7 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { +@@ -4856,6 +4902,7 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { SET_TOOL_TABLE_ENTRY(idx, settings->tool_table[idx].toolno, settings->tool_table[idx].offset, @@ -726,7 +1038,7 @@ index be11b73201..99f9e6fdb8 100644 settings->tool_table[idx].diameter, settings->tool_table[idx].frontangle, settings->tool_table[idx].backangle, -@@ -4700,6 +4737,15 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { +@@ -4910,6 +4957,15 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { settings->parameters[5411] = settings->tool_table[0].frontangle; settings->parameters[5412] = settings->tool_table[0].backangle; settings->parameters[5413] = settings->tool_table[0].orientation; @@ -742,7 +1054,7 @@ index be11b73201..99f9e6fdb8 100644 // if the modified tool is currently in the spindle, then copy its // information to index 0 of the tool table (which signifies the -@@ -4709,6 +4755,7 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { +@@ -4919,6 +4975,7 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { SET_TOOL_TABLE_ENTRY(0, settings->tool_table[idx].toolno, settings->tool_table[idx].offset, @@ -750,7 +1062,7 @@ index be11b73201..99f9e6fdb8 100644 settings->tool_table[idx].diameter, settings->tool_table[idx].frontangle, settings->tool_table[idx].backangle, -@@ -6099,11 +6146,9 @@ This implements the "Next tool in T word" approach to tool selection. +@@ -6438,11 +6495,9 @@ This implements the "Next tool in T word" approach to tool selection. The tool is selected when the T word is read (and the carousel may move at that time) but is changed when M6 is read. @@ -765,69 +1077,109 @@ index be11b73201..99f9e6fdb8 100644 */ -@@ -6266,15 +6311,15 @@ int Interp::convert_tool_length_offset(int g_code, //!< g_code being execu +@@ -6662,15 +6717,15 @@ int Interp::convert_tool_length_offset(int g_code, //!< g_code being execu logDebug("convert_tool_length_offset: using index=%d spindle_toolno=%d pocket_toolno=%d", idx, settings->tool_table[0].toolno,settings->tool_table[settings->current_pocket].toolno); - tool_offset.tran.x = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.x); - tool_offset.tran.y = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.y); - tool_offset.tran.z = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.z); -- tool_offset.a = USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.a); -- tool_offset.b = USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.b); -- tool_offset.c = USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.c); -- tool_offset.u = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.u); -- tool_offset.v = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.v); -- tool_offset.w = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.w); +- tool_offset.a = USER_TO_PROGRAM_AX(AXIS_A, settings->tool_table[idx].offset.a); +- tool_offset.b = USER_TO_PROGRAM_AX(AXIS_B, settings->tool_table[idx].offset.b); +- tool_offset.c = USER_TO_PROGRAM_AX(AXIS_C, settings->tool_table[idx].offset.c); +- tool_offset.u = USER_TO_PROGRAM_AX(AXIS_U, settings->tool_table[idx].offset.u); +- tool_offset.v = USER_TO_PROGRAM_AX(AXIS_V, settings->tool_table[idx].offset.v); +- tool_offset.w = USER_TO_PROGRAM_AX(AXIS_W, settings->tool_table[idx].offset.w); + tool_offset.tran.x = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.x + settings->tool_table[idx].wear_offset.tran.x); + tool_offset.tran.y = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.y + settings->tool_table[idx].wear_offset.tran.y); + tool_offset.tran.z = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.z + settings->tool_table[idx].wear_offset.tran.z); -+ tool_offset.a = USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.a + settings->tool_table[idx].wear_offset.a); -+ tool_offset.b = USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.b + settings->tool_table[idx].wear_offset.b); -+ tool_offset.c = USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.c + settings->tool_table[idx].wear_offset.c); -+ tool_offset.u = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.u + settings->tool_table[idx].wear_offset.u); -+ tool_offset.v = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.v + settings->tool_table[idx].wear_offset.v); -+ tool_offset.w = USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.w + settings->tool_table[idx].wear_offset.w); ++ tool_offset.a = USER_TO_PROGRAM_AX(AXIS_A, settings->tool_table[idx].offset.a + settings->tool_table[idx].wear_offset.a); ++ tool_offset.b = USER_TO_PROGRAM_AX(AXIS_B, settings->tool_table[idx].offset.b + settings->tool_table[idx].wear_offset.b); ++ tool_offset.c = USER_TO_PROGRAM_AX(AXIS_C, settings->tool_table[idx].offset.c + settings->tool_table[idx].wear_offset.c); ++ tool_offset.u = USER_TO_PROGRAM_AX(AXIS_U, settings->tool_table[idx].offset.u + settings->tool_table[idx].wear_offset.u); ++ tool_offset.v = USER_TO_PROGRAM_AX(AXIS_V, settings->tool_table[idx].offset.v + settings->tool_table[idx].wear_offset.v); ++ tool_offset.w = USER_TO_PROGRAM_AX(AXIS_W, settings->tool_table[idx].offset.w + settings->tool_table[idx].wear_offset.w); settings->g43_with_zero_offset = !(tool_offset.tran.x || tool_offset.tran.y || tool_offset.tran.z || tool_offset.a || tool_offset.b || tool_offset.c || -@@ -6301,15 +6346,15 @@ int Interp::convert_tool_length_offset(int g_code, //!< g_code being execu +@@ -6697,15 +6752,15 @@ int Interp::convert_tool_length_offset(int g_code, //!< g_code being execu tool_offset = settings->tool_offset; if (block->h_flag){ CHP((find_tool_index(settings, block->h_number, &idx))); - tool_offset.tran.x += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.x); - tool_offset.tran.y += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.y); - tool_offset.tran.z += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.z); -- tool_offset.a += USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.a); -- tool_offset.b += USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.b); -- tool_offset.c += USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.c); -- tool_offset.u += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.u); -- tool_offset.v += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.v); -- tool_offset.w += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.w); +- tool_offset.a += USER_TO_PROGRAM_AX(AXIS_A, settings->tool_table[idx].offset.a); +- tool_offset.b += USER_TO_PROGRAM_AX(AXIS_B, settings->tool_table[idx].offset.b); +- tool_offset.c += USER_TO_PROGRAM_AX(AXIS_C, settings->tool_table[idx].offset.c); +- tool_offset.u += USER_TO_PROGRAM_AX(AXIS_U, settings->tool_table[idx].offset.u); +- tool_offset.v += USER_TO_PROGRAM_AX(AXIS_V, settings->tool_table[idx].offset.v); +- tool_offset.w += USER_TO_PROGRAM_AX(AXIS_W, settings->tool_table[idx].offset.w); + tool_offset.tran.x += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.x + settings->tool_table[idx].wear_offset.tran.x); + tool_offset.tran.y += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.y + settings->tool_table[idx].wear_offset.tran.y); + tool_offset.tran.z += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.tran.z + settings->tool_table[idx].wear_offset.tran.z); -+ tool_offset.a += USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.a + settings->tool_table[idx].wear_offset.a); -+ tool_offset.b += USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.b + settings->tool_table[idx].wear_offset.b); -+ tool_offset.c += USER_TO_PROGRAM_ANG(settings->tool_table[idx].offset.c + settings->tool_table[idx].wear_offset.c); -+ tool_offset.u += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.u + settings->tool_table[idx].wear_offset.u); -+ tool_offset.v += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.v + settings->tool_table[idx].wear_offset.v); -+ tool_offset.w += USER_TO_PROGRAM_LEN(settings->tool_table[idx].offset.w + settings->tool_table[idx].wear_offset.w); ++ tool_offset.a += USER_TO_PROGRAM_AX(AXIS_A, settings->tool_table[idx].offset.a + settings->tool_table[idx].wear_offset.a); ++ tool_offset.b += USER_TO_PROGRAM_AX(AXIS_B, settings->tool_table[idx].offset.b + settings->tool_table[idx].wear_offset.b); ++ tool_offset.c += USER_TO_PROGRAM_AX(AXIS_C, settings->tool_table[idx].offset.c + settings->tool_table[idx].wear_offset.c); ++ tool_offset.u += USER_TO_PROGRAM_AX(AXIS_U, settings->tool_table[idx].offset.u + settings->tool_table[idx].wear_offset.u); ++ tool_offset.v += USER_TO_PROGRAM_AX(AXIS_V, settings->tool_table[idx].offset.v + settings->tool_table[idx].wear_offset.v); ++ tool_offset.w += USER_TO_PROGRAM_AX(AXIS_W, settings->tool_table[idx].offset.w + settings->tool_table[idx].wear_offset.w); } else { if(block->x_flag) tool_offset.tran.x += block->x_number; if(block->y_flag) tool_offset.tran.y += block->y_number; +@@ -6749,15 +6804,7 @@ int Interp::convert_tool_length_offset(int g_code, //!< g_code being execu + // G10 L1. See issue #2994. + // tool_offset here is in program units; params follow the user-unit + // convention used elsewhere. +- settings->parameters[5081] = PROGRAM_TO_USER_LEN(tool_offset.tran.x); +- settings->parameters[5082] = PROGRAM_TO_USER_LEN(tool_offset.tran.y); +- settings->parameters[5083] = PROGRAM_TO_USER_LEN(tool_offset.tran.z); +- settings->parameters[5084] = PROGRAM_TO_USER_AX(AXIS_A, tool_offset.a); +- settings->parameters[5085] = PROGRAM_TO_USER_AX(AXIS_B, tool_offset.b); +- settings->parameters[5086] = PROGRAM_TO_USER_AX(AXIS_C, tool_offset.c); +- settings->parameters[5087] = PROGRAM_TO_USER_AX(AXIS_U, tool_offset.u); +- settings->parameters[5088] = PROGRAM_TO_USER_AX(AXIS_V, tool_offset.v); +- settings->parameters[5089] = PROGRAM_TO_USER_AX(AXIS_W, tool_offset.w); ++ set_applied_tool_offset_parameters(settings); + + if (g_code == G_49 && settings->kins_by_g43_4) { + // G49 undoes what G43.4 did: after the cancel it drops the machine +@@ -6808,6 +6855,22 @@ int Interp::convert_tool_select(block_pointer block, //!< pointer to a block + return INTERP_OK; + } + ++/* #5081-#5089 from the applied offset settings->tool_offset (program ++ units), in the user-unit convention of the other offset parameters. */ ++void Interp::set_applied_tool_offset_parameters(setup_pointer settings) ++{ ++ const EmcPose &tool_offset = settings->tool_offset; ++ settings->parameters[5081] = PROGRAM_TO_USER_LEN(tool_offset.tran.x); ++ settings->parameters[5082] = PROGRAM_TO_USER_LEN(tool_offset.tran.y); ++ settings->parameters[5083] = PROGRAM_TO_USER_LEN(tool_offset.tran.z); ++ settings->parameters[5084] = PROGRAM_TO_USER_AX(AXIS_A, tool_offset.a); ++ settings->parameters[5085] = PROGRAM_TO_USER_AX(AXIS_B, tool_offset.b); ++ settings->parameters[5086] = PROGRAM_TO_USER_AX(AXIS_C, tool_offset.c); ++ settings->parameters[5087] = PROGRAM_TO_USER_AX(AXIS_U, tool_offset.u); ++ settings->parameters[5088] = PROGRAM_TO_USER_AX(AXIS_V, tool_offset.v); ++ settings->parameters[5089] = PROGRAM_TO_USER_AX(AXIS_W, tool_offset.w); ++} ++ + /*! convert_kins_switch + + Returned Value: int (INTERP_OK) diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh -index b734b66ee8..fed82a67d8 100644 +index 8066f0e..6f90dbe 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh -@@ -342,7 +342,6 @@ enum phases { - STEP_PREPARE, +@@ -366,7 +366,6 @@ enum phases { + STEP_M_3, STEP_M_5, STEP_M_6, - STEP_RETAIN_G43, STEP_M_7, STEP_M_8, STEP_M_9, -@@ -837,7 +836,6 @@ struct setup +@@ -887,7 +886,6 @@ struct setup bool iscircle; #define FEATURE(x) (_setup.feature_set & FEATURE_ ## x) @@ -836,10 +1188,10 @@ index b734b66ee8..fed82a67d8 100644 #define FEATURE_INI_VARS 0x00000004 #define FEATURE_HAL_PIN_VARS 0x00000008 diff --git a/src/emc/rs274ngc/interp_parameter_def.hh b/src/emc/rs274ngc/interp_parameter_def.hh -index 6892840940..a4c17dab21 100644 +index d0c81d3..666b4d5 100644 --- a/src/emc/rs274ngc/interp_parameter_def.hh +++ b/src/emc/rs274ngc/interp_parameter_def.hh -@@ -196,6 +196,16 @@ enum InterpParameterIndex { +@@ -206,6 +206,16 @@ enum InterpParameterIndex { RELATIVE_POSITION_U, RELATIVE_POSITION_V, RELATIVE_POSITION_W, @@ -857,7 +1209,7 @@ index 6892840940..a4c17dab21 100644 DEBUG_LEVEL_FLAG=5599, RS274NGC_MAX_PARAMETERS=5602 diff --git a/src/emc/rs274ngc/pyemctypes.cc b/src/emc/rs274ngc/pyemctypes.cc -index fb5b346db9..5107e0e55b 100644 +index fb5b346..5107e0e 100644 --- a/src/emc/rs274ngc/pyemctypes.cc +++ b/src/emc/rs274ngc/pyemctypes.cc @@ -57,6 +57,7 @@ static bp::object tool_str( CANON_TOOL_TABLE &t) { @@ -876,11 +1228,23 @@ index fb5b346db9..5107e0e55b 100644 .def_readwrite("diameter", &CANON_TOOL_TABLE::diameter) .def_readwrite("frontangle", &CANON_TOOL_TABLE::frontangle) .def_readwrite("backangle", &CANON_TOOL_TABLE::backangle) +diff --git a/src/emc/rs274ngc/rs274ngc_interp.hh b/src/emc/rs274ngc/rs274ngc_interp.hh +index 6054da8..e834041 100644 +--- a/src/emc/rs274ngc/rs274ngc_interp.hh ++++ b/src/emc/rs274ngc/rs274ngc_interp.hh +@@ -138,6 +138,7 @@ public: + int init_tool_parameters(); + int default_tool_parameters(); + int set_tool_parameters(); ++ void set_applied_tool_offset_parameters(setup_pointer settings); + + int on_abort(int reason, const char *message) override; + diff --git a/src/emc/rs274ngc/rs274ngc_pre.cc b/src/emc/rs274ngc/rs274ngc_pre.cc -index 2ea4bf5550..a4ef597412 100644 +index ac70436..2ea3ba1 100644 --- a/src/emc/rs274ngc/rs274ngc_pre.cc +++ b/src/emc/rs274ngc/rs274ngc_pre.cc -@@ -901,8 +901,6 @@ int Interp::init() +@@ -933,8 +933,6 @@ int Interp::init() _setup.feature_set |= FEATURE_HAL_PIN_VARS; // Now those that (currently) default to off @@ -889,7 +1253,26 @@ index 2ea4bf5550..a4ef597412 100644 if (inifile.findBoolV("OWORD_NARGS", "RS274NGC", false)) _setup.feature_set |= FEATURE_OWORD_N_ARGS; if (inifile.findBoolV("NO_DOWNCASE_OWORD", "RS274NGC", false)) -@@ -2544,10 +2542,21 @@ int Interp::init_tool_parameters() +@@ -2130,6 +2128,18 @@ int Interp::synch() + _setup.flood = GET_EXTERNAL_FLOOD(); + _setup.length_units = GET_EXTERNAL_LENGTH_UNIT_TYPE(); + _setup.mist = GET_EXTERNAL_MIST(); ++ // The applied tool offset is canon's: after an abort it is the offset ++ // motion was given, not one read ahead and then discarded. ++ _setup.tool_offset.tran.x = GET_EXTERNAL_TOOL_LENGTH_XOFFSET(); ++ _setup.tool_offset.tran.y = GET_EXTERNAL_TOOL_LENGTH_YOFFSET(); ++ _setup.tool_offset.tran.z = GET_EXTERNAL_TOOL_LENGTH_ZOFFSET(); ++ _setup.tool_offset.a = GET_EXTERNAL_TOOL_LENGTH_AOFFSET(); ++ _setup.tool_offset.b = GET_EXTERNAL_TOOL_LENGTH_BOFFSET(); ++ _setup.tool_offset.c = GET_EXTERNAL_TOOL_LENGTH_COFFSET(); ++ _setup.tool_offset.u = GET_EXTERNAL_TOOL_LENGTH_UOFFSET(); ++ _setup.tool_offset.v = GET_EXTERNAL_TOOL_LENGTH_VOFFSET(); ++ _setup.tool_offset.w = GET_EXTERNAL_TOOL_LENGTH_WOFFSET(); ++ set_applied_tool_offset_parameters(&_setup); + _setup.plane = GET_EXTERNAL_PLANE(); + _setup.kins_type = GET_EXTERNAL_KINS_TYPE(); + _setup.traverse_rate = GET_EXTERNAL_TRAVERSE_RATE(); +@@ -2632,10 +2642,21 @@ int Interp::init_tool_parameters() _setup.parameters[5411] = _setup.tool_table[0].frontangle; _setup.parameters[5412] = _setup.tool_table[0].backangle; _setup.parameters[5413] = _setup.tool_table[0].orientation; @@ -911,7 +1294,7 @@ index 2ea4bf5550..a4ef597412 100644 } } return 0; -@@ -2562,6 +2571,9 @@ int Interp::default_tool_parameters() +@@ -2657,6 +2678,9 @@ int Interp::default_tool_parameters() _setup.parameters[5411] = 0; // frontangle _setup.parameters[5412] = 0; // backangle _setup.parameters[5413] = 0; // orientation @@ -921,16 +1304,7 @@ index 2ea4bf5550..a4ef597412 100644 return 0; } -@@ -2583,13 +2595,21 @@ int Interp::set_tool_parameters() - _setup.tool_table[0].comment); - #endif //} - _setup.parameters[5400] = _setup.tool_table[0].toolno; -- // #5401-#5409 reflect the applied tool length offset (G43-family) and -- // are deliberately not updated by M6: M6 changes the loaded tool but -- // does not by itself apply its offset to motion. See #2994. -+ // #5401-#5409 reflect the applied tool length offset (G43-family). -+ // Built-in tool changes update them through convert_tool_length_offset. - _setup.parameters[5410] = _setup.tool_table[0].diameter; +@@ -2694,6 +2718,15 @@ int Interp::set_tool_parameters() _setup.parameters[5411] = _setup.tool_table[0].frontangle; _setup.parameters[5412] = _setup.tool_table[0].backangle; _setup.parameters[5413] = _setup.tool_table[0].orientation; @@ -947,10 +1321,10 @@ index 2ea4bf5550..a4ef597412 100644 return 0; } diff --git a/src/emc/sai/saicanon.cc b/src/emc/sai/saicanon.cc -index c63354d6a4..b349f4952d 100644 +index d60d661..73a77d2 100644 --- a/src/emc/sai/saicanon.cc +++ b/src/emc/sai/saicanon.cc -@@ -507,12 +507,14 @@ void USE_NO_SPINDLE_FORCE() +@@ -513,12 +513,14 @@ void USE_NO_SPINDLE_FORCE() {PRINT("USE_NO_SPINDLE_FORCE()\n");} /* Tool Functions */ @@ -966,7 +1340,7 @@ index c63354d6a4..b349f4952d 100644 _sai._tools[idx].diameter = diameter; _sai._tools[idx].frontangle = frontangle; _sai._tools[idx].backangle = backangle; -@@ -524,6 +526,7 @@ void SET_TOOL_TABLE_ENTRY(int idx, int toolno, const EmcPose& offset, double dia +@@ -530,6 +532,7 @@ void SET_TOOL_TABLE_ENTRY(int idx, int toolno, const EmcPose& offset, double dia } tdata.toolno = toolno; tdata.offset = offset; @@ -975,10 +1349,10 @@ index c63354d6a4..b349f4952d 100644 tdata.frontangle = frontangle; tdata.backangle = backangle; diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc -index d2a0e0d0f2..e5d71a60e8 100644 +index 706a6e4..92c2d99 100644 --- a/src/emc/task/emccanon.cc +++ b/src/emc/task/emccanon.cc -@@ -3072,13 +3072,16 @@ void USE_NO_SPINDLE_FORCE(void) +@@ -2914,13 +2914,16 @@ void USE_NO_SPINDLE_FORCE(void) /* Tool Functions */ /* this is called with distances in external (machine) units */ @@ -996,16 +1370,165 @@ index d2a0e0d0f2..e5d71a60e8 100644 o->diameter = diameter; o->frontangle = frontangle; o->backangle = backangle; -@@ -4362,4 +4365,3 @@ int LOCK_ROTARY(int /*line_number*/, int /*joint_num*/) { +@@ -2961,12 +2964,50 @@ void USE_TOOL_LENGTH_OFFSET(const EmcPose& offset) + set_offset_msg->offset.v = TO_EXT_AX(AXIS_V, canon.toolOffset.v); + set_offset_msg->offset.w = TO_EXT_AX(AXIS_W, canon.toolOffset.w); + ++ /* An offset commanded right behind a tool change (the automatic ++ activation of a built-in M6 or M61, or a G43/G49 in the same block) ++ travels with the change and takes effect when the tool does, so an ++ abort can never leave one without the other. Spindle speeds this ++ function queued for CSS run after the change anyway; anything else ++ queued in between, or no change at all, keeps the separate command. */ ++ NMLmsg *last = interp_list.back(EMC_SPINDLE_SPEED_TYPE); ++ bool with_change = false; ++ if (last && last->_type == EMC_TOOL_LOAD_TYPE) { ++ auto *load = static_cast(last); ++ load->apply_offset = true; ++ load->offset = set_offset_msg->offset; ++ with_change = true; ++ } else if (last && last->_type == EMC_TOOL_SET_NUMBER_TYPE) { ++ auto *number = static_cast(last); ++ number->apply_offset = true; ++ number->offset = set_offset_msg->offset; ++ with_change = true; ++ } ++ + for (int s = 0; s < emcStatus->motion.traj.spindles; s++){ + if(canon.spindle[s].css_maximum) { + SET_SPINDLE_SPEED(s, canon.spindle[s].speed); + } + } +- interp_list.append(std::move(set_offset_msg)); ++ if (!with_change) { ++ interp_list.append(std::move(set_offset_msg)); ++ } ++} ++ ++void CANON_RESYNC_TOOL_OFFSET() ++{ ++ // emcStatus->task.toolOffset is written when task issues ++ // EMC_TRAJ_SET_OFFSET to motion, in external units. ++ const EmcPose &applied = emcStatus->task.toolOffset; ++ canon.toolOffset.tran.x = FROM_EXT_LEN(applied.tran.x); ++ canon.toolOffset.tran.y = FROM_EXT_LEN(applied.tran.y); ++ canon.toolOffset.tran.z = FROM_EXT_LEN(applied.tran.z); ++ canon.toolOffset.a = FROM_EXT_AX(AXIS_A, applied.a); ++ canon.toolOffset.b = FROM_EXT_AX(AXIS_B, applied.b); ++ canon.toolOffset.c = FROM_EXT_AX(AXIS_C, applied.c); ++ canon.toolOffset.u = FROM_EXT_AX(AXIS_U, applied.u); ++ canon.toolOffset.v = FROM_EXT_AX(AXIS_V, applied.v); ++ canon.toolOffset.w = FROM_EXT_AX(AXIS_W, applied.w); + } + + /* CHANGE_TOOL results from M6 */ +@@ -3060,7 +3101,11 @@ void SELECT_TOOL(int tool) + void CHANGE_TOOL_NUMBER(int pocket_number) + { + auto emc_tool_set_number_msg = std::make_unique(); +- ++ ++ // queue any blended motion first, as CHANGE_TOOL does: M61 takes ++ // effect after the moves before it, not ahead of a buffered one ++ flush_segments(); ++ + emc_tool_set_number_msg->tool = pocket_number; + + interp_list.append(std::move(emc_tool_set_number_msg)); +@@ -3539,16 +3584,11 @@ void CANON_ERROR(const char *fmt, ...) + */ + CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int idx) + { +- CANON_TOOL_TABLE tdata; ++ CANON_TOOL_TABLE tdata = CANON_TOOL_TABLE_INIT; + + if (idx < 0 || idx >= CANON_POCKETS_MAX) { +- tdata.toolno = -1; ++ // an empty entry, wear and comment included + tdata.pocketno = 0; +- ZERO_EMC_POSE(tdata.offset); +- tdata.frontangle = 0.0; +- tdata.backangle = 0.0; +- tdata.diameter = 0.0; +- tdata.orientation = 0; + } else { + if (tooldata_get(&tdata,idx) != IDX_OK) { + rcs_print_error("UNEXPECTED idx %s %d\n",__FILE__,__LINE__); +@@ -4263,4 +4303,3 @@ int LOCK_ROTARY(int /*line_number*/, int /*joint_num*/) { canon.rotary_unlock_for_traverse = -1; return 0; } - +diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc +index 7620a30..55fb417 100644 +--- a/src/emc/task/emctask.cc ++++ b/src/emc/task/emctask.cc +@@ -250,6 +250,10 @@ int emcTaskAbort() + // clear out the pending command + emcTaskCommand = NULL; + interp_list.clear(); ++ // a discarded tool offset (G43 read ahead, or the one a built-in M6 or ++ // M61 queues behind its tool change) must not stay in canon; the ++ // interpreter takes it back from canon in the synch queued below ++ CANON_RESYNC_TOOL_OFFSET(); + + // clear out the interpreter state + emcStatus->task.interpState = EMC_TASK_INTERP::IDLE; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 2810757914..64b5497e58 100644 +index 3e73c7b..ec76402 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -2321,6 +2321,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -612,6 +612,9 @@ interpret_again: + emcStatus->task.interpState = + EMC_TASK_INTERP::WAITING; + interp_list.clear(); ++ // the discarded commands may include a tool ++ // offset canon already took on ++ CANON_RESYNC_TOOL_OFFSET(); + emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, + "interpreter error"); + } else if (execRetval == -1 +@@ -1957,6 +1960,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) + break; + + case EMC_TOOL_SET_NUMBER_TYPE: ++ // one carrying a tool offset (built-in M61) applies it with the ++ // number, so it waits for previous motions as the offset would ++ if ((reinterpret_cast(cmd))->apply_offset) { ++ return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; ++ } + return EMC_TASK_EXEC::WAITING_FOR_IO; + break; + +@@ -2034,6 +2042,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) + } + + // issues command immediately ++int emcToolApplyOffset(const EmcPose& offset) ++{ ++ emcStatus->task.toolOffset = offset; ++ return emcTrajSetOffset(emcStatus->task.toolOffset); ++} ++ + static int emcTaskIssueCommand(NMLmsg * cmd) + { + int retval = 0; +@@ -2537,9 +2551,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + retval = emcToolPrepare(tool_prepare_msg->tool); + break; + +- case EMC_TOOL_LOAD_TYPE: ++ case EMC_TOOL_LOAD_TYPE: { ++ auto *load_msg = reinterpret_cast(cmd); ++ // the offset, if any, takes effect when the change completes ++ emcToolSetChangeOffset(load_msg->apply_offset, load_msg->offset); + retval = emcToolLoad(); + break; ++ } + + case EMC_TOOL_UNLOAD_TYPE: + retval = emcToolUnload(); +@@ -2555,6 +2573,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcToolSetOffset(emc_tool_set_offset_msg->pocket, emc_tool_set_offset_msg->toolno, emc_tool_set_offset_msg->offset, @@ -1014,11 +1537,48 @@ index 2810757914..64b5497e58 100644 emc_tool_set_offset_msg->diameter, emc_tool_set_offset_msg->frontangle, emc_tool_set_offset_msg->backangle, +@@ -2564,6 +2584,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + case EMC_TOOL_SET_NUMBER_TYPE: + emc_tool_set_number_msg = reinterpret_cast(cmd); + retval = emcToolSetNumber(emc_tool_set_number_msg->tool); ++ if (retval == 0 && emc_tool_set_number_msg->apply_offset) { ++ // in the same cycle as the number ++ retval = emcToolApplyOffset(emc_tool_set_number_msg->offset); ++ } + break; + + // task commands +@@ -3152,6 +3176,7 @@ static int emcTaskExecute(void) + // clear out pending command + emcTaskCommand = NULL; + interp_list.clear(); ++ CANON_RESYNC_TOOL_OFFSET(); + emcAbortCleanup(EMC_ABORT::TASK_EXEC_ERROR); + emcStatus->task.currentLine = 0; + +@@ -3718,7 +3743,8 @@ static int emctask_startup() + } + // initialize the subsystems + +- // IO first ++ // IO first; a completed tool change applies its offset through this ++ emcToolRegisterApplyOffset(emcToolApplyOffset); + if (emcIoInit() != 0) { + rcs_print_error("can't initialize IO\n"); + return -1; +@@ -4168,6 +4194,7 @@ int main(int argc, char *argv[]) + // clear out the pending command + emcTaskCommand = NULL; + interp_list.clear(); ++ CANON_RESYNC_TOOL_OFFSET(); + emcStatus->task.currentLine = 0; + + emcAbortCleanup(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index c484e5a986..2869ee6fb7 100644 +index 6694667..0d076c8 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc -@@ -102,10 +102,13 @@ int emcToolPrepare(int tool) { return task_methods->emcToolPrepare(tool); } +@@ -114,12 +114,44 @@ int emcToolPrepare(int tool) { return task_methods->emcToolPrepare(tool); } int emcToolLoad() { return task_methods->emcToolLoad(); } int emcToolUnload() { return task_methods->emcToolUnload(); } int emcToolLoadToolTable(const char *file) { return task_methods->emcToolLoadToolTable(file); } @@ -1035,8 +1595,142 @@ index c484e5a986..2869ee6fb7 100644 + backangle, orientation); } int emcToolSetNumber(int number) { return task_methods->emcToolSetNumber(number); } ++// The tool offset a tool change carries (EMC_TOOL_LOAD.apply_offset): held ++// while the change is pending and applied in the same cycle the new tool ++// takes effect, so the spindle and the applied offset change together; ++// dropped by emcIoAbort() together with the change. ++static bool change_offset_pending = false; ++static EmcPose change_offset; ++ ++void emcToolSetChangeOffset(bool apply, const EmcPose& offset) ++{ ++ change_offset_pending = apply; ++ change_offset = offset; ++} ++ ++// emcToolApplyOffset() lives with the motion interface in milltask, which ++// registers it; the standalone interpreter links this file without one ++static int (*apply_offset)(const EmcPose&) = nullptr; ++ ++void emcToolRegisterApplyOffset(int (*fn)(const EmcPose&)) ++{ ++ apply_offset = fn; ++} ++ ++static int apply_change_offset() ++{ ++ if (!change_offset_pending) return 0; ++ change_offset_pending = false; ++ return apply_offset ? apply_offset(change_offset) : 0; ++} ++ int emcTaskOnce(const char * /*filename*/, EMC_IO_STAT &emcioStatus) -@@ -524,8 +527,10 @@ int Task::emcToolLoadToolTable(const char *file)//EMC_TOOL_LOAD_TOOL_TABLE_TYPE + { + task_methods = new Task(emcioStatus); +@@ -307,7 +339,7 @@ static int iniTool(const char *filename) + return retval; + } + +-void Task::load_tool(int idx) { ++int Task::load_tool(int idx) { + CANON_TOOL_TABLE tdata; + if(random_toolchanger) { + // swap the tools between the desired pocket and the spindle pocket +@@ -315,7 +347,7 @@ void Task::load_tool(int idx) { + CANON_TOOL_TABLE tzero,tpocket; + if ( tooldata_get(&tzero,0 ) != IDX_OK + || tooldata_get(&tpocket,idx) != IDX_OK) { +- UNEXPECTED_MSG; return; ++ UNEXPECTED_MSG; return -1; + } + // spindle-->pocket (specified by idx) + tooldata_db_notify(SPINDLE_UNLOAD,tzero.toolno,idx,tzero); +@@ -332,7 +364,14 @@ void Task::load_tool(int idx) { + } + + if (0 != tooldata_save(tooltable_filename)) { +- emcioStatus.status = RCS_STATUS::ERROR; ++ // the tools are swapped: the table in memory shows it, the ++ // file does not ++ emcOperatorError("tool table %s not saved after the tool change: " ++ "it does not show the tools now in the spindle " ++ "and in pocket %d", ++ tooltable_filename ? tooltable_filename : "(none)", ++ idx); ++ return -1; + } + } else if(idx == 0) { + // on non-random tool-changers, asking for pocket 0 is the secret +@@ -341,22 +380,23 @@ void Task::load_tool(int idx) { + tdata.toolno = 0; // nonrandom unload tool from spindle + tdata.pocketno = 0; // nonrandom unload tool from spindle + if (tooldata_put(tdata,0) != IDX_OK) { +- UNEXPECTED_MSG; return; ++ UNEXPECTED_MSG; return -1; + } + if (tooldata_db_notify(SPINDLE_UNLOAD,0,0,tdata)) { UNEXPECTED_MSG; } + } else { + // just copy the desired tool to the spindle + if (tooldata_get(&tdata,idx) != IDX_OK) { +- UNEXPECTED_MSG; return; ++ UNEXPECTED_MSG; return -1; + } + if (tooldata_put(tdata,0) != IDX_OK) { +- UNEXPECTED_MSG; return; ++ UNEXPECTED_MSG; return -1; + } + // notify idx==0 tool in spindle: + CANON_TOOL_TABLE temp; + if (tooldata_get(&temp,0) != IDX_OK) { UNEXPECTED_MSG; } + if (tooldata_db_notify(SPINDLE_LOAD,temp.toolno,0,temp)) { UNEXPECTED_MSG; } + } ++ return 0; + } // load_tool() + + void Task::reload_tool_number(int toolno) { +@@ -367,7 +407,7 @@ void Task::reload_tool_number(int toolno) { + UNEXPECTED_MSG; return; + } + if(tdata.toolno == toolno) { +- load_tool(idx); ++ (void)load_tool(idx); // a non-random load saves nothing + break; + } + } +@@ -392,6 +432,8 @@ int Task::emcIoAbort(EMC_ABORT /*reason*/)//EMC_TOOL_ABORT_TYPE + // this gets sent on any Task Abort, so it might be safer to stop + // the spindle and coolant + rtapi_print_msg(RTAPI_MSG_DBG, "EMC_TOOL_ABORT\n"); ++ // the change did not complete, so neither does its offset ++ change_offset_pending = false; + emcioStatus.coolant.mist = 0; + emcioStatus.coolant.flood = 0; + hal_set_bool(iocontrol_data->coolant_mist, 0); /* coolant mist output pin */ +@@ -512,7 +554,7 @@ int Task::emcToolLoad()//EMC_TOOL_LOAD_TYPE + { + // it doesn't make sense to load a tool from the spindle pocket + if (random_toolchanger && emcioStatus.tool.pocketPrepped == 0) { +- return 0; ++ return apply_change_offset(); // no change: the offset applies now + } + + // it's not necessary to load the tool already in the spindle +@@ -522,10 +564,12 @@ int Task::emcToolLoad()//EMC_TOOL_LOAD_TYPE + } + if (!random_toolchanger && (emcioStatus.tool.pocketPrepped > 0) && + (emcioStatus.tool.toolInSpindle == tdata.toolno) ) { +- return 0; ++ return apply_change_offset(); // tool already loaded: applies now + } + +- if (emcioStatus.tool.pocketPrepped != -1) { ++ if (emcioStatus.tool.pocketPrepped == -1) { ++ return apply_change_offset(); // nothing to change: applies now ++ } else { + //notify HW for toolchange + hal_set_bool(iocontrol_data->tool_change, 1); + // the feedback logic is done inside read_hal_inputs() we only +@@ -553,8 +597,10 @@ int Task::emcToolLoadToolTable(const char *file)//EMC_TOOL_LOAD_TOOL_TABLE_TYPE return 0; } @@ -1049,8 +1743,11 @@ index c484e5a986..2869ee6fb7 100644 { int o; -@@ -547,6 +552,9 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, double di +@@ -574,8 +620,12 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, double di + if (tooldata_get(&tdata,idx) != IDX_OK) { + UNEXPECTED_MSG; } ++ const CANON_TOOL_TABLE previous = tdata; tdata.toolno = toolno; tdata.offset = offset; + if (wear_offset_valid) { @@ -1059,11 +1756,75 @@ index c484e5a986..2869ee6fb7 100644 tdata.diameter = d; tdata.frontangle = f; tdata.backangle = b; +@@ -583,17 +633,24 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, double di + if (tooldata_put(tdata,idx) != IDX_OK) { + UNEXPECTED_MSG; + } +- if (0 != tooldata_save(tooltable_filename)) { +- emcioStatus.status = RCS_STATUS::ERROR; +- } +- if (db_mode == tooldb_t::DB_ACTIVE) { ++ bool stored = (0 == tooldata_save(tooltable_filename)); ++ if (stored && db_mode == tooldb_t::DB_ACTIVE) { + // tooldata_save() does not write tool table entries in db mode, + // so the db_program must be notified to persist the new offsets + int pno = idx; // for random_toolchanger + if (!random_toolchanger) { pno = tdata.pocketno; } + if (tooldata_db_notify(TOOL_OFFSET,toolno,pno,tdata)) { ++ stored = false; ++ } ++ } ++ if (!stored) { ++ // what could not be stored is not kept: the table in memory goes ++ // back to what the file (or the db program) still has ++ if (tooldata_put(previous,idx) != IDX_OK) { + UNEXPECTED_MSG; + } ++ emcOperatorError("tool %d: offsets not stored, tool table unchanged", toolno); ++ return -1; + } + + return 0; +@@ -608,7 +665,10 @@ int Task::emcToolSetNumber(int number)//EMC_TOOL_SET_NUMBER + if (tooldata_get(&tdata,idx) != IDX_OK) { + UNEXPECTED_MSG; + } +- load_tool(idx); ++ if (load_tool(idx)) { ++ // the number is set: its offset still applies ++ emcioStatus.status = RCS_STATUS::ERROR; ++ } + + idx=0; // update spindle (fix legacy behavior) + if (tooldata_get(&tdata,idx) != IDX_OK) { +@@ -667,13 +727,20 @@ int Task::read_tool_inputs(void) + emcioStatus.tool.toolFromPocket = hal_set_si32(iocontrol_data->tool_from_pocket, 0); + } + hal_set_si32(iocontrol_data->tool_number, emcioStatus.tool.toolInSpindle); //likewise in HAL +- load_tool(emcioStatus.tool.pocketPrepped); ++ const int loaded = load_tool(emcioStatus.tool.pocketPrepped); + emcioStatus.tool.pocketPrepped = -1; //reset the tool preped number, -1 to permit tool 0 to be loaded + hal_set_si32(iocontrol_data->tool_prep_number, 0); //likewise in HAL + hal_set_si32(iocontrol_data->tool_prep_pocket, 0); //likewise in HAL + hal_set_si32(iocontrol_data->tool_prep_index, 0); //likewise in HAL + hal_set_bool(iocontrol_data->tool_change, 0); //also reset the tool change signal +- emcioStatus.status = RCS_STATUS::DONE; // we finally finished to do tool-changing, signal task with RCS_DONE ++ // we finally finished to do tool-changing, signal task with RCS_DONE; ++ // a table that could not be saved fails the change ++ emcioStatus.status = loaded ? RCS_STATUS::ERROR : RCS_STATUS::DONE; ++ // the new tool's offset takes effect with the tool, which is in the ++ // spindle whether or not the table was saved ++ if (apply_change_offset()) { ++ emcioStatus.status = RCS_STATUS::ERROR; ++ } + return 11; //change finished + } + return 0; diff --git a/src/emc/task/taskclass.hh b/src/emc/task/taskclass.hh -index b19c0a00aa..5e32a1a65d 100644 +index 6f4aff7..509f11f 100644 --- a/src/emc/task/taskclass.hh +++ b/src/emc/task/taskclass.hh -@@ -66,8 +66,9 @@ public: +@@ -67,8 +67,9 @@ public: virtual int emcCoolantMistOff(); virtual int emcCoolantFloodOn(); virtual int emcCoolantFloodOff(); @@ -1075,19 +1836,46 @@ index b19c0a00aa..5e32a1a65d 100644 virtual int emcToolPrepare(int tool); virtual int emcToolLoad(); virtual int emcToolLoadToolTable(const char *file); +@@ -77,7 +78,7 @@ public: + + int iocontrol_hal_init(void); + void reload_tool_number(int toolno); +- void load_tool(int idx); ++ int load_tool(int idx); + void run(); + int read_tool_inputs(void); + void hal_init_pins(void); +diff --git a/src/emc/tooldata/tooldata.hh b/src/emc/tooldata/tooldata.hh +index 524bd8b..db3e6b7 100644 +--- a/src/emc/tooldata/tooldata.hh ++++ b/src/emc/tooldata/tooldata.hh +@@ -61,7 +61,9 @@ int tooldata_find_index_for_tool(int toolno); + + // ignore_zero_values:1 for file writes + // :0 for use with tooldata_db_notify() +-void tooldata_format_toolline (int idx, ++// appends to formatted_line; -1, appending nothing, if the line would be ++// longer than CANON_TOOL_LINE_MAX characters ++int tooldata_format_toolline (int idx, + bool ignore_zero_values, + CANON_TOOL_TABLE tdata, + char formatted_line[CANON_TOOL_ENTRY_LEN] diff --git a/src/emc/tooldata/tooldata_common.cc b/src/emc/tooldata/tooldata_common.cc -index 040ff7ad80..4e9651c86f 100644 +index 3447f4d..ceefe9b 100644 --- a/src/emc/tooldata/tooldata_common.cc +++ b/src/emc/tooldata/tooldata_common.cc -@@ -48,6 +48,7 @@ struct CANON_TOOL_TABLE tooldata_entry_init() - tdata.backangle = 0; - tdata.orientation = 0; - ZERO_EMC_POSE(tdata.offset); -+ ZERO_EMC_POSE(tdata.wear_offset); - tdata.comment[0] = 0; +@@ -21,8 +21,10 @@ + ** along with this program; if not, write to the Free Software + ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ ++#include + #include + #include ++#include + #include "tooldata.hh" - return tdata; -@@ -73,7 +74,8 @@ int tooldata_read_entry(const char *input_line) + #define UNEXPECTED_MSG fprintf(stderr,"UNEXPECTED %s %d\n",__FILE__,__LINE__); +@@ -63,7 +65,8 @@ int tooldata_read_entry(const char *input_line) const char *token; char *buff, *comment; int toolno,orientation,valid=1; @@ -1097,7 +1885,22 @@ index 040ff7ad80..4e9651c86f 100644 double diameter, frontangle, backangle; int idx = 0; int realpocket = 0; -@@ -93,6 +95,7 @@ int tooldata_read_entry(const char *input_line) +@@ -73,8 +76,12 @@ int tooldata_read_entry(const char *input_line) + return -1; + } + if (input_line[0] == ';') {return 0;} //ignore leading ';' +- strncpy(work_line, input_line, sizeof(work_line)-1); +- work_line[sizeof(work_line)-1] = 0; ++ if (strlen(input_line) >= sizeof(work_line)) { ++ fprintf(stderr, "tool line longer than %d characters refused: %.40s...\n", ++ CANON_TOOL_LINE_MAX, input_line); ++ return -1; ++ } ++ strcpy(work_line, input_line); + + CANON_TOOL_TABLE empty = tooldata_entry_init(); + toolno = empty.toolno; +@@ -83,6 +90,7 @@ int tooldata_read_entry(const char *input_line) backangle = empty.backangle; orientation = empty.orientation; offset = empty.offset; @@ -1105,7 +1908,7 @@ index 040ff7ad80..4e9651c86f 100644 char* saveptr; buff = strtok_r(work_line, ";", &saveptr); -@@ -170,8 +173,20 @@ int tooldata_read_entry(const char *input_line) +@@ -160,8 +168,20 @@ int tooldata_read_entry(const char *input_line) valid = 0; break; case 'W': @@ -1128,7 +1931,7 @@ index 040ff7ad80..4e9651c86f 100644 break; case 'I': if (sscanf(&token[1], "%lf", &frontangle) != 1) -@@ -206,6 +221,7 @@ int tooldata_read_entry(const char *input_line) +@@ -196,6 +216,7 @@ int tooldata_read_entry(const char *input_line) tdata.toolno = toolno; tdata.pocketno = realpocket; tdata.offset = offset; @@ -1136,7 +1939,74 @@ index 040ff7ad80..4e9651c86f 100644 tdata.diameter = diameter; tdata.frontangle = frontangle; tdata.backangle = backangle; -@@ -272,6 +288,15 @@ void tooldata_format_toolline (int idx, +@@ -221,35 +242,45 @@ int tooldata_read_entry(const char *input_line) + return idx; + } // tooldata_read_entry() + +-void tooldata_format_toolline (int idx, +- bool ignore_zero_values, +- CANON_TOOL_TABLE tdata, +- char formatted_line[CANON_TOOL_ENTRY_LEN] +- ) ++// Append to a tool line of at most CANON_TOOL_LINE_MAX characters plus its ++// newline; returns false, leaving the line unchanged, if it would not fit. ++static bool __attribute__((format(printf, 3, 4))) ++append_item(char *line, size_t *used, const char *fmt, ...) ++{ ++ const size_t size = CANON_TOOL_ENTRY_LEN; ++ va_list ap; ++ va_start(ap, fmt); ++ int len = vsnprintf(line + *used, size - *used, fmt, ap); ++ va_end(ap); ++ if (len < 0 || (size_t)len >= size - *used) { ++ line[*used] = 0; ++ return false; ++ } ++ *used += len; ++ return true; ++} ++ ++int tooldata_format_toolline (int idx, ++ bool ignore_zero_values, ++ CANON_TOOL_TABLE tdata, ++ char formatted_line[CANON_TOOL_ENTRY_LEN] ++ ) + { +- char tmp[CANON_TOOL_ENTRY_LEN-1] = {0}; +- int space = sizeof(tmp); +- int len; +- len = snprintf(tmp,sizeof(tmp),"T%-3d P%-3d" ++ size_t used = strnlen(formatted_line, CANON_TOOL_ENTRY_LEN - 1); ++ const size_t start = used; ++ bool fits = append_item(formatted_line, &used, "T%-3d P%-3d" + ,tdata.toolno + ,is_random_toolchanger ? idx : tdata.pocketno); +- strncat(formatted_line,tmp,space); +- space -= len; + // format zero float values as %.0f for brevity +-#define F_ITEM(item,letter) if (!ignore_zero_values || tdata.item) { \ +- char local_tmp[64] = {}; \ ++#define F_ITEM(item,letter) if (fits && (!ignore_zero_values || tdata.item)) { \ + if (tdata.item) { \ +- len = snprintf(local_tmp,sizeof(local_tmp)," " letter "%+f", tdata.item); \ ++ fits = append_item(formatted_line, &used, " " letter "%+f", tdata.item); \ + } else { \ +- len = snprintf(local_tmp,sizeof(local_tmp)," " letter "%.0f",tdata.item); \ ++ fits = append_item(formatted_line, &used, " " letter "%.0f", tdata.item); \ + } \ +- strncat(formatted_line,local_tmp,space); \ +- space -= len; \ + } +-#define I_ITEM(item,letter) if (!ignore_zero_values || tdata.item) { \ +- len = snprintf(tmp,sizeof(tmp)," " letter "%d",tdata.item); \ +- strncat(formatted_line,tmp,space); \ +- space -= len; \ ++#define I_ITEM(item,letter) if (fits && (!ignore_zero_values || tdata.item)) { \ ++ fits = append_item(formatted_line, &used, " " letter "%d", tdata.item); \ + } + + F_ITEM(diameter, "D"); +@@ -262,21 +293,40 @@ void tooldata_format_toolline (int idx, F_ITEM(offset.u, "U"); F_ITEM(offset.v, "V"); F_ITEM(offset.w, "W"); @@ -1152,8 +2022,152 @@ index 040ff7ad80..4e9651c86f 100644 F_ITEM(frontangle, "I"); F_ITEM(backangle, "J"); I_ITEM(orientation, "Q"); + #undef F_ITEM + #undef I_ITEM +- // Stop tracking len and space here for current tool table format +- if (tdata.comment[0]) { +- snprintf(tmp,space," ;%s\n",tdata.comment); +- } else { +- snprintf(tmp,space,"\n"); ++ if (fits && tdata.comment[0]) { ++ fits = append_item(formatted_line, &used, " ;%s", tdata.comment); + } +- strncat(formatted_line,tmp,space); +- return; ++ if (fits) { ++ fits = append_item(formatted_line, &used, "\n"); ++ } ++ if (!fits) { ++ // never hand on a line with a number cut short ++ formatted_line[start] = 0; ++ fprintf(stderr, "tool %d: tool line longer than %d characters, not written\n", ++ tdata.toolno, CANON_TOOL_LINE_MAX); ++ return -1; ++ } ++ return 0; + } // tooldata_format_toolline() + ++// The last table file loaded had a line refused as too long: that tool is ++// not in memory, so writing the table back would delete the user's line. ++static bool table_has_refused_lines = false; ++ + int tooldata_load(const char *filename) + { + FILE *fp; +@@ -314,6 +364,8 @@ int tooldata_load(const char *filename) + const int nonrandom_start_idx = 1; // when reading file start at 0 + tooldata_add_init(nonrandom_start_idx); + ++ table_has_refused_lines = false; ++ int lineno = 0; + while (!feof(fp)) { + // for nonrandom machines, just read the tools into pockets 1..n + // no matter their tool numbers. NB leave the spindle pocket 0 +@@ -321,6 +373,19 @@ int tooldata_load(const char *filename) + if (NULL == fgets(input_line, CANON_TOOL_ENTRY_LEN, fp)) { + break; + } ++ lineno++; ++ size_t len = strlen(input_line); ++ bool complete = len > 0 && input_line[len - 1] == '\n'; ++ if (!complete && len > CANON_TOOL_LINE_MAX) { ++ // fgets stopped at the buffer, not at the end of the line: ++ // refuse the whole line rather than parse a number cut short ++ int c; ++ while ((c = fgetc(fp)) != EOF && c != '\n') {} ++ fprintf(stderr, "File: %s line %d: tool line longer than %d characters refused\n", ++ filename, lineno, CANON_TOOL_LINE_MAX); ++ table_has_refused_lines = true; ++ continue; ++ } + strcpy(orig_line, input_line); + + // parse and store one line from tool table file +@@ -352,22 +417,25 @@ int tooldata_load(const char *filename) + return 0; + } // tooldata_load() + +-static void write_tool_line(FILE* fp,int idx) ++// Append idx's tool line to table; -1 if it is too long to write. ++static int write_tool_line(std::string &table,int idx) + { + CANON_TOOL_TABLE tdata; +- if (tooldata_get(&tdata,idx) != IDX_OK) {return;} ++ if (tooldata_get(&tdata,idx) != IDX_OK) {return 0;} + if (db_mode == DB_ACTIVE && idx != 0 ) { +- return; ++ return 0; + } + + if (tdata.toolno != -1) { + char theline[CANON_TOOL_ENTRY_LEN] = {0}; +- tooldata_format_toolline (idx, +- 1, // ignore_zero_values +- tdata,theline); +- fprintf(fp,"%s",theline); ++ if (tooldata_format_toolline (idx, ++ 1, // ignore_zero_values ++ tdata,theline)) { ++ return -1; ++ } ++ table += theline; + } +- return; ++ return 0; + } // write_tool_line() + + int tooldata_save(const char *filename) +@@ -390,24 +458,38 @@ int tooldata_save(const char *filename) + if (filename[0] == 0) { + UNEXPECTED_MSG; + } ++ if (table_has_refused_lines) { ++ fprintf(stderr, "%s: not saved: lines refused when it was loaded " ++ "would be lost; shorten them and reload the tool table\n", ++ filename); ++ return -1; ++ } + } + +- // open tool table file +- if (NULL == (fp = fopen(filename, "w"))) { +- fprintf(stderr, "%s, %d: Failed to open tool table file '%s': %s\n", +- __FILE__, __LINE__, filename, strerror(errno)); +- return -1; +- } +- ++ // format every line first: a tool whose line is too long leaves the ++ // file as it was rather than written without that tool ++ std::string table; + if (db_mode == DB_ACTIVE) { + int spindle_idx = 0; +- write_tool_line(fp,spindle_idx); ++ if (write_tool_line(table,spindle_idx)) {return -1;} + } else { + start_idx = is_random_toolchanger ? 0 : 1; + for (idx = start_idx; idx < CANON_POCKETS_MAX; idx++) { +- write_tool_line(fp,idx); ++ if (write_tool_line(table,idx)) {return -1;} + } + } +- fclose(fp); ++ ++ // open tool table file ++ if (NULL == (fp = fopen(filename, "w"))) { ++ fprintf(stderr, "%s, %d: Failed to open tool table file '%s': %s\n", ++ __FILE__, __LINE__, filename, strerror(errno)); ++ return -1; ++ } ++ int written = fputs(table.c_str(), fp); ++ if (fclose(fp) != 0 || written == EOF) { ++ fprintf(stderr, "%s, %d: Failed to write tool table file '%s': %s\n", ++ __FILE__, __LINE__, filename, strerror(errno)); ++ return -1; ++ } + return 0; + } //tooldata_save() diff --git a/src/emc/tooldata/tooldata_db.cc b/src/emc/tooldata/tooldata_db.cc -index 32df138863..99e263f80d 100644 +index 4a5f885..963f4a5 100644 --- a/src/emc/tooldata/tooldata_db.cc +++ b/src/emc/tooldata/tooldata_db.cc @@ -27,7 +27,7 @@ @@ -1165,11 +2179,130 @@ index 32df138863..99e263f80d 100644 #define MAX_DB_PROGRAM_ARGS 10 #define UNEXPECTED_MSG fprintf(stderr,"UNEXPECTED %s %d\n",__FILE__,__LINE__); +@@ -145,32 +145,53 @@ static int send_request(char *cmd) + return 0; + } // send_request() + ++// read_reply(): a reply too long for a tool line, consumed and refused ++#define READ_REPLY_REFUSED (-2) ++ + static int read_reply(char reply[],int len) + { +- char buffer[CANON_TOOL_ENTRY_LEN]; ++ // The reply pipe is in packet mode (O_DIRECT): a read() returns one ++ // packet, one write() of the db program, and discards what does not fit ++ // the buffer. So read into a buffer that holds any packet, then refuse ++ // a reply too long for a tool line instead of cutting it. A write longer ++ // than PIPE_BUF arrives as several packets: read them all, up to the one ++ // that ends the line, so the next reply stays in step. ++ char buffer[PIPE_BUF + 1]; + int count = 0; +- buffer[count] = 0; ++ bool too_long = false; + if (!db_live) { + fprintf(stderr,"read_reply: db not active\n"); + return -1; + } +- if ( !readready() ) { +- fprintf(stderr,"!!!! tooldata_db:read_reply fail: timeout_ms=%d\n" +- ,READ_TIMEOUT_MS); +- return -1; +- } +- count = read(PARENT_READ_FD, buffer, sizeof(buffer)-1); +- if (count > 1) { ++ while (1) { ++ if ( !readready() ) { ++ fprintf(stderr,"!!!! tooldata_db:read_reply fail: timeout_ms=%d\n" ++ ,READ_TIMEOUT_MS); ++ return -1; ++ } ++ count = read(PARENT_READ_FD, buffer, PIPE_BUF); ++ if (count < 1) { ++ fprintf(stderr,"read_reply IO Error count=%d\n",count); ++ return -1; ++ } + buffer[count] = 0; +- // strip \n +- if (buffer[strlen(buffer)-1] =='\n') { +- buffer[strlen(buffer)-1] = 0; ++ if (buffer[count-1] == '\n') { ++ buffer[--count] = 0; ++ break; + } +- } else { ++ if (count < PIPE_BUF) break; // a last reply without its newline ++ too_long = true; // the line goes on in the next packet ++ } ++ if (too_long || count > CANON_TOOL_LINE_MAX) { ++ fprintf(stderr,"read_reply: reply longer than %d characters refused: %.40s...\n", ++ CANON_TOOL_LINE_MAX, buffer); ++ return READ_REPLY_REFUSED; ++ } ++ if (count < 1 || count >= len) { + fprintf(stderr,"read_reply IO Error count=%d\n",count); + return -1; + } +- snprintf(reply,len,"%s",buffer); ++ memcpy(reply, buffer, count + 1); + if (strstr(reply,"NAK")) { + fprintf(stderr,"!!!! %s\n",reply); + } +@@ -211,7 +232,13 @@ int tooldata_db_getall() { + //int ct=1; + while (1) { + char reply[CANON_TOOL_ENTRY_LEN]; +- if (read_reply(reply,sizeof(reply)) <0) { ++ int got = read_reply(reply,sizeof(reply)); ++ if (got == READ_REPLY_REFUSED) { ++ // that tool is left out, as a refused table file line is; ++ // the db program keeps it, and the replies stay in step ++ continue; ++ } ++ if (got <0) { + //fprintf(stderr,"%5d ??????replylen=%lu active=%d\n" + // ,getpid(),strlen(reply),db_live); + return -1; +@@ -316,16 +343,16 @@ int tooldata_db_notify(tool_notify_t ntype, + notifydata.pocketno = pocketno; + switch (ntype) { + case SPINDLE_LOAD: // 'l' command +- tooldata_format_toolline(pocketno, +- 1, // ignore_zero_values +- notifydata, buffer); ++ if (tooldata_format_toolline(pocketno, ++ 1, // ignore_zero_values ++ notifydata, buffer)) {return -1;} + snprintf(msg,sizeof(msg),"l %s\n",buffer); + if (db_debug) {fprintf(stderr,"SPINDLE_LOAD:%s\n",msg);} + break; + case SPINDLE_UNLOAD: // 'u' command +- tooldata_format_toolline(pocketno, +- 1, // ignore_zero_values +- notifydata, buffer); ++ if (tooldata_format_toolline(pocketno, ++ 1, // ignore_zero_values ++ notifydata, buffer)) {return -1;} + snprintf(msg,sizeof(msg),"u %s\n",buffer); + if (db_debug) {fprintf(stderr,"SPINDLE_UNLOAD:%s\n",msg);} + break; +@@ -333,9 +360,9 @@ int tooldata_db_notify(tool_notify_t ntype, + notifydata = tdata; // from caller + notifydata.toolno = toolno; + notifydata.pocketno = pocketno; +- tooldata_format_toolline(pocketno, +- 0, // do not ignore_zero_values +- notifydata, buffer); ++ if (tooldata_format_toolline(pocketno, ++ 0, // do not ignore_zero_values ++ notifydata, buffer)) {return -1;} + snprintf(msg,sizeof(msg),"p %s\n",buffer); + if (db_debug) {fprintf(stderr,"PUT: %s\n",msg);} + break; diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index 5f47d78ec1..bd747787e4 100644 +index 9261f61..6a0b6d7 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1094,6 +1094,15 @@ static PyObject *toolinfo(pyStatChannel * /*s*/, PyObject *o) { +@@ -1098,6 +1098,15 @@ static PyObject *toolinfo(pyStatChannel * /*s*/, PyObject *o) { dict_add(res, "uoffset", tdata.offset.u); dict_add(res, "voffset", tdata.offset.v); dict_add(res, "woffset", tdata.offset.w); @@ -1185,7 +2318,7 @@ index 5f47d78ec1..bd747787e4 100644 PyDict_SetItemString(res, "comment", o= PyUnicode_FromString(tdata.comment)); Py_DECREF(o); -@@ -1481,6 +1490,15 @@ static PyStructSequence_Field tool_fields[] = { +@@ -1486,6 +1495,15 @@ static PyStructSequence_Field tool_fields[] = { {(char*)"frontangle", NULL}, {(char*)"backangle", NULL}, {(char*)"orientation", NULL}, @@ -1201,7 +2334,7 @@ index 5f47d78ec1..bd747787e4 100644 {}, }; -@@ -1488,7 +1506,7 @@ static PyStructSequence_Desc tool_result_desc = { +@@ -1493,7 +1511,7 @@ static PyStructSequence_Desc tool_result_desc = { (char*)"tool_result", /* name */ (char*)"", /* doc */ tool_fields, @@ -1210,7 +2343,7 @@ index 5f47d78ec1..bd747787e4 100644 }; static PyTypeObject ToolResultType; -@@ -1526,6 +1544,15 @@ static PyObject *Stat_tool_table(pyStatChannel * /*s*/, void *) { +@@ -1531,6 +1549,15 @@ static PyObject *Stat_tool_table(pyStatChannel * /*s*/, void *) { PyStructSequence_SET_ITEM(tool, 11, PyFloat_FromDouble(t.frontangle)); PyStructSequence_SET_ITEM(tool, 12, PyFloat_FromDouble(t.backangle)); PyStructSequence_SET_ITEM(tool, 13, PyLong_FromLong(t.orientation)); @@ -1227,7 +2360,7 @@ index 5f47d78ec1..bd747787e4 100644 j++; } diff --git a/tests/ccomp/lathe-comp/expected b/tests/ccomp/lathe-comp/expected -index 4fabddb4b7..bba4efd501 100644 +index 4fabddb..bba4efd 100644 --- a/tests/ccomp/lathe-comp/expected +++ b/tests/ccomp/lathe-comp/expected @@ -13,6 +13,7 @@ @@ -1263,7 +2396,7 @@ index 4fabddb4b7..bba4efd501 100644 N..... SET_XY_ROTATION(0.0000) N..... SELECT_PLANE(CANON_PLANE_XY) diff --git a/tests/ccomp/mill-g90g91g92/expected b/tests/ccomp/mill-g90g91g92/expected -index f58e400842..7327c18c64 100644 +index f58e400..7327c18 100644 --- a/tests/ccomp/mill-g90g91g92/expected +++ b/tests/ccomp/mill-g90g91g92/expected @@ -8,6 +8,7 @@ @@ -1275,7 +2408,7 @@ index f58e400842..7327c18c64 100644 N..... SET_FEED_RATE(100.0000) N..... STRAIGHT_TRAVERSE(0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) diff --git a/tests/ccomp/mill-line-arc-entry/expected b/tests/ccomp/mill-line-arc-entry/expected -index ab893c5e6e..ea4339f8cb 100644 +index ab893c5..ea4339f 100644 --- a/tests/ccomp/mill-line-arc-entry/expected +++ b/tests/ccomp/mill-line-arc-entry/expected @@ -24,6 +24,7 @@ @@ -1286,8 +2419,111 @@ index ab893c5e6e..ea4339f8cb 100644 N..... STRAIGHT_TRAVERSE(1.0000, 5.0000, 0.0000, 0.0000, 0.0000, 0.0000) N..... COMMENT("interpreter: cutter radius compensation on left") N..... STRAIGHT_FEED(1.5000, 4.0000, 0.0000, 0.0000, 0.0000, 0.0000) +diff --git a/tests/gcode-renderer/canon.py b/tests/gcode-renderer/canon.py +index 41c6dc8..e71e3e2 100644 +--- a/tests/gcode-renderer/canon.py ++++ b/tests/gcode-renderer/canon.py +@@ -102,7 +102,8 @@ class HeadlessCanon(_GLCanon): + _GLCanon.__init__(self, COLORS, geometry, **kw) + self.progress = _Progress() + +- #: pocket -> the 14-tuple ``StatMixin.get_tool`` returns. Empty means no ++ #: pocket -> the tuple ``StatMixin.get_tool`` returns: 14 fields, or 23 ++ #: with the nine wear fields a ``stat.tool_table`` entry carries. Empty means no + #: tool table, which is the standalone gcode module's normal state; a + #: program using ``G43 H`` needs an entry, or the interpreter walks off + #: the end of one that is not there. +diff --git a/tests/gcode-renderer/test_renderer.py b/tests/gcode-renderer/test_renderer.py +index 2893d82..4f26c38 100755 +--- a/tests/gcode-renderer/test_renderer.py ++++ b/tests/gcode-renderer/test_renderer.py +@@ -1034,5 +1034,84 @@ class ToolOffsetRecords(unittest.TestCase): + self.assertAlmostEqual(float(z[row_b - 1]) + off_a[2], 0.0, places=6) + self.assertAlmostEqual(float(z[-1]) + off_b[2], 0.0, places=6) + ++ ++class _WearToolCanon(HeadlessCanon): ++ """T3 in the spindle (pocket 0) as a full ``linuxcnc.stat.tool_table`` ++ entry: 14 geometry fields followed by nine wear fields (X 0.1, Z 0.25). ++ ++ The spindle pocket and a bare G43 rather than ``G43 H3`` or ``M61 Q3``: ++ both of those look the tool up through the tool data the standalone ++ ``gcode`` module never attaches.""" ++ TOOLS = {0: (3, 1.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, ++ 0.0, 0.0, 0.0, 0, ++ 0.1, 0.0, 0.25, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)} ++ ++ ++class _GeometryToolCanon(HeadlessCanon): ++ """The same tool as the 14-field entry older callers return: no wear.""" ++ TOOLS = {0: _WearToolCanon.TOOLS[0][:14]} ++ ++ ++class ToolWearInPreview(unittest.TestCase): ++ """The preview applies the offset the machine will: geometry plus wear ++ from a 23-field tool entry, geometry alone from a 14-field one. The ++ table is in machine units (mm here) and the record in inches.""" ++ ++ PROGRAM = "G21 G17 G90\nG0 X0 Y0 Z0\nG43\nG1 F10 X1\nM2\n" ++ ++ def offset_mm(self, cls): ++ pg = parse(self.PROGRAM, cls=cls, axis_mask=0b111).program_geometry ++ (off,) = [o for _row, o in pg.tool_offsets] ++ return [v * 25.4 for v in off] ++ ++ def test_a_full_entry_applies_geometry_plus_wear(self): ++ off = self.offset_mm(_WearToolCanon) ++ self.assertAlmostEqual(off[0], 1.1, places=6) ++ self.assertAlmostEqual(off[2], 0.75, places=6) ++ ++ def test_a_geometry_only_entry_applies_geometry(self): ++ off = self.offset_mm(_GeometryToolCanon) ++ self.assertAlmostEqual(off[0], 1.0, places=6) ++ self.assertAlmostEqual(off[2], 0.5, places=6) ++ ++ ++ ++class _TraverseRecorder(CallbackCanon): ++ """The callback protocol, recording where each traverse goes.""" ++ ++ def __init__(self, *args, **kw): ++ CallbackCanon.__init__(self, *args, **kw) ++ self.traverses = [] ++ ++ def straight_feed(self, *args): ++ self.traverses.append(tuple(round(v, 6) for v in args[:3])) ++ ++ ++class _WearToolCallbackCanon(_TraverseRecorder): ++ def get_tool(self, pocket): ++ return _WearToolCanon.TOOLS.get(int(pocket), (-1,) + (0.0,) * 12 + (0,)) ++ ++ ++class EachParseStartsWithoutAToolOffset(unittest.TestCase): ++ """The interpreter takes its applied tool offset from the canon when it ++ synchronises, so a parse must not inherit the offset the previous parse ++ in the same process ended with. A machine-coordinate move shows it: it ++ is converted to program coordinates through the applied offset.""" ++ ++ FIRST = "G21 G17 G90\nG0 X0 Y0 Z0\nG43\nG1 F10 X1\nM2\n" ++ SECOND = "G20 G17 G90\nG0 X0 Y0 Z0\nG1 F10 X0.5\nG53 G1 X1 Y0 Z1\nM2\n" ++ ++ def test_renderer_mode(self): ++ first = parse(self.FIRST, cls=_WearToolCanon, axis_mask=0b111) ++ self.assertEqual(len(first.program_geometry.tool_offsets), 1) ++ second = parse(self.SECOND, axis_mask=0b111) ++ self.assertEqual(positions(second)[-1], (1.0, 0.0, 1.0)) ++ ++ def test_callback_mode(self): ++ parse(self.FIRST, cls=_WearToolCallbackCanon, axis_mask=0b111) ++ second = parse(self.SECOND, cls=_TraverseRecorder, axis_mask=0b111) ++ self.assertEqual(second.traverses[-1], (1.0, 0.0, 1.0)) ++ ++ + if __name__ == "__main__": + unittest.main() diff --git a/tests/interp/cam-nisley/expected b/tests/interp/cam-nisley/expected -index 4bc9ee3753..6f3aab576f 100644 +index 4bc9ee3..6f3aab5 100644 --- a/tests/interp/cam-nisley/expected +++ b/tests/interp/cam-nisley/expected @@ -51,6 +51,7 @@ @@ -1299,7 +2535,7 @@ index 4bc9ee3753..6f3aab576f 100644 N..... MESSAGE("Verify METRIC Sherline.tbl file!") N..... MESSAGE("Align XY=0 at center, Z=0 at surface, spindle to match S value, hit [Run]") diff --git a/tests/interp/compile/use-rs274.cc b/tests/interp/compile/use-rs274.cc -index 223fcdf3bd..4a55bad0de 100644 +index 2d388b5..e30cc2f 100644 --- a/tests/interp/compile/use-rs274.cc +++ b/tests/interp/compile/use-rs274.cc @@ -143,7 +143,8 @@ void WAIT_SPINDLE_ORIENT_COMPLETE(int spindle, double timeout) {} @@ -1313,7 +2549,7 @@ index 223fcdf3bd..4a55bad0de 100644 void USE_TOOL_LENGTH_OFFSET(const EmcPose& offset) {} void CHANGE_TOOL() {} diff --git a/tests/interp/g10/g10-l1-l10/expected b/tests/interp/g10/g10-l1-l10/expected -index cbc131cb22..c9b18bd22c 100644 +index 0cad340..2c183bd 100644 --- a/tests/interp/g10/g10-l1-l10/expected +++ b/tests/interp/g10/g10-l1-l10/expected @@ -16,6 +16,7 @@ @@ -1324,7 +2560,7 @@ index cbc131cb22..c9b18bd22c 100644 N..... MESSAGE(" should be 0 0 0: 0.000000 0.000000 0.000000") N..... SET_TOOL_TABLE_ENTRY(1, 1, 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) N..... SET_TOOL_TABLE_ENTRY(0, 1, 1.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -@@ -56,6 +57,7 @@ +@@ -50,6 +51,7 @@ N..... STOP_SPINDLE_TURNING(0) N..... CHANGE_TOOL() N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) @@ -1332,7 +2568,7 @@ index cbc131cb22..c9b18bd22c 100644 N..... STRAIGHT_TRAVERSE(0.1000, 0.2000, 0.3000, 0.0000, 0.0000, 0.0000) N..... MESSAGE(" should be 0 0 0: 0.000000 0.000000 0.000000") N..... SET_TOOL_TABLE_ENTRY(1, 1, -0.9000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -@@ -99,6 +101,7 @@ +@@ -87,6 +89,7 @@ N..... STOP_SPINDLE_TURNING(0) N..... CHANGE_TOOL() N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) @@ -1340,7 +2576,7 @@ index cbc131cb22..c9b18bd22c 100644 N..... MESSAGE(" should be 0 0 0: 0.000000 0.000000 0.000000") N..... SET_TOOL_TABLE_ENTRY(1, 1, -0.7071 -0.7071 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) N..... SET_TOOL_TABLE_ENTRY(0, 1, -0.7071 -0.7071 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -@@ -121,6 +124,7 @@ +@@ -110,6 +113,7 @@ N..... STOP_SPINDLE_TURNING(0) N..... CHANGE_TOOL() N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) @@ -1348,64 +2584,49 @@ index cbc131cb22..c9b18bd22c 100644 N..... MESSAGE(" should be 0 0 0: 0.000000 0.000000 0.000000") N..... SET_TOOL_TABLE_ENTRY(1, 1, -0.7071 -0.7071 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) N..... SET_TOOL_TABLE_ENTRY(0, 1, -0.7071 -0.7071 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -@@ -131,14 +135,15 @@ - N..... MESSAGE(" should be 0 -1.414 0: 0.000000 -1.414214 0.000000") - N..... MESSAGE(" should be 1 1: 1.000000 1.000000") - N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -- N..... MESSAGE("Model B contract: M6 alone and G10 alone do not change tool offset params") -+ N..... MESSAGE("automatic M6 applies the current stored offset; G10 alone does not change it") - N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - N..... SET_TOOL_TABLE_ENTRY(1, 1, 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) - N..... SET_TOOL_TABLE_ENTRY(0, 1, 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) - N..... SELECT_TOOL(1) - N..... STOP_SPINDLE_TURNING(0) - N..... CHANGE_TOOL() -- N..... MESSAGE(" after M6 alone, should be 0 0 0: 0.000000 0.000000 0.000000") -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ N..... MESSAGE(" after M6 alone, stored zero offset should be 0 0 0: 0.000000 0.000000 0.000000") - N..... SET_TOOL_TABLE_ENTRY(1, 1, 5.0000 6.0000 7.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) - N..... SET_TOOL_TABLE_ENTRY(0, 1, 5.0000 6.0000 7.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) - N..... MESSAGE(" after G10 alone, should still be 0 0 0: 0.000000 0.000000 0.000000") -diff --git a/tests/interp/g10/g10-l1-l10/test.ngc b/tests/interp/g10/g10-l1-l10/test.ngc -index bd7fb9dde0..34011f4a12 100644 ---- a/tests/interp/g10/g10-l1-l10/test.ngc -+++ b/tests/interp/g10/g10-l1-l10/test.ngc -@@ -98,11 +98,11 @@ g43 - g49 - - --(debug,Model B contract: M6 alone and G10 alone do not change tool offset params) -+(debug,automatic M6 applies the current stored offset; G10 alone does not change it) - g49 - g10 l1 p1 x0 y0 z0 - t1 m6 --(debug, after M6 alone, should be 0 0 0: #5401 #5402 #5403) -+(debug, after M6 alone, stored zero offset should be 0 0 0: #5401 #5402 #5403) - g10 l1 p1 x5 y6 z7 - (debug, after G10 alone, should still be 0 0 0: #5401 #5402 #5403) - g43 diff --git a/tests/interp/g10/g10-l11/expected b/tests/interp/g10/g10-l11/expected -index 7907f263f2..4a9bb955bb 100644 +index 867b953..68d9ed6 100644 --- a/tests/interp/g10/g10-l11/expected +++ b/tests/interp/g10/g10-l11/expected -@@ -23,6 +23,7 @@ +@@ -22,20 +22,21 @@ + N..... SELECT_TOOL(1) N..... STOP_SPINDLE_TURNING(0) N..... CHANGE_TOOL() - N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 -3.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 -3.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) N..... MESSAGE("-3.000000") N..... SET_G5X_OFFSET(2, 4.0000, 5.0000, -6.0000, 0.0000, 0.0000, 0.0000) N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -@@ -46,6 +47,7 @@ + N..... SET_XY_ROTATION(20.0000) +- N..... STRAIGHT_TRAVERSE(-5.4689, -3.3304, -24.0000, 0.0000, 0.0000, 0.0000) ++ N..... STRAIGHT_TRAVERSE(-5.4689, -3.3304, -21.0000, 0.0000, 0.0000, 0.0000) + N..... SET_TOOL_TABLE_ENTRY(1, 1, 0.0000 0.0000 -4.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) + N..... SET_TOOL_TABLE_ENTRY(0, 1, 0.0000 0.0000 -4.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) + N..... MESSAGE("-4.000000") + N..... SET_G5X_OFFSET(3, 7.0000, 8.0000, -9.0000, 0.0000, 0.0000, 0.0000) + N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(30.0000) +- N..... SET_G92_OFFSET(-43.0622, -47.4282, -76.0000, 0.0000, 0.0000, 0.0000) ++ N..... SET_G92_OFFSET(-43.0622, -47.4282, -73.0000, 0.0000, 0.0000, 0.0000) + N..... SET_G5X_OFFSET(1, 1.0000, 2.0000, -3.0000, 0.0000, 0.0000, 0.0000) +- N..... SET_G92_OFFSET(-43.0622, -47.4282, -76.0000, 0.0000, 0.0000, 0.0000) ++ N..... SET_G92_OFFSET(-43.0622, -47.4282, -73.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(10.0000) + N..... STRAIGHT_TRAVERSE(41.7301, 45.6322, 49.0000, 0.0000, 0.0000, 0.0000) + N..... SET_TOOL_TABLE_ENTRY(1, 1, 0.0000 0.0000 -3.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) +@@ -43,9 +44,10 @@ + N..... SELECT_TOOL(1) N..... STOP_SPINDLE_TURNING(0) N..... CHANGE_TOOL() - N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 -3.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 -3.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) N..... MESSAGE("-3.000000") N..... SET_G5X_OFFSET(2, 4.0000, 5.0000, -6.0000, 0.0000, 0.0000, 0.0000) - N..... SET_G92_OFFSET(-43.0622, -47.4282, -72.0000, 0.0000, 0.0000, 0.0000) +- N..... SET_G92_OFFSET(-43.0622, -47.4282, -76.0000, 0.0000, 0.0000, 0.0000) ++ N..... SET_G92_OFFSET(-43.0622, -47.4282, -73.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(20.0000) + N..... STRAIGHT_TRAVERSE(37.5933, 44.0978, 52.0000, 0.0000, 0.0000, 0.0000) + N..... SET_TOOL_TABLE_ENTRY(1, 1, 0.0000 0.0000 -4.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) diff --git a/tests/interp/g72-facing/expected b/tests/interp/g72-facing/expected -index 1096d6d415..5bf73147be 100644 +index 1096d6d..5bf7314 100644 --- a/tests/interp/g72-facing/expected +++ b/tests/interp/g72-facing/expected @@ -11,6 +11,7 @@ @@ -1417,7 +2638,7 @@ index 1096d6d415..5bf73147be 100644 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 2.5400, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) N..... SET_SPINDLE_SPEED(0, 100.0000) diff --git a/tests/interp/g72-missing-iteration/expected b/tests/interp/g72-missing-iteration/expected -index 56181de06e..0498594f03 100644 +index 56181de..0498594 100644 --- a/tests/interp/g72-missing-iteration/expected +++ b/tests/interp/g72-missing-iteration/expected @@ -11,6 +11,7 @@ @@ -1429,7 +2650,7 @@ index 56181de06e..0498594f03 100644 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 2.5400, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) N..... SET_SPINDLE_SPEED(0, 100.0000) diff --git a/tests/interp/g76/expected b/tests/interp/g76/expected -index c2c4921112..f7485e7c89 100644 +index 488e01b..d94d652 100644 --- a/tests/interp/g76/expected +++ b/tests/interp/g76/expected @@ -14,6 +14,7 @@ @@ -1440,198 +2661,8 @@ index c2c4921112..f7485e7c89 100644 N..... SET_SPINDLE_SPEED(0, 800.0000) N..... START_SPINDLE_CLOCKWISE(0) N..... DWELL(1.0000) -diff --git a/tests/interp/tool-wear/expected b/tests/interp/tool-wear/expected -new file mode 100644 -index 0000000000..dedb2edd48 ---- /dev/null -+++ b/tests/interp/tool-wear/expected -@@ -0,0 +1,60 @@ -+ N..... USE_LENGTH_UNITS(CANON_UNITS_MM) -+ N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_XY_ROTATION(0.0000) -+ N..... SET_FEED_REFERENCE(CANON_XYZ) -+ N..... ON_RESET() -+ N..... USE_LENGTH_UNITS(CANON_UNITS_INCHES) -+ N..... SELECT_TOOL(7) -+ N..... STOP_SPINDLE_TURNING(0) -+ N..... CHANGE_TOOL() -+ N..... USE_TOOL_LENGTH_OFFSET(10.1000 20.2000 30.3000, 40.4000 50.5000 60.6000, 70.7000 80.8000 90.9000) -+ N..... MESSAGE("auto 10.100000-90.900000: 10.100000 20.200000 30.300000 40.400000 50.500000 60.600000 70.700000 80.800000 90.900000") -+ N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... MESSAGE("applied unchanged: 10.100000 20.200000 30.300000 40.400000 50.500000 60.600000 70.700000 80.800000 90.900000") -+ N..... MESSAGE("edited wear: 0.000000 -0.200000 0.030000 -0.400000 0.050000 -0.060000 0.700000 0.800000 0.900000") -+ N..... USE_TOOL_LENGTH_OFFSET(10.0000 19.8000 30.0300, 39.6000 50.0500 59.9400, 70.7000 80.8000 90.9000) -+ N..... MESSAGE("composed 10.000000-90.900000: 10.000000 19.800000 30.030000 39.600000 50.050000 59.940000 70.700000 80.800000 90.900000") -+ N..... USE_TOOL_LENGTH_OFFSET(10.0000 19.8000 30.0300, 39.6000 50.0500 59.9400, 70.7000 80.8000 90.9000) -+ N..... MESSAGE("idempotent 10.000000-90.900000: 10.000000 19.800000 30.030000 39.600000 50.050000 59.940000 70.700000 80.800000 90.900000") -+ N..... USE_TOOL_LENGTH_OFFSET(11.0000 21.8000 33.0300, 43.6000 55.0500 65.9400, 70.7000 80.8000 90.9000) -+ N..... COMMENT("interpreter: motion mode set to none") -+ N..... MESSAGE("additive 11.000000-90.900000: 11.000000 21.800000 33.030000 43.600000 55.050000 65.940000 70.700000 80.800000 90.900000") -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ N..... MESSAGE("cancelled 0.0000000.000000: 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000") -+ N..... MESSAGE("stored after g49: 0.000000 -0.200000 0.030000 -0.400000 0.050000 -0.060000 0.700000 0.800000 0.900000") -+ N..... USE_LENGTH_UNITS(CANON_UNITS_MM) -+ N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... MESSAGE("metric edit in machine units: 1.000000 -0.200000 -0.100000 -0.400000 0.050000 -0.060000 0.700000 0.800000 0.900000") -+ N..... USE_TOOL_LENGTH_OFFSET(279.4000 502.9200 759.4600, 39.6000 50.0500 59.9400, 1795.7800 2052.3200 2308.8600) -+ N..... MESSAGE("metric composition in machine units: 11.000000 19.800000 29.900000 39.600000 50.050000 59.940000 70.700000 80.800000 90.900000") -+ N..... USE_LENGTH_UNITS(CANON_UNITS_INCHES) -+ N..... COMMENT("interpreter: Lathe diameter mode changed to diameter") -+ N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... MESSAGE("g7 diameter x interpretation: 1.000000") -+ N..... COMMENT("interpreter: Lathe diameter mode changed to radius") -+ N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) -+ N..... MESSAGE("g8 radius x interpretation: 2.000000") -+ N..... CHANGE_TOOL_NUMBER(2) -+ N..... USE_TOOL_LENGTH_OFFSET(-1.1000 -2.2000 -3.3000, -4.4000 -5.5000 -6.6000, -7.7000 -8.8000 -9.9000) -+ N..... MESSAGE("m61 auto -1.100000--9.900000: -1.100000 -2.200000 -3.300000 -4.400000 -5.500000 -6.600000 -7.700000 -8.800000 -9.900000") -+ N..... CHANGE_TOOL_NUMBER(3) -+ N..... USE_TOOL_LENGTH_OFFSET(123456789.2469 123456789.2469 123456789.2469, 123456789.2469 123456789.2469 123456789.2469, 123456789.2469 123456789.2469 123456789.2469) -+ N..... MESSAGE("long complete record: 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912") -+ N..... CHANGE_TOOL_NUMBER(1) -+ N..... USE_TOOL_LENGTH_OFFSET(12.0000 19.8000 29.9000, 39.6000 50.0500 59.9400, 70.7000 80.8000 90.9000) -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ N..... MESSAGE("same-block g49: 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000") -+ N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_XY_ROTATION(0.0000) -+ N..... SET_FEED_MODE(0, 0) -+ N..... SET_FEED_RATE(0.0000) -+ N..... STOP_SPINDLE_TURNING(0) -+ N..... SET_SPINDLE_MODE(0 0.0000) -+ N..... PROGRAM_END() -+ N..... ON_RESET() -+ N..... ON_RESET() -diff --git a/tests/interp/tool-wear/invalid-i.ngc b/tests/interp/tool-wear/invalid-i.ngc -new file mode 100644 -index 0000000000..3ee52a24ca ---- /dev/null -+++ b/tests/interp/tool-wear/invalid-i.ngc -@@ -0,0 +1,3 @@ -+g20 -+g10 l3 p7 x1 i1 -+m2 -diff --git a/tests/interp/tool-wear/invalid-j.ngc b/tests/interp/tool-wear/invalid-j.ngc -new file mode 100644 -index 0000000000..3613d3983e ---- /dev/null -+++ b/tests/interp/tool-wear/invalid-j.ngc -@@ -0,0 +1,3 @@ -+g20 -+g10 l3 p7 x1 j1 -+m2 -diff --git a/tests/interp/tool-wear/invalid-missing-tool.ngc b/tests/interp/tool-wear/invalid-missing-tool.ngc -new file mode 100644 -index 0000000000..c9cf799567 ---- /dev/null -+++ b/tests/interp/tool-wear/invalid-missing-tool.ngc -@@ -0,0 +1,3 @@ -+g20 -+g10 l3 p99 x1 -+m2 -diff --git a/tests/interp/tool-wear/invalid-q.ngc b/tests/interp/tool-wear/invalid-q.ngc -new file mode 100644 -index 0000000000..c995e9ba0e ---- /dev/null -+++ b/tests/interp/tool-wear/invalid-q.ngc -@@ -0,0 +1,3 @@ -+g20 -+g10 l3 p7 x1 q1 -+m2 -diff --git a/tests/interp/tool-wear/invalid-r.ngc b/tests/interp/tool-wear/invalid-r.ngc -new file mode 100644 -index 0000000000..8ef7a87dfc ---- /dev/null -+++ b/tests/interp/tool-wear/invalid-r.ngc -@@ -0,0 +1,3 @@ -+g20 -+g10 l3 p7 x1 r1 -+m2 -diff --git a/tests/interp/tool-wear/invalid-zero-tool.ngc b/tests/interp/tool-wear/invalid-zero-tool.ngc -new file mode 100644 -index 0000000000..3a172d8fdf ---- /dev/null -+++ b/tests/interp/tool-wear/invalid-zero-tool.ngc -@@ -0,0 +1,3 @@ -+g20 -+g10 l3 p0 x1 -+m2 -diff --git a/tests/interp/tool-wear/test.ngc b/tests/interp/tool-wear/test.ngc -new file mode 100644 -index 0000000000..7142c12e4c ---- /dev/null -+++ b/tests/interp/tool-wear/test.ngc -@@ -0,0 +1,36 @@ -+g20 -+t7 m6 -+(debug,auto #5401-#5409: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+ -+g10 l3 p7 x0 y-0.2 z0.03 a-0.4 b0.05 c-0.06 -+(debug,applied unchanged: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+(debug,edited wear: #5430 #5431 #5432 #5433 #5434 #5435 #5436 #5437 #5438) -+ -+g43 h7 -+(debug,composed #5401-#5409: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+g43 h7 -+(debug,idempotent #5401-#5409: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+g43.2 x1 y2 z3 a4 b5 c6 -+(debug,additive #5401-#5409: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+g49 -+(debug,cancelled #5401-#5409: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+(debug,stored after g49: #5430 #5431 #5432 #5433 #5434 #5435 #5436 #5437 #5438) -+ -+g21 -+g10 l3 p7 x25.4 z-2.54 -+(debug,metric edit in machine units: #5430 #5431 #5432 #5433 #5434 #5435 #5436 #5437 #5438) -+g43 h7 -+(debug,metric composition in machine units: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+g20 -+g7 g10 l3 p7 x2 -+(debug,g7 diameter x interpretation: #5430) -+g8 g10 l3 p7 x2 -+(debug,g8 radius x interpretation: #5430) -+ -+m61 q8 -+(debug,m61 auto #5401-#5409: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+m61 q9 -+(debug,long complete record: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+m61 q7 g49 -+(debug,same-block g49: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) -+m2 -diff --git a/tests/interp/tool-wear/test.sh b/tests/interp/tool-wear/test.sh -new file mode 100755 -index 0000000000..604d25ee9f ---- /dev/null -+++ b/tests/interp/tool-wear/test.sh -@@ -0,0 +1,13 @@ -+#!/bin/bash -+rs274 -g test.ngc -t test.tbl | awk '{$1=""; print}' | sed 's/-0\.0000/0.0000/g' -+result=${PIPESTATUS[0]} -+if (( result != 0 )); then -+ exit "$result" -+fi -+ -+for invalid_program in invalid-*.ngc; do -+ if rs274 -g "$invalid_program" -t test.tbl >/dev/null 2>&1; then -+ echo "$invalid_program unexpectedly succeeded" >&2 -+ exit 1 -+ fi -+done -diff --git a/tests/interp/tool-wear/test.tbl b/tests/interp/tool-wear/test.tbl -new file mode 100644 -index 0000000000..1a6d140b4b ---- /dev/null -+++ b/tests/interp/tool-wear/test.tbl -@@ -0,0 +1,3 @@ -+T7 P7 X+10 Y+20 Z+30 A+40 B+50 C+60 U+70 V+80 W+90 WX+0.1 WY+0.2 WZ+0.3 WA+0.4 WB+0.5 WC+0.6 WU+0.7 WV+0.8 WW+0.9 ;all positive -+T8 P8 X-1 Y-2 Z-3 A-4 B-5 C-6 U-7 V-8 W-9 WX-0.1 WY-0.2 WZ-0.3 WA-0.4 WB-0.5 WC-0.6 WU-0.7 WV-0.8 WW-0.9 ;all negative -+T9 P9 X+123456789.123456 Y+123456789.123456 Z+123456789.123456 A+123456789.123456 B+123456789.123456 C+123456789.123456 U+123456789.123456 V+123456789.123456 W+123456789.123456 WX+0.123456 WY+0.123456 WZ+0.123456 WA+0.123456 WB+0.123456 WC+0.123456 WU+0.123456 WV+0.123456 WW+0.123456 ;over 256 bytes diff --git a/tests/remap/introspect/expected b/tests/remap/introspect/expected -index 4e6bd8af9d..4f3d021855 100644 +index 2f33b4b..7655928 100644 --- a/tests/remap/introspect/expected +++ b/tests/remap/introspect/expected @@ -9,9 +9,10 @@ executing @@ -1650,8 +2681,8 @@ index 4e6bd8af9d..4f3d021855 100644 argc= 4 @@ -31,12 +32,12 @@ parameter set via test.ini: 3.14159 locals: ['a_new_local'] - globals: ['_a', '_a_global_set_in_test_dot_ngc', '_a_new_global', '_abs_a', '_abs_b', '_abs_c', '_abs_x', '_abs_y', '_abs_z', '_absolute', '_adaptive_feed', '_b', '_c', '_call_level', '_ccomp', '_coord_system', '_current_pocket', '_current_tool', '_feed', '_feed_hold', '_feed_override', '_flood', '_ijk_absolute_mode', '_imperial', '_incremental', '_ini[example]variable', '_inverse_time', '_lathe_diameter_mode', '_lathe_radius_mode', '_line', '_metric', '_metric_machine', '_mist', '_motion_mode', '_plane', '_remap_level', '_retract_old_z', '_retract_r_plane', '_rpm', '_selected_pocket', '_selected_tool', '_speed_override', '_spindle_css_mode', '_spindle_cw', '_spindle_on', '_spindle_rpm_mode', '_task', '_tool_offset', '_u', '_units_per_minute', '_units_per_rev', '_v', '_value', '_value_returned', '_vmajor', '_vminor', '_w', '_x', '_y', '_z', 'foo'] - params(): ['a_new_local', '_a', '_a_global_set_in_test_dot_ngc', '_a_new_global', '_abs_a', '_abs_b', '_abs_c', '_abs_x', '_abs_y', '_abs_z', '_absolute', '_adaptive_feed', '_b', '_c', '_call_level', '_ccomp', '_coord_system', '_current_pocket', '_current_tool', '_feed', '_feed_hold', '_feed_override', '_flood', '_ijk_absolute_mode', '_imperial', '_incremental', '_ini[example]variable', '_inverse_time', '_lathe_diameter_mode', '_lathe_radius_mode', '_line', '_metric', '_metric_machine', '_mist', '_motion_mode', '_plane', '_remap_level', '_retract_old_z', '_retract_r_plane', '_rpm', '_selected_pocket', '_selected_tool', '_speed_override', '_spindle_css_mode', '_spindle_cw', '_spindle_on', '_spindle_rpm_mode', '_task', '_tool_offset', '_u', '_units_per_minute', '_units_per_rev', '_v', '_value', '_value_returned', '_vmajor', '_vminor', '_w', '_x', '_y', '_z', 'foo'] + globals: ['_a', '_a_global_set_in_test_dot_ngc', '_a_new_global', '_abs_a', '_abs_b', '_abs_c', '_abs_u', '_abs_v', '_abs_w', '_abs_x', '_abs_y', '_abs_z', '_absolute', '_adaptive_feed', '_b', '_c', '_call_level', '_ccomp', '_coord_system', '_current_pocket', '_current_tool', '_feed', '_feed_hold', '_feed_override', '_flood', '_ijk_absolute_mode', '_imperial', '_incremental', '_ini[example]variable', '_inverse_time', '_kins_type', '_lathe_diameter_mode', '_lathe_radius_mode', '_line', '_metric', '_metric_machine', '_mist', '_motion_mode', '_plane', '_remap_level', '_retract_old_z', '_retract_r_plane', '_rpm', '_selected_pocket', '_selected_tool', '_speed_override', '_spindle_css_mode', '_spindle_cw', '_spindle_on', '_spindle_rpm_mode', '_task', '_tool_offset', '_u', '_units_per_minute', '_units_per_rev', '_v', '_value', '_value_returned', '_vmajor', '_vminor', '_w', '_x', '_y', '_z', 'foo'] + params(): ['a_new_local', '_a', '_a_global_set_in_test_dot_ngc', '_a_new_global', '_abs_a', '_abs_b', '_abs_c', '_abs_u', '_abs_v', '_abs_w', '_abs_x', '_abs_y', '_abs_z', '_absolute', '_adaptive_feed', '_b', '_c', '_call_level', '_ccomp', '_coord_system', '_current_pocket', '_current_tool', '_feed', '_feed_hold', '_feed_override', '_flood', '_ijk_absolute_mode', '_imperial', '_incremental', '_ini[example]variable', '_inverse_time', '_kins_type', '_lathe_diameter_mode', '_lathe_radius_mode', '_line', '_metric', '_metric_machine', '_mist', '_motion_mode', '_plane', '_remap_level', '_retract_old_z', '_retract_r_plane', '_rpm', '_selected_pocket', '_selected_tool', '_speed_override', '_spindle_css_mode', '_spindle_cw', '_spindle_on', '_spindle_rpm_mode', '_task', '_tool_offset', '_u', '_units_per_minute', '_units_per_rev', '_v', '_value', '_value_returned', '_vmajor', '_vminor', '_w', '_x', '_y', '_z', 'foo'] - 14 N..... MESSAGE(" after introspect: return value=2.718280 call_level= 0.000000") - 15 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) - 16 N..... SET_XY_ROTATION(0.0000) @@ -1671,7 +2702,7 @@ index 4e6bd8af9d..4f3d021855 100644 + 22 N..... PROGRAM_END() + 23 N..... ON_RESET() diff --git a/tests/remap/oword-pycall/expected b/tests/remap/oword-pycall/expected -index a11f8e0c78..ba04016cf3 100644 +index a11f8e0..ba04016 100644 --- a/tests/remap/oword-pycall/expected +++ b/tests/remap/oword-pycall/expected @@ -12,15 +12,16 @@ multiply: number of arguments= 3 @@ -1704,67 +2735,55 @@ index a11f8e0c78..ba04016cf3 100644 + 23 N..... PROGRAM_END() + 24 N..... ON_RESET() diff --git a/tests/t0/nonrandom/expected-gcode-output b/tests/t0/nonrandom/expected-gcode-output -index a05b5207e6..1e37a9b6bc 100644 +index 9d94ac4..196289e 100644 --- a/tests/t0/nonrandom/expected-gcode-output +++ b/tests/t0/nonrandom/expected-gcode-output -@@ -134,9 +134,9 @@ tlo_z = 0.000000 +@@ -134,7 +134,7 @@ tlo_z = 0.000000 sequence number 100.000000 X = 0.000000 Y = 0.000000 -Z = 0.000000 +Z = -2.000000 toolno = 50.000000 --tlo_z = 0.000000 -+tlo_z = 2.000000 + tlo_z = 2.000000 - sequence number 101.000000 - X = 0.000000 -@@ -309,9 +309,9 @@ tlo_z = -1.700000 +@@ -309,7 +309,7 @@ tlo_z = -1.700000 sequence number 200.000000 X = 0.000000 Y = 0.000000 -Z = 1.700000 +Z = 0.000000 toolno = 0.000000 --tlo_z = -1.700000 -+tlo_z = 0.000000 + tlo_z = 0.000000 - sequence number 201.000000 - X = 0.000000 diff --git a/tests/t0/random-with-t0/expected-gcode-output b/tests/t0/random-with-t0/expected-gcode-output -index 927161c938..16b2b723ec 100644 +index d23b22c..d16fc25 100644 --- a/tests/t0/random-with-t0/expected-gcode-output +++ b/tests/t0/random-with-t0/expected-gcode-output -@@ -134,9 +134,9 @@ tlo_z = 0.000000 +@@ -134,7 +134,7 @@ tlo_z = 0.000000 sequence number 100.000000 X = 0.000000 Y = 0.000000 -Z = 0.000000 +Z = -2.000000 toolno = 50.000000 --tlo_z = 0.000000 -+tlo_z = 2.000000 + tlo_z = 2.000000 - sequence number 101.000000 - X = 0.000000 diff --git a/tests/t0/random-without-t0/expected-gcode-output b/tests/t0/random-without-t0/expected-gcode-output -index 5e63053dd0..c274cf0905 100644 +index 71fa114..2075e4a 100644 --- a/tests/t0/random-without-t0/expected-gcode-output +++ b/tests/t0/random-without-t0/expected-gcode-output -@@ -134,9 +134,9 @@ tlo_z = 4.200000 +@@ -134,7 +134,7 @@ tlo_z = 0.000000 sequence number 100.000000 X = 0.000000 Y = 0.000000 -Z = -4.200000 +Z = -2.000000 toolno = 50.000000 --tlo_z = 4.200000 -+tlo_z = 2.000000 + tlo_z = 2.000000 - sequence number 101.000000 - X = 0.000000 diff --git a/tests/tlo/test-ui.py b/tests/tlo/test-ui.py -index c6c1f5e040..4ddcad9a8f 100755 +index 42fe939..2814fe0 100755 --- a/tests/tlo/test-ui.py +++ b/tests/tlo/test-ui.py @@ -153,14 +153,14 @@ verify_tool( @@ -1799,24 +2818,21 @@ index c6c1f5e040..4ddcad9a8f 100755 sys.exit(0) - diff --git a/tests/toolchanger/m61/test-ui.py b/tests/toolchanger/m61/test-ui.py -index 83110f6ed2..51dd84d263 100755 +index 025cc58..8514d33 100755 --- a/tests/toolchanger/m61/test-ui.py +++ b/tests/toolchanger/m61/test-ui.py -@@ -175,11 +175,10 @@ do_tool_change_handshake(tool_number=1, pocket_number=1) +@@ -175,6 +175,10 @@ do_tool_change_handshake(tool_number=1, pocket_number=1) print("*** tool change complete") verify_tool_number(1) --# M6 changes the loaded tool but does not by itself apply its offset --# to motion, so #5401-#5409 (applied tool length offset) stay at 0. -+# Built-in M6 automatically applies the loaded tool's offset. ++# #5401-#5409 hold the loaded tool's stored offset. Built-in M6 also ++# applies it automatically, so #5081-#5089 (applied offset) follow. ++verify_interp_param(5081, 0) # applied x ++verify_interp_param(5083, 1) # applied z verify_interp_param(5401, 0) # tlo x verify_interp_param(5402, 0) # tlo y --verify_interp_param(5403, 0) # tlo z (not applied yet) -+verify_interp_param(5403, 1) # tlo z - verify_interp_param(5404, 0) # tlo a - verify_interp_param(5405, 0) # tlo b - verify_interp_param(5406, 0) # tlo c -@@ -193,7 +192,7 @@ verify_interp_param(5413, 0) # tool orientation + verify_interp_param(5403, 1) # tlo z +@@ -191,7 +195,7 @@ verify_interp_param(5413, 0) # tool orientation verify_interp_param(5420, 0) # current x verify_interp_param(5421, 0) # current y @@ -1825,33 +2841,27 @@ index 83110f6ed2..51dd84d263 100755 verify_interp_param(5423, 0) # current a verify_interp_param(5424, 0) # current b verify_interp_param(5425, 0) # current c -@@ -204,8 +203,8 @@ verify_interp_param(5428, 0) # current w +@@ -202,6 +206,10 @@ verify_interp_param(5428, 0) # current w c.mdi('g43') c.wait_complete() --# After G43 the tool length offset is applied; #5403 now reflects it. --verify_interp_param(5403, 1) # tlo z (now applied) +# Repeating G43 is idempotent. -+verify_interp_param(5403, 1) # tlo z - ++verify_interp_param(5403, 1) # stored tlo z ++verify_interp_param(5083, 1) # applied z ++ verify_interp_param(5420, 0) # current x verify_interp_param(5421, 0) # current y -@@ -244,12 +243,10 @@ verify_stable_pin_values( + verify_interp_param(5422, -1) # current z +@@ -239,6 +247,8 @@ verify_stable_pin_values( verify_tool_number(10) --# M61 changes the loaded tool but does not by itself apply its offset --# to motion. The previous offset from T1 (z=1) is still applied here, --# until the next G43. -+# Built-in M61 automatically replaces the active offset with T10's offset. ++# Built-in M61 automatically replaces the applied offset with T10's. ++verify_interp_param(5083, 3) # applied z verify_interp_param(5401, 0) # tlo x verify_interp_param(5402, 0) # tlo y --verify_interp_param(5403, 1) # tlo z (still T1's offset, not yet reapplied) -+verify_interp_param(5403, 3) # tlo z - verify_interp_param(5404, 0) # tlo a - verify_interp_param(5405, 0) # tlo b - verify_interp_param(5406, 0) # tlo c -@@ -263,7 +260,7 @@ verify_interp_param(5413, 0) # tool orientation + verify_interp_param(5403, 3) # tlo z +@@ -255,7 +265,7 @@ verify_interp_param(5413, 0) # tool orientation verify_interp_param(5420, 0) # current x verify_interp_param(5421, 0) # current y @@ -1860,40 +2870,43 @@ index 83110f6ed2..51dd84d263 100755 verify_interp_param(5423, 0) # current a verify_interp_param(5424, 0) # current b verify_interp_param(5425, 0) # current c -@@ -274,8 +271,8 @@ verify_interp_param(5428, 0) # current w +@@ -266,6 +276,10 @@ verify_interp_param(5428, 0) # current w c.mdi('g43') c.wait_complete() --# After G43 the new tool's offset is applied; #5403 now reflects T10. --verify_interp_param(5403, 3) # tlo z (now applied) +# Repeating G43 is idempotent. -+verify_interp_param(5403, 3) # tlo z - ++verify_interp_param(5403, 3) # stored tlo z ++verify_interp_param(5083, 3) # applied z ++ verify_interp_param(5420, 0) # current x verify_interp_param(5421, 0) # current y -@@ -297,6 +294,8 @@ c.mdi("t0 m6") + verify_interp_param(5422, -3) # current z +@@ -286,6 +300,9 @@ c.mdi("t0 m6") c.wait_complete() do_tool_change_handshake(tool_number=0, pocket_number=0) verify_tool_number(0) +verify_interp_param(5403, 0) ++verify_interp_param(5083, 0) +verify_interp_param(5422, 0) # -@@ -307,6 +306,8 @@ print("*** using 'M61 Q1' to load a tool again") +@@ -296,6 +313,9 @@ print("*** using 'M61 Q1' to load a tool again") c.mdi("m61 q1") c.wait_complete() verify_tool_number(1) +verify_interp_param(5403, 1) ++verify_interp_param(5083, 1) +verify_interp_param(5422, -1) # -@@ -317,8 +318,9 @@ print("*** using 'M61 Q0' to unload the spindle again") +@@ -306,8 +326,10 @@ print("*** using 'M61 Q0' to unload the spindle again") c.mdi("m61 q0") c.wait_complete() verify_tool_number(0) +verify_interp_param(5403, 0) ++verify_interp_param(5083, 0) +verify_interp_param(5422, 0) @@ -1901,154 +2914,118 @@ index 83110f6ed2..51dd84d263 100755 sys.exit(0) - diff --git a/tests/toolchanger/toolno-pocket-differ/nonrandom/expected-gcode-output b/tests/toolchanger/toolno-pocket-differ/nonrandom/expected-gcode-output -index 5e5cb8a042..3b102e9823 100644 +index edc3501..554663c 100644 --- a/tests/toolchanger/toolno-pocket-differ/nonrandom/expected-gcode-output +++ b/tests/toolchanger/toolno-pocket-differ/nonrandom/expected-gcode-output -@@ -8,9 +8,9 @@ tlo_z = 0.000000 +@@ -8,7 +8,7 @@ tlo_z = 0.000000 sequence number 1.000000 X = 0.111000 Y = 0.222000 -Z = 0.333000 +Z = -0.667000 toolno = 1.000000 --tlo_z = 0.000000 -+tlo_z = 1.000000 + tlo_z = 1.000000 - sequence number 2.000000 - X = 0.111000 -@@ -64,9 +64,9 @@ tlo_z = 0.233000 +@@ -64,7 +64,7 @@ tlo_z = 0.233000 sequence number 9.000000 X = 0.111000 Y = 0.222000 -Z = 0.100000 +Z = 0.150000 toolno = 10.000000 --tlo_z = 0.233000 -+tlo_z = 0.183000 + tlo_z = 0.183000 - sequence number 10.000000 - X = 0.111000 -@@ -120,9 +120,9 @@ tlo_z = 0.229500 +@@ -120,7 +120,7 @@ tlo_z = 0.229500 sequence number 17.000000 X = 0.111000 Y = 0.222000 -Z = 0.103500 +Z = 0.104000 toolno = 99999.000000 --tlo_z = 0.229500 -+tlo_z = 0.229000 + tlo_z = 0.229000 - sequence number 18.000000 - X = 0.111000 -@@ -176,9 +176,9 @@ tlo_z = -0.067000 +@@ -176,7 +176,7 @@ tlo_z = -0.067000 sequence number 25.000000 X = 0.111000 Y = 0.222000 -Z = 0.400000 +Z = 0.300000 toolno = 1.000000 --tlo_z = -0.067000 -+tlo_z = 0.033000 + tlo_z = 0.033000 - sequence number 26.000000 - X = 0.111000 -@@ -190,9 +190,9 @@ tlo_z = 0.033000 +@@ -190,7 +190,7 @@ tlo_z = 0.033000 sequence number 27.000000 X = 0.111000 Y = 0.222000 -Z = 0.300000 +Z = 0.350000 toolno = 10.000000 --tlo_z = 0.033000 -+tlo_z = -0.017000 + tlo_z = -0.017000 - sequence number 28.000000 - X = 0.111000 -@@ -204,9 +204,9 @@ tlo_z = -0.017000 +@@ -204,7 +204,7 @@ tlo_z = -0.017000 sequence number 29.000000 X = 0.111000 Y = 0.222000 -Z = 0.350000 +Z = 0.400000 toolno = 99999.000000 --tlo_z = -0.017000 -+tlo_z = -0.067000 + tlo_z = -0.067000 - sequence number 30.000000 - X = 0.111000 diff --git a/tests/toolchanger/toolno-pocket-differ/random/expected-gcode-output b/tests/toolchanger/toolno-pocket-differ/random/expected-gcode-output -index d5986569f1..928fdfd1ed 100644 +index 30edd89..59bed1c 100644 --- a/tests/toolchanger/toolno-pocket-differ/random/expected-gcode-output +++ b/tests/toolchanger/toolno-pocket-differ/random/expected-gcode-output -@@ -8,9 +8,9 @@ tlo_z = 0.000000 +@@ -8,7 +8,7 @@ tlo_z = 0.000000 sequence number 1.000000 X = 0.111000 Y = 0.222000 -Z = 0.333000 +Z = -0.667000 toolno = 1.000000 --tlo_z = 0.000000 -+tlo_z = 1.000000 + tlo_z = 1.000000 - sequence number 2.000000 - X = 0.111000 -@@ -64,9 +64,9 @@ tlo_z = 0.233000 +@@ -64,7 +64,7 @@ tlo_z = 0.233000 sequence number 9.000000 X = 0.111000 Y = 0.222000 -Z = 0.100000 +Z = 0.150000 toolno = 10.000000 --tlo_z = 0.233000 -+tlo_z = 0.183000 + tlo_z = 0.183000 - sequence number 10.000000 - X = 0.111000 -@@ -120,9 +120,9 @@ tlo_z = 0.229500 +@@ -120,7 +120,7 @@ tlo_z = 0.229500 sequence number 17.000000 X = 0.111000 Y = 0.222000 -Z = 0.103500 +Z = 0.104000 toolno = 99999.000000 --tlo_z = 0.229500 -+tlo_z = 0.229000 + tlo_z = 0.229000 - sequence number 18.000000 - X = 0.111000 -@@ -176,9 +176,9 @@ tlo_z = -0.067000 +@@ -176,7 +176,7 @@ tlo_z = -0.067000 sequence number 25.000000 X = 0.111000 Y = 0.222000 -Z = 0.400000 +Z = 0.300000 toolno = 1.000000 --tlo_z = -0.067000 -+tlo_z = 0.033000 + tlo_z = 0.033000 - sequence number 26.000000 - X = 0.111000 -@@ -190,9 +190,9 @@ tlo_z = 0.033000 +@@ -190,7 +190,7 @@ tlo_z = 0.033000 sequence number 27.000000 X = 0.111000 Y = 0.222000 -Z = 0.300000 +Z = 0.350000 toolno = 10.000000 --tlo_z = 0.033000 -+tlo_z = -0.017000 + tlo_z = -0.017000 - sequence number 28.000000 - X = 0.111000 -@@ -204,9 +204,9 @@ tlo_z = -0.017000 +@@ -204,7 +204,7 @@ tlo_z = -0.017000 sequence number 29.000000 X = 0.111000 Y = 0.222000 -Z = 0.350000 +Z = 0.400000 toolno = 99999.000000 --tlo_z = -0.017000 -+tlo_z = -0.067000 + tlo_z = -0.067000 - sequence number 30.000000 - X = 0.111000 diff --git a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch index 345049c8..856870fc 100644 --- a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch +++ b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch @@ -4,38 +4,64 @@ Date: Sat, 15 Aug 2026 22:14:12 +0200 Subject: [PATCH] interp: extend G76 with tapered threads and alternating infeed +Ported to v2.10.0-pre2, where G76 checks its synchronized feed against +the axis velocity limits and holds the spindle override for the cycle. +A tapered cycle now checks every synchronized move of every pass at the +lead it is commanded with: the drive line, the X-only feed in and the +angled move of an entry taper, and the angled move of an exit taper, +each with its own X and Z components and, in G96, its own smallest +radius. Upstream's cylindrical checks are kept unchanged for a G76 +without X. The pass geometry is computed once and used both for the +checks and for the moves. G76.1 is G76 with alternating infeed; D stays +unavailable on G76, as upstream later gives it another meaning there. +tests/g76-tapered-pitch exercises the check on a simulated lathe. --- - docs/src/gcode/g-code.adoc | 39 +- - src/emc/rs274ngc/interp_check.cc | 11 +- - src/emc/rs274ngc/interp_convert.cc | 142 ++++++- - tests/interp/g76-tapered/README | 8 + - tests/interp/g76-tapered/expected | 377 ++++++++++++++++++ - .../interp/g76-tapered/invalid-d-fraction.ngc | 5 + - tests/interp/g76-tapered/invalid-d2.ngc | 5 + - tests/interp/g76-tapered/invalid-g96-d.ngc | 5 + - tests/interp/g76-tapered/invalid-y.ngc | 5 + - tests/interp/g76-tapered/test.ngc | 63 +++ - tests/interp/g76-tapered/test.sh | 14 + - 11 files changed, 653 insertions(+), 21 deletions(-) - create mode 100644 tests/interp/g76-tapered/README - create mode 100644 tests/interp/g76-tapered/expected - create mode 100644 tests/interp/g76-tapered/invalid-d-fraction.ngc - create mode 100644 tests/interp/g76-tapered/invalid-d2.ngc - create mode 100644 tests/interp/g76-tapered/invalid-g96-d.ngc - create mode 100644 tests/interp/g76-tapered/invalid-y.ngc - create mode 100644 tests/interp/g76-tapered/test.ngc - create mode 100644 tests/interp/g76-tapered/test.sh + docs/src/gcode/g-code.adoc | 55 ++++-- + src/emc/rs274ngc/interp_convert.cc | 273 ++++++++++++++++++++++++---- + src/emc/rs274ngc/interp_internal.cc | 1 + + src/emc/rs274ngc/interp_internal.hh | 2 + + src/emc/rs274ngc/interp_read.cc | 5 + + src/emc/rs274ngc/rs274ngc_interp.hh | 4 + + 6 files changed, 293 insertions(+), 47 deletions(-) diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index fa46049723..4160cfb4a2 100644 +index f8f9d01..6f196b6 100644 --- a/docs/src/gcode/g-code.adoc +++ b/docs/src/gcode/g-code.adoc -@@ -1900,15 +1900,24 @@ In example S100 with 1.25MM per revolution thread pitch gives a feed of F125. +@@ -98,7 +98,7 @@ as the 'L number', and so on for any other letter. + |<> |Lathe roughing cycle + |<> |Drilling Cycle with Chip Breaking + |<> |Left-hand Tapping Cycle with Dwell +-|<> |Multi-pass Threading Cycle (Lathe) ++|<> |Multi-pass Threading Cycle (Lathe) + |<> |Cancel Motion Modes + |<> |Drilling Cycle + |<> |Drilling Cycle with Dwell +@@ -1390,7 +1390,11 @@ It is an error if: + this command is executed. + * The pitch and the spindle speed together ask an axis to move faster than + its maximum velocity. See <> for how the speed is determined +- in constant surface speed mode. ++ in constant surface speed mode. With an 'X-' endpoint every synchronized ++ move of every pass is checked at the lead it is commanded with: the tapered ++ drive line, the feed in along X and the angled move of an entry taper, and ++ the angled move of an exit taper, each at the spindle speed reached at its ++ own smallest radius in constant surface speed mode. + + [[gcode:g38]] + == G38._n_ Straight Probe(((G38.n Probe))) +@@ -2213,19 +2217,29 @@ The feed rate 'F-' is spindle speed multiplied by distance per revolution + In example S100 with 1.25MM per revolution thread pitch gives a feed of F125. + + [[gcode:g76]] +-== G76 Threading Cycle(((G76 Threading Cycle))) ++== G76, G76.1 Threading Cycle(((G76 Threading Cycle))) [source,ngc] ---- -G76 P- Z- I- J- R- K- Q- H- E- L- $- -+G76 P- Z- I- J- K- [X-] [D-] [R-] [Q-] [H-] [E-] [L-] [$-] ++G76 P- Z- I- J- K- [X-] [R-] [Q-] [H-] [E-] [L-] [$-] ++G76.1 P- Z- I- J- K- [X-] [R-] [Q-] [H-] [E-] [L-] [$-] ---- .G76 Threading @@ -59,7 +85,7 @@ index fa46049723..4160cfb4a2 100644 [NOTE] When G7 'Lathe Diameter Mode' is in force the values for 'I', 'J' and 'K' are diameter measurements. -@@ -1937,7 +1946,17 @@ Unnecessarily high degression values will produce an unnecessarily high number o +@@ -2254,11 +2268,22 @@ Unnecessarily high degression values will produce an unnecessarily high number o * 'Q-' - The 'compound slide angle' is the angle (in degrees) describing to what extent successive passes should be offset along the drive line. This is used to cause one side of the tool to remove more material than the other. @@ -67,18 +93,23 @@ index fa46049723..4160cfb4a2 100644 + A positive 'Q' value causes the leading edge of the tool to cut more heavily + on the first pass. Typical values are 29, 29.5 or 30. 'Q0' keeps every pass + on the centered final thread line. -+* 'D-' - Selects the compound-infeed mode. 'D0' (the default) uses the -+ existing fixed compound-infeed direction, with the side selected by the -+ sign of Q. 'D1' alternates -+ roughing passes across the centered final thread line, starting on the flank -+ selected by the sign of Q. The alternating offset decreases with remaining -+ cut depth. The full-depth pass and all H spring passes use the centered final -+ path. Program G96 and its D spindle-speed limit in a separate block from a -+ G76 D infeed selection. * 'H-' - The number of 'spring passes'. Spring passes are additional passes at full thread depth. If no additional passes are desired, program 'H0'. -@@ -1957,8 +1976,10 @@ Thread entries and exits can be programmed tapered with the 'E' and 'L' values. + ++'G76' uses a fixed compound-infeed direction, with the side selected by the ++sign of 'Q'. 'G76.1' takes the same words and alternates roughing passes across ++the centered final thread line, starting on the flank selected by the sign of ++'Q'. The alternating offset decreases with remaining cut depth. A pass on the ++opposite flank starts with its offset but ends where the final pass ends, so no ++pass cuts past the programmed 'Z'. The full-depth ++pass and all 'H' spring passes use the centered final path. Status reports ++'G76.1' as the active motion code 'G76'. ++ + Thread entries and exits can be programmed tapered with the 'E' and 'L' values. + + * 'E-' - Specifies the distance along the drive line used for the taper. +@@ -2274,8 +2299,10 @@ Thread entries and exits can be programmed tapered with the 'E' and 'L' values. cut depth then synchronize and begin the cut. The tool is moved to the initial X and Z positions prior to issuing @@ -91,141 +122,218 @@ index fa46049723..4160cfb4a2 100644 The tool will pause briefly for synchronization before each threading pass, so a relief groove will be required at the entry unless the -@@ -1981,7 +2002,9 @@ from the hole. +@@ -2298,14 +2325,18 @@ from the hole. It is an error if: * The active plane is not the ZX plane. -* Other axis words, such as X- or Y-, are specified. +* A Y- word is specified, or another axis besides X or Z is moved. -+* A 'D-' infeed mode other than 0 or 1 is specified. -+* 'G96' and 'G76' use 'D-' in the same block. * The 'R-' degression value is less than 1.0. * All the required words are not specified. * 'P-', 'J-', 'K-' or 'H-' is negative. -diff --git a/src/emc/rs274ngc/interp_check.cc b/src/emc/rs274ngc/interp_check.cc -index cf3b8050c9..3b139a0ca6 100644 ---- a/src/emc/rs274ngc/interp_check.cc -+++ b/src/emc/rs274ngc/interp_check.cc -@@ -256,9 +256,9 @@ int Interp::check_other_codes(block_pointer block) //!< pointer to a block - (block->g_modes[7] != G_41_1) && (block->g_modes[7] != G_42_1) && - (motion != G_70) && (motion != G_71) && (motion != G_71_1) && - (motion != G_71_2) && (motion != G_72) && (motion != G_72_1) && -- (motion != G_72_2) && (motion != G_73) && (motion != G_83) && -+ (motion != G_72_2) && (motion != G_73) && (motion != G_76) && (motion != G_83) && - (block->g_modes[14] != G_96)), -- _("D word with no G41, G41.1, G42, G42.1, G71, G71.1, G71.2 G73, G83 or G96 to use it")); -+ _("D word with no G41, G41.1, G42, G42.1, G71, G71.1, G71.2 G73, G76, G83 or G96 to use it")); - } - - if (block->dollar_flag) { -@@ -383,6 +383,13 @@ int Interp::check_other_codes(block_pointer block) //!< pointer to a block - - CHKS((!block->i_flag || !block->j_flag || !block->k_flag), - NCE_I_J_OR_K_WORDS_MISSING_WITH_G76); -+ -+ if (block->d_flag) { -+ CHKS((block->d_number_float != 0.0 && block->d_number_float != 1.0), -+ _("In G76, D must be 0 or 1")); -+ CHKS((block->g_modes[GM_SPINDLE_MODE] == G_96), -+ _("D cannot select both G76 infeed mode and G96 spindle limit in the same block")); -+ } - } + * 'E-' is greater than half the drive line length. + * The pitch and the spindle speed together ask an axis to move faster than + its maximum velocity. See <> for how the speed is determined +- in constant surface speed mode. ++ in constant surface speed mode. With an 'X-' endpoint every synchronized ++ move of every pass is checked at the lead it is commanded with: the tapered ++ drive line, the feed in along X and the angled move of an entry taper, and ++ the angled move of an exit taper, each at the spindle speed reached at its ++ own smallest radius in constant surface speed mode. - return INTERP_OK; + [NOTE] + The spindle speed override is held for the whole G76 cycle at the value in diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 99f9e6fdb8..373916cfb0 100644 +index ab502ad..6d051a2 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -5659,6 +5659,88 @@ threading_pass(setup_pointer settings, block_pointer block, +@@ -5944,7 +5944,8 @@ int Interp::issue_straight_index(int axis, int jnum, double target, int lineno, + static void + threading_pass(setup_pointer settings, block_pointer block, + int boring, double safe_x, double depth, double end_depth, +- double start_y, double start_z, double zoff, double taper_dist, ++ double start_y, double start_z, double zoff, double end_zoff, ++ double taper_dist, + int entry_taper, int exit_taper, double taper_pitch, + double pitch, double full_threadheight, double target_z) { + STRAIGHT_TRAVERSE(block->line_number, boring? +@@ -5970,24 +5971,171 @@ threading_pass(setup_pointer settings, block_pointer block, + + if(taper_dist && exit_taper) { + STRAIGHT_FEED(block->line_number, boring? safe_x + depth: safe_x - depth, //over +- start_y, target_z - zoff + taper_dist, AABBCC); ++ start_y, target_z - end_zoff + taper_dist, AABBCC); + START_SPEED_FEED_SYNCH(settings->active_spindle, taper_pitch, 0); + STRAIGHT_FEED(block->line_number, boring? + safe_x + depth - full_threadheight: + safe_x - depth + full_threadheight, +- start_y, target_z - zoff, AABBCC); //angled out ++ start_y, target_z - end_zoff, AABBCC); //angled out + } else { + STRAIGHT_FEED(block->line_number, boring? safe_x + depth: safe_x - depth, +- start_y, target_z - zoff, AABBCC); //over ++ start_y, target_z - end_zoff, AABBCC); //over + } + STOP_SPEED_FEED_SYNCH(); + STRAIGHT_TRAVERSE(block->line_number, boring? + safe_x + depth - end_depth: + safe_x - depth + end_depth, +- start_y, target_z - zoff, AABBCC); //out ++ start_y, target_z - end_zoff, AABBCC); //out ENABLE_FEED_OVERRIDE(); } -+// Make one threading pass along a tapered XZ drive line. X coordinates are -+// offset from the drive line just as they are for a cylindrical thread, while -+// compound offsets and entry/exit distances are measured along that line. -+static void -+tapered_threading_pass(setup_pointer settings, block_pointer block, -+ int boring, double start_x, double start_z, -+ double end_x, double end_z, double depth, double end_depth, -+ double start_y, double compound_offset, -+ double full_compound_offset, double taper_dist, -+ int entry_taper, int exit_taper, double pitch, -+ double full_threadheight) { ++// Geometry of one threading pass along a tapered XZ drive line. X coordinates ++// are offset from the drive line just as they are for a cylindrical thread, ++// while compound offsets and entry/exit distances are measured along that line. ++// It is computed once per pass and used both to check every synchronized lead ++// the pass commands and to issue its moves, so the two cannot disagree. ++struct tapered_pass_geometry { ++ double drive_pitch; // synchronized lead along the drive line ++ double pass_start_z, pass_end_z; ++ double back_x, out_x; // clearance before and after the cut ++ double cut_start_x, cut_end_x; // drive line offset to the pass depth ++ bool entry; // tapered entry ++ double crest_start_x, entry_end_x, entry_end_z, entry_pitch; ++ bool exit; // tapered exit ++ double exit_start_x, exit_start_z, crest_end_x, exit_pitch; ++}; ++ ++static tapered_pass_geometry ++tapered_pass(int boring, double start_x, double start_z, ++ double end_x, double end_z, double depth, double end_depth, ++ double compound_offset, double end_compound_offset, ++ double full_compound_offset, ++ double taper_dist, int entry_taper, int exit_taper, double pitch, ++ double full_threadheight) { ++ tapered_pass_geometry g = {}; + const double drive_dx = end_x - start_x; + const double drive_dz = end_z - start_z; + const double drive_length = hypot(drive_dx, drive_dz); + const double drive_x = drive_dx / drive_length; + const double drive_z = drive_dz / drive_length; + const double depth_direction = boring ? 1.0 : -1.0; -+ const double drive_pitch = pitch * drive_length / fabs(drive_dz); ++ g.drive_pitch = pitch * drive_length / fabs(drive_dz); + + const double pass_start_x = start_x + drive_x * compound_offset; -+ const double pass_start_z = start_z + drive_z * compound_offset; ++ g.pass_start_z = start_z + drive_z * compound_offset; + const double pass_end_x = end_x + drive_x * -+ (compound_offset - full_compound_offset); -+ const double pass_end_z = end_z + drive_z * -+ (compound_offset - full_compound_offset); -+ const double cut_start_x = pass_start_x + depth_direction * depth; -+ const double cut_end_x = pass_end_x + depth_direction * depth; ++ (end_compound_offset - full_compound_offset); ++ g.pass_end_z = end_z + drive_z * ++ (end_compound_offset - full_compound_offset); ++ g.cut_start_x = pass_start_x + depth_direction * depth; ++ g.cut_end_x = pass_end_x + depth_direction * depth; ++ g.back_x = g.cut_start_x - depth_direction * end_depth; ++ g.out_x = g.cut_end_x - depth_direction * end_depth; ++ ++ g.entry = taper_dist && entry_taper; ++ if(g.entry) { ++ g.entry_end_x = g.cut_start_x + drive_x * taper_dist; ++ g.entry_end_z = g.pass_start_z + drive_z * taper_dist; ++ g.crest_start_x = g.cut_start_x - depth_direction * full_threadheight; ++ g.entry_pitch = pitch * ++ hypot(g.entry_end_x - g.crest_start_x, ++ g.entry_end_z - g.pass_start_z) / ++ fabs(g.entry_end_z - g.pass_start_z); ++ } + -+ STRAIGHT_TRAVERSE(block->line_number, -+ cut_start_x - depth_direction * end_depth, -+ start_y, pass_start_z, AABBCC); // back ++ g.exit = taper_dist && exit_taper; ++ if(g.exit) { ++ g.exit_start_x = g.cut_end_x - drive_x * taper_dist; ++ g.exit_start_z = g.pass_end_z - drive_z * taper_dist; ++ g.crest_end_x = g.cut_end_x - depth_direction * full_threadheight; ++ g.exit_pitch = pitch * ++ hypot(g.crest_end_x - g.exit_start_x, ++ g.pass_end_z - g.exit_start_z) / ++ fabs(g.pass_end_z - g.exit_start_z); ++ } ++ return g; ++} + -+ if(taper_dist && entry_taper) { -+ const double entry_end_x = cut_start_x + drive_x * taper_dist; -+ const double entry_end_z = pass_start_z + drive_z * taper_dist; -+ const double crest_start_x = -+ cut_start_x - depth_direction * full_threadheight; -+ const double entry_pitch = pitch * -+ hypot(entry_end_x - crest_start_x, -+ entry_end_z - pass_start_z) / -+ fabs(entry_end_z - pass_start_z); ++// Make one threading pass along a tapered XZ drive line. ++static void ++tapered_threading_pass(setup_pointer settings, block_pointer block, ++ const tapered_pass_geometry &g, double start_y) { ++ STRAIGHT_TRAVERSE(block->line_number, g.back_x, ++ start_y, g.pass_start_z, AABBCC); // back + ++ if(g.entry) { + DISABLE_FEED_OVERRIDE(); -+ START_SPEED_FEED_SYNCH(settings->active_spindle, entry_pitch, 0); -+ STRAIGHT_FEED(block->line_number, crest_start_x, -+ start_y, pass_start_z, AABBCC); // in -+ STRAIGHT_FEED(block->line_number, entry_end_x, -+ start_y, entry_end_z, AABBCC); // angled in -+ START_SPEED_FEED_SYNCH(settings->active_spindle, drive_pitch, 0); ++ START_SPEED_FEED_SYNCH(settings->active_spindle, g.entry_pitch, 0); ++ STRAIGHT_FEED(block->line_number, g.crest_start_x, ++ start_y, g.pass_start_z, AABBCC); // in ++ STRAIGHT_FEED(block->line_number, g.entry_end_x, ++ start_y, g.entry_end_z, AABBCC); // angled in ++ START_SPEED_FEED_SYNCH(settings->active_spindle, g.drive_pitch, 0); + } else { -+ STRAIGHT_TRAVERSE(block->line_number, cut_start_x, -+ start_y, pass_start_z, AABBCC); // in ++ STRAIGHT_TRAVERSE(block->line_number, g.cut_start_x, ++ start_y, g.pass_start_z, AABBCC); // in + DISABLE_FEED_OVERRIDE(); -+ START_SPEED_FEED_SYNCH(settings->active_spindle, drive_pitch, 0); ++ START_SPEED_FEED_SYNCH(settings->active_spindle, g.drive_pitch, 0); + } + -+ if(taper_dist && exit_taper) { -+ const double exit_start_x = cut_end_x - drive_x * taper_dist; -+ const double exit_start_z = pass_end_z - drive_z * taper_dist; -+ const double crest_end_x = -+ cut_end_x - depth_direction * full_threadheight; -+ const double exit_pitch = pitch * -+ hypot(crest_end_x - exit_start_x, -+ pass_end_z - exit_start_z) / -+ fabs(pass_end_z - exit_start_z); -+ -+ STRAIGHT_FEED(block->line_number, exit_start_x, -+ start_y, exit_start_z, AABBCC); // over -+ START_SPEED_FEED_SYNCH(settings->active_spindle, exit_pitch, 0); -+ STRAIGHT_FEED(block->line_number, crest_end_x, -+ start_y, pass_end_z, AABBCC); // angled out ++ if(g.exit) { ++ STRAIGHT_FEED(block->line_number, g.exit_start_x, ++ start_y, g.exit_start_z, AABBCC); // over ++ START_SPEED_FEED_SYNCH(settings->active_spindle, g.exit_pitch, 0); ++ STRAIGHT_FEED(block->line_number, g.crest_end_x, ++ start_y, g.pass_end_z, AABBCC); // angled out + } else { -+ STRAIGHT_FEED(block->line_number, cut_end_x, -+ start_y, pass_end_z, AABBCC); // over ++ STRAIGHT_FEED(block->line_number, g.cut_end_x, ++ start_y, g.pass_end_z, AABBCC); // over + } + STOP_SPEED_FEED_SYNCH(); -+ STRAIGHT_TRAVERSE(block->line_number, -+ cut_end_x - depth_direction * end_depth, -+ start_y, pass_end_z, AABBCC); // out ++ STRAIGHT_TRAVERSE(block->line_number, g.out_x, ++ start_y, g.pass_end_z, AABBCC); // out + ENABLE_FEED_OVERRIDE(); +} ++ ++int Interp::check_tapered_threading_pass(setup_pointer settings, ++ const tapered_pass_geometry &g) { ++ // Every move the pass makes while synchronized, at the lead it is ++ // commanded with. The Z advance per revolution of each is the programmed ++ // pitch, but X moves too, and a tapered entry first feeds in along X alone ++ // at the entry lead. In G96 the spindle speed is bounded by each move's ++ // own smallest radius. ++ struct sync_move { ++ const char *what; ++ double lead, x0, z0, x1, z1; ++ } moves[4]; ++ int count = 0; ++ double drive_x0 = g.cut_start_x, drive_z0 = g.pass_start_z; ++ double drive_x1 = g.cut_end_x, drive_z1 = g.pass_end_z; ++ ++ if(g.entry) { ++ moves[count++] = {"G76 entry taper", g.entry_pitch, ++ g.back_x, g.pass_start_z, g.crest_start_x, g.pass_start_z}; ++ moves[count++] = {"G76 entry taper", g.entry_pitch, ++ g.crest_start_x, g.pass_start_z, g.entry_end_x, g.entry_end_z}; ++ drive_x0 = g.entry_end_x; ++ drive_z0 = g.entry_end_z; ++ } ++ if(g.exit) { ++ drive_x1 = g.exit_start_x; ++ drive_z1 = g.exit_start_z; ++ } ++ moves[count++] = {"G76 tapered thread", g.drive_pitch, ++ drive_x0, drive_z0, drive_x1, drive_z1}; ++ if(g.exit) ++ moves[count++] = {"G76 exit taper", g.exit_pitch, ++ g.exit_start_x, g.exit_start_z, g.crest_end_x, g.pass_end_z}; ++ ++ for(int i = 0; i < count; i++) { ++ const sync_move &m = moves[i]; ++ double delta[9] = {m.x1 - m.x0, 0.0, m.z1 - m.z0, 0, 0, 0, 0, 0, 0}; ++ CHP(check_spindle_sync_feed(settings, m.lead, m.what, delta, ++ min_abs_over_range(m.x0, m.x1))); ++ } ++ return INTERP_OK; ++} + int Interp::convert_threading_cycle(block_pointer block, setup_pointer settings, double end_x, double end_y, double end_z) { -@@ -5666,6 +5748,8 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -5995,6 +6143,8 @@ int Interp::convert_threading_cycle(block_pointer block, CHKS((settings->cutter_comp_side != CUTTER_COMP::OFF), (_("Cannot use G76 threading cycle with cutter radius compensation on"))); @@ -234,13 +342,12 @@ index 99f9e6fdb8..373916cfb0 100644 CHKS((block->i_number == 0), (_("In G76, I must not be 0"))); -@@ -5705,7 +5789,18 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6034,7 +6184,17 @@ int Interp::convert_threading_cycle(block_pointer block, double compound_angle = block->q_number; if(compound_angle == -1) compound_angle = 0; compound_angle *= M_PIl/180.0; - if(end_z > start_z) compound_angle = -compound_angle; -+ const bool alternating_infeed = -+ block->d_flag && block->d_number_float == 1.0; ++ const bool alternating_infeed = block->g76_alternating_infeed; + + const bool tapered_drive_line = block->x_flag; + CHKS((tapered_drive_line && end_z == start_z), @@ -254,7 +361,7 @@ index 99f9e6fdb8..373916cfb0 100644 int spring_cuts = block->h_flag ? block->h_number: 0; -@@ -5717,7 +5812,8 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6046,7 +6206,8 @@ int Interp::convert_threading_cycle(block_pointer block, double taper_pitch = taper_dist > 0.0? pitch * hypot(taper_dist, full_threadheight)/taper_dist: pitch; @@ -264,7 +371,7 @@ index 99f9e6fdb8..373916cfb0 100644 int taper_flags = block->l_number; if(taper_flags < 0) taper_flags = 0; -@@ -5728,25 +5824,49 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6057,44 +6218,86 @@ int Interp::convert_threading_cycle(block_pointer block, double depth, zoff; int pass = 1; @@ -272,6 +379,40 @@ index 99f9e6fdb8..373916cfb0 100644 + const double full_compound_offset = full_threadheight * compound_tangent; double target_z = end_z + fabs(k_number) * tan(compound_angle); +- // A taper also moves X by the thread height over the taper distance, at +- // the correspondingly larger pitch. +- double plain_pass[9] = {0.0, 0.0, target_z - start_z, 0, 0, 0, 0, 0, 0}; +- /* the passes run between the first and last cut depth, so the tightest +- radius is the last cut outside, the first cut boring */ +- double thread_min_x = boring +- ? min_abs_over_range(safe_x + start_depth, safe_x + end_depth) +- : min_abs_over_range(safe_x - end_depth, safe_x - start_depth); +- CHP(check_spindle_sync_feed(settings, pitch, "G76", plain_pass, +- thread_min_x)); +- if (taper_dist != 0.0 && (entry_taper || exit_taper)) { +- double taper_pass[9] = {full_threadheight, 0.0, taper_dist, +- 0, 0, 0, 0, 0, 0}; +- CHP(check_spindle_sync_feed(settings, taper_pitch, "G76", taper_pass, +- thread_min_x)); +- } +- +- lock_speed_override(settings); ++ // The depth and compound offset of every pass, roughing passes first, ++ // then the full-depth pass and the spring passes. ++ // end_zoff is the offset applied to the end of the pass. It equals zoff ++ // except on a mirrored pass, whose offset lies beyond the final one: ++ // shifting its end as far would cut past the programmed Z, so the end ++ // stops where the final pass ends. The start keeps the full offset, ++ // because that is what moves the cut onto the other flank. ++ struct threading_pass_plan { ++ double depth, zoff, end_zoff; ++ }; ++ const auto end_offset = [&](double offset) { ++ return fabs(offset) > fabs(full_compound_offset) ? ++ full_compound_offset : offset; ++ }; ++ std::vector passes; + depth = start_depth; - zoff = (depth - full_dia_depth) * tan(compound_angle); + zoff = (depth - full_dia_depth) * compound_tangent; @@ -284,18 +425,7 @@ index 99f9e6fdb8..373916cfb0 100644 + // passes always use the same centered final path. + if(alternating_infeed && !(pass & 1)) + zoff = 2.0 * full_compound_offset - zoff; -+ if(tapered_drive_line) { -+ tapered_threading_pass(settings, block, boring, start_x, start_z, -+ end_x, end_z, depth, end_depth, start_y, zoff, -+ full_compound_offset, -+ taper_dist, entry_taper, exit_taper, pitch, -+ full_threadheight); -+ } else { -+ threading_pass(settings, block, boring, safe_x, depth, end_depth, -+ start_y, start_z, zoff, taper_dist, entry_taper, -+ exit_taper, taper_pitch, pitch, full_threadheight, -+ target_z); -+ } ++ passes.push_back({depth, zoff, end_offset(zoff)}); depth = full_dia_depth + cut_increment * pow(++pass, 1.0/degression); - zoff = (depth - full_dia_depth) * tan(compound_angle); + zoff = (depth - full_dia_depth) * compound_tangent; @@ -303,553 +433,126 @@ index 99f9e6fdb8..373916cfb0 100644 // full specified depth now depth = end_depth; - zoff = (depth - full_dia_depth) * tan(compound_angle); -+ zoff = full_compound_offset; ++ zoff = (tapered_drive_line || alternating_infeed) ? full_compound_offset : ++ (depth - full_dia_depth) * compound_tangent; // cut at least once -- more if spring cuts. - for(int i = 0; i tapered_passes; ++ if(tapered_drive_line) { ++ for(const threading_pass_plan &p : passes) { ++ tapered_passes.push_back( ++ tapered_pass(boring, start_x, start_z, end_x, end_z, p.depth, ++ end_depth, p.zoff, p.end_zoff, full_compound_offset, ++ taper_dist, entry_taper, exit_taper, pitch, ++ full_threadheight)); ++ CHP(check_tapered_threading_pass(settings, tapered_passes.back())); ++ } ++ } else { ++ // A taper also moves X by the thread height over the taper distance, at ++ // the correspondingly larger pitch. ++ double plain_pass[9] = {0.0, 0.0, target_z - start_z, 0, 0, 0, 0, 0, 0}; ++ /* the passes run between the first and last cut depth, so the tightest ++ radius is the last cut outside, the first cut boring */ ++ double thread_min_x = boring ++ ? min_abs_over_range(safe_x + start_depth, safe_x + end_depth) ++ : min_abs_over_range(safe_x - end_depth, safe_x - start_depth); ++ CHP(check_spindle_sync_feed(settings, pitch, "G76", plain_pass, ++ thread_min_x)); ++ if (taper_dist != 0.0 && (entry_taper || exit_taper)) { ++ double taper_pass[9] = {full_threadheight, 0.0, taper_dist, ++ 0, 0, 0, 0, 0, 0}; ++ CHP(check_spindle_sync_feed(settings, taper_pitch, "G76", taper_pass, ++ thread_min_x)); ++ } ++ } ++ ++ lock_speed_override(settings); ++ ++ for(size_t i = 0; i < passes.size(); i++) { + if(tapered_drive_line) { -+ tapered_threading_pass(settings, block, boring, start_x, start_z, -+ end_x, end_z, depth, end_depth, start_y, zoff, -+ zoff, taper_dist, entry_taper, exit_taper, pitch, -+ full_threadheight); ++ tapered_threading_pass(settings, block, tapered_passes[i], start_y); + } else { -+ threading_pass(settings, block, boring, safe_x, depth, end_depth, -+ start_y, start_z, zoff, taper_dist, entry_taper, -+ exit_taper, taper_pitch, pitch, full_threadheight, -+ target_z); ++ threading_pass(settings, block, boring, safe_x, passes[i].depth, ++ end_depth, start_y, start_z, passes[i].zoff, ++ passes[i].end_zoff, taper_dist, entry_taper, exit_taper, taper_pitch, ++ pitch, full_threadheight, target_z); + } } + restore_speed_override(settings); STRAIGHT_TRAVERSE(block->line_number, end_x, end_y, end_z, AABBCC); - settings->current_x = end_x; -diff --git a/tests/interp/g76-tapered/README b/tests/interp/g76-tapered/README -new file mode 100644 -index 0000000000..645af3ae97 ---- /dev/null -+++ b/tests/interp/g76-tapered/README -@@ -0,0 +1,8 @@ -+Verify that optional G76 X endpoints produce tapered XZ drive lines while -+preserving axial P pitch. The canonical trace covers absolute and incremental -+endpoints, radius and diameter mode, internal and external threads, both drive -+line slopes, entry/exit taper in both Z directions, compound infeed, and spring -+passes. Compound-infeed coverage verifies fixed-direction D0 and -+alternating-flank D1 on tapered and cylindrical drive lines, plus centered Q0 -+paths. Negative tests verify that G76 rejects a Y endpoint, invalid D modes, -+and an ambiguous same-block G96 D word. -diff --git a/tests/interp/g76-tapered/expected b/tests/interp/g76-tapered/expected -new file mode 100644 -index 0000000000..ec0ccc9fb4 ---- /dev/null -+++ b/tests/interp/g76-tapered/expected -@@ -0,0 +1,377 @@ -+ N..... USE_LENGTH_UNITS(CANON_UNITS_MM) -+ N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_XY_ROTATION(0.0000) -+ N..... SET_FEED_REFERENCE(CANON_XYZ) -+ N..... ON_RESET() -+ N..... COMMENT("Test tapered G76 drive lines") -+ N..... SELECT_PLANE(CANON_PLANE_XZ) -+ N..... USE_LENGTH_UNITS(CANON_UNITS_INCHES) -+ N..... SET_SPINDLE_SPEED(0, 100.0000) -+ N..... START_SPINDLE_CLOCKWISE(0) -+ N..... COMMENT("basic external, decreasing X") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("basic external, increasing X") -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.6100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.6000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("incremental endpoint") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("interpreter: distance mode changed to incremental") -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("interpreter: distance mode changed to absolute") -+ N..... COMMENT("diameter mode endpoint and depths") -+ N..... COMMENT("interpreter: Lathe diameter mode changed to diameter") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("radius mode endpoint and depths") -+ N..... COMMENT("interpreter: Lathe diameter mode changed to radius") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("internal thread") -+ N..... STRAIGHT_TRAVERSE(0.5000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.4900, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.6900, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.8900, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.6900, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.5000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.7000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.9000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.7000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.7000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("entry and exit taper") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.157731,0) -+ N..... STRAIGHT_FEED(0.9100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_FEED(0.7904, 0.0000, -0.0981, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6296, 0.0000, -0.9019, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.129309,0) -+ N..... STRAIGHT_FEED(0.7100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.157731,0) -+ N..... STRAIGHT_FEED(0.9000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_FEED(0.7804, 0.0000, -0.0981, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6196, 0.0000, -0.9019, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.129309,0) -+ N..... STRAIGHT_FEED(0.7000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("positive Z entry and exit taper") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.157731,0) -+ N..... STRAIGHT_FEED(0.9100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_FEED(0.7904, 0.0000, 0.0981, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6296, 0.0000, 0.9019, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.129309,0) -+ N..... STRAIGHT_FEED(0.7100, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.157731,0) -+ N..... STRAIGHT_FEED(0.9000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_FEED(0.7804, 0.0000, 0.0981, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6196, 0.0000, 0.9019, 0.0000, 0.0000, 0.0000) -+ N..... START_SPEED_FEED_SYNC(0.129309,0) -+ N..... STRAIGHT_FEED(0.7000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("fixed-direction compound infeed") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.9998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.7998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("alternating-flank compound infeed") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0666, 0.0000, -0.0170, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8666, 0.0000, -0.0170, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6779, 0.0000, -0.9604, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8779, 0.0000, -0.9604, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0241, 0.0000, -0.0793, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8241, 0.0000, -0.0793, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6355, 0.0000, -1.0226, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8355, 0.0000, -1.0226, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.9998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.7998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("alternating mode with centered Q0 infeed") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8700, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8700, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8400, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("cylindrical alternating-flank compound infeed") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, -0.0173, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8700, 0.0000, -0.0173, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8700, 0.0000, -0.9596, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, -0.9596, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, -0.0808, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8400, 0.0000, -0.0808, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8400, 0.0000, -1.0231, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, -1.0231, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -0.0520, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -0.0520, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8100, 0.0000, -0.9942, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -0.9942, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.100000,0) -+ N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... COMMENT("spring passes") -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... DISABLE_FEED_OVERRIDE() -+ N..... START_SPEED_FEED_SYNC(0.101980,0) -+ N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPEED_FEED_SYNCH() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... ENABLE_FEED_OVERRIDE() -+ N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) -+ N..... STOP_SPINDLE_TURNING(0) -+ N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_XY_ROTATION(0.0000) -+ N..... SELECT_PLANE(CANON_PLANE_XY) -+ N..... SET_FEED_MODE(0, 0) -+ N..... SET_FEED_RATE(0.0000) -+ N..... STOP_SPINDLE_TURNING(0) -+ N..... SET_SPINDLE_MODE(0 0.0000) -+ N..... PROGRAM_END() -+ N..... ON_RESET() -+ N..... ON_RESET() -diff --git a/tests/interp/g76-tapered/invalid-d-fraction.ngc b/tests/interp/g76-tapered/invalid-d-fraction.ngc -new file mode 100644 -index 0000000000..6eb002dc8a ---- /dev/null -+++ b/tests/interp/g76-tapered/invalid-d-fraction.ngc -@@ -0,0 +1,5 @@ -+g20 g18 g8 -+s100 m3 -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 d.5 -+m2 -diff --git a/tests/interp/g76-tapered/invalid-d2.ngc b/tests/interp/g76-tapered/invalid-d2.ngc -new file mode 100644 -index 0000000000..87e80949f9 ---- /dev/null -+++ b/tests/interp/g76-tapered/invalid-d2.ngc -@@ -0,0 +1,5 @@ -+g20 g18 g8 -+s100 m3 -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 d2 -+m2 -diff --git a/tests/interp/g76-tapered/invalid-g96-d.ngc b/tests/interp/g76-tapered/invalid-g96-d.ngc -new file mode 100644 -index 0000000000..66e30e804a ---- /dev/null -+++ b/tests/interp/g76-tapered/invalid-g96-d.ngc -@@ -0,0 +1,5 @@ -+g20 g18 g8 -+s100 m3 -+g0 x1 z0 -+g96 s100 d1 g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 -+m2 -diff --git a/tests/interp/g76-tapered/invalid-y.ngc b/tests/interp/g76-tapered/invalid-y.ngc -new file mode 100644 -index 0000000000..f79aa85850 ---- /dev/null -+++ b/tests/interp/g76-tapered/invalid-y.ngc -@@ -0,0 +1,5 @@ -+g20 g18 g8 -+s100 m3 -+g0 x1 y0 z0 -+g76 p.1 x.8 y.1 z-1 i-.1 j.09 k.1 h0 q0 -+m2 -diff --git a/tests/interp/g76-tapered/test.ngc b/tests/interp/g76-tapered/test.ngc -new file mode 100644 -index 0000000000..fc3f9a5545 ---- /dev/null -+++ b/tests/interp/g76-tapered/test.ngc -@@ -0,0 +1,63 @@ -+(Test tapered G76 drive lines) -+ -+g20 g18 g8 -+s100 m3 -+ -+(basic external, decreasing X) -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q0 -+ -+(basic external, increasing X) -+g0 x.8 z0 -+g76 p.1 x1 z-1 i-.1 j.09 k.1 h0 q0 -+ -+(incremental endpoint) -+g0 x1 z0 -+g91 -+g76 p.1 x-.2 z-1 i-.1 j.09 k.1 h0 q0 -+g90 -+ -+(diameter mode endpoint and depths) -+g7 -+g0 x2 z0 -+g76 p.1 x1.6 z-1 i-.2 j.18 k.2 h0 q0 -+ -+(radius mode endpoint and depths) -+g8 -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q0 -+ -+(internal thread) -+g0 x.5 z0 -+g76 p.1 x.7 z-1 i.1 j.09 k.1 h0 q0 -+ -+(entry and exit taper) -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q0 e.1 l3 -+ -+(positive Z entry and exit taper) -+g0 x1 z0 -+g76 p.1 x.8 z1 i-.1 j.09 k.1 h0 q0 e.1 l3 -+ -+(fixed-direction compound infeed) -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 d0 -+ -+(alternating-flank compound infeed) -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.03 k.1 r1 h2 q30 d1 -+ -+(alternating mode with centered Q0 infeed) -+g0 x1 z0 -+g76 p.1 z-1 i-.1 j.03 k.1 r1 h0 q0 d1 -+ -+(cylindrical alternating-flank compound infeed) -+g0 x1 z0 -+g76 p.1 z-1 i-.1 j.03 k.1 r1 h1 q30 d1 -+ -+(spring passes) -+g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h2 q0 -+ -+m5 -+m2 -diff --git a/tests/interp/g76-tapered/test.sh b/tests/interp/g76-tapered/test.sh -new file mode 100644 -index 0000000000..949e9fdf47 ---- /dev/null -+++ b/tests/interp/g76-tapered/test.sh -@@ -0,0 +1,14 @@ -+#!/bin/bash -+ -+rs274 -g test.ngc | awk '{$1=""; print}' -+result=${PIPESTATUS[0]} -+if (( result != 0 )); then -+ exit "$result" -+fi +diff --git a/src/emc/rs274ngc/interp_internal.cc b/src/emc/rs274ngc/interp_internal.cc +index 4ec4f7a..e08e4a6 100644 +--- a/src/emc/rs274ngc/interp_internal.cc ++++ b/src/emc/rs274ngc/interp_internal.cc +@@ -274,6 +274,7 @@ int Interp::init_block(block_pointer block) //!< pointer to a block to be i + block->dollar_flag = false; + block->e_flag = false; + block->f_flag = false; ++ block->g76_alternating_infeed = false; + for (n = 0; n < GM_MAX_MODAL_GROUPS; n++) { + block->g_modes[n] = -1; + } +diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh +index 6f90dbe..210b4db 100644 +--- a/src/emc/rs274ngc/interp_internal.hh ++++ b/src/emc/rs274ngc/interp_internal.hh +@@ -287,6 +287,7 @@ enum GCodes + G_73 = 730, + G_74 = 740, + G_76 = 760, ++ G_76_1 = 761, + G_80 = 800, + G_81 = 810, + G_82 = 820, +@@ -488,6 +489,7 @@ struct block_struct + bool b_flag{}; + bool c_flag{}; + bool d_flag{}; ++ bool g76_alternating_infeed{}; // the block programs G76.1 + bool e_flag{}; + bool f_flag{}; + bool h_flag{}; +diff --git a/src/emc/rs274ngc/interp_read.cc b/src/emc/rs274ngc/interp_read.cc +index 6e58d16..b397cc0 100644 +--- a/src/emc/rs274ngc/interp_read.cc ++++ b/src/emc/rs274ngc/interp_read.cc +@@ -593,6 +593,11 @@ int Interp::read_g(char *line, //!< string: line of RS274/NGC code being proce + block->g_modes[mode] = value; + return INTERP_OK; + } ++ // G76.1 is G76 with alternating infeed ++ if (value == G_76_1) { ++ block->g76_alternating_infeed = true; ++ value = G_76; ++ } + mode = gees[value]; + CHKS((mode == -1), NCE_UNKNOWN_G_CODE_USED); + if ((value == G_80) && (block->g_modes[mode] != -1)); +diff --git a/src/emc/rs274ngc/rs274ngc_interp.hh b/src/emc/rs274ngc/rs274ngc_interp.hh +index e834041..2fb074a 100644 +--- a/src/emc/rs274ngc/rs274ngc_interp.hh ++++ b/src/emc/rs274ngc/rs274ngc_interp.hh +@@ -21,6 +21,8 @@ + #include "interp_internal.hh" + #include "nml_intf/interp_return.hh" + ++struct tapered_pass_geometry; + -+for invalid_program in invalid-*.ngc; do -+ if rs274 -g "$invalid_program" >/dev/null 2>&1; then -+ echo "$invalid_program unexpectedly succeeded" >&2 -+ exit 1 -+ fi -+done + class Interp : public InterpBase { + + public: +@@ -363,6 +365,8 @@ public: + double u_end, double v_end, double w_end); + int convert_threading_cycle(block_pointer block, setup_pointer settings, + double end_x, double end_y, double end_z); ++ int check_tapered_threading_pass(setup_pointer settings, ++ const tapered_pass_geometry &pass); + int convert_tool_change(setup_pointer settings); + int convert_tool_length_offset(int g_code, block_pointer block, + setup_pointer settings); diff --git a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch index c948eb73..ba56823e 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -8,56 +8,48 @@ Give each generated G76 pass an internal identity spanning its safe approach, sy Split Single Step into two internal units per pass: return to the pass start while remaining at safe clearance, followed by the infeed, synchronized thread, and clearance retract together. Teach motion-level Step to preserve those same boundaries when later passes were already queued by AUTO_RUN, while ordinary unmarked motion retains source-line stepping. Preserve pass ownership on synthetic blend arcs, make marked clearance endpoints non-blendable, reset pass-step state on abort and mode changes, and extend resumable-stop coverage to cylindrical and tapered Stop-to-Step handoffs, exit tapers, arc blending, deterministic cut/retract timing, and two-step safe-approach/thread-clearance sequencing. + +Ported onto v2.10.0-pre2 and the ported resumable Stop, which tracks a +finishing position-synchronized run with stop_sync_run and decides every +hold with tpStopHolds(). stop_tc returns only as the G76 clearance target: +tpStopHolds() holds nothing while that target is pending, an ordinary G33 +or rigid tap keeps the stop_sync_run boundary, and a not-yet-active chained +G76 cut that continues the current synchronization also latches its pass. +Upstream now holds the spindle override for the whole G76 cycle; the lock +is issued inside the first pass so that the first Single Step unit is still +the safe approach. The in-flight Single Step scenarios move to the patch +that adds in-flight stepping. --- - docs/src/gcode/g-code.adoc | 15 + - src/emc/motion/command.c | 31 +- - src/emc/motion/control.c | 25 +- - src/emc/motion/motion.h | 2 + - src/emc/nml_intf/canon.hh | 8 + - src/emc/nml_intf/emc.cc | 12 + - src/emc/nml_intf/emc.hh | 5 +- - src/emc/nml_intf/emc_nml.hh | 19 +- - src/emc/nml_intf/interpl.cc | 17 +- - src/emc/nml_intf/interpl.hh | 5 + - src/emc/rs274ngc/gcodemodule.cc | 5 + - src/emc/rs274ngc/interp_convert.cc | 12 + - src/emc/sai/saicanon.cc | 6 + - src/emc/task/emccanon.cc | 63 ++- - src/emc/task/emctask.cc | 4 +- - src/emc/task/emctaskmain.cc | 74 +++- - src/emc/task/task.hh | 2 +- - src/emc/task/taskintf.cc | 8 +- - src/emc/tp/tc_types.h | 2 + - src/emc/tp/tp.c | 189 +++++++- - src/emc/tp/tp.h | 3 +- - src/emc/tp/tp_types.h | 10 +- - tests/interp/compile/use-rs274.cc | 5 + - tests/resumable-stop/README | 22 +- - tests/resumable-stop/checkresult | 3 +- - .../resumable-stop/g33-followed-by-rapid.ngc | 7 + - tests/resumable-stop/g76-exit-taper.ngc | 7 + - tests/resumable-stop/g76-handoff.ngc | 7 + - tests/resumable-stop/g76-step.ngc | 4 + - .../resumable-stop/g76-tapered-exit-taper.ngc | 7 + - tests/resumable-stop/g76-tapered-step.ngc | 4 + - tests/resumable-stop/g76-tapered.ngc | 7 + - tests/resumable-stop/test-ui.py | 410 +++++++++++++++++- - tests/resumable-stop/test.ini | 1 + - tests/resumable-stop/test.sh | 15 + - 35 files changed, 957 insertions(+), 59 deletions(-) - create mode 100644 tests/resumable-stop/g33-followed-by-rapid.ngc - create mode 100644 tests/resumable-stop/g76-exit-taper.ngc - create mode 100644 tests/resumable-stop/g76-handoff.ngc - create mode 100644 tests/resumable-stop/g76-step.ngc - create mode 100644 tests/resumable-stop/g76-tapered-exit-taper.ngc - create mode 100644 tests/resumable-stop/g76-tapered-step.ngc - create mode 100644 tests/resumable-stop/g76-tapered.ngc + docs/src/gcode/g-code.adoc | 15 +++ + src/emc/motion/command.c | 34 ++++- + src/emc/motion/control.c | 25 +++- + src/emc/motion/motion.h | 2 + + src/emc/nml_intf/canon.hh | 8 ++ + src/emc/nml_intf/emc.cc | 12 ++ + src/emc/nml_intf/emc.hh | 4 +- + src/emc/nml_intf/emc_nml.hh | 19 ++- + src/emc/nml_intf/interpl.cc | 17 ++- + src/emc/nml_intf/interpl.hh | 5 + + src/emc/rs274ngc/gcodemodule.cc | 5 + + src/emc/rs274ngc/interp_convert.cc | 18 ++- + src/emc/sai/saicanon.cc | 6 + + src/emc/task/emccanon.cc | 63 ++++++++- + src/emc/task/emctask.cc | 4 +- + src/emc/task/emctaskmain.cc | 74 ++++++++--- + src/emc/task/task.hh | 2 +- + src/emc/task/taskintf.cc | 5 +- + src/emc/tp/tc_types.h | 2 + + src/emc/tp/tp.c | 204 +++++++++++++++++++++++++++-- + src/emc/tp/tp.h | 3 +- + src/emc/tp/tp_types.h | 16 ++- + tests/interp/compile/use-rs274.cc | 5 + + 23 files changed, 497 insertions(+), 51 deletions(-) diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index 4160cfb4a2..760cfe2384 100644 +index 6f196b6..3b3d18c 100644 --- a/docs/src/gcode/g-code.adoc +++ b/docs/src/gcode/g-code.adoc -@@ -1986,6 +1986,21 @@ pass, so a relief groove will be required at the entry unless the +@@ -2309,6 +2309,21 @@ pass, so a relief groove will be required at the entry unless the beginning of the thread is past the end of the material or an entry taper is used. @@ -80,19 +72,20 @@ index 4160cfb4a2..760cfe2384 100644 spindle speed and will be a <>. With a slow spindle, the exit move might take only a small fraction of a revolution. If the diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index efe02af73d..b6ad9c1504 100644 +index 35cf0db..a8e8ae3 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -509,6 +509,8 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) - } else if (GET_MOTION_COORD_FLAG()) { - emcmotInternal->coord_tp.stopping = 0; - emcmotInternal->coord_tp.stop_tc = 0; -+ emcmotInternal->coord_tp.stop_target_pending = 0; -+ emcmotInternal->coord_tp.stop_pass_id = 0; - emcmotStatus->stopped = 0; - tpAbort(&emcmotInternal->coord_tp); - } else { -@@ -1052,7 +1054,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -545,6 +545,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + } + emcmotInternal->coord_tp.stopping = 0; + emcmotInternal->coord_tp.stop_sync_run = 0; ++ emcmotInternal->coord_tp.stop_tc = 0; ++ emcmotInternal->coord_tp.stop_target_pending = 0; ++ emcmotInternal->coord_tp.stop_pass_id = 0; + emcmotStatus->stopped = 0; + /* check for coord or free space motion active */ + if (GET_MOTION_TELEOP_FLAG()) { +@@ -1113,7 +1116,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) emcmotStatus->enables_new, issue_atspeed, emcmotCommand->turn, @@ -103,22 +96,24 @@ index efe02af73d..b6ad9c1504 100644 //KLUDGE ignore zero length line if (res_addline < 0) { reportError(_("can't add linear move at line %d, error code %d"), -@@ -1226,8 +1230,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1335,8 +1340,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) case EMCMOT_STOP: rtapi_print_msg(RTAPI_MSG_DBG, "STOP"); + emcmotStatus->stepping = 0; emcmotInternal->coord_tp.stopping = 1; - emcmotInternal->coord_tp.stop_tc = 0; + emcmotInternal->coord_tp.stop_sync_run = 0; ++ emcmotInternal->coord_tp.stop_tc = 0; + emcmotInternal->coord_tp.stop_target_pending = 0; + emcmotInternal->coord_tp.stop_pass_id = 0; tpPause(&emcmotInternal->coord_tp); emcmotStatus->paused = 1; emcmotStatus->stopped = 0; -@@ -1254,19 +1261,31 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1363,19 +1372,32 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) emcmotStatus->stepping = 0; emcmotInternal->coord_tp.stopping = 0; - emcmotInternal->coord_tp.stop_tc = 0; + emcmotInternal->coord_tp.stop_sync_run = 0; ++ emcmotInternal->coord_tp.stop_tc = 0; + emcmotInternal->coord_tp.stop_target_pending = 0; + emcmotInternal->coord_tp.stop_pass_id = 0; tpResume(&emcmotInternal->coord_tp); @@ -150,9 +145,9 @@ index efe02af73d..b6ad9c1504 100644 emcmotStatus->paused = 1; } else { reportError(_("MOTION: can't STEP while already executing")); -@@ -1523,7 +1542,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1665,7 +1687,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) emcmotStatus->enables_new, - 0, + issue_atspeed, -1, - emcmotCommand->tag)) { + emcmotCommand->tag, @@ -162,26 +157,26 @@ index efe02af73d..b6ad9c1504 100644 emcmotStatus->commandStatus = EMCMOT_COMMAND_BAD_EXEC; tpAbort(&emcmotInternal->coord_tp); diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 0a5d550480..160c2dcd2c 100644 +index ccd0f34..e347bf1 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1993,12 +1993,11 @@ static void output_to_hal(void) - /* +@@ -2083,10 +2083,13 @@ static void output_to_hal(void) * Alternate trajectory planners only provide the established tpPause() * interface. Treat a completed fallback pause as a completed Stop. The -- * default planner sets stop_tc while an active position-synchronized -- * segment must finish, so do not complete Stop at an intermediate zero -- * velocity in that case. -+ * default planner latches stop_target_pending while a selected segment -+ * must finish, so do not complete Stop at an intermediate zero velocity. + * default planner sets stop_sync_run while a position-synchronized run +- * must finish, so do not complete Stop at an intermediate zero velocity +- * in that case, such as an exact-stop boundary between two G33 moves. ++ * must finish, and latches stop_target_pending while a G76 pass must ++ * reach its marked clearance, so do not complete Stop at an intermediate ++ * zero velocity in either case, such as an exact-stop boundary between ++ * two G33 moves. */ if (emcmotInternal->coord_tp.stopping && -- !emcmotInternal->coord_tp.stop_tc && + !emcmotInternal->coord_tp.stop_target_pending && + !emcmotInternal->coord_tp.stop_sync_run && fabs(emcmotStatus->current_vel) < TP_VEL_EPSILON) { emcmotStatus->stopped = 1; - } -@@ -2224,10 +2223,20 @@ static void update_status(void) +@@ -2314,10 +2317,20 @@ static void update_status(void) /* check to see if we should pause in order to implement single emcmotStatus->stepping */ @@ -207,23 +202,23 @@ index 0a5d550480..160c2dcd2c 100644 // State Tags handling // Get the current executing trajectory component (the "Source of Truth") diff --git a/src/emc/motion/motion.h b/src/emc/motion/motion.h -index 84ab8eb6ce..dfc990f853 100644 +index 1915616..ad391e1 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h -@@ -275,6 +275,8 @@ extern "C" { - double ext_offset_vel; /* velocity for an external axis offset */ - double ext_offset_acc; /* acceleration for an external axis offset */ +@@ -278,6 +278,8 @@ extern "C" { struct state_tag_t tag; + + int switchkins_type; /* switchkins type requested by G12.1 */ + int g76_pass_id; /* internal G76 pass ownership, zero otherwise */ + int g76_pass_clearance;/* 1: clearance retract, 2: approach endpoint */ } emcmot_command_t; /*! \todo FIXME - these packed bits might be replaced with chars diff --git a/src/emc/nml_intf/canon.hh b/src/emc/nml_intf/canon.hh -index 23ef06ec5f..9a41b2647f 100644 +index 68cf5d4..ee99e8e 100644 --- a/src/emc/nml_intf/canon.hh +++ b/src/emc/nml_intf/canon.hh -@@ -1056,6 +1056,14 @@ extern int USER_DEFINED_FUNCTION_ADD(USER_DEFINED_FUNCTION_TYPE func, +@@ -1089,6 +1089,14 @@ extern int USER_DEFINED_FUNCTION_ADD(USER_DEFINED_FUNCTION_TYPE func, * last segment to be output, if it has been held to do segment merging */ extern void FINISH(void); @@ -239,10 +234,10 @@ index 23ef06ec5f..9a41b2647f 100644 // it to the interp list in certain cases extern void ON_RESET(void); diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index 5e69fbb997..da68282b6d 100644 +index 7a02127..891516e 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -214,6 +214,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) +@@ -212,6 +212,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) case EMC_TASK_PLAN_SYNCH_TYPE: ((EMC_TASK_PLAN_SYNCH *) buffer)->update(cms); break; @@ -252,7 +247,7 @@ index 5e69fbb997..da68282b6d 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: ((EMC_TASK_PLAN_SET_OPTIONAL_STOP *) buffer)->update(cms); break; -@@ -472,6 +475,8 @@ const char *emc_symbol_lookup(uint32_t type) +@@ -473,6 +476,8 @@ const char *emc_symbol_lookup(uint32_t type) return "EMC_TASK_PLAN_STEP"; case EMC_TASK_PLAN_SYNCH_TYPE: return "EMC_TASK_PLAN_SYNCH"; @@ -261,7 +256,7 @@ index 5e69fbb997..da68282b6d 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: return "EMC_TASK_PLAN_SET_OPTIONAL_STOP"; case EMC_TASK_PLAN_SET_BLOCK_DELETE_TYPE: -@@ -757,6 +762,11 @@ void EMC_TASK_PLAN_SYNCH::update(CMS * cms) +@@ -761,6 +766,11 @@ void EMC_TASK_PLAN_SYNCH::update(CMS * cms) EMC_TASK_CMD_MSG::update(cms); } @@ -273,8 +268,8 @@ index 5e69fbb997..da68282b6d 100644 /* * NML/CMS Update function for EMC_COOLANT_CMD_MSG * Automatically generated by NML CodeGen Java Applet. -@@ -1090,6 +1100,8 @@ void EMC_TRAJ_LINEAR_MOVE::update(CMS * cms) - cms->update(acc); +@@ -1099,6 +1109,8 @@ void EMC_TRAJ_LINEAR_MOVE::update(CMS * cms) + cms->update(vlimit_scale); cms->update(feed_mode); cms->update(indexer_jnum); + cms->update(g76_pass_id); @@ -283,10 +278,10 @@ index 5e69fbb997..da68282b6d 100644 /* diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index a98ae39f20..d2ab16d3ba 100644 +index fb1faa8..c98adba 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh -@@ -144,6 +144,7 @@ struct PM_CARTESIAN; +@@ -145,6 +145,7 @@ struct PM_CARTESIAN; #define EMC_TASK_PLAN_OPTIONAL_STOP_TYPE ((NMLTYPE) 519) #define EMC_TASK_PLAN_REVERSE_TYPE ((NMLTYPE) 520) #define EMC_TASK_PLAN_FORWARD_TYPE ((NMLTYPE) 521) @@ -294,24 +289,23 @@ index a98ae39f20..d2ab16d3ba 100644 #define EMC_TASK_STAT_TYPE ((NMLTYPE) 599) -@@ -380,7 +381,9 @@ extern int emcTrajStep(); - extern int emcTrajResume(); +@@ -395,7 +396,8 @@ extern int emcTrajResume(); extern int emcTrajDelay(double delay); extern int emcTrajLinearMove(const EmcPose& end, int type, double vel, -- double ini_maxvel, double acc, double ini_maxjerk, int indexer_jnum); -+ double ini_maxvel, double acc, double ini_maxjerk, -+ int indexer_jnum, int g76_pass_id, -+ int g76_pass_clearance); + double ini_maxvel, double acc, double ini_maxjerk, +- double vlimit_scale, int indexer_jnum); ++ double vlimit_scale, int indexer_jnum, ++ int g76_pass_id, int g76_pass_clearance); extern int emcTrajCircularMove(const EmcPose& end, const PM_CARTESIAN& center, const PM_CARTESIAN& - normal, int turn, int type, double vel, double ini_maxvel, double acc, double ini_maxjerk); - extern int emcTrajSetTermCond(int cond, double tolerance); + normal, int turn, int type, double vel, double ini_maxvel, double acc, double ini_maxjerk, + double vlimit_scale); diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index 92e21f800b..e9a2be99fa 100644 +index b41c212..6a5632c 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -746,7 +746,9 @@ class EMC_TRAJ_LINEAR_MOVE:public EMC_TRAJ_CMD_MSG { - acc(0.0), +@@ -752,7 +752,9 @@ class EMC_TRAJ_LINEAR_MOVE:public EMC_TRAJ_CMD_MSG { ini_maxjerk(0.0), + vlimit_scale(1.0), feed_mode(0), - indexer_jnum(0) + indexer_jnum(0), @@ -320,8 +314,8 @@ index 92e21f800b..e9a2be99fa 100644 {}; // For internal NML/CMS use only. -@@ -759,6 +761,8 @@ class EMC_TRAJ_LINEAR_MOVE:public EMC_TRAJ_CMD_MSG { - double vel, ini_maxvel, acc, ini_maxjerk; +@@ -766,6 +768,8 @@ class EMC_TRAJ_LINEAR_MOVE:public EMC_TRAJ_CMD_MSG { + double vlimit_scale; // see emcmot_command_t int feed_mode; int indexer_jnum; + int g76_pass_id; @@ -329,7 +323,7 @@ index 92e21f800b..e9a2be99fa 100644 }; class EMC_TRAJ_CIRCULAR_MOVE:public EMC_TRAJ_CMD_MSG { -@@ -1396,6 +1400,19 @@ class EMC_TASK_PLAN_SYNCH:public EMC_TASK_CMD_MSG { +@@ -1445,6 +1449,19 @@ class EMC_TASK_PLAN_SYNCH:public EMC_TASK_CMD_MSG { void update(CMS * cms); }; @@ -350,7 +344,7 @@ index 92e21f800b..e9a2be99fa 100644 public: EMC_TASK_PLAN_SET_OPTIONAL_STOP() diff --git a/src/emc/nml_intf/interpl.cc b/src/emc/nml_intf/interpl.cc -index 80fd26ffb1..1c58826f25 100644 +index 2385cec..415f873 100644 --- a/src/emc/nml_intf/interpl.cc +++ b/src/emc/nml_intf/interpl.cc @@ -30,6 +30,11 @@ void NML_INTERP_LIST::set_line_number(int line) @@ -400,7 +394,7 @@ index 80fd26ffb1..1c58826f25 100644 } void NML_INTERP_LIST::print() -@@ -118,3 +128,8 @@ int NML_INTERP_LIST::get_line_number() +@@ -128,3 +138,8 @@ int NML_INTERP_LIST::get_line_number() { return line_number; } @@ -410,7 +404,7 @@ index 80fd26ffb1..1c58826f25 100644 + return pass_group; +} diff --git a/src/emc/nml_intf/interpl.hh b/src/emc/nml_intf/interpl.hh -index b5ef1652a6..324db10675 100644 +index e68f0f1..52c338e 100644 --- a/src/emc/nml_intf/interpl.hh +++ b/src/emc/nml_intf/interpl.hh @@ -26,6 +26,7 @@ class NMLmsg; @@ -430,7 +424,7 @@ index b5ef1652a6..324db10675 100644 int append(std::unique_ptr&& command); std::unique_ptr get(); void clear(); -@@ -46,6 +49,8 @@ private: +@@ -49,6 +52,8 @@ private: std::deque linked_list; int next_line_number = 0; // line number used to fill temp_node int line_number = 0; // line number of node from get() @@ -440,10 +434,10 @@ index b5ef1652a6..324db10675 100644 }; diff --git a/src/emc/rs274ngc/gcodemodule.cc b/src/emc/rs274ngc/gcodemodule.cc -index 32aeed560b..d97d0ac765 100644 +index 91d4b7b..109cf46 100644 --- a/src/emc/rs274ngc/gcodemodule.cc +++ b/src/emc/rs274ngc/gcodemodule.cc -@@ -559,6 +559,11 @@ void WAIT_SPINDLE_ORIENT_COMPLETE(int /*s*/, double /*timeout*/) {} +@@ -642,6 +642,11 @@ void WAIT_SPINDLE_ORIENT_COMPLETE(int /*s*/, double /*timeout*/) {} void PROGRAM_STOP() {} void PROGRAM_END() {} void FINISH() {} @@ -454,16 +448,15 @@ index 32aeed560b..d97d0ac765 100644 +void FINISH_G76_PASS(int /*line_number*/) {} void ON_RESET() {} void PALLET_SHUTTLE() {} - void SELECT_TOOL(int tool) {selected_tool = tool;} + void SELECT_TOOL(int tool) {parse_state.selected_tool = tool;} diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 373916cfb0..33a35bda2e 100644 +index 6d051a2..663668a 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -5618,11 +5618,14 @@ threading_pass(setup_pointer settings, block_pointer block, - double start_y, double start_z, double zoff, double taper_dist, +@@ -5948,11 +5948,13 @@ threading_pass(setup_pointer settings, block_pointer block, + double taper_dist, int entry_taper, int exit_taper, double taper_pitch, double pitch, double full_threadheight, double target_z) { -+ START_G76_PASS(); + FINISH_G76_APPROACH(); STRAIGHT_TRAVERSE(block->line_number, boring? safe_x + depth - end_depth: @@ -474,7 +467,7 @@ index 373916cfb0..33a35bda2e 100644 DISABLE_FEED_OVERRIDE(); START_SPEED_FEED_SYNCH(settings->active_spindle, taper_pitch, 0); STRAIGHT_FEED(block->line_number, boring? -@@ -5633,6 +5636,7 @@ threading_pass(setup_pointer settings, block_pointer block, +@@ -5963,6 +5965,7 @@ threading_pass(setup_pointer settings, block_pointer block, start_y, start_z - zoff - taper_dist, AABBCC); START_SPEED_FEED_SYNCH(settings->active_spindle, pitch, 0); } else { @@ -482,70 +475,74 @@ index 373916cfb0..33a35bda2e 100644 STRAIGHT_TRAVERSE(block->line_number, boring? safe_x + depth: safe_x - depth, start_y, start_z - zoff, AABBCC); //in DISABLE_FEED_OVERRIDE(); -@@ -5652,11 +5656,13 @@ threading_pass(setup_pointer settings, block_pointer block, - start_y, target_z - zoff, AABBCC); //over +@@ -5982,11 +5985,13 @@ threading_pass(setup_pointer settings, block_pointer block, + start_y, target_z - end_zoff, AABBCC); //over } STOP_SPEED_FEED_SYNCH(); + START_G76_CLEARANCE(); STRAIGHT_TRAVERSE(block->line_number, boring? safe_x + depth - end_depth: safe_x - depth + end_depth, - start_y, target_z - zoff, AABBCC); //out + start_y, target_z - end_zoff, AABBCC); //out ENABLE_FEED_OVERRIDE(); + FINISH_G76_PASS(block->line_number); } - // Make one threading pass along a tapered XZ drive line. X coordinates are -@@ -5670,6 +5676,7 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, - double full_compound_offset, double taper_dist, - int entry_taper, int exit_taper, double pitch, - double full_threadheight) { -+ START_G76_PASS(); - const double drive_dx = end_x - start_x; - const double drive_dz = end_z - start_z; - const double drive_length = hypot(drive_dx, drive_dz); -@@ -5687,6 +5694,7 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, - const double cut_start_x = pass_start_x + depth_direction * depth; - const double cut_end_x = pass_end_x + depth_direction * depth; - + // Geometry of one threading pass along a tapered XZ drive line. X coordinates +@@ -6060,10 +6065,12 @@ tapered_pass(int boring, double start_x, double start_z, + static void + tapered_threading_pass(setup_pointer settings, block_pointer block, + const tapered_pass_geometry &g, double start_y) { + FINISH_G76_APPROACH(); - STRAIGHT_TRAVERSE(block->line_number, - cut_start_x - depth_direction * end_depth, - start_y, pass_start_z, AABBCC); // back -@@ -5701,6 +5709,7 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, - entry_end_z - pass_start_z) / - fabs(entry_end_z - pass_start_z); + STRAIGHT_TRAVERSE(block->line_number, g.back_x, + start_y, g.pass_start_z, AABBCC); // back + if(g.entry) { + START_G76_CUT(); DISABLE_FEED_OVERRIDE(); - START_SPEED_FEED_SYNCH(settings->active_spindle, entry_pitch, 0); - STRAIGHT_FEED(block->line_number, crest_start_x, -@@ -5709,6 +5718,7 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, - start_y, entry_end_z, AABBCC); // angled in - START_SPEED_FEED_SYNCH(settings->active_spindle, drive_pitch, 0); + START_SPEED_FEED_SYNCH(settings->active_spindle, g.entry_pitch, 0); + STRAIGHT_FEED(block->line_number, g.crest_start_x, +@@ -6072,6 +6079,7 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, + start_y, g.entry_end_z, AABBCC); // angled in + START_SPEED_FEED_SYNCH(settings->active_spindle, g.drive_pitch, 0); } else { + START_G76_CUT(); - STRAIGHT_TRAVERSE(block->line_number, cut_start_x, - start_y, pass_start_z, AABBCC); // in + STRAIGHT_TRAVERSE(block->line_number, g.cut_start_x, + start_y, g.pass_start_z, AABBCC); // in DISABLE_FEED_OVERRIDE(); -@@ -5735,10 +5745,12 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, - start_y, pass_end_z, AABBCC); // over +@@ -6089,9 +6097,11 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, + start_y, g.pass_end_z, AABBCC); // over } STOP_SPEED_FEED_SYNCH(); + START_G76_CLEARANCE(); - STRAIGHT_TRAVERSE(block->line_number, - cut_end_x - depth_direction * end_depth, - start_y, pass_end_z, AABBCC); // out + STRAIGHT_TRAVERSE(block->line_number, g.out_x, + start_y, g.pass_end_z, AABBCC); // out ENABLE_FEED_OVERRIDE(); + FINISH_G76_PASS(block->line_number); } - int Interp::convert_threading_cycle(block_pointer block, + int Interp::check_tapered_threading_pass(setup_pointer settings, +@@ -6287,9 +6297,13 @@ int Interp::convert_threading_cycle(block_pointer block, + } + } + +- lock_speed_override(settings); +- + for(size_t i = 0; i < passes.size(); i++) { ++ START_G76_PASS(); ++ // Hold the override from the first pass on. Issued inside that pass ++ // so that its first Single Step unit is the safe approach, not this ++ // command alone. ++ if(i == 0) ++ lock_speed_override(settings); + if(tapered_drive_line) { + tapered_threading_pass(settings, block, tapered_passes[i], start_y); + } else { diff --git a/src/emc/sai/saicanon.cc b/src/emc/sai/saicanon.cc -index b349f4952d..c4703d40d8 100644 +index 73a77d2..faeae9f 100644 --- a/src/emc/sai/saicanon.cc +++ b/src/emc/sai/saicanon.cc -@@ -1072,6 +1072,12 @@ void FINISH(void) { +@@ -1103,6 +1103,12 @@ void FINISH(void) { PRINT("FINISH()\n"); } @@ -559,10 +556,10 @@ index b349f4952d..c4703d40d8 100644 { PRINT("ON_RESET()\n"); diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc -index e5d71a60e8..ad1352a7d4 100644 +index 92c2d99..513c932 100644 --- a/src/emc/task/emccanon.cc +++ b/src/emc/task/emccanon.cc -@@ -149,6 +149,56 @@ struct JerkData{ +@@ -159,6 +159,56 @@ struct JerkData{ static PM_QUATERNION quat(1, 0, 0, 0); static void flush_segments(void); @@ -619,7 +616,7 @@ index e5d71a60e8..ad1352a7d4 100644 /** -@@ -1047,6 +1097,8 @@ struct pt { +@@ -870,6 +920,8 @@ struct pt { double x, y, z, a, b, c, u, v, w; int line_no; StateTag tag; @@ -628,7 +625,7 @@ index e5d71a60e8..ad1352a7d4 100644 }; static std::vector chained_points; -@@ -1092,6 +1144,8 @@ static void flush_segments(void) { +@@ -915,6 +967,8 @@ static void flush_segments(void) { auto linearMoveMsg = std::make_unique(); linearMoveMsg->feed_mode = canon.feed_mode; @@ -637,7 +634,7 @@ index e5d71a60e8..ad1352a7d4 100644 // now x, y, z, and b are in absolute mm or degree units linearMoveMsg->end.tran.x = TO_EXT_LEN(x); -@@ -1191,7 +1245,8 @@ see_segment(int line_number, +@@ -1015,7 +1069,8 @@ see_segment(int line_number, if(!chained_points.empty() && !linkable(x, y, z, a, b, c, u, v, w)) { flush_segments(); } @@ -647,7 +644,7 @@ index e5d71a60e8..ad1352a7d4 100644 chained_points.push_back(pos); if(changed_abc || changed_uvw) { flush_segments(); -@@ -1204,6 +1259,10 @@ void FINISH() { +@@ -1028,6 +1083,10 @@ void FINISH() { void ON_RESET() { drop_segments(); @@ -657,8 +654,8 @@ index e5d71a60e8..ad1352a7d4 100644 + motion_g76_pass_clearance = 0; } - -@@ -1294,6 +1353,8 @@ void STRAIGHT_TRAVERSE(int line_number, + void SELECT_KINS_TYPE(int switchkins_type) +@@ -1131,6 +1190,8 @@ void STRAIGHT_TRAVERSE(int line_number, auto linearMoveMsg = std::make_unique(); linearMoveMsg->feed_mode = 0; @@ -668,10 +665,10 @@ index e5d71a60e8..ad1352a7d4 100644 linearMoveMsg->type = EMC_MOTION_TYPE_INDEXROTARY; else diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index d5c060f669..e0fe4e3616 100644 +index 55fb417..90cc136 100644 --- a/src/emc/task/emctask.cc +++ b/src/emc/task/emctask.cc -@@ -249,8 +249,7 @@ int emcTaskAbort() +@@ -264,8 +264,7 @@ int emcTaskAbort() emcStatus->task.command[0] = 0; emcStatus->task.callLevel = 0; @@ -681,16 +678,16 @@ index d5c060f669..e0fe4e3616 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -791,4 +790,3 @@ int emcAbortCleanup(EMC_ABORT reason, const char *message) +@@ -854,4 +853,3 @@ int emcAbortCleanup(EMC_ABORT reason, const char *message) print_interp_error(status); return status; } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 64b5497e58..beb6d565d6 100644 +index ec76402..14f26b5 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -462,6 +462,22 @@ static int programStartLine = 0; // which line to run program from +@@ -503,6 +503,22 @@ static int programStartLine = 0; // which line to run program from int stepping = 0; int steppingWait = 0; static int steppedLine = 0; @@ -713,7 +710,7 @@ index 64b5497e58..beb6d565d6 100644 // Variables to handle MDI call interrupts // Depth of call level before interrupted MDI call -@@ -788,8 +804,7 @@ static void emcTaskResumeInterpreter() +@@ -873,8 +889,7 @@ static void emcTaskResumeInterpreter() emcStatus->task.interpState = interpResumeState; } emcStatus->motion.traj.single_stepping = 0; @@ -723,7 +720,7 @@ index 64b5497e58..beb6d565d6 100644 } static void emcTaskStepInterpreter() -@@ -1420,6 +1435,10 @@ static int emcTaskPlan(void) +@@ -1576,6 +1591,10 @@ static int emcTaskPlan(void) emcStatus->motion.traj.single_stepping = 1; stepping = 1; // set stepping mode in case it's not steppingWait = 0; // clear the wait @@ -734,7 +731,7 @@ index 64b5497e58..beb6d565d6 100644 break; // otherwise we can't handle it -@@ -1572,6 +1591,10 @@ static int emcTaskPlan(void) +@@ -1728,6 +1747,10 @@ static int emcTaskPlan(void) emcStatus->motion.traj.single_stepping = 1; stepping = 1; // set stepping mode in case it's not steppingWait = 0; // clear the wait @@ -745,7 +742,7 @@ index 64b5497e58..beb6d565d6 100644 break; // otherwise we can't handle it -@@ -1824,6 +1847,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1985,6 +2008,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; @@ -757,10 +754,10 @@ index 64b5497e58..beb6d565d6 100644 case EMC_TRAJ_DELAY_TYPE: return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2065,7 +2093,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) - retval = emcTrajLinearMove(emcTrajLinearMoveMsg->end, +@@ -2290,7 +2318,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajLinearMoveMsg->type, emcTrajLinearMoveMsg->vel, emcTrajLinearMoveMsg->ini_maxvel, emcTrajLinearMoveMsg->acc, emcTrajLinearMoveMsg->ini_maxjerk, + emcTrajLinearMoveMsg->vlimit_scale, - emcTrajLinearMoveMsg->indexer_jnum); + emcTrajLinearMoveMsg->indexer_jnum, + emcTrajLinearMoveMsg->g76_pass_id, @@ -768,16 +765,16 @@ index 64b5497e58..beb6d565d6 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2401,6 +2431,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) - } else { // we can honour the modeswitch - if (mode_msg->mode != emcStatus->task.mode) { +@@ -2661,6 +2691,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + if (mode_msg->mode != emcStatus->task.mode || + mode_msg->mode != EMC_TASK_MODE::MANUAL) { emcTaskStopClear(); + emcStatus->motion.traj.single_stepping = 0; + emcTaskResetSteppingState(); } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { -@@ -2434,8 +2466,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2694,8 +2726,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcStatus->task.interpState = EMC_TASK_INTERP::IDLE; emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcStatus->motion.traj.single_stepping = 0; @@ -787,7 +784,7 @@ index 64b5497e58..beb6d565d6 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2448,6 +2479,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2708,6 +2739,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) state_msg = reinterpret_cast(cmd); if (state_msg->state != EMC_TASK_STATE::ON) { emcTaskStopClear(); @@ -796,7 +793,7 @@ index 64b5497e58..beb6d565d6 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2532,8 +2565,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2792,8 +2825,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_EXECUTE_TYPE: emcStatus->motion.traj.single_stepping = 0; @@ -806,7 +803,7 @@ index 64b5497e58..beb6d565d6 100644 execute_msg = reinterpret_cast(cmd); if (!all_homed() && !no_force_homing) { //!no_force_homing = force homing before MDI emcOperatorError(_("Can't issue MDI command when not homed")); -@@ -2628,8 +2660,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2888,8 +2920,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -816,7 +813,7 @@ index 64b5497e58..beb6d565d6 100644 if (!taskplanopen && emcStatus->task.file[0] != 0) { emcTaskPlanOpen(emcStatus->task.file); } -@@ -2697,6 +2728,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2958,6 +2989,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -827,7 +824,7 @@ index 64b5497e58..beb6d565d6 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: os_msg = reinterpret_cast(cmd); emcTaskPlanSetOptionalStop(os_msg->state); -@@ -2800,6 +2835,7 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3066,6 +3101,7 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) case EMC_TASK_PLAN_END_TYPE: case EMC_TASK_PLAN_INIT_TYPE: case EMC_TASK_PLAN_SYNCH_TYPE: @@ -835,7 +832,7 @@ index 64b5497e58..beb6d565d6 100644 case EMC_TASK_PLAN_EXECUTE_TYPE: case EMC_TASK_PLAN_OPTIONAL_STOP_TYPE: return EMC_TASK_EXEC::DONE; -@@ -2841,11 +2877,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3118,11 +3154,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) #define STEPPING_CHECK() \ if (stepping) { \ if (! steppingWait) { \ @@ -857,7 +854,7 @@ index 64b5497e58..beb6d565d6 100644 break; \ } \ } \ -@@ -2906,8 +2949,7 @@ static int emcTaskExecute(void) +@@ -3184,8 +3227,7 @@ static int emcTaskExecute(void) emcStatus->task.interpState = EMC_TASK_INTERP::IDLE; emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcStatus->motion.traj.single_stepping = 0; @@ -867,15 +864,15 @@ index 64b5497e58..beb6d565d6 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2929,6 +2971,7 @@ static int emcTaskExecute(void) - if (0 != emcTaskCommand) { +@@ -3207,6 +3249,7 @@ static int emcTaskExecute(void) + if (NULL != emcTaskCommand) { emcTaskEager = 1; emcStatus->task.currentLine = interp_list.get_line_number(); + currentPassGroup = interp_list.get_pass_group(); - emcStatus->task.callLevel = emcTaskPlanLevel(); - // and set it for all subsystems which use queued ids - emcTrajSetMotionId(emcStatus->task.currentLine); -@@ -3754,8 +3797,7 @@ int main(int argc, char *argv[]) + // callLevel is set by emcTaskUpdate() from the executing + // move's StateTag; the interpreter's live level at dequeue + // time leads motion by the whole read-ahead queue. +@@ -4203,8 +4246,7 @@ int main(int argc, char *argv[]) emcStatus->task.interpState = EMC_TASK_INTERP::IDLE; emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcStatus->motion.traj.single_stepping = 0; @@ -886,7 +883,7 @@ index 64b5497e58..beb6d565d6 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh -index d8c619cdb5..79dbeb68bc 100644 +index d8c619c..79dbeb6 100644 --- a/src/emc/task/task.hh +++ b/src/emc/task/task.hh @@ -22,6 +22,7 @@ @@ -903,25 +900,22 @@ index d8c619cdb5..79dbeb68bc 100644 #endif - diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index 86fdd15940..4796832331 100644 +index 3f66a0b..3328659 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -1499,8 +1499,10 @@ int emcTrajSetTermCond(int cond, double tolerance) - return usrmotWriteEmcmotCommand(&emcmotCommand); +@@ -1576,7 +1576,8 @@ int emcTrajSetTermCond(int cond, double tolerance) } --int emcTrajLinearMove(const EmcPose& end, int type, double vel, double ini_maxvel, double acc, double ini_maxjerk, -- int indexer_jnum) -+int emcTrajLinearMove(const EmcPose& end, int type, double vel, -+ double ini_maxvel, double acc, double ini_maxjerk, -+ int indexer_jnum, int g76_pass_id, + int emcTrajLinearMove(const EmcPose& end, int type, double vel, double ini_maxvel, double acc, double ini_maxjerk, +- double vlimit_scale, int indexer_jnum) ++ double vlimit_scale, int indexer_jnum, int g76_pass_id, + int g76_pass_clearance) { #ifdef ISNAN_TRAP if (std::isnan(end.tran.x) || std::isnan(end.tran.y) || std::isnan(end.tran.z) || -@@ -1523,6 +1525,8 @@ int emcTrajLinearMove(const EmcPose& end, int type, double vel, double ini_maxve - emcmotCommand.acc = acc; +@@ -1600,6 +1601,8 @@ int emcTrajLinearMove(const EmcPose& end, int type, double vel, double ini_maxve emcmotCommand.ini_maxjerk = ini_maxjerk; + emcmotCommand.vlimit_scale = vlimit_scale; emcmotCommand.turn = indexer_jnum; + emcmotCommand.g76_pass_id = g76_pass_id; + emcmotCommand.g76_pass_clearance = g76_pass_clearance; @@ -929,10 +923,10 @@ index 86fdd15940..4796832331 100644 return usrmotWriteEmcmotCommand(&emcmotCommand); } diff --git a/src/emc/tp/tc_types.h b/src/emc/tp/tc_types.h -index c1767d5613..17ebe59d7c 100644 +index 47018b2..bd8ad13 100644 --- a/src/emc/tp/tc_types.h +++ b/src/emc/tp/tc_types.h -@@ -167,6 +167,8 @@ typedef struct { +@@ -168,6 +168,8 @@ typedef struct { // TC_RIGIDTAP (coords.rigidtap) int active; // this motion is being executed int canon_motion_type; // this motion is due to which canon function? @@ -942,34 +936,40 @@ index c1767d5613..17ebe59d7c 100644 // this segment (g64 mode) diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index e48127c5a9..00a06f1a75 100644 +index e481a43..a9dfacc 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c -@@ -254,7 +254,7 @@ STATIC double tpGetFeedScale(TP_STRUCT const * const tp, - (tp->pausing && - (tc->synchronized == TC_SYNC_NONE || - tc->synchronized == TC_SYNC_VELOCITY)) || -- (tp->stopping && tc != tp->stop_tc); -+ (tp->stopping && !tp->stop_target_pending); - bool aborting = tp->aborting; - if (pausing) { - tc_debug_print("pausing\n"); -@@ -342,7 +342,10 @@ STATIC inline double tpGetRealFinalVel(TP_STRUCT const * const tp, +@@ -240,10 +240,12 @@ STATIC int tpGetMachineActiveLimit(double * const act_limit, PmCartesian const * + * does a blend arc that the trapezoidal planner inserts at the end of the + * run: it carries the run's last stretch into the following move. Every + * other segment is held. ++ * While a G76 Stop target is pending, nothing is held until the pass's marked ++ * clearance retract has completed. + */ + STATIC bool tpStopHolds(TP_STRUCT const * const tp, + TC_STRUCT const * const tc) { +- if (!tp->stopping) { ++ if (!tp->stopping || tp->stop_target_pending) { + return false; + } + bool synchronized = tc->synchronized == TC_SYNC_POSITION || +@@ -355,7 +357,10 @@ STATIC inline double tpGetRealFinalVel(TP_STRUCT const * const tp, * If the term_cond gets changed out from under us, detect this and force final velocity to zero */ - if (emcmotStatus->stepping || tc->term_cond != TC_TERM_COND_TANGENT || tp->reverse_run) { + if ((emcmotStatus->stepping && !tp->stepping_to_pass_clearance) || -+ (tp->stopping && tc == tp->stop_tc) || ++ (tp->stop_pass_id && tc == tp->stop_tc) || + (tp->stepping_to_pass_clearance && tc == tp->step_tc) || + tc->term_cond != TC_TERM_COND_TANGENT || tp->reverse_run) { return 0.0; } -@@ -496,6 +499,12 @@ int tpClear(TP_STRUCT * const tp) +@@ -486,6 +491,13 @@ int tpClear(TP_STRUCT * const tp) tp->pausing = 0; tp->stopping = 0; - tp->stop_tc = 0; + tp->stop_sync_run = 0; ++ tp->stop_tc = 0; + tp->stop_target_pending = 0; + tp->stop_pass_id = 0; + tp->step_tc = 0; @@ -979,7 +979,7 @@ index e48127c5a9..00a06f1a75 100644 tp->reverse_run = 0; tp->synchronized = 0; tp->uu_per_rev = 0.0; -@@ -914,6 +923,8 @@ STATIC int tpInitBlendArcFromPrev(TP_STRUCT const * const tp, +@@ -908,6 +920,8 @@ STATIC int tpInitBlendArcFromPrev(TP_STRUCT const * const tp, // copy state tag from previous segment during blend motion blend_tc->tag = prev_tc->tag; @@ -988,7 +988,7 @@ index e48127c5a9..00a06f1a75 100644 return TP_ERR_OK; } -@@ -1579,6 +1590,23 @@ tp_err_t tpCreateLineLineBlend(TP_STRUCT * const tp, TC_STRUCT * const prev_tc, +@@ -1573,6 +1587,23 @@ tp_err_t tpCreateLineLineBlend(TP_STRUCT * const tp, TC_STRUCT * const prev_tc, */ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc, int inc_id) { @@ -1012,7 +1012,7 @@ index e48127c5a9..00a06f1a75 100644 tc->id = tp->nextId; if (tcqPut(&tp->queue, tc) == -1) { rtapi_print_msg(RTAPI_MSG_ERR, "tcqPut failed.\n"); -@@ -1588,6 +1616,20 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc +@@ -1582,6 +1613,20 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc tp->nextId++; } @@ -1033,39 +1033,39 @@ index e48127c5a9..00a06f1a75 100644 // Store end of current move as new final goal of TP // KLUDGE: endpoint is garbage for rigid tap since it's supposed to retract past the start point. if (tc->motion_type != TC_RIGIDTAP) { -@@ -1611,6 +1653,10 @@ STATIC int handleModeChange(TC_STRUCT * const prev_tc, TC_STRUCT * const tc) +@@ -1605,6 +1650,10 @@ STATIC int handleModeChange(TC_STRUCT * const prev_tc, TC_STRUCT * const tc) tp_debug_print("Blending disabled: can't blend between rapid and feed motions\n"); tcSetTermCond(prev_tc, tc, TC_TERM_COND_STOP); } -+ if (prev_tc->g76_pass_clearance == 1) { -+ tp_debug_print("Blending disabled: G76 pass clearance endpoint\n"); ++ if (prev_tc->g76_pass_clearance) { ++ tp_debug_print("Blending disabled: G76 pass clearance or approach endpoint\n"); + tcSetTermCond(prev_tc, tc, TC_TERM_COND_STOP); + } if (prev_tc->synchronized != TC_SYNC_POSITION && tc->synchronized == TC_SYNC_POSITION) { tp_debug_print("Blending disabled: changing spindle sync mode from %d to %d\n", -@@ -2108,6 +2154,10 @@ tc_blend_type_t tpHandleBlendArc(TP_STRUCT * const tp, TC_STRUCT * const tc) { +@@ -2102,6 +2151,10 @@ tc_blend_type_t tpHandleBlendArc(TP_STRUCT * const tp, TC_STRUCT * const tc) { tp_debug_print(" queue empty\n"); return NO_BLEND; } -+ if (prev_tc->g76_pass_clearance == 1) { -+ tp_debug_print(" G76 pass clearance is an exact endpoint\n"); ++ if (prev_tc->g76_pass_clearance) { ++ tp_debug_print(" G76 pass clearance or approach is an exact endpoint\n"); + return NO_BLEND; + } if (prev_tc->progress > prev_tc->target / 2.0) { tp_debug_print(" prev_tc progress (%f) is too large, aborting blend arc\n", prev_tc->progress); return NO_BLEND; -@@ -2156,7 +2206,8 @@ tc_blend_type_t tpHandleBlendArc(TP_STRUCT * const tp, TC_STRUCT * const tc) { - +@@ -2151,7 +2204,8 @@ tc_blend_type_t tpHandleBlendArc(TP_STRUCT * const tp, TC_STRUCT * const tc) { int tpAddLine(TP_STRUCT * const tp, EmcPose end, int canon_motion_type, - double vel, double ini_maxvel, double acc, double ini_maxjerk, unsigned char enables, + double vel, double ini_maxvel, double acc, double ini_maxjerk, + double vlimit_scale, unsigned char enables, - char atspeed, int indexer_jnum, struct state_tag_t tag) + char atspeed, int indexer_jnum, struct state_tag_t tag, + int g76_pass_id, int g76_pass_clearance) { if (tpErrorCheck(tp) < 0) { return TP_ERR_FAIL; -@@ -2172,12 +2223,17 @@ int tpAddLine(TP_STRUCT * const tp, EmcPose end, int canon_motion_type, +@@ -2167,12 +2221,18 @@ int tpAddLine(TP_STRUCT * const tp, EmcPose end, int canon_motion_type, enables, atspeed); tc.tag = tag; @@ -1077,22 +1077,14 @@ index e48127c5a9..00a06f1a75 100644 // Copy over state data from the trajectory planner tcSetupState(&tc, tp); -+ if (tc.g76_pass_clearance == 1) { ++ // Step stops at these, so no blend may trim them. ++ if (tc.g76_pass_clearance) { + tc.term_cond = TC_TERM_COND_STOP; + } // Copy in motion parameters tcSetupMotion(&tc, -@@ -2840,7 +2896,7 @@ int tpCalculateSCurveAccel(TP_STRUCT const * const tp, TC_STRUCT * const tc, TC_ - (tp->pausing && - (tc->synchronized == TC_SYNC_NONE || - tc->synchronized == TC_SYNC_VELOCITY)) || -- (tp->stopping && tc != tp->stop_tc); -+ (tp->stopping && !tp->stop_target_pending); - bool is_aborting = tp->aborting; - - /* -@@ -3319,7 +3375,7 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) +@@ -3370,7 +3430,7 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) tpUpdateMovementStatus(tp, NULL); @@ -1101,7 +1093,7 @@ index e48127c5a9..00a06f1a75 100644 tpResume(tp); } } -@@ -3381,6 +3437,17 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, +@@ -3432,6 +3492,17 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, // Clean up Ruckig planner resources tcCleanupRuckig(tc); @@ -1119,7 +1111,7 @@ index e48127c5a9..00a06f1a75 100644 //TODO make progress to match target? // done with this move if (tp->reverse_run) { -@@ -4143,22 +4210,31 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4314,6 +4385,10 @@ int tpRunCycle(TP_STRUCT * const tp, long period) if(!tc) { if (tp->stopping) { tpHandleEmptyQueue(tp); @@ -1128,8 +1120,9 @@ index e48127c5a9..00a06f1a75 100644 + return TP_ERR_WAITING; + } if (tp->stopping) { + tp->stop_sync_run = 0; tp->pausing = 1; - emcmotStatus->stopped = 1; +@@ -4321,6 +4396,11 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -1141,19 +1134,7 @@ index e48127c5a9..00a06f1a75 100644 tpHandleEmptyQueue(tp); return TP_ERR_WAITING; } - -- if (tp->stopping && tc != tp->stop_tc) { -+ if (tp->stopping && !tp->stop_target_pending) { - tp->pausing = 1; - } - - if (((tp->pausing && tc->synchronized != TC_SYNC_POSITION) || -- (tp->stopping && tc != tp->stop_tc)) && -+ (tp->stopping && !tp->stop_target_pending)) && - fabs(emcmotStatus->current_vel) < TP_VEL_EPSILON) { - emcmotStatus->stopped = 1; - } -@@ -4263,6 +4339,42 @@ int tpSetSpindleSync(TP_STRUCT * const tp, int spindle, double sync, int mode) { +@@ -4469,6 +4549,42 @@ int tpSetSpindleSync(TP_STRUCT * const tp, int spindle, double sync, int mode) { return TP_ERR_OK; } @@ -1196,7 +1177,7 @@ index e48127c5a9..00a06f1a75 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4270,12 +4382,59 @@ int tpPause(TP_STRUCT * const tp) +@@ -4476,22 +4592,75 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -1205,37 +1186,56 @@ index e48127c5a9..00a06f1a75 100644 + tp->step_pass_id = 0; + tp->stepping_to_pass_clearance = 0; TC_STRUCT *tc = tcqItem(&tp->queue, 0); -- if (tc && tc->active && tc->synchronized == TC_SYNC_POSITION) { + /* +- * A position-synchronized head is let finish when it is active, and +- * also when it is not yet active but continues a synchronization +- * already in effect: tpRunCycle() activates the next chained G33 one +- * servo period after the previous one is popped, and a Stop handled +- * in that period must not halt the thread. ++ * A G76 cut that has passed spindle index, or its explicitly marked ++ * retract, extends Stop to that pass's clearance. This also covers ++ * the handoff cycle where the marked retract has become queue head ++ * but is not active yet, and a chained cut (an entry taper followed ++ * by the drive line) that is not yet active but continues the ++ * synchronization already in effect. If task has not delivered the ++ * retract yet, retain the pass ID and bind the exact target as soon ++ * as it enters the TP queue. + */ +- if (tc && tc->synchronized == TC_SYNC_POSITION && + bool in_g76_cut_or_clearance = tc && tc->g76_pass_id && -+ ((tc->active && tc->synchronized == TC_SYNC_POSITION && ++ ((tc->synchronized == TC_SYNC_POSITION && ++ (tc->active || emcmotStatus->spindleSync) && + tp->spindle.waiting_for_index != tc->id) || + tc->g76_pass_clearance == 1); + if (in_g76_cut_or_clearance) { -+ /* -+ * Only a G76 cut that has passed spindle index, or an explicitly -+ * marked retract, may extend Stop to its pass clearance. This -+ * also covers the handoff cycle where the marked retract has -+ * become queue head but is not active yet. -+ * If task has not delivered the retract yet, retain the pass ID -+ * and bind the exact target as soon as it enters the TP queue. -+ */ + tp->stop_pass_id = tc->g76_pass_id; + tp->stop_tc = tpFindG76PassClearance(tp, tp->stop_pass_id); + tp->stop_target_pending = 1; ++ tp->stop_sync_run = 0; + tp->pausing = 0; -+ } else if (tc && tc->active && !tc->g76_pass_id && -+ tc->synchronized == TC_SYNC_POSITION) { -+ /* Preserve the established G33 and rigid-tap Stop boundary. */ ++ } else if (tc && !tc->g76_pass_id && ++ tc->synchronized == TC_SYNC_POSITION && + (tc->active || emcmotStatus->spindleSync)) { ++ /* ++ * Preserve the established G33 and rigid-tap Stop boundary. A ++ * position-synchronized head is let finish when it is active, and ++ * also when it is not yet active but continues a synchronization ++ * already in effect: tpRunCycle() activates the next chained G33 ++ * one servo period after the previous one is popped, and a Stop ++ * handled in that period must not halt the thread. ++ */ + tp->stop_pass_id = 0; - tp->stop_tc = tc; -+ tp->stop_target_pending = 1; ++ tp->stop_tc = 0; ++ tp->stop_target_pending = 0; + tp->stop_sync_run = 1; tp->pausing = 0; } else { + tp->stop_pass_id = 0; - tp->stop_tc = 0; ++ tp->stop_tc = 0; + tp->stop_target_pending = 0; -+ tp->pausing = 1; -+ } + tp->stop_sync_run = 0; + tp->pausing = 1; + } + } else if (emcmotStatus->stepping && + tp->stepping_to_pass_clearance) { + /* @@ -1254,13 +1254,16 @@ index e48127c5a9..00a06f1a75 100644 + tp->step_target_pending = 0; + tp->step_pass_id = 0; + tp->stepping_to_pass_clearance = 0; - tp->pausing = 1; - } ++ tp->pausing = 1; ++ } } else { -@@ -4292,6 +4451,16 @@ int tpResume(TP_STRUCT * const tp) + tp->pausing = 1; + } +@@ -4506,6 +4675,17 @@ int tpResume(TP_STRUCT * const tp) tp->pausing = 0; tp->stopping = 0; - tp->stop_tc = 0; + tp->stop_sync_run = 0; ++ tp->stop_tc = 0; + tp->stop_target_pending = 0; + tp->stop_pass_id = 0; + tp->step_tc = 0; @@ -1274,7 +1277,7 @@ index e48127c5a9..00a06f1a75 100644 emcmotStatus->stopped = 0; return TP_ERR_OK; } -@@ -4304,6 +4473,10 @@ int tpAbort(TP_STRUCT * const tp) +@@ -4518,6 +4698,10 @@ int tpAbort(TP_STRUCT * const tp) if (!tp->aborting) { /* const to abort, signal a pause and set our abort flag */ @@ -1286,24 +1289,24 @@ index e48127c5a9..00a06f1a75 100644 tp->aborting = 1; } diff --git a/src/emc/tp/tp.h b/src/emc/tp/tp.h -index e00b457ad2..c89f3608f6 100644 +index 7d2eff1..f0a85a8 100644 --- a/src/emc/tp/tp.h +++ b/src/emc/tp/tp.h -@@ -57,7 +57,8 @@ int tpAddRigidTap(TP_STRUCT * const tp, - struct state_tag_t tag); +@@ -58,7 +58,8 @@ int tpAddRigidTap(TP_STRUCT * const tp, int tpAddLine(TP_STRUCT * const tp, EmcPose end, int canon_motion_type, - double vel, double ini_maxvel, double acc, double ini_maxjerk, unsigned char enables, + double vel, double ini_maxvel, double acc, double ini_maxjerk, + double vlimit_scale, unsigned char enables, - char atspeed, int indexrotary, struct state_tag_t tag); + char atspeed, int indexrotary, struct state_tag_t tag, + int g76_pass_id, int g76_pass_clearance); int tpAddCircle(TP_STRUCT * const tp, EmcPose end, PmCartesian center, PmCartesian normal, int turn, int canon_motion_type, double vel, - double ini_maxvel, double acc, double ini_maxjerk, unsigned char enables, + double ini_maxvel, double acc, double ini_maxjerk, diff --git a/src/emc/tp/tp_types.h b/src/emc/tp/tp_types.h -index 8d8aa3a362..15be0f3127 100644 +index d11e695..2963bcc 100644 --- a/src/emc/tp/tp_types.h +++ b/src/emc/tp/tp_types.h -@@ -137,11 +137,17 @@ typedef struct { +@@ -150,8 +150,8 @@ typedef struct { syncdio_t syncdio; //record tpSetDout's here /* @@ -1313,7 +1316,17 @@ index 8d8aa3a362..15be0f3127 100644 + * trajectory planners retain every established member offset. */ int stopping; - TC_STRUCT *stop_tc; + /* +@@ -160,6 +160,18 @@ typedef struct { + * queue or the queue empties. + */ + int stop_sync_run; ++ /* ++ * G76 Stop target: the marked clearance retract of the pass that was ++ * cutting when Stop arrived. stop_target_pending stays set until that ++ * retract completes; stop_tc is bound once the retract is queued. ++ */ ++ TC_STRUCT *stop_tc; + int stop_target_pending; + int stop_pass_id; + TC_STRUCT *step_tc; @@ -1324,7 +1337,7 @@ index 8d8aa3a362..15be0f3127 100644 } TP_STRUCT; diff --git a/tests/interp/compile/use-rs274.cc b/tests/interp/compile/use-rs274.cc -index 4a55bad0de..a5a795f475 100644 +index e30cc2f..6afd929 100644 --- a/tests/interp/compile/use-rs274.cc +++ b/tests/interp/compile/use-rs274.cc @@ -258,6 +258,11 @@ int GET_EXTERNAL_DIGITAL_INPUT(int index, int def) { return 0; } @@ -1339,660 +1352,3 @@ index 4a55bad0de..a5a795f475 100644 void ON_RESET(void) {} void CANON_ERROR(const char *fmt, ...) {} void UPDATE_TAG(const StateTag& tag) {} -diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -index e457195324..e845030ffb 100644 ---- a/tests/resumable-stop/README -+++ b/tests/resumable-stop/README -@@ -5,6 +5,22 @@ This regression test exercises the task-level Stop operation directly through - the Python command API. It checks that an active feed move stops without - aborting queued AUTO state, that spindle and coolant outputs are disabled - while stopped, and that Resume restores them before continuing the same --program to completion. The G95 scenario enables the jerk-limited trajectory --planner and rejects zero-limit Ruckig fallback errors while spindle feedback --recovers after Resume. -+program to completion. The G76 scenarios check that Stop executes only the -+explicitly marked post-cut rapid retract, leaving the tool clear of the -+finished thread rather than stopped at cutting depth. Coverage includes -+cylindrical and tapered drive lines, synchronized exit tapers, repeated Stop -+requests across the cut/retract handoff, and a negative G33 test proving that -+an unrelated following rapid is not executed. Single Step coverage enters the -+first G76 pass directly and verifies every cylindrical and tapered safe -+approach step followed by its combined infeed, synchronized-cut, and clearance -+step. It also starts G76 in normal AUTO_RUN, stops after the first pass with later passes -+already queued, and verifies that each -+following AUTO_STEP reaches exactly one cylindrical or tapered safe approach -+endpoint, and the next AUTO_STEP completes that pass's infeed, thread, and -+clearance. -+Arc blending is enabled for all scenarios, so the exact-clearance assertions -+also prove that a marked G76 retract endpoint is not trimmed by a following -+rapid. The handoff stress case uses a slow synchronized feed and issues Stop at -+least 20 task cycles before the cut endpoint. The G95 scenario enables the -+jerk-limited trajectory planner and rejects zero-limit Ruckig fallback errors -+while spindle feedback recovers after Resume. -diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -index c491888fc8..4792b570e1 100755 ---- a/tests/resumable-stop/checkresult -+++ b/tests/resumable-stop/checkresult -@@ -1,3 +1,4 @@ - #!/bin/sh --test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 15 -+set -e -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 24 - grep -q '^resumable stop scenarios complete$' "$1" -diff --git a/tests/resumable-stop/g33-followed-by-rapid.ngc b/tests/resumable-stop/g33-followed-by-rapid.ngc -new file mode 100644 -index 0000000000..a12bcb3029 ---- /dev/null -+++ b/tests/resumable-stop/g33-followed-by-rapid.ngc -@@ -0,0 +1,7 @@ -+G21 G18 G90 -+G0 X10 Z0 -+S60 M3 -+G33 Z-5 K1 -+G0 X30 -+M5 -+M2 -diff --git a/tests/resumable-stop/g76-exit-taper.ngc b/tests/resumable-stop/g76-exit-taper.ngc -new file mode 100644 -index 0000000000..5b04e6921e ---- /dev/null -+++ b/tests/resumable-stop/g76-exit-taper.ngc -@@ -0,0 +1,7 @@ -+G21 G18 G90 -+G0 X10 Z0 -+S60 M3 -+G76 P1 Z-5 I-1 J0.2 K0.6 R1 E1 L2 -+G1 X20 F600 -+M5 -+M2 -diff --git a/tests/resumable-stop/g76-handoff.ngc b/tests/resumable-stop/g76-handoff.ngc -new file mode 100644 -index 0000000000..01a62a26a5 ---- /dev/null -+++ b/tests/resumable-stop/g76-handoff.ngc -@@ -0,0 +1,7 @@ -+G21 G18 G90 -+G0 X10 Z0 -+S60 M3 -+G76 P1 Z-1 I-1 J0.2 K0.21 R1 -+G1 X20 F600 -+M5 -+M2 -diff --git a/tests/resumable-stop/g76-step.ngc b/tests/resumable-stop/g76-step.ngc -new file mode 100644 -index 0000000000..c8ee28f7ed ---- /dev/null -+++ b/tests/resumable-stop/g76-step.ngc -@@ -0,0 +1,4 @@ -+G21 G18 G90 G76 P1 Z-5 I-1 J0.2 K0.6 R1 -+G1 X20 F600 -+M5 -+M2 -diff --git a/tests/resumable-stop/g76-tapered-exit-taper.ngc b/tests/resumable-stop/g76-tapered-exit-taper.ngc -new file mode 100644 -index 0000000000..488d2a9300 ---- /dev/null -+++ b/tests/resumable-stop/g76-tapered-exit-taper.ngc -@@ -0,0 +1,7 @@ -+G21 G18 G90 -+G0 X10 Z0 -+S60 M3 -+G76 P1 X8 Z-5 I-1 J0.2 K0.6 R1 E1 L2 -+G1 X20 F600 -+M5 -+M2 -diff --git a/tests/resumable-stop/g76-tapered-step.ngc b/tests/resumable-stop/g76-tapered-step.ngc -new file mode 100644 -index 0000000000..241f777682 ---- /dev/null -+++ b/tests/resumable-stop/g76-tapered-step.ngc -@@ -0,0 +1,4 @@ -+G21 G18 G90 G76 P1 X8 Z-5 I-1 J0.2 K0.6 R1 -+G1 X20 F600 -+M5 -+M2 -diff --git a/tests/resumable-stop/g76-tapered.ngc b/tests/resumable-stop/g76-tapered.ngc -new file mode 100644 -index 0000000000..b0eb997e19 ---- /dev/null -+++ b/tests/resumable-stop/g76-tapered.ngc -@@ -0,0 +1,7 @@ -+G21 G18 G90 -+G0 X10 Z0 -+S60 M3 -+G76 P1 X8 Z-5 I-1 J0.2 K0.6 R1 -+G1 X20 F600 -+M5 -+M2 -diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index d3c9646b11..463ec75590 100755 ---- a/tests/resumable-stop/test-ui.py -+++ b/tests/resumable-stop/test-ui.py -@@ -2,6 +2,7 @@ - - import math - import os -+import subprocess - import sys - import time - -@@ -17,14 +18,30 @@ def fail(message): - sys.exit(1) - - --def wait_for(predicate, message, timeout=10.0): -+def wait_for(predicate, message, timeout=10.0, poll_interval=0.02): - start = time.time() - while time.time() - start < timeout: - s.poll() - if predicate(): - return -- time.sleep(0.02) -- fail(message) -+ time.sleep(poll_interval) -+ fail( -+ "%s: X=%.6f Z=%.6f vel=%.6f queue=%d task_paused=%s " -+ "motion_paused=%s stepping=%s " -+ "interp=%d exec=%d" -+ % ( -+ message, -+ s.position[0], -+ s.position[2], -+ s.current_vel, -+ s.queue, -+ s.task_paused, -+ s.paused, -+ s.single_stepping, -+ s.interp_state, -+ s.exec_state, -+ ) -+ ) - - - def wait_complete(message, timeout=10.0): -@@ -215,6 +232,43 @@ def run_stop_single_step_test(): - assert_outputs_stopped_after_program() - - -+def run_inflight_single_step_test(): -+ open_auto_program("inflight-step.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.queue >= 3 -+ and s.position[0] > 1.0 -+ and s.position[0] < 9.0, -+ "program did not prequeue later blocks during its first move", -+ ) -+ -+ c.auto(linuxcnc.AUTO_STEP) -+ wait_for( -+ lambda: s.single_stepping and not s.task_paused and not s.paused, -+ "in-flight Single Step did not remain unpaused while armed", -+ ) -+ wait_for( -+ lambda: s.task_paused -+ and s.paused -+ and math.isclose(s.position[0], 10.0, abs_tol=0.01) -+ and abs(s.current_vel) < 0.001, -+ "in-flight Single Step did not finish the active source block", -+ timeout=15.0, -+ ) -+ -+ if s.queue < 3: -+ fail("in-flight Single Step did not preserve prequeued later blocks") -+ -+ time.sleep(0.25) -+ s.poll() -+ if not math.isclose(s.position[0], 10.0, abs_tol=0.001): -+ fail("in-flight Single Step advanced into the next source block") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(40.0, timeout=10.0) -+ -+ - def run_rapid_resume_without_at_speed_test(): - hal.set_p("spindle.0.at-speed", "false") - open_auto_program("rapid-then-feed.ngc") -@@ -410,6 +464,41 @@ def run_threading_stop_resume_test(): - ) - - -+def run_g33_does_not_execute_following_rapid_test(): -+ open_auto_program("g33-followed-by-rapid.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.position[2] < -0.5 and s.position[2] > -4.5, -+ "G33 did not enter synchronized motion before negative Stop test", -+ timeout=15.0, -+ ) -+ c.program_stop() -+ wait_complete("G33 negative Stop command did not complete") -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "G33 negative test did not reach STOPPED", -+ timeout=15.0, -+ ) -+ -+ if s.position[2] > -4.90: -+ fail("G33 negative test stopped before its synchronized move completed") -+ if not math.isclose(s.position[0], 10.0, abs_tol=0.05): -+ fail( -+ "Stop executed the unmarked rapid following G33: X=%.6f" -+ % s.position[0] -+ ) -+ -+ time.sleep(0.25) -+ s.poll() -+ if not math.isclose(s.position[0], 10.0, abs_tol=0.05): -+ fail("unmarked post-G33 rapid moved while stopped") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(30.0, expected_z=-5.0, timeout=20.0) -+ assert_outputs_stopped_after_program() -+ -+ - def run_fperrev_stop_resume_test(): - open_auto_program("fperrev.ngc") - c.auto(linuxcnc.AUTO_RUN, 0) -@@ -474,9 +563,9 @@ def run_g76_stop_resume_test(): - if s.position[2] > -4.90: - fail("G76 stopped before its active threading TC completed") - -- if s.position[0] >= 9.5: -+ if not math.isclose(s.position[0], 10.4, abs_tol=0.05): - fail( -- "G76 executed its retract or a later pass before STOPPED: X=%.6f" -+ "G76 did not stop at the first pass clearance: X=%.6f" - % s.position[0] - ) - -@@ -495,6 +584,307 @@ def run_g76_stop_resume_test(): - assert_outputs_stopped_after_program() - - -+def run_g76_stop_while_waiting_for_index_test(): -+ subprocess.run(["halcmd", "unlinkp", "encoder_0.phase-Z"], check=True) -+ hal.set_p("encoder_0.phase-Z", "false") -+ open_auto_program("g76.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: hal.get_value("spindle.0.index-enable") -+ and s.position[0] < 9.95 -+ and math.isclose(s.position[2], 0.0, abs_tol=0.001) -+ and abs(s.current_vel) < 0.001, -+ "G76 did not arm its first cut while waiting for spindle index", -+ timeout=15.0, -+ ) -+ -+ c.program_stop() -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "G76 did not stop with its index-waiting cut preserved", -+ ) -+ -+ # Deliver the delayed index after Stop. The armed cut must remain queued -+ # for Resume rather than starting merely because its prerequisite arrived. -+ subprocess.run( -+ ["halcmd", "net", "spindle-phase-Z", "encoder_0.phase-Z"], -+ check=True, -+ ) -+ -+ if not math.isclose(s.position[2], 0.0, abs_tol=0.001): -+ fail("G76 started its cut after Stop: Z=%.6f" % s.position[2]) -+ -+ time.sleep(0.25) -+ s.poll() -+ if not math.isclose(s.position[2], 0.0, abs_tol=0.001): -+ fail("index-waiting G76 moved while stopped: Z=%.6f" % s.position[2]) -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(20.0, expected_z=-5.0, timeout=40.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_tapered_g76_stop_resume_test(): -+ open_auto_program("g76-tapered.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.task_mode == linuxcnc.MODE_AUTO -+ and s.position[0] < 8.6 -+ and s.position[2] < -0.5 -+ and s.position[2] > -4.5, -+ "tapered G76 did not enter its first synchronized pass", -+ timeout=15.0, -+ ) -+ -+ c.program_stop() -+ wait_complete("tapered G76 stop command did not complete") -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "task did not stop after the active tapered G76 pass", -+ timeout=15.0, -+ ) -+ -+ if s.position[2] > -4.90: -+ fail("tapered G76 stopped before its synchronized cut completed") -+ if not math.isclose(s.position[0], 8.4, abs_tol=0.05): -+ fail( -+ "tapered G76 did not stop at the first pass clearance: X=%.6f Z=%.6f" -+ % (s.position[0], s.position[2]) -+ ) -+ -+ stopped_x = s.position[0] -+ stopped_z = s.position[2] -+ time.sleep(0.25) -+ s.poll() -+ if ( -+ not math.isclose(s.position[0], stopped_x, abs_tol=0.001) -+ or not math.isclose(s.position[2], stopped_z, abs_tol=0.001) -+ ): -+ fail("tapered G76 moved while stopped") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(20.0, expected_z=-5.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def step_g76_approach(expected_approach_x, label="G76"): -+ c.auto(linuxcnc.AUTO_STEP) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.task_paused -+ and abs(s.current_vel) < 0.001 -+ and math.isclose(s.position[2], 0.0, abs_tol=0.05) -+ and math.isclose(s.position[0], expected_approach_x, abs_tol=0.05), -+ "%s Single Step did not stop at the approach endpoint X%.3f" -+ % (label, expected_approach_x), -+ timeout=20.0, -+ ) -+ -+ stepped_x = s.position[0] -+ stepped_z = s.position[2] -+ time.sleep(0.25) -+ s.poll() -+ if ( -+ not math.isclose(s.position[0], stepped_x, abs_tol=0.001) -+ or not math.isclose(s.position[2], stepped_z, abs_tol=0.001) -+ ): -+ fail("%s advanced into its synchronized cut" % label) -+ -+ -+def step_g76_thread_and_clearance(expected_clear_x, label="G76"): -+ c.auto(linuxcnc.AUTO_STEP) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.task_paused -+ and abs(s.current_vel) < 0.001 -+ and s.position[2] <= -4.90 -+ and math.isclose(s.position[0], expected_clear_x, abs_tol=0.05), -+ "%s Single Step did not finish the thread and clearance at X%.3f" -+ % (label, expected_clear_x), -+ timeout=20.0, -+ ) -+ -+ stepped_x = s.position[0] -+ stepped_z = s.position[2] -+ time.sleep(0.25) -+ s.poll() -+ if ( -+ not math.isclose(s.position[0], stepped_x, abs_tol=0.001) -+ or not math.isclose(s.position[2], stepped_z, abs_tol=0.001) -+ ): -+ fail("%s advanced into another pass after the thread Step" % label) -+ -+ -+def run_g76_single_step_program(program, expected_steps, label): -+ c.mode(linuxcnc.MODE_MDI) -+ wait_complete("G76 Single Step setup did not enter MDI") -+ c.mdi("G21 G18 G90 G0 X10 Z0") -+ wait_complete("G76 Single Step setup did not reach X10 Z0") -+ c.spindle(linuxcnc.SPINDLE_FORWARD, 60.0, 0) -+ wait_complete("G76 Single Step setup did not start the spindle") -+ -+ open_auto_program(program) -+ -+ # LinuxCNC's first AUTO_STEP from IDLE primes the program in PAUSED state. -+ c.auto(linuxcnc.AUTO_STEP) -+ wait_for( -+ lambda: s.interp_state == linuxcnc.INTERP_PAUSED and s.task_paused, -+ "G76 Single Step did not prime the program", -+ ) -+ -+ for expected_approach, expected_clearance in expected_steps: -+ step_g76_approach(expected_approach, label) -+ step_g76_thread_and_clearance(expected_clearance, label) -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(20.0, expected_z=-5.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_g76_single_step_test(): -+ run_g76_single_step_program( -+ "g76-step.ngc", ((10.4, 10.4), (10.2, 10.2), (10.0, 10.0)), -+ "cylindrical G76", -+ ) -+ -+ -+def run_tapered_g76_single_step_test(): -+ run_g76_single_step_program( -+ "g76-tapered-step.ngc", -+ ((10.4, 8.4), (10.2, 8.2), (10.0, 8.0)), -+ "tapered-drive G76", -+ ) -+ -+ -+def run_inflight_g76_single_step_test(): -+ open_auto_program("g76.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.queue > 3 -+ and s.position[0] < 9.5 -+ and s.position[2] < -0.5 -+ and s.position[2] > -4.5, -+ "G76 did not prequeue later passes during its first cut", -+ timeout=15.0, -+ ) -+ -+ c.auto(linuxcnc.AUTO_STEP) -+ wait_for( -+ lambda: s.single_stepping and not s.task_paused and not s.paused, -+ "in-flight G76 Single Step did not remain unpaused while armed", -+ ) -+ wait_for( -+ lambda: s.task_paused -+ and s.paused -+ and abs(s.current_vel) < 0.001 -+ and s.position[2] <= -4.90 -+ and math.isclose(s.position[0], 10.4, abs_tol=0.01), -+ "in-flight G76 Single Step did not finish the active thread and clearance", -+ timeout=20.0, -+ ) -+ -+ stepped_x = s.position[0] -+ stepped_z = s.position[2] -+ time.sleep(0.25) -+ s.poll() -+ if ( -+ not math.isclose(s.position[0], stepped_x, abs_tol=0.001) -+ or not math.isclose(s.position[2], stepped_z, abs_tol=0.001) -+ ): -+ fail("in-flight G76 Single Step advanced into the next approach") -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(20.0, expected_z=-5.0, timeout=20.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_g76_exit_taper_stop_test(program, expected_clear_x, label): -+ open_auto_program(program) -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+ wait_for( -+ lambda: s.position[2] < -0.5 -+ and s.position[2] > -3.5 -+ and s.position[0] < 9.5, -+ "%s did not enter its first synchronized pass" % label, -+ timeout=15.0, -+ ) -+ c.program_stop() -+ wait_complete("%s Stop command did not complete" % label) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "%s did not reach STOPPED" % label, -+ timeout=15.0, -+ ) -+ -+ if s.position[2] > -4.90 or not math.isclose( -+ s.position[0], expected_clear_x, abs_tol=0.05 -+ ): -+ fail( -+ "%s did not complete its synchronized exit taper and clearance: " -+ "X=%.6f Z=%.6f" % (label, s.position[0], s.position[2]) -+ ) -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(20.0, expected_z=-5.0) -+ assert_outputs_stopped_after_program() -+ -+ -+def run_cylindrical_g76_exit_taper_stop_test(): -+ run_g76_exit_taper_stop_test( -+ "g76-exit-taper.ngc", 10.4, "cylindrical exit-taper G76" -+ ) -+ -+ -+def run_tapered_g76_exit_taper_stop_test(): -+ run_g76_exit_taper_stop_test( -+ "g76-tapered-exit-taper.ngc", 8.4, "tapered-drive exit-taper G76" -+ ) -+ -+ -+def run_g76_cut_retract_handoff_stress_test(): -+ # At S60 and P1 the synchronized feed is 1 mm/s. Even the closest -+ # trigger remains 20 task cycles before the endpoint, so Python polling -+ # reliably submits Stop while the cut is active instead of after retract. -+ thresholds = (-0.92, -0.94, -0.96, -0.97, -0.98) * 2 -+ -+ for attempt, threshold in enumerate(thresholds, 1): -+ open_auto_program("g76-handoff.ngc") -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ wait_for( -+ lambda: s.position[2] <= threshold and s.position[0] < 9.5, -+ "G76 handoff attempt %d missed the cut/retract boundary" % attempt, -+ timeout=10.0, -+ poll_interval=0.001, -+ ) -+ -+ c.program_stop() -+ wait_complete( -+ "G76 handoff attempt %d Stop command did not complete" % attempt -+ ) -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, -+ "G76 handoff attempt %d did not reach STOPPED" % attempt, -+ timeout=10.0, -+ poll_interval=0.001, -+ ) -+ -+ if s.position[2] > -0.99 or not math.isclose( -+ s.position[0], 10.01, abs_tol=0.01 -+ ): -+ fail( -+ "G76 handoff attempt %d missed complete clearance: " -+ "X=%.6f Z=%.6f" % (attempt, s.position[0], s.position[2]) -+ ) -+ -+ c.auto(linuxcnc.AUTO_RESUME) -+ wait_for_program_complete(20.0, expected_z=-1.0, timeout=10.0) -+ assert_outputs_stopped_after_program() -+ -+ - def run_queued_threading_stop_resume_test(): - hal.set_p("spindle.0.at-speed", "false") - open_auto_program("thread.ngc") -@@ -748,14 +1138,24 @@ SCENARIOS = { - "idle-rejected": run_idle_program_stop_rejected_test, - "ordinary": run_ordinary_stop_resume_test, - "single-step": run_stop_single_step_test, -+ "inflight-single-step": run_inflight_single_step_test, - "rapid-no-atspeed": run_rapid_resume_without_at_speed_test, - "paused-resume": lambda: run_stop_while_program_paused_test(False), - "paused-run": lambda: run_stop_while_program_paused_test(True), - "abort-empty": run_abort_from_empty_stopped_queue_test, - "queued-g33": run_queued_threading_stop_resume_test, - "g33": run_threading_stop_resume_test, -+ "g33-no-following-rapid": run_g33_does_not_execute_following_rapid_test, - "fperrev": run_fperrev_stop_resume_test, - "g76": run_g76_stop_resume_test, -+ "g76-waiting-index": run_g76_stop_while_waiting_for_index_test, -+ "g76-tapered": run_tapered_g76_stop_resume_test, -+ "g76-single-step": run_g76_single_step_test, -+ "g76-tapered-single-step": run_tapered_g76_single_step_test, -+ "g76-inflight-single-step": run_inflight_g76_single_step_test, -+ "g76-exit-taper": run_cylindrical_g76_exit_taper_stop_test, -+ "g76-tapered-exit-taper": run_tapered_g76_exit_taper_stop_test, -+ "g76-handoff-stress": run_g76_cut_retract_handoff_stress_test, - "rigid-tap": run_rigid_tap_stop_resume_test, - "orientation": run_spindle_orientation_stop_test, - "dwell": run_dwell_stop_resume_test, -diff --git a/tests/resumable-stop/test.ini b/tests/resumable-stop/test.ini -index b73c0956b5..ef31f9a636 100644 ---- a/tests/resumable-stop/test.ini -+++ b/tests/resumable-stop/test.ini -@@ -29,6 +29,7 @@ SPINDLES = 2 - LINEAR_UNITS = mm - ANGULAR_UNITS = degree - PLANNER_TYPE = 1 -+ARC_BLEND_ENABLE = 1 - DEFAULT_LINEAR_VELOCITY = 10 - MAX_LINEAR_VELOCITY = 50 - MAX_LINEAR_JERK = 5000 -diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh -index 7a9a863436..20e0d14d78 100755 ---- a/tests/resumable-stop/test.sh -+++ b/tests/resumable-stop/test.sh -@@ -7,23 +7,38 @@ if nm -D -u "$EMC2_HOME/rtlib/motmod.so" | grep -q '[[:space:]]tpStop$'; then - exit 1 - fi - -+if nm -D -u "$EMC2_HOME/rtlib/motmod.so" | grep -q '[[:space:]]tpStep$'; then -+ echo "motmod unexpectedly requires the nonstandard tpStep symbol" >&2 -+ exit 1 -+fi -+ - scenarios=( - idle-rejected - ordinary - single-step -+ inflight-single-step - rapid-no-atspeed - paused-resume - paused-run - abort-empty - queued-g33 - g33 -+ g33-no-following-rapid - fperrev - g76 -+ g76-waiting-index -+ g76-tapered - rigid-tap - orientation - dwell - multi-spindle - css -+ g76-single-step -+ g76-tapered-single-step -+ g76-inflight-single-step -+ g76-exit-taper -+ g76-tapered-exit-taper -+ g76-handoff-stress - ) - - scenario_log=$(mktemp) diff --git a/linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch b/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch similarity index 72% rename from linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch rename to linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch index 8651f323..eef8da40 100644 --- a/linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch +++ b/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch @@ -1,31 +1,33 @@ From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Sun, 23 Aug 2026 22:34:37 +0200 -Subject: [PATCH] rs274: add recording canon preview backend +Subject: [PATCH] rs274: support the native G-code preview +The native server records previews with its own canon implementation. Two +things it needs have to live in LinuxCNC. The interpreter reports cutter +compensation being switched on and off through the canon calls that already +exist for it, so a recording keeps that state. tool_mmap_user() is safe to +call from several threads and returns early for an existing mapping; it +keeps upstream's record of the mapping descriptor (8c8e048). --- - src/emc/rs274ngc/interp_convert.cc | 6 + - src/emc/rs274ngc/recordingcanon.cc | 626 +++++++++++++++++++ - src/emc/rs274ngc/recordingcanon.hh | 147 +++++ - src/emc/tooldata/tooldata_mmap.cc | 5 + + src/emc/rs274ngc/interp_convert.cc | 6 ++ + src/emc/tooldata/tooldata_mmap.cc | 4 + tests/ccomp/lathe-comp/expected | 4 + tests/ccomp/mill-g90g91g92/expected | 2 + tests/ccomp/mill-line-arc-entry/expected | 2 + - tests/ccomp/mill-zchanges/expected | 20 + + tests/ccomp/mill-zchanges/expected | 20 ++++ tests/interp/cam-nisley/expected | 2 + - tests/interp/crazy-paths/expected | 100 +++ + tests/interp/crazy-paths/expected | 100 +++++++++++++++++++ tests/interp/g71-endless-loop_2/expected | 2 + - tests/interp/inside-corners/expected | 12 + - tests/interp/inverse-time-with-comp/expected | 6 + - 13 files changed, 934 insertions(+) - create mode 100644 src/emc/rs274ngc/recordingcanon.cc - create mode 100644 src/emc/rs274ngc/recordingcanon.hh + tests/interp/inside-corners/expected | 12 +++ + tests/interp/inverse-time-with-comp/expected | 6 ++ + 11 files changed, 160 insertions(+) diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 33a35bda2e..e0c95f83cb 100644 +index 663668a..a823ac5 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -2495,6 +2495,7 @@ Called by: convert_cutter_compensation +@@ -2528,6 +2528,7 @@ Called by: convert_cutter_compensation int Interp::convert_cutter_compensation_off(setup_pointer settings) //!< pointer to machine settings { @@ -33,7 +35,7 @@ index 33a35bda2e..e0c95f83cb 100644 #ifdef DEBUG_EMC enqueue_COMMENT("interpreter: cutter radius compensation off"); #endif -@@ -2511,6 +2512,9 @@ int Interp::convert_cutter_compensation_off(setup_pointer settings) //!< po +@@ -2544,6 +2545,9 @@ int Interp::convert_cutter_compensation_off(setup_pointer settings) //!< po } settings->cutter_comp_side = CUTTER_COMP::OFF; settings->cutter_comp_firstmove = true; @@ -43,7 +45,7 @@ index 33a35bda2e..e0c95f83cb 100644 return INTERP_OK; } -@@ -2619,6 +2623,8 @@ int Interp::convert_cutter_compensation_on(CUTTER_COMP side, //!< side of pa +@@ -2652,6 +2656,8 @@ int Interp::convert_cutter_compensation_on(CUTTER_COMP side, //!< side of pa settings->cutter_comp_radius = radius; settings->cutter_comp_orientation = orientation; settings->cutter_comp_side = side; @@ -52,793 +54,8 @@ index 33a35bda2e..e0c95f83cb 100644 return INTERP_OK; } -diff --git a/src/emc/rs274ngc/recordingcanon.cc b/src/emc/rs274ngc/recordingcanon.cc -new file mode 100644 -index 0000000000..235da9b7ea ---- /dev/null -+++ b/src/emc/rs274ngc/recordingcanon.cc -@@ -0,0 +1,626 @@ -+#include "recordingcanon.hh" -+ -+#include -+#include -+#include -+#include -+ -+namespace recording = linuxcnc::recording; -+ -+int _task = 0; -+char _parameter_file_name[PARAMETER_FILE_NAME_LENGTH]{}; -+EmcPose tool_offset{}; -+USER_DEFINED_FUNCTION_TYPE USER_DEFINED_FUNCTION[USER_DEFINED_FUNCTION_NUM]{}; -+ -+namespace linuxcnc::recording { -+ -+struct Session::Impl { -+ std::vector events; -+ EmcPose position{}; -+ EmcPose probe_position{}; -+ CANON_UNITS units = CANON_UNITS_INCHES; -+ std::vector tools; -+ std::size_t max_events = 0; -+ std::size_t max_bytes = 0; -+ std::size_t recorded_bytes = 0; -+ std::size_t max_control_points = 0; -+ bool exceeded = false; -+ CANON_PLANE plane = CANON_PLANE::XY; -+ CANON_MOTION_MODE motion_mode = CANON_CONTINUOUS; -+ double motion_tolerance = 0.1; -+ double naivecam_tolerance = 0.1; -+ double feed_rate = 1.0; -+ double traverse_rate = 0.0; -+ double spindle_speed[EMCMOT_MAX_SPINDLES]{}; -+ CANON_DIRECTION spindle_direction[EMCMOT_MAX_SPINDLES]{}; -+ int selected_tool = 0; -+ int tool_slot = 0; -+ bool block_delete = false; -+ bool optional_stop = false; -+ bool flood = false; -+ bool mist = false; -+}; -+ -+namespace { -+ -+thread_local Session::Impl *active_session = nullptr; -+ -+Session::Impl &active() -+{ -+ assert(active_session && "recording canon call without an active Session"); -+ return *active_session; -+} -+ -+template -+std::size_t event_size(const T &) { return sizeof(T); } -+ -+std::size_t event_size(const NurbsG5Feed &event) -+{ -+ return sizeof(event) + event.control_points.size() * sizeof(NURBS_CONTROL_POINT); -+} -+ -+std::size_t event_size(const NurbsG6Feed &event) -+{ -+ return sizeof(event) + event.control_points.size() * sizeof(NURBS_G6_CONTROL_POINT); -+} -+ -+template -+void record(T &&event) -+{ -+ auto &state = active(); -+ const auto bytes = event_size(event); -+ if (state.events.size() >= state.max_events || -+ bytes > state.max_bytes - std::min(state.recorded_bytes, state.max_bytes)) { -+ state.exceeded = true; -+ return; -+ } -+ state.recorded_bytes += bytes; -+ state.events.emplace_back(std::forward(event)); -+} -+ -+EmcPose pose(double x, double y, double z, -+ double a, double b, double c, -+ double u, double v, double w) -+{ -+ EmcPose result{}; -+ result.tran.x = x; -+ result.tran.y = y; -+ result.tran.z = z; -+ result.a = a; -+ result.b = b; -+ result.c = c; -+ result.u = u; -+ result.v = v; -+ result.w = w; -+ return result; -+} -+ -+void scale_pose(EmcPose &value, double scale) -+{ -+ value.tran.x *= scale; -+ value.tran.y *= scale; -+ value.tran.z *= scale; -+ value.u *= scale; -+ value.v *= scale; -+ value.w *= scale; -+} -+ -+double millimetres_per_unit(CANON_UNITS units) -+{ -+ switch (units) { -+ case CANON_UNITS_INCHES: return 25.4; -+ case CANON_UNITS_MM: return 1.0; -+ case CANON_UNITS_CM: return 10.0; -+ } -+ return 1.0; -+} -+ -+void set_plane_end(EmcPose &position, CANON_PLANE plane, -+ double first, double second, double axis) -+{ -+ switch (plane) { -+ case CANON_PLANE::XY: -+ position.tran.x = first; -+ position.tran.y = second; -+ position.tran.z = axis; -+ break; -+ case CANON_PLANE::YZ: -+ position.tran.y = first; -+ position.tran.z = second; -+ position.tran.x = axis; -+ break; -+ case CANON_PLANE::XZ: -+ position.tran.z = first; -+ position.tran.x = second; -+ position.tran.y = axis; -+ break; -+ case CANON_PLANE::UV: -+ position.u = first; -+ position.v = second; -+ break; -+ case CANON_PLANE::VW: -+ position.v = first; -+ position.w = second; -+ break; -+ case CANON_PLANE::UW: -+ position.u = first; -+ position.w = second; -+ break; -+ } -+} -+ -+double orthogonal_axis(const EmcPose &position, CANON_PLANE plane) -+{ -+ switch (plane) { -+ case CANON_PLANE::XY: return position.tran.z; -+ case CANON_PLANE::YZ: return position.tran.x; -+ case CANON_PLANE::XZ: return position.tran.y; -+ default: return 0.0; -+ } -+} -+ -+bool valid_spindle(int spindle) -+{ -+ return spindle >= 0 && spindle < EMCMOT_MAX_SPINDLES; -+} -+ -+} // namespace -+ -+Session::Session(SessionConfig config) : impl(std::make_unique()) -+{ -+ assert(!active_session && "recording canon Sessions may not overlap"); -+ active_session = impl.get(); -+ impl->units = config.units; -+ impl->tools = std::move(config.tools); -+ impl->max_events = config.max_events; -+ impl->max_bytes = config.max_bytes; -+ impl->max_control_points = config.max_control_points; -+ tool_offset = {}; -+} -+ -+bool Session::limit_exceeded() const { return impl->exceeded; } -+ -+Session::~Session() -+{ -+ assert(active_session == impl.get()); -+ active_session = nullptr; -+} -+ -+std::vector Session::take_events() -+{ -+ std::vector result; -+ result.swap(impl->events); -+ impl->recorded_bytes = 0; -+ return result; -+} -+ -+} // namespace linuxcnc::recording -+ -+void INIT_CANON() {} -+ -+void STRAIGHT_TRAVERSE(int line_number, -+ double x, double y, double z, -+ double a, double b, double c, -+ double u, double v, double w) -+{ -+ auto &state = recording::active(); -+ state.position = recording::pose(x, y, z, a, b, c, u, v, w); -+ recording::record(recording::StraightTraverse{line_number, state.position}); -+} -+ -+void STRAIGHT_FEED(int line_number, -+ double x, double y, double z, -+ double a, double b, double c, -+ double u, double v, double w) -+{ -+ auto &state = recording::active(); -+ state.position = recording::pose(x, y, z, a, b, c, u, v, w); -+ recording::record(recording::StraightFeed{line_number, state.position}); -+} -+ -+void ARC_FEED(int line_number, -+ double first_end, double second_end, -+ double first_axis, double second_axis, int rotation, -+ double axis_end_point, -+ double a, double b, double c, -+ double u, double v, double w) -+{ -+ auto &state = recording::active(); -+ recording::record(recording::ArcFeed{ -+ line_number, first_end, second_end, first_axis, second_axis, -+ rotation, axis_end_point, a, b, c, u, v, w, state.plane}); -+ recording::set_plane_end(state.position, state.plane, -+ first_end, second_end, axis_end_point); -+ state.position.a = a; -+ state.position.b = b; -+ state.position.c = c; -+ state.position.u = u; -+ state.position.v = v; -+ state.position.w = w; -+} -+ -+void STRAIGHT_PROBE(int line_number, -+ double x, double y, double z, -+ double a, double b, double c, -+ double u, double v, double w, -+ unsigned char probe_type) -+{ -+ auto &state = recording::active(); -+ state.probe_position = recording::pose(x, y, z, a, b, c, u, v, w); -+ state.position = state.probe_position; -+ recording::record(recording::StraightProbe{ -+ line_number, state.position, probe_type}); -+} -+ -+void RIGID_TAP(int line_number, double x, double y, double z, double scale) -+{ -+ auto &state = recording::active(); -+ recording::record(recording::RigidTap{line_number, x, y, z, scale}); -+ state.position.tran.x = x; -+ state.position.tran.y = y; -+} -+ -+void DWELL(double seconds) -+{ -+ recording::record(recording::Dwell{seconds}); -+} -+ -+void NURBS_G5_FEED(int line_number, -+ const std::vector &control_points, -+ unsigned int order, CANON_PLANE plane) -+{ -+ auto &state = recording::active(); -+ if (control_points.size() > state.max_control_points) { -+ state.exceeded = true; -+ return; -+ } -+ recording::record(recording::NurbsG5Feed{ -+ line_number, control_points, order, plane}); -+ if (!control_points.empty()) { -+ const auto &last = control_points.back(); -+ recording::set_plane_end(state.position, plane, -+ last.NURBS_X, last.NURBS_Y, -+ recording::orthogonal_axis(state.position, plane)); -+ } -+} -+ -+void NURBS_G6_FEED(int line_number, -+ const std::vector &control_points, -+ unsigned int order, double feed_rate, int l_option, -+ CANON_PLANE plane) -+{ -+ auto &state = recording::active(); -+ if (control_points.size() > state.max_control_points) { -+ state.exceeded = true; -+ return; -+ } -+ recording::record(recording::NurbsG6Feed{ -+ line_number, control_points, order, feed_rate, l_option, plane}); -+ if (control_points.size() > order) { -+ const auto &last = control_points.back(); -+ recording::set_plane_end(state.position, plane, -+ last.NURBS_X, last.NURBS_Y, -+ recording::orthogonal_axis(state.position, plane)); -+ } -+} -+ -+void USE_LENGTH_UNITS(CANON_UNITS units) -+{ -+ auto &state = recording::active(); -+ if (state.units != units) { -+ const double scale = recording::millimetres_per_unit(state.units) / -+ recording::millimetres_per_unit(units); -+ recording::scale_pose(state.position, scale); -+ recording::scale_pose(state.probe_position, scale); -+ recording::scale_pose(tool_offset, scale); -+ state.units = units; -+ } -+ recording::record(recording::LengthUnits{units}); -+} -+ -+void SELECT_PLANE(CANON_PLANE plane) -+{ -+ auto &state = recording::active(); -+ state.plane = plane; -+ recording::record(recording::Plane{plane}); -+} -+ -+void SET_G5X_OFFSET(int index, -+ double x, double y, double z, -+ double a, double b, double c, -+ double u, double v, double w) -+{ -+ recording::record(recording::G5xOffset{ -+ index, recording::pose(x, y, z, a, b, c, u, v, w)}); -+} -+ -+void SET_G92_OFFSET(double x, double y, double z, -+ double a, double b, double c, -+ double u, double v, double w) -+{ -+ recording::record(recording::G92Offset{ -+ recording::pose(x, y, z, a, b, c, u, v, w)}); -+} -+ -+void SET_XY_ROTATION(double degrees) -+{ -+ recording::record(recording::XyRotation{degrees}); -+} -+ -+void CANON_UPDATE_END_POINT(double x, double y, double z, -+ double a, double b, double c, -+ double u, double v, double w) -+{ -+ recording::active().position = recording::pose(x, y, z, a, b, c, u, v, w); -+} -+ -+void SET_FEED_RATE(double rate) -+{ -+ auto &state = recording::active(); -+ state.feed_rate = rate; -+ recording::record(recording::FeedRate{rate}); -+} -+ -+void SET_TRAVERSE_RATE(double rate) { recording::active().traverse_rate = rate; } -+void SET_FEED_REFERENCE(CANON_FEED_REFERENCE) {} -+void SET_FEED_MODE(int, int) {} -+ -+void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode, double tolerance) -+{ -+ auto &state = recording::active(); -+ state.motion_mode = mode; -+ state.motion_tolerance = tolerance; -+} -+ -+void SET_NAIVECAM_TOLERANCE(double tolerance) -+{ -+ recording::active().naivecam_tolerance = tolerance; -+} -+ -+void SET_CUTTER_RADIUS_COMPENSATION(double) {} -+void START_CUTTER_RADIUS_COMPENSATION(int side) -+{ -+ recording::record(recording::CutterCompensation{ -+ static_cast(side)}); -+} -+ -+void STOP_CUTTER_RADIUS_COMPENSATION() -+{ -+ recording::record(recording::CutterCompensation{CANON_SIDE_OFF}); -+} -+void START_SPEED_FEED_SYNCH(int, double, bool) {} -+void STOP_SPEED_FEED_SYNCH() {} -+void STOP() {} -+ -+void SET_SPINDLE_MODE(int, double) {} -+void SPINDLE_RETRACT_TRAVERSE() {} -+void SPINDLE_RETRACT() {} -+void LOCK_SPINDLE_Z() {} -+void USE_SPINDLE_FORCE() {} -+void USE_NO_SPINDLE_FORCE() {} -+void ORIENT_SPINDLE(int, double, int) {} -+void WAIT_SPINDLE_ORIENT_COMPLETE(int, double) {} -+ -+void START_SPINDLE_CLOCKWISE(int spindle, int) -+{ -+ if (recording::valid_spindle(spindle)) -+ recording::active().spindle_direction[spindle] = CANON_CLOCKWISE; -+} -+ -+void START_SPINDLE_COUNTERCLOCKWISE(int spindle, int) -+{ -+ if (recording::valid_spindle(spindle)) -+ recording::active().spindle_direction[spindle] = CANON_COUNTERCLOCKWISE; -+} -+ -+void SET_SPINDLE_SPEED(int spindle, double speed) -+{ -+ if (recording::valid_spindle(spindle)) -+ recording::active().spindle_speed[spindle] = speed; -+} -+ -+void STOP_SPINDLE_TURNING(int spindle) -+{ -+ if (recording::valid_spindle(spindle)) -+ recording::active().spindle_direction[spindle] = CANON_STOPPED; -+} -+ -+void USE_TOOL_LENGTH_OFFSET(const EmcPose &offset) -+{ -+ tool_offset = offset; -+ recording::record(recording::ToolOffset{offset}); -+} -+ -+void SET_TOOL_TABLE_ENTRY(int, int, const EmcPose &, const EmcPose &, -+ double, double, double, int) {} -+ -+void SELECT_TOOL(int tool) { recording::active().selected_tool = tool; } -+ -+void CHANGE_TOOL() -+{ -+ auto &state = recording::active(); -+ state.tool_slot = state.selected_tool; -+ recording::record(recording::ToolChange{state.selected_tool}); -+} -+ -+void CHANGE_TOOL_NUMBER(int number) -+{ -+ auto &state = recording::active(); -+ state.tool_slot = number; -+ recording::record(recording::ToolChange{number}); -+} -+ -+void RELOAD_TOOLDATA() {} -+void CLAMP_AXIS(CANON_AXIS) {} -+void UNCLAMP_AXIS(CANON_AXIS) {} -+void COMMENT(const char *) {} -+void MESSAGE(char *) {} -+void LOG(char *) {} -+void LOGOPEN(char *) {} -+void LOGAPPEND(char *) {} -+void LOGCLOSE() {} -+void DISABLE_ADAPTIVE_FEED() {} -+void ENABLE_ADAPTIVE_FEED() {} -+void DISABLE_FEED_OVERRIDE() {} -+void ENABLE_FEED_OVERRIDE() {} -+void DISABLE_SPEED_OVERRIDE(int) {} -+void ENABLE_SPEED_OVERRIDE(int) {} -+void DISABLE_FEED_HOLD() {} -+void ENABLE_FEED_HOLD() {} -+void FLOOD_OFF() { recording::active().flood = false; } -+void FLOOD_ON() { recording::active().flood = true; } -+void MIST_OFF() { recording::active().mist = false; } -+void MIST_ON() { recording::active().mist = true; } -+void PALLET_SHUTTLE() {} -+void TURN_PROBE_OFF() {} -+void TURN_PROBE_ON() {} -+void NURB_KNOT_VECTOR() {} -+void NURB_CONTROL_POINT(int, double, double, double, double) {} -+void NURB_FEED(double, double) {} -+ -+void SET_BLOCK_DELETE(bool enabled) { recording::active().block_delete = enabled; } -+bool GET_BLOCK_DELETE() { return recording::active().block_delete; } -+void OPTIONAL_PROGRAM_STOP() {} -+void SET_OPTIONAL_PROGRAM_STOP(bool enabled) { recording::active().optional_stop = enabled; } -+bool GET_OPTIONAL_PROGRAM_STOP() { return recording::active().optional_stop; } -+void PROGRAM_END() {} -+void PROGRAM_STOP() {} -+void SET_MOTION_OUTPUT_BIT(int) {} -+void CLEAR_MOTION_OUTPUT_BIT(int) {} -+void SET_AUX_OUTPUT_BIT(int) {} -+void CLEAR_AUX_OUTPUT_BIT(int) {} -+void SET_MOTION_OUTPUT_VALUE(int, double) {} -+void SET_AUX_OUTPUT_VALUE(int, double) {} -+int WAIT(int, int, int, double) { return 0; } -+int UNLOCK_ROTARY(int, int) { return 0; } -+int LOCK_ROTARY(int, int) { return 0; } -+ -+double GET_EXTERNAL_ANGLE_UNIT_FACTOR() { return 1.0; } -+double GET_EXTERNAL_LENGTH_UNIT_FACTOR() { return 1.0; } -+double GET_EXTERNAL_LENGTH_UNITS() -+{ -+ return 1.0 / recording::millimetres_per_unit(recording::active().units); -+} -+double GET_EXTERNAL_ANGLE_UNITS() { return 1.0; } -+CANON_UNITS GET_EXTERNAL_LENGTH_UNIT_TYPE() { return recording::active().units; } -+double GET_EXTERNAL_FEED_RATE() { return recording::active().feed_rate; } -+double GET_EXTERNAL_TRAVERSE_RATE() { return recording::active().traverse_rate; } -+int GET_EXTERNAL_FLOOD() { return recording::active().flood; } -+int GET_EXTERNAL_MIST() { return recording::active().mist; } -+CANON_MOTION_MODE GET_EXTERNAL_MOTION_CONTROL_MODE() { return recording::active().motion_mode; } -+double GET_EXTERNAL_MOTION_CONTROL_TOLERANCE() { return recording::active().motion_tolerance; } -+double GET_EXTERNAL_MOTION_CONTROL_NAIVECAM_TOLERANCE() { return recording::active().naivecam_tolerance; } -+double GET_EXTERNAL_ORIGIN_X() { return 0.0; } -+double GET_EXTERNAL_ORIGIN_Y() { return 0.0; } -+double GET_EXTERNAL_ORIGIN_Z() { return 0.0; } -+double GET_EXTERNAL_ORIGIN_A() { return 0.0; } -+double GET_EXTERNAL_ORIGIN_B() { return 0.0; } -+double GET_EXTERNAL_ORIGIN_C() { return 0.0; } -+ -+void GET_EXTERNAL_PARAMETER_FILE_NAME(char *name, int max_size) -+{ -+ if (!name || max_size <= 0) return; -+ std::strncpy(name, _parameter_file_name, max_size - 1); -+ name[max_size - 1] = '\0'; -+} -+ -+void SET_PARAMETER_FILE_NAME(const char *name) -+{ -+ if (!name) return; -+ std::strncpy(_parameter_file_name, name, PARAMETER_FILE_NAME_LENGTH - 1); -+ _parameter_file_name[PARAMETER_FILE_NAME_LENGTH - 1] = '\0'; -+} -+ -+CANON_PLANE GET_EXTERNAL_PLANE() { return recording::active().plane; } -+#define RECORDING_POSITION_GETTER(axis, member) \ -+ double GET_EXTERNAL_POSITION_##axis() { return recording::active().position.member; } -+RECORDING_POSITION_GETTER(X, tran.x) -+RECORDING_POSITION_GETTER(Y, tran.y) -+RECORDING_POSITION_GETTER(Z, tran.z) -+RECORDING_POSITION_GETTER(A, a) -+RECORDING_POSITION_GETTER(B, b) -+RECORDING_POSITION_GETTER(C, c) -+RECORDING_POSITION_GETTER(U, u) -+RECORDING_POSITION_GETTER(V, v) -+RECORDING_POSITION_GETTER(W, w) -+#undef RECORDING_POSITION_GETTER -+ -+#define RECORDING_PROBE_GETTER(axis, member) \ -+ double GET_EXTERNAL_PROBE_POSITION_##axis() { return recording::active().probe_position.member; } -+RECORDING_PROBE_GETTER(X, tran.x) -+RECORDING_PROBE_GETTER(Y, tran.y) -+RECORDING_PROBE_GETTER(Z, tran.z) -+RECORDING_PROBE_GETTER(A, a) -+RECORDING_PROBE_GETTER(B, b) -+RECORDING_PROBE_GETTER(C, c) -+RECORDING_PROBE_GETTER(U, u) -+RECORDING_PROBE_GETTER(V, v) -+RECORDING_PROBE_GETTER(W, w) -+#undef RECORDING_PROBE_GETTER -+ -+double GET_EXTERNAL_PROBE_VALUE() { return 0.0; } -+int GET_EXTERNAL_PROBE_TRIPPED_VALUE() { return 0; } -+int GET_EXTERNAL_QUEUE_EMPTY() { return 1; } -+double GET_EXTERNAL_SPEED(int spindle) -+{ -+ return recording::valid_spindle(spindle) -+ ? recording::active().spindle_speed[spindle] : 0.0; -+} -+CANON_DIRECTION GET_EXTERNAL_SPINDLE(int spindle) -+{ -+ return recording::valid_spindle(spindle) -+ ? recording::active().spindle_direction[spindle] : CANON_STOPPED; -+} -+ -+double GET_EXTERNAL_TOOL_LENGTH_XOFFSET() { return tool_offset.tran.x; } -+double GET_EXTERNAL_TOOL_LENGTH_YOFFSET() { return tool_offset.tran.y; } -+double GET_EXTERNAL_TOOL_LENGTH_ZOFFSET() { return tool_offset.tran.z; } -+double GET_EXTERNAL_TOOL_LENGTH_AOFFSET() { return tool_offset.a; } -+double GET_EXTERNAL_TOOL_LENGTH_BOFFSET() { return tool_offset.b; } -+double GET_EXTERNAL_TOOL_LENGTH_COFFSET() { return tool_offset.c; } -+double GET_EXTERNAL_TOOL_LENGTH_UOFFSET() { return tool_offset.u; } -+double GET_EXTERNAL_TOOL_LENGTH_VOFFSET() { return tool_offset.v; } -+double GET_EXTERNAL_TOOL_LENGTH_WOFFSET() { return tool_offset.w; } -+int GET_EXTERNAL_TOOL_SLOT() { return recording::active().tool_slot; } -+int GET_EXTERNAL_SELECTED_TOOL_SLOT() { return recording::active().selected_tool; } -+ -+CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int pocket) -+{ -+ auto &state = recording::active(); -+ if (pocket >= 0 && static_cast(pocket) < state.tools.size()) -+ return state.tools[pocket]; -+ CANON_TOOL_TABLE result{}; -+ result.pocketno = -1; -+ result.toolno = -1; -+ return result; -+} -+ -+int GET_EXTERNAL_TC_FAULT() { return 0; } -+int GET_EXTERNAL_TC_REASON() { return 0; } -+int GET_EXTERNAL_FEED_OVERRIDE_ENABLE() { return 1; } -+int GET_EXTERNAL_SPINDLE_OVERRIDE_ENABLE(int) { return 1; } -+int GET_EXTERNAL_ADAPTIVE_FEED_ENABLE() { return 0; } -+int GET_EXTERNAL_FEED_HOLD_ENABLE() { return 1; } -+int GET_EXTERNAL_DIGITAL_INPUT(int, int default_value) { return default_value; } -+double GET_EXTERNAL_ANALOG_INPUT(int, double default_value) { return default_value; } -+int GET_EXTERNAL_AXIS_MASK() { return 7; } -+ -+int USER_DEFINED_FUNCTION_ADD(USER_DEFINED_FUNCTION_TYPE function, int index) -+{ -+ if (index < 0 || index >= USER_DEFINED_FUNCTION_NUM) return -1; -+ USER_DEFINED_FUNCTION[index] = function; -+ return 0; -+} -+ -+void FINISH() {} -+void START_G76_PASS() {} -+void FINISH_G76_APPROACH() {} -+void START_G76_CUT() {} -+void START_G76_CLEARANCE() {} -+void FINISH_G76_PASS(int) {} -+void ON_RESET() {} -+void CANON_ERROR(const char *, ...) {} -+int GET_EXTERNAL_OFFSET_APPLIED() { return 0; } -+EmcPose GET_EXTERNAL_OFFSETS() { return {}; } -+void UPDATE_TAG(const StateTag &) {} -+void INTERP_ABORT(int, const char *) {} -diff --git a/src/emc/rs274ngc/recordingcanon.hh b/src/emc/rs274ngc/recordingcanon.hh -new file mode 100644 -index 0000000000..dca1242649 ---- /dev/null -+++ b/src/emc/rs274ngc/recordingcanon.hh -@@ -0,0 +1,147 @@ -+#ifndef RECORDING_CANON_HH -+#define RECORDING_CANON_HH -+ -+#include "canon.hh" -+ -+#include -+#include -+#include -+ -+namespace linuxcnc::recording { -+ -+struct SessionConfig { -+ CANON_UNITS units = CANON_UNITS_INCHES; -+ std::vector tools; -+ std::size_t max_events = 100000; -+ std::size_t max_bytes = 8 * 1024 * 1024; -+ std::size_t max_control_points = 10000; -+}; -+ -+struct StraightTraverse { -+ int line_number; -+ EmcPose end; -+}; -+ -+struct StraightFeed { -+ int line_number; -+ EmcPose end; -+}; -+ -+struct ArcFeed { -+ int line_number; -+ double first_end; -+ double second_end; -+ double first_axis; -+ double second_axis; -+ int rotation; -+ double axis_end_point; -+ double a; -+ double b; -+ double c; -+ double u; -+ double v; -+ double w; -+ CANON_PLANE plane; -+}; -+ -+struct StraightProbe { -+ int line_number; -+ EmcPose end; -+ unsigned char probe_type; -+}; -+ -+struct RigidTap { -+ int line_number; -+ double x; -+ double y; -+ double z; -+ double scale; -+}; -+ -+struct Dwell { -+ double seconds; -+}; -+ -+struct NurbsG5Feed { -+ int line_number; -+ std::vector control_points; -+ unsigned int order; -+ CANON_PLANE plane; -+}; -+ -+struct NurbsG6Feed { -+ int line_number; -+ std::vector control_points; -+ unsigned int order; -+ double feed_rate; -+ int l_option; -+ CANON_PLANE plane; -+}; -+ -+struct LengthUnits { -+ CANON_UNITS units; -+}; -+ -+struct Plane { -+ CANON_PLANE plane; -+}; -+ -+struct G5xOffset { -+ int index; -+ EmcPose offset; -+}; -+ -+struct G92Offset { -+ EmcPose offset; -+}; -+ -+struct XyRotation { -+ double degrees; -+}; -+ -+struct FeedRate { -+ double rate; -+}; -+ -+struct CutterCompensation { -+ CANON_SIDE side; -+}; -+ -+struct ToolOffset { -+ EmcPose offset; -+}; -+ -+struct ToolChange { -+ int tool_number; -+}; -+ -+using Event = std::variant; -+ -+// A Session selects this canon implementation for one interpreter run and -+// owns the resulting event stream. Canon calls without an active Session are -+// programming errors; this keeps the invariant in one place instead of adding -+// a nullable callback check to every motion function. -+class Session { -+public: -+ struct Impl; -+ -+ explicit Session(SessionConfig config = {}); -+ ~Session(); -+ -+ Session(const Session &) = delete; -+ Session &operator=(const Session &) = delete; -+ -+ std::vector take_events(); -+ bool limit_exceeded() const; -+ -+private: -+ std::unique_ptr impl; -+}; -+ -+} // namespace linuxcnc::recording -+ -+#endif diff --git a/src/emc/tooldata/tooldata_mmap.cc b/src/emc/tooldata/tooldata_mmap.cc -index f9ad3cb7da..45d0c2e7c2 100644 +index 7ba07b4..d13d877 100644 --- a/src/emc/tooldata/tooldata_mmap.cc +++ b/src/emc/tooldata/tooldata_mmap.cc @@ -23,6 +23,7 @@ @@ -849,7 +66,7 @@ index f9ad3cb7da..45d0c2e7c2 100644 #include "config.h" #include #include "tooldata.hh" -@@ -167,6 +168,9 @@ int tool_mmap_creator(EMC_TOOL_STAT const * ptr,int random_toolchanger) +@@ -185,6 +186,9 @@ int tool_mmap_creator(EMC_TOOL_STAT const * ptr,int random_toolchanger) //typ: milltask, guis (emcmodule,emcsh,...), halui int tool_mmap_user() { @@ -859,16 +76,8 @@ index f9ad3cb7da..45d0c2e7c2 100644 int fd = open(tool_mmap_fname(), TOOL_MMAP_USER_OPEN_FLAGS, TOOL_MMAP_MODE); -@@ -191,6 +195,7 @@ int tool_mmap_user() - perror("tool_mmap_user(): mmap fail"); - exit(EXIT_FAILURE); - } -+ close(fd); - return 0; - } //tool_mmap_user() - diff --git a/tests/ccomp/lathe-comp/expected b/tests/ccomp/lathe-comp/expected -index bba4efd501..5b35a2dc62 100644 +index bba4efd..5b35a2d 100644 --- a/tests/ccomp/lathe-comp/expected +++ b/tests/ccomp/lathe-comp/expected @@ -30,6 +30,7 @@ @@ -904,7 +113,7 @@ index bba4efd501..5b35a2dc62 100644 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) N..... SELECT_TOOL(0) diff --git a/tests/ccomp/mill-g90g91g92/expected b/tests/ccomp/mill-g90g91g92/expected -index 7327c18c64..e6d7cf04c0 100644 +index 7327c18..e6d7cf0 100644 --- a/tests/ccomp/mill-g90g91g92/expected +++ b/tests/ccomp/mill-g90g91g92/expected @@ -24,6 +24,7 @@ @@ -924,7 +133,7 @@ index 7327c18c64..e6d7cf04c0 100644 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) N..... SET_XY_ROTATION(0.0000) diff --git a/tests/ccomp/mill-line-arc-entry/expected b/tests/ccomp/mill-line-arc-entry/expected -index ea4339f8cb..40dc7a995b 100644 +index ea4339f..40dc7a9 100644 --- a/tests/ccomp/mill-line-arc-entry/expected +++ b/tests/ccomp/mill-line-arc-entry/expected @@ -27,6 +27,7 @@ @@ -944,7 +153,7 @@ index ea4339f8cb..40dc7a995b 100644 N..... SET_XY_ROTATION(0.0000) N..... SET_FEED_MODE(0, 0) diff --git a/tests/ccomp/mill-zchanges/expected b/tests/ccomp/mill-zchanges/expected -index 3cfeabcc65..58f0c3c7f2 100644 +index 3cfeabc..58f0c3c 100644 --- a/tests/ccomp/mill-zchanges/expected +++ b/tests/ccomp/mill-zchanges/expected @@ -11,42 +11,52 @@ @@ -1058,7 +267,7 @@ index 3cfeabcc65..58f0c3c7f2 100644 N..... STRAIGHT_FEED(1.2500, -0.2500, 0.2500, 0.0000, 0.0000, 0.0000) N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) diff --git a/tests/interp/cam-nisley/expected b/tests/interp/cam-nisley/expected -index 6f3aab576f..4a85d26ac5 100644 +index 6f3aab5..4a85d26 100644 --- a/tests/interp/cam-nisley/expected +++ b/tests/interp/cam-nisley/expected @@ -69,6 +69,7 @@ @@ -1078,7 +287,7 @@ index 6f3aab576f..4a85d26ac5 100644 N..... STRAIGHT_TRAVERSE(75.0000, 0.0000, 75.0000, 0.0000, 0.0000, 0.0000) N..... MESSAGE("Done!") diff --git a/tests/interp/crazy-paths/expected b/tests/interp/crazy-paths/expected -index c3b6e9a2dc..575ea1a49e 100644 +index c3b6e9a..575ea1a 100644 --- a/tests/interp/crazy-paths/expected +++ b/tests/interp/crazy-paths/expected @@ -18,6 +18,7 @@ @@ -1802,7 +1011,7 @@ index c3b6e9a2dc..575ea1a49e 100644 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) N..... SET_XY_ROTATION(0.0000) diff --git a/tests/interp/g71-endless-loop_2/expected b/tests/interp/g71-endless-loop_2/expected -index 6c42f3a6b1..a53d19afa2 100644 +index 6c42f3a..a53d19a 100644 --- a/tests/interp/g71-endless-loop_2/expected +++ b/tests/interp/g71-endless-loop_2/expected @@ -28,6 +28,7 @@ @@ -1822,7 +1031,7 @@ index 6c42f3a6b1..a53d19afa2 100644 N..... FLOOD_OFF() N..... STRAIGHT_TRAVERSE(12.5000, 0.0000, -25.0000, 0.0000, 0.0000, 0.0000) diff --git a/tests/interp/inside-corners/expected b/tests/interp/inside-corners/expected -index 0312994b1c..c37a26d5a2 100644 +index 0312994..c37a26d 100644 --- a/tests/interp/inside-corners/expected +++ b/tests/interp/inside-corners/expected @@ -26,6 +26,7 @@ @@ -1917,7 +1126,7 @@ index 0312994b1c..c37a26d5a2 100644 N..... STRAIGHT_FEED(0.0000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) diff --git a/tests/interp/inverse-time-with-comp/expected b/tests/interp/inverse-time-with-comp/expected -index e2193e7ee5..74ffad1c79 100644 +index e2193e7..74ffad1 100644 --- a/tests/interp/inverse-time-with-comp/expected +++ b/tests/interp/inverse-time-with-comp/expected @@ -7,6 +7,7 @@ diff --git a/linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch b/linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch index 00e7cd12..ebbad87b 100644 --- a/linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch +++ b/linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch @@ -6,23 +6,49 @@ Subject: [PATCH] motion: arm Single Step during active execution Forward AUTO_STEP to motion while an AUTO program is already running. The default trajectory planner latches the active source block, or the active G76 safe-approach or infeed-thread-clearance unit, and finishes that unit at an exact boundary before pausing. Keep later prequeued motion from starting, restore temporary exact boundaries when Step is canceled by Resume or Stop, and report single_stepping while an in-flight step remains armed. Cover ordinary multi-move blocks and an active G76 thread with later passes queued. + +Ported onto v2.10.0-pre2. The two in-flight scenarios, already present +in the earlier G76 Stop patch's test list, are added here with the +feature and its program. --- - src/emc/motion/command.c | 17 +++--- - src/emc/motion/control.c | 9 +-- - src/emc/task/emctaskmain.cc | 48 ++++++++-------- - src/emc/tp/tp.c | 80 ++++++++++++++++++++------ - src/emc/tp/tp_types.h | 6 +- - tests/resumable-stop/README | 10 +++- - tests/resumable-stop/checkresult | 2 +- - tests/resumable-stop/inflight-step.ngc | 7 +++ - 8 files changed, 125 insertions(+), 54 deletions(-) - create mode 100644 tests/resumable-stop/inflight-step.ngc + src/emc/motion/command.c | 27 +++-- + src/emc/motion/control.c | 9 +- + src/emc/task/emctaskmain.cc | 48 ++++---- + src/emc/tp/tc.c | 10 +- + src/emc/tp/tc_types.h | 3 + + src/emc/tp/tp.c | 224 +++++++++++++++++++++++++++++++++--- + src/emc/tp/tp_types.h | 5 +- + 7 files changed, 274 insertions(+), 52 deletions(-) diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index b6ad9c1504..c166af652b 100644 +index a8e8ae3..0347123 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -1269,26 +1269,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -592,6 +592,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + SET_JOINT_FAULT_FLAG(joint, 0); + } + emcmotStatus->paused = 0; ++ /* An armed Step would otherwise pause the planner again on the ++ next cycle and leave paused set after the abort. */ ++ emcmotStatus->stepping = 0; + /* Drop any pending at-speed barrier so it can't strand a later move. */ + emcmotStatus->atspeed_next_feed = 0; + // Clear pins on abort so tests see a clean state +@@ -1334,6 +1337,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + /* pause the motion */ + /* can happen at any time */ + rtapi_print_msg(RTAPI_MSG_DBG, "PAUSE"); ++ if (emcmotStatus->stepping && ++ emcmotInternal->coord_tp.stepping_to_motion_target) { ++ /* Pause overrides an armed Step: drop its target, so this is ++ an ordinary pause instead of re-arming the Step. */ ++ tpResume(&emcmotInternal->coord_tp); ++ emcmotStatus->stepping = 0; ++ } + tpPause(&emcmotInternal->coord_tp); + emcmotStatus->paused = 1; + break; +@@ -1381,26 +1391,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_STEP: @@ -60,10 +86,10 @@ index b6ad9c1504..c166af652b 100644 break; diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 160c2dcd2c..040e534653 100644 +index e347bf1..75a9f1c 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2225,14 +2225,15 @@ static void update_status(void) +@@ -2319,14 +2319,15 @@ static void update_status(void) if (emcmotStatus->stepping) { TP_STRUCT *tp = &emcmotInternal->coord_tp; @@ -84,10 +110,10 @@ index 160c2dcd2c..040e534653 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index beb6d565d6..e01ef50ce8 100644 +index 14f26b5..635418d 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -462,6 +462,7 @@ static int programStartLine = 0; // which line to run program from +@@ -503,6 +503,7 @@ static int programStartLine = 0; // which line to run program from int stepping = 0; int steppingWait = 0; static int steppedLine = 0; @@ -95,7 +121,7 @@ index beb6d565d6..e01ef50ce8 100644 /* * Pass groups delimit commands that are still owned by task. Motion that was * already queued before resumable Stop is stepped by TP to its marked G76 -@@ -477,6 +478,7 @@ void emcTaskResetSteppingState() +@@ -518,6 +519,7 @@ void emcTaskResetSteppingState() steppedLine = 0; currentPassGroup = 0; steppedPassGroup = 0; @@ -103,7 +129,7 @@ index beb6d565d6..e01ef50ce8 100644 } // Variables to handle MDI call interrupts -@@ -818,6 +820,22 @@ static void emcTaskStepInterpreter() +@@ -906,6 +908,22 @@ static void emcTaskStepInterpreter() emcStatus->task.task_paused = 1; } @@ -126,7 +152,7 @@ index beb6d565d6..e01ef50ce8 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1432,13 +1450,7 @@ static int emcTaskPlan(void) +@@ -1588,13 +1606,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -141,7 +167,7 @@ index beb6d565d6..e01ef50ce8 100644 break; // otherwise we can't handle it -@@ -1512,17 +1524,9 @@ static int emcTaskPlan(void) +@@ -1668,17 +1680,9 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -160,7 +186,7 @@ index beb6d565d6..e01ef50ce8 100644 break; // otherwise we can't handle it -@@ -1588,13 +1592,7 @@ static int emcTaskPlan(void) +@@ -1744,13 +1748,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -175,7 +201,7 @@ index beb6d565d6..e01ef50ce8 100644 break; // otherwise we can't handle it -@@ -3676,6 +3674,10 @@ int main(int argc, char *argv[]) +@@ -4124,6 +4122,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); @@ -186,36 +212,78 @@ index beb6d565d6..e01ef50ce8 100644 // On a motion enabled -> disabled edge (limit switch, amp fault, // following error, etc.) unhome joints marked VOLATILE_HOME. The estop // and machine-off paths already do their own unhome; this catches the +diff --git a/src/emc/tp/tc.c b/src/emc/tp/tc.c +index 68f2192..3a5089a 100644 +--- a/src/emc/tp/tc.c ++++ b/src/emc/tp/tc.c +@@ -556,7 +556,15 @@ int tcSetTermCond(TC_STRUCT *prev_tc, TC_STRUCT *tc, int term_cond) { + } + if (prev_tc) { + tp_debug_print("setting term condition %d on tc id %d, type %d\n", term_cond, prev_tc->id, prev_tc->motion_type); +- prev_tc->term_cond = term_cond; ++ if (prev_tc->step_saved) { ++ /* An armed Single Step holds this segment at an exact stop. ++ * Record the condition the queue now requires (for example no ++ * blend into a following G33) so cancelling the Step restores ++ * it, not the one saved before. */ ++ prev_tc->step_saved_term_cond = term_cond; ++ } else { ++ prev_tc->term_cond = term_cond; ++ } + } + return 0; + } +diff --git a/src/emc/tp/tc_types.h b/src/emc/tp/tc_types.h +index bd8ad13..5d6e0b4 100644 +--- a/src/emc/tp/tc_types.h ++++ b/src/emc/tp/tc_types.h +@@ -170,6 +170,9 @@ typedef struct { + int canon_motion_type; // this motion is due to which canon function? + int g76_pass_id; // internal G76 pass ownership, zero otherwise + int g76_pass_clearance; // 1: clearance retract, 2: approach endpoint ++ int step_saved; // Single Step changed term_cond/finalvel below ++ int step_saved_term_cond; ++ double step_saved_finalvel; + int term_cond; // gcode requests continuous feed at the end of + // this segment (g64 mode) + diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index 00a06f1a75..81d50e10d3 100644 +index a9dfacc..63c138c 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c -@@ -342,9 +342,9 @@ STATIC inline double tpGetRealFinalVel(TP_STRUCT const * const tp, +@@ -127,6 +127,8 @@ STATIC int tpUpdateCycle(TP_STRUCT * const tp, + STATIC int tpRunOptimization(TP_STRUCT * const tp); + + STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc, int inc_id); ++STATIC void tpOverrideStepSegment(TP_STRUCT * const tp, TC_STRUCT * const tc, ++ int term_cond, double finalvel); + + STATIC inline double tpGetMaxTargetVel(TP_STRUCT const * const tp, TC_STRUCT const * const tc); + +@@ -357,9 +359,9 @@ STATIC inline double tpGetRealFinalVel(TP_STRUCT const * const tp, * If the term_cond gets changed out from under us, detect this and force final velocity to zero */ - if ((emcmotStatus->stepping && !tp->stepping_to_pass_clearance) || + if ((emcmotStatus->stepping && !tp->stepping_to_motion_target) || - (tp->stopping && tc == tp->stop_tc) || + (tp->stop_pass_id && tc == tp->stop_tc) || - (tp->stepping_to_pass_clearance && tc == tp->step_tc) || + (tp->stepping_to_motion_target && tc == tp->step_tc) || tc->term_cond != TC_TERM_COND_TANGENT || tp->reverse_run) { return 0.0; } -@@ -504,7 +504,11 @@ int tpClear(TP_STRUCT * const tp) +@@ -497,7 +499,9 @@ int tpClear(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; - tp->stepping_to_pass_clearance = 0; + tp->step_motion_id = 0; + tp->stepping_to_motion_target = 0; -+ tp->step_target_term_cond = 0; -+ tp->step_target_finalvel = 0.0; + tp->step_target_overridden = 0; tp->reverse_run = 0; tp->synchronized = 0; tp->uu_per_rev = 0.0; -@@ -1598,7 +1602,7 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc +@@ -1595,7 +1599,7 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc tp->stop_pass_id); return TP_ERR_FAIL; } @@ -224,7 +292,7 @@ index 00a06f1a75..81d50e10d3 100644 tp->step_target_pending && tp->step_pass_id && !tp->step_tc && tc->g76_pass_id != tp->step_pass_id) { rtapi_print_msg(RTAPI_MSG_ERR, -@@ -1624,12 +1628,11 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc +@@ -1621,12 +1625,29 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc } } if (queued_tc && queued_tc->g76_pass_clearance && @@ -235,10 +303,28 @@ index 00a06f1a75..81d50e10d3 100644 tp->step_tc = queued_tc; } - ++ /* A Step armed on a position-synchronized run ends at the run's last ++ queued segment. When the run continues, move the exact stop to the ++ newly queued segment so the axis does not stop mid-run. */ ++ int queue_len = tcqLen(&tp->queue); ++ TC_STRUCT *before_queued = queue_len > 1 ? ++ tcqItem(&tp->queue, queue_len - 2) : 0; ++ if (inc_id && queued_tc && before_queued && ++ tp->stepping_to_motion_target && tp->step_target_pending && ++ !tp->step_pass_id && tp->step_tc == before_queued && ++ before_queued->synchronized == TC_SYNC_POSITION && ++ queued_tc->synchronized == TC_SYNC_POSITION && ++ before_queued->step_saved) { ++ before_queued->term_cond = before_queued->step_saved_term_cond; ++ before_queued->finalvel = before_queued->step_saved_finalvel; ++ before_queued->step_saved = 0; ++ tpOverrideStepSegment(tp, queued_tc, TC_TERM_COND_STOP, 0.0); ++ tp->step_tc = queued_tc; ++ } // Store end of current move as new final goal of TP // KLUDGE: endpoint is garbage for rigid tap since it's supposed to retract past the start point. if (tc->motion_type != TC_RIGIDTAP) { -@@ -3442,10 +3445,11 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, +@@ -3497,10 +3518,11 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, tp->stop_tc = 0; tp->stop_pass_id = 0; } @@ -251,7 +337,7 @@ index 00a06f1a75..81d50e10d3 100644 } //TODO make progress to match target? -@@ -4220,7 +4224,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4396,7 +4418,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -260,16 +346,21 @@ index 00a06f1a75..81d50e10d3 100644 tp->step_pass_id && !tp->step_tc) { tpHandleEmptyQueue(tp); return TP_ERR_WAITING; -@@ -4375,6 +4379,30 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) +@@ -4585,6 +4607,158 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) return tc ? tc->g76_pass_id : 0; } -+STATIC TC_STRUCT *tpFindSourceBlockTarget(TP_STRUCT * const tp, int motion_id) ++/* ++ * The last queued segment of the position-synchronized run at the head of the ++ * queue. Stopping between the moves of one run would leave the axis behind ++ * the turning spindle, so Step, like Stop, ends at the end of the run. ++ */ ++STATIC TC_STRUCT *tpFindSyncRunTarget(TP_STRUCT * const tp) +{ + TC_STRUCT *target = 0; + for (int i = 0; i < tcqLen(&tp->queue); ++i) { + TC_STRUCT *candidate = tcqItem(&tp->queue, i); -+ if (!candidate || candidate->id != motion_id) { ++ if (!candidate || candidate->synchronized != TC_SYNC_POSITION) { + break; + } + target = candidate; @@ -279,19 +370,142 @@ index 00a06f1a75..81d50e10d3 100644 + +STATIC void tpRestoreStepTarget(TP_STRUCT * const tp) +{ -+ if (tp->step_target_overridden && tp->step_target_pending && -+ tp->step_tc) { -+ tp->step_tc->term_cond = tp->step_target_term_cond; -+ tp->step_tc->finalvel = tp->step_target_finalvel; ++ if (tp->step_target_overridden) { ++ for (int i = 0; i < tcqLen(&tp->queue); ++i) { ++ TC_STRUCT *tc = tcqItem(&tp->queue, i); ++ if (tc && tc->step_saved) { ++ tc->term_cond = tc->step_saved_term_cond; ++ tc->finalvel = tc->step_saved_finalvel; ++ tc->step_saved = 0; ++ } ++ } + tpRunOptimization(tp); + } + tp->step_target_overridden = 0; +} ++ ++STATIC void tpOverrideStepSegment(TP_STRUCT * const tp, TC_STRUCT * const tc, ++ int term_cond, double finalvel) ++{ ++ if (!tc->step_saved) { ++ tc->step_saved = 1; ++ tc->step_saved_term_cond = tc->term_cond; ++ tc->step_saved_finalvel = tc->finalvel; ++ } ++ tc->term_cond = term_cond; ++ tc->finalvel = finalvel; ++ tp->step_target_overridden = 1; ++} ++ ++/* Fastest start from which tc can still slow to end_vel within its length. */ ++STATIC double tpStepMaxStartVel(TC_STRUCT const * const tc, double end_vel) ++{ ++ double acc = tcGetTangentialMaxAccel(tc); ++ double start_vel = pmSqrt(pmSq(end_vel) + 2.0 * acc * tc->target); ++ if (GET_TRAJ_PLANNER_TYPE() == 1) { ++ double jerk = fmin(tc->maxjerk, emcmotStatus->jerk); ++ double scurve_vel; ++ if (findSCurveMaxStartSpeed(tc->target, end_vel, acc, jerk, ++ &scurve_vel) == 1) { ++ start_vel = fmin(start_vel, scurve_vel); ++ } else { ++ start_vel = end_vel; ++ } ++ } ++ return start_vel; ++} ++ ++/* ++ * Queue index where a Single Step armed now stops: the end of the source ++ * block in progress or, when that end is closer than the distance needed to ++ * stop from the current speed within the acceleration (and, for S-curve, jerk) ++ * limits, the first later block end that is far enough. A block end the ++ * planner already brings to rest (an exact stop or the end of the queue) is ++ * always reachable. ++ */ ++STATIC int tpFindReachableStepTarget(TP_STRUCT * const tp) ++{ ++ int len = tcqLen(&tp->queue); ++ TC_STRUCT *head = tcqItem(&tp->queue, 0); ++ if (!head) { ++ return -1; ++ } ++ double vel = head->currentvel; ++ if (head->blending_next) { ++ TC_STRUCT *next = tcqItem(&tp->queue, 1); ++ if (next) { ++ vel += next->currentvel; ++ } ++ } ++ double dist = tcGetDistanceToGo(head, tp->reverse_run); ++ double acc = tcGetTangentialMaxAccel(head); ++ double jerk = fmin(head->maxjerk, emcmotStatus->jerk); ++ for (int i = 0; i < len; ++i) { ++ TC_STRUCT *tc = tcqItem(&tp->queue, i); ++ if (i > 0) { ++ // A segment already blending in has run part of its length. ++ dist += i == 1 && head->blending_next ? ++ tcGetDistanceToGo(tc, tp->reverse_run) : tc->target; ++ acc = fmin(acc, tcGetTangentialMaxAccel(tc)); ++ jerk = fmin(jerk, fmin(tc->maxjerk, emcmotStatus->jerk)); ++ } ++ TC_STRUCT *next = tcqItem(&tp->queue, i + 1); ++ if (next && next->id == tc->id) { ++ continue; ++ } ++ // The head's blend into the next segment is under way; an exact ++ // stop at the head's end can no longer be made. ++ if (i == 0 && next && head->blending_next) { ++ continue; ++ } ++ if (!next || tc->term_cond != TC_TERM_COND_TANGENT) { ++ return i; ++ } ++ double stop_dist = GET_TRAJ_PLANNER_TYPE() == 1 ? ++ stoppingDist(vel, head->currentacc, acc, jerk) : ++ pmSq(vel) / (2.0 * acc); ++ // Braking starts in the next servo cycle at the earliest. ++ stop_dist += vel * tp->cycleTime; ++ if (dist >= stop_dist) { ++ return i; ++ } ++ } ++ return len - 1; ++} ++ ++/* ++ * Make the chosen block end an exact stop, and lower the end speed of every ++ * segment before it so each can still slow down in time, as tpRunOptimization ++ * does for segments it queues. Returns the target segment. ++ */ ++STATIC TC_STRUCT *tpArmReachableStepTarget(TP_STRUCT * const tp) ++{ ++ int target = tpFindReachableStepTarget(tp); ++ if (target < 0) { ++ return 0; ++ } ++ TC_STRUCT *step_tc = tcqItem(&tp->queue, target); ++ tpOverrideStepSegment(tp, step_tc, TC_TERM_COND_STOP, 0.0); ++ for (int i = target - 1; i >= 0; --i) { ++ TC_STRUCT *tc = tcqItem(&tp->queue, i); ++ TC_STRUCT *next = tcqItem(&tp->queue, i + 1); ++ if (tc->term_cond != TC_TERM_COND_TANGENT) { ++ continue; ++ } ++ double next_end = next->term_cond == TC_TERM_COND_TANGENT ? ++ next->finalvel : 0.0; ++ double limit = tpStepMaxStartVel(next, next_end); ++ if (limit < tc->finalvel) { ++ tpOverrideStepSegment(tp, tc, tc->term_cond, limit); ++ } ++ } ++ return step_tc; ++} + int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4382,10 +4410,12 @@ int tpPause(TP_STRUCT * const tp) +@@ -4592,10 +4766,12 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -303,9 +517,9 @@ index 00a06f1a75..81d50e10d3 100644 + tp->step_motion_id = 0; + tp->stepping_to_motion_target = 0; TC_STRUCT *tc = tcqItem(&tp->queue, 0); - bool in_g76_cut_or_clearance = tc && tc->g76_pass_id && - ((tc->active && tc->synchronized == TC_SYNC_POSITION && -@@ -4418,7 +4448,7 @@ int tpPause(TP_STRUCT * const tp) + /* + * A G76 cut that has passed spindle index, or its explicitly marked +@@ -4642,7 +4818,7 @@ int tpPause(TP_STRUCT * const tp) tp->pausing = 1; } } else if (emcmotStatus->stepping && @@ -314,7 +528,7 @@ index 00a06f1a75..81d50e10d3 100644 /* * EMCMOT_STEP requests default-TP pass targeting through the existing * tpPause ABI. Alternate planners leave step_target_pending clear and -@@ -4427,15 +4457,25 @@ int tpPause(TP_STRUCT * const tp) +@@ -4651,15 +4827,27 @@ int tpPause(TP_STRUCT * const tp) int pass_id = tpGetQueuedG76PassId(tp); if (pass_id) { tp->step_pass_id = pass_id; @@ -330,114 +544,64 @@ index 00a06f1a75..81d50e10d3 100644 - tp->stepping_to_pass_clearance = 0; - tp->pausing = 1; + tp->step_motion_id = tc ? tc->id : 0; -+ tp->step_tc = tpFindSourceBlockTarget(tp, tp->step_motion_id); -+ tp->step_target_pending = tp->step_tc != 0; -+ if (tp->step_tc) { -+ /* Finalize the latched block as an exact runnable boundary. */ -+ tp->step_target_term_cond = tp->step_tc->term_cond; -+ tp->step_target_finalvel = tp->step_tc->finalvel; -+ tp->step_target_overridden = 1; -+ tp->step_tc->term_cond = TC_TERM_COND_STOP; -+ tp->step_tc->finalvel = 0.0; ++ if (tc && tc->synchronized == TC_SYNC_POSITION) { ++ /* A spindle-synchronized move cannot change speed; stop at ++ * the end of its synchronized run. */ ++ tp->step_tc = tpFindSyncRunTarget(tp); ++ if (tp->step_tc) { ++ tpOverrideStepSegment(tp, tp->step_tc, ++ TC_TERM_COND_STOP, 0.0); ++ } ++ } else { ++ tp->step_tc = tpArmReachableStepTarget(tp); + } ++ tp->step_target_pending = tp->step_tc != 0; + tp->pausing = !tp->step_target_pending; } } else { tp->pausing = 1; -@@ -4448,6 +4488,7 @@ int tpResume(TP_STRUCT * const tp) +@@ -4672,6 +4860,7 @@ int tpResume(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } + tpRestoreStepTarget(tp); tp->pausing = 0; tp->stopping = 0; - tp->stop_tc = 0; -@@ -4456,7 +4497,10 @@ int tpResume(TP_STRUCT * const tp) + tp->stop_sync_run = 0; +@@ -4681,7 +4870,8 @@ int tpResume(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; - tp->stepping_to_pass_clearance = 0; + tp->step_motion_id = 0; + tp->stepping_to_motion_target = 0; -+ tp->step_target_term_cond = 0; -+ tp->step_target_finalvel = 0.0; if (MOTION_ID_VALID(tp->spindle.waiting_for_index)) { emcmotStatus->spindle_status[ tp->spindle.spindle_num].spindle_index_enable = 1; -@@ -4476,7 +4520,11 @@ int tpAbort(TP_STRUCT * const tp) +@@ -4701,7 +4891,9 @@ int tpAbort(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; - tp->stepping_to_pass_clearance = 0; + tp->step_motion_id = 0; + tp->stepping_to_motion_target = 0; -+ tp->step_target_term_cond = 0; -+ tp->step_target_finalvel = 0.0; + tp->step_target_overridden = 0; tpPause(tp); tp->aborting = 1; } diff --git a/src/emc/tp/tp_types.h b/src/emc/tp/tp_types.h -index 15be0f3127..893a9df4c2 100644 +index 2963bcc..0d3f164 100644 --- a/src/emc/tp/tp_types.h +++ b/src/emc/tp/tp_types.h -@@ -147,7 +147,11 @@ typedef struct { +@@ -171,7 +171,10 @@ typedef struct { TC_STRUCT *step_tc; int step_target_pending; int step_pass_id; - int stepping_to_pass_clearance; + int step_motion_id; + int stepping_to_motion_target; -+ int step_target_term_cond; -+ double step_target_finalvel; ++ /* Single Step changed queued segments; their originals are in the TCs. */ + int step_target_overridden; } TP_STRUCT; -diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -index e845030ffb..72607e0da2 100644 ---- a/tests/resumable-stop/README -+++ b/tests/resumable-stop/README -@@ -13,11 +13,17 @@ requests across the cut/retract handoff, and a negative G33 test proving that - an unrelated following rapid is not executed. Single Step coverage enters the - first G76 pass directly and verifies every cylindrical and tapered safe - approach step followed by its combined infeed, synchronized-cut, and clearance --step. It also starts G76 in normal AUTO_RUN, stops after the first pass with later passes --already queued, and verifies that each -+step. It also starts G76 in normal AUTO_RUN, stops after the first pass with -+later passes already queued, and verifies that each - following AUTO_STEP reaches exactly one cylindrical or tapered safe approach - endpoint, and the next AUTO_STEP completes that pass's infeed, thread, and - clearance. -+In-flight Single Step coverage arms during an ordinary source block with three -+later motion blocks already queued and during an active G76 cut with later -+passes queued. It verifies that the active block or thread-plus-clearance unit -+finishes normally and motion remains at its boundary until Resume. While the -+step is armed and the active unit is still moving, both task and motion report -+unpaused; they change to paused only when motion reaches the latched boundary. - Arc blending is enabled for all scenarios, so the exact-clearance assertions - also prove that a marked G76 retract endpoint is not trimmed by a following - rapid. The handoff stress case uses a slow synchronized feed and issues Stop at -diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -index 4792b570e1..dcdfb2d76f 100755 ---- a/tests/resumable-stop/checkresult -+++ b/tests/resumable-stop/checkresult -@@ -1,4 +1,4 @@ - #!/bin/sh - set -e --test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 24 -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 26 - grep -q '^resumable stop scenarios complete$' "$1" -diff --git a/tests/resumable-stop/inflight-step.ngc b/tests/resumable-stop/inflight-step.ngc -new file mode 100644 -index 0000000000..1f72544983 ---- /dev/null -+++ b/tests/resumable-stop/inflight-step.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+F600 -+G1 X10 -+G1 X20 -+G1 X30 -+G1 X40 -+M2 diff --git a/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch b/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch index 73acffd1..15b17d34 100644 --- a/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch +++ b/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch @@ -3,26 +3,46 @@ From: Dariusz Majnert Date: Thu, 27 Aug 2026 16:58:14 +0200 Subject: [PATCH] emc: own transactional tool CRUD in task +Ported to v2.10.0-pre2. Task reads the changer's HAL pins through +upstream's hal_get_bool()/hal_get_si32(). The read-only mmap remapping +uses upstream's mmap_is_creator and mmap_fd (8c8e048) instead of its own +creator flag and closed descriptor; a replaced or vanished mapping also +closes its descriptor. + +Kept from the tool wear patch: a tool line is at most 510 characters, +and a table whose line is too long is not written (the temporary file is +dropped, so the table file stays as it was) and the edit is not +published. A table loaded with lines refused as too long is not saved +over until a table without them is loaded; tooldata_load_snapshot() +reports refused lines and the caller records them when it publishes the +table. G10 tool edits whose save fails are still rolled back. +tooldata_save() keeps upstream's message for a missing [EMCIO]TOOL_TABLE. + +Upstream's G10 db_program notification (b53e523) stays in place but is a +no-op, since IO initialization now refuses [EMCIO]DB_PROGRAM; the +tests/tooldb tests, which need a db program, are skipped. --- - src/emc/nml_intf/emc.cc | 33 +++ + src/emc/nml_intf/emc.cc | 33 ++ src/emc/nml_intf/emc.hh | 5 + - src/emc/nml_intf/emc_nml.hh | 44 ++++ - src/emc/task/emctaskmain.cc | 61 ++++- - src/emc/task/taskclass.cc | 232 ++++++++++++++++-- - src/emc/task/taskclass.hh | 5 +- - src/emc/tooldata/tooldata.hh | 8 + - src/emc/tooldata/tooldata_common.cc | 186 ++++++++------ - src/emc/tooldata/tooldata_mmap.cc | 97 +++++++- - src/emc/tooldata/tooldata_nml.cc | 16 ++ - .../reload-tool/non-random/test-ui.py | 14 ++ + src/emc/nml_intf/emc_nml.hh | 44 ++ + src/emc/task/emctaskmain.cc | 72 +++- + src/emc/task/taskclass.cc | 372 ++++++++++++++++- + src/emc/task/taskclass.hh | 7 +- + src/emc/tooldata/tooldata.hh | 21 + + src/emc/tooldata/tooldata_common.cc | 386 ++++++++++++++---- + src/emc/tooldata/tooldata_mmap.cc | 102 ++++- + src/emc/tooldata/tooldata_nml.cc | 16 + + .../reload-tool/non-random/test-ui.py | 14 + .../toolchanger/reload-tool/random/test-ui.py | 3 +- - 12 files changed, 601 insertions(+), 103 deletions(-) + tests/tooldb/db-g10-offset/skip | 3 + + 13 files changed, 950 insertions(+), 128 deletions(-) + create mode 100644 tests/tooldb/db-g10-offset/skip diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index da68282b6d..7663c33f7e 100644 +index 891516e..61fa3b6 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -256,6 +256,12 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) +@@ -254,6 +254,12 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) case EMC_TOOL_SET_NUMBER_TYPE: ((EMC_TOOL_SET_NUMBER *) buffer)->update(cms); break; @@ -35,7 +55,7 @@ index da68282b6d..7663c33f7e 100644 case EMC_TOOL_STAT_TYPE: ((EMC_TOOL_STAT *) buffer)->update(cms); break; -@@ -503,6 +509,10 @@ const char *emc_symbol_lookup(uint32_t type) +@@ -504,6 +510,10 @@ const char *emc_symbol_lookup(uint32_t type) return "EMC_TOOL_SET_OFFSET"; case EMC_TOOL_SET_NUMBER_TYPE: return "EMC_TOOL_SET_NUMBER"; @@ -46,7 +66,7 @@ index da68282b6d..7663c33f7e 100644 case EMC_TOOL_STAT_TYPE: return "EMC_TOOL_STAT"; case EMC_TOOL_UNLOAD_TYPE: -@@ -1018,6 +1028,29 @@ void EMC_TOOL_SET_OFFSET::update(CMS * cms) +@@ -1024,6 +1034,29 @@ void EMC_TOOL_SET_OFFSET::update(CMS * cms) cms->update(orientation); } @@ -77,7 +97,7 @@ index da68282b6d..7663c33f7e 100644 /* * NML/CMS Update function for EMC_TOOL_SET_NUMBER diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index d2ab16d3ba..0dca92c7e0 100644 +index c98adba..d035390 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -28,6 +28,7 @@ class EMC_TRAJ_STAT; @@ -88,7 +108,7 @@ index d2ab16d3ba..0dca92c7e0 100644 class EMC_AUX_STAT; class EMC_SPINDLE_STAT; class EMC_COOLANT_STAT; -@@ -158,6 +159,8 @@ struct PM_CARTESIAN; +@@ -159,6 +160,8 @@ struct PM_CARTESIAN; #define EMC_TOOL_LOAD_TOOL_TABLE_TYPE ((NMLTYPE) 1107) #define EMC_TOOL_SET_OFFSET_TYPE ((NMLTYPE) 1108) #define EMC_TOOL_SET_NUMBER_TYPE ((NMLTYPE) 1109) @@ -97,20 +117,20 @@ index d2ab16d3ba..0dca92c7e0 100644 #define EMC_TOOL_STAT_TYPE ((NMLTYPE) 1199) -@@ -426,6 +429,8 @@ extern int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, - double diameter, double frontangle, double backangle, - int orientation); - extern int emcToolSetNumber(int number); +@@ -453,6 +456,8 @@ extern void emcToolSetChangeOffset(bool apply, const EmcPose& offset); + extern int emcToolApplyOffset(const EmcPose& offset); + // how the IO side applies a completed change's offset (milltask) + extern void emcToolRegisterApplyOffset(int (*fn)(const EmcPose&)); +extern int emcToolUpdate(const EMC_TOOL_UPDATE &update); +extern int emcToolDelete(int toolno); // implementation functions for EMC_AUX types diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index e9a2be99fa..225b549d38 100644 +index 6a5632c..e4a04b1 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -1642,6 +1642,50 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { +@@ -1732,6 +1732,50 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { int orientation; }; @@ -162,10 +182,10 @@ index e9a2be99fa..225b549d38 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index e01ef50ce8..0be1c528c2 100644 +index 635418d..6c57192 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1129,7 +1129,18 @@ static int emcTaskPlan(void) +@@ -1285,7 +1285,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -185,7 +205,7 @@ index e01ef50ce8..0be1c528c2 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO emcTaskQueueCommand(std::make_unique(*static_cast(emcCommand))); -@@ -1258,6 +1269,18 @@ static int emcTaskPlan(void) +@@ -1414,6 +1425,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -204,7 +224,7 @@ index e01ef50ce8..0be1c528c2 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO -@@ -1383,6 +1406,18 @@ static int emcTaskPlan(void) +@@ -1539,6 +1562,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -223,7 +243,7 @@ index e01ef50ce8..0be1c528c2 100644 // otherwise we can't handle it default: -@@ -1718,6 +1753,18 @@ static int emcTaskPlan(void) +@@ -1874,6 +1909,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -242,7 +262,7 @@ index e01ef50ce8..0be1c528c2 100644 // otherwise we can't handle it default: -@@ -1821,6 +1868,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1977,6 +2024,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) case EMC_TOOL_LOAD_TOOL_TABLE_TYPE: case EMC_TOOL_SET_OFFSET_TYPE: @@ -251,7 +271,7 @@ index e01ef50ce8..0be1c528c2 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2357,6 +2406,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2609,6 +2658,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emc_tool_set_offset_msg->orientation); break; @@ -266,7 +286,7 @@ index e01ef50ce8..0be1c528c2 100644 case EMC_TOOL_SET_NUMBER_TYPE: emc_tool_set_number_msg = reinterpret_cast(cmd); retval = emcToolSetNumber(emc_tool_set_number_msg->tool); -@@ -2816,6 +2873,8 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3082,6 +3139,8 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) case EMC_TOOL_UNLOAD_TYPE: case EMC_TOOL_LOAD_TOOL_TABLE_TYPE: case EMC_TOOL_SET_OFFSET_TYPE: @@ -275,20 +295,57 @@ index e01ef50ce8..0be1c528c2 100644 case EMC_TOOL_SET_NUMBER_TYPE: case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: +@@ -3266,10 +3325,19 @@ static int emcTaskExecute(void) + // emcTaskCheckPostconditions(), i.e. the only one whose commands + // can reach a WAITING_FOR_* state. See issuingQueuedCommand. + issuingQueuedCommand = true; ++ // read first: an abort while issuing clears emcTaskCommand ++ const NMLTYPE issued_type = emcTaskCommand->_type; + const int issue_retval = emcTaskIssueCommand(emcTaskCommand.get()); + issuingQueuedCommand = false; + if (0 != issue_retval) { +- emcStatus->task.execState = EMC_TASK_EXEC::ERROR; ++ // A refused tool edit changed nothing: it fails its own ++ // command (retval reaches the RCS status) and the machine ++ // carries on. Everything else aborts. ++ emcStatus->task.execState = ++ issued_type == EMC_TOOL_UPDATE_TYPE || ++ issued_type == EMC_TOOL_DELETE_TYPE || ++ issued_type == EMC_TOOL_LOAD_TOOL_TABLE_TYPE ++ ? EMC_TASK_EXEC::DONE : EMC_TASK_EXEC::ERROR; + retval = -1; + } else { + emcStatus->task.execState = emcTaskCheckPostconditions(emcTaskCommand.get()); diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index 2869ee6fb7..bbdff026a4 100644 +index 0d076c8..b4ec501 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc -@@ -110,6 +110,8 @@ int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, +@@ -17,6 +17,7 @@ + #include // DBL_MAX + #include // memcpy() strncpy() + #include // malloc() ++#include + #include + + #include "libnml/rcs/rcs.hh" // RCS_CMD_CHANNEL, etc. +@@ -26,6 +27,7 @@ + + #include "pythonplugin/python_plugin.hh" + #include "taskclass.hh" ++#include + + using namespace linuxcnc; + +@@ -122,6 +124,8 @@ int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, wear_offset_valid, diameter, frontangle, backangle, orientation); } int emcToolSetNumber(int number) { return task_methods->emcToolSetNumber(number); } +int emcToolUpdate(const EMC_TOOL_UPDATE &update) { return task_methods->emcToolUpdate(update); } +int emcToolDelete(int toolno) { return task_methods->emcToolDelete(toolno); } - int emcTaskOnce(const char * /*filename*/, EMC_IO_STAT &emcioStatus) - { -@@ -147,15 +149,10 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : + // The tool offset a tool change carries (EMC_TOOL_LOAD.apply_offset): held + // while the change is pending and applied in the same cycle the new tool +@@ -205,15 +209,10 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : if (auto t = inifile.findString("TOOL_TABLE", "EMCIO")) tooltable_filename = strdup(t->c_str()); @@ -308,7 +365,7 @@ index 2869ee6fb7..bbdff026a4 100644 } } -@@ -168,14 +165,6 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : +@@ -226,14 +225,6 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : #endif //} tooldata_init(random_toolchanger); @@ -323,27 +380,66 @@ index 2869ee6fb7..bbdff026a4 100644 emcioStatus.status = RCS_STATUS::DONE;//TODO?? emcioStatus.tool.pocketPrepped = -1; -@@ -188,7 +177,7 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : +@@ -246,8 +237,12 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : } } - if (0 != tooldata_load(tooltable_filename)) { -+ if (!unsupported_db_program && 0 != tooldata_load(tooltable_filename)) { - rcs_print_error("can't load tool table.\n"); +- rcs_print_error("can't load tool table.\n"); ++ if (!unsupported_db_program) { ++ if (0 == tooldata_load(tooltable_filename)) { ++ have_tool_table = true; ++ } else { ++ rcs_print_error("can't load tool table.\n"); ++ } } -@@ -351,6 +340,10 @@ void Task::reload_tool_number(int toolno) { + if (random_toolchanger) { +@@ -399,6 +394,21 @@ int Task::load_tool(int idx) { + return 0; + } // load_tool() + ++// A table has just been published. On a random changer the table says which ++// tool is in the spindle; until one has loaded nothing was known, so the ++// first one to load decides, as it would have at startup. ++void Task::tool_table_loaded(void) { ++ const bool first = !have_tool_table; ++ have_tool_table = true; ++ if (!first || !random_toolchanger) return; ++ CANON_TOOL_TABLE tdata; ++ if (tooldata_get(&tdata,0) != IDX_OK) { ++ UNEXPECTED_MSG; return; ++ } ++ emcioStatus.tool.toolInSpindle = tdata.toolno; ++ hal_set_si32(iocontrol_data->tool_number, emcioStatus.tool.toolInSpindle); ++} ++ + void Task::reload_tool_number(int toolno) { + CANON_TOOL_TABLE tdata; + if(random_toolchanger) return; // doesn't need special handling here +@@ -417,7 +427,20 @@ void Task::reload_tool_number(int toolno) { int Task::emcIoInit()//EMC_TOOL_INIT { +- tooldata_load(tooltable_filename); + if (unsupported_db_program) { + rcs_print_error("can't initialize IO: [EMCIO]DB_PROGRAM is not supported\n"); + return -1; + } - tooldata_load(tooltable_filename); ++ if (tooltable_filename) { ++ if (0 == tooldata_load(tooltable_filename)) { ++ tool_table_loaded(); ++ } else { ++ // the machine starts without the table, and the file is not ++ // saved over until it loads ++ emcOperatorError("can't load tool table %s: no tools until it is " ++ "corrected and reloaded", tooltable_filename); ++ } ++ } reload_tool_number(emcioStatus.tool.toolInSpindle); -@@ -519,10 +512,26 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE + if (0 != iniTool(emc_inifile)) { +@@ -589,10 +612,73 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE return 0; } @@ -351,27 +447,86 @@ index 2869ee6fb7..bbdff026a4 100644 +int find_tool(const CANON_TOOL_TABLE *table, int last, int toolno, + bool random); +bool valid_table(const CANON_TOOL_TABLE *table, int last, bool random); ++ ++bool same_file(const char *a, const char *b) ++{ ++ struct stat sa, sb; ++ return a && b && stat(a, &sa) == 0 && stat(b, &sb) == 0 && ++ sa.st_dev == sb.st_dev && sa.st_ino == sb.st_ino; ++} +} + int Task::emcToolLoadToolTable(const char *file)//EMC_TOOL_LOAD_TOOL_TABLE_TYPE { if(!strlen(file)) file = tooltable_filename;//use filename from ini if none is provided - tooldata_load(file); -+ if (iocontrol_data.tool_prepare || iocontrol_data.tool_change) return -1; ++ if (hal_get_bool(iocontrol_data->tool_prepare) || hal_get_bool(iocontrol_data->tool_change)) { ++ emcOperatorError("can't load tool table %s during a tool change; the table in use is kept", file); ++ return -1; ++ } + CANON_TOOL_TABLE loaded[CANON_POCKETS_MAX]; + int loaded_last = 0; -+ if (tooldata_load_snapshot(file, loaded, &loaded_last) || -+ !valid_table(loaded, loaded_last, random_toolchanger) || -+ (emcioStatus.tool.toolInSpindle > 0 && -+ find_tool(loaded, loaded_last, emcioStatus.tool.toolInSpindle, -+ random_toolchanger) < 0)) { ++ bool refused_lines = false; ++ const int spindle_tool = emcioStatus.tool.toolInSpindle; ++ const char *problem = nullptr; ++ const bool parsed = ++ !tooldata_load_snapshot(file, loaded, &loaded_last, &refused_lines); ++ if (!parsed) { ++ problem = "it could not be read"; ++ } else if (!valid_table(loaded, loaded_last, random_toolchanger)) { ++ problem = "it has invalid or duplicate entries"; ++ } else if (spindle_tool > 0 && ++ find_tool(loaded, loaded_last, spindle_tool, ++ random_toolchanger) < 0) { ++ problem = "it does not have the tool in the spindle"; ++ } else if (random_toolchanger && spindle_tool > 0 && ++ loaded[0].toolno != spindle_tool) { ++ // the file must say where the tools are: the changer moves by it ++ problem = "pocket 0 does not hold the tool in the spindle"; ++ } ++ if (problem) { ++ // the table in memory stays. If the configured file now holds ++ // something else, it is not saved over until it loads ++ CANON_TOOL_TABLE current[CANON_POCKETS_MAX]; ++ int current_last = 0; ++ const bool unchanged = parsed && !refused_lines && ++ !tooldata_snapshot(current, ¤t_last) && ++ tooldata_tables_match(loaded, loaded_last, current, current_last); ++ if (same_file(file, tooltable_filename)) { ++ if (unchanged) { ++ tooldata_adopt_loaded_file(); ++ } else { ++ tooldata_set_refused_lines(true); ++ } ++ } ++ emcOperatorError("can't load tool table %s: %s; the table in use is kept", ++ file, problem); + return -1; + } + if (tooldata_replace(loaded, loaded_last)) return -1; ++ // only loading the configured file says anything about that file, the ++ // one saves go to ++ if (same_file(file, tooltable_filename)) { ++ tooldata_adopt_loaded_file(); ++ tooldata_set_refused_lines(refused_lines); ++ } ++ tool_table_loaded(); reload_tool_number(emcioStatus.tool.toolInSpindle); return 0; } -@@ -577,6 +586,191 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -634,9 +720,10 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, + UNEXPECTED_MSG; + } + bool stored = (0 == tooldata_save(tooltable_filename)); +- if (stored && db_mode == tooldb_t::DB_ACTIVE) { ++ if (stored) { + // tooldata_save() does not write tool table entries in db mode, + // so the db_program must be notified to persist the new offsets ++ // (a no-op without one; IO init refuses [EMCIO]DB_PROGRAM) + int pno = idx; // for random_toolchanger + if (!random_toolchanger) { pno = tdata.pocketno; } + if (tooldata_db_notify(TOOL_OFFSET,toolno,pno,tdata)) { +@@ -656,6 +743,247 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, return 0; } @@ -414,7 +569,9 @@ index 2869ee6fb7..bbdff026a4 100644 + for (int idx = random ? 0 : 1; idx <= last; ++idx) { + const auto &entry = table[idx]; + if (entry.toolno < 0) continue; -+ if (entry.pocketno < 0 || entry.pocketno >= CANON_POCKETS_MAX || ++ // without a random changer the pocket number is only a label ++ if (entry.pocketno < 0 || ++ (random && entry.pocketno >= CANON_POCKETS_MAX) || + entry.orientation < 0 || entry.orientation > 9 || + !isfinite(entry.diameter) || entry.diameter < 0.0 || + !isfinite(entry.frontangle) || !isfinite(entry.backangle)) return false; @@ -432,6 +589,22 @@ index 2869ee6fb7..bbdff026a4 100644 +} +} + ++namespace { ++// A refused tool edit changes nothing, so it fails only its own command; ++// the operator is told why here. ++int refuse_tool_update(int toolno, const char *reason) ++{ ++ emcOperatorError("can't update tool %d: %s", toolno, reason); ++ return -1; ++} ++ ++int refuse_tool_delete(int toolno, const char *reason) ++{ ++ emcOperatorError("can't delete tool %d: %s", toolno, reason); ++ return -1; ++} ++} ++ +int Task::emcToolUpdate(const EMC_TOOL_UPDATE &update) +{ + const char *comment_end = static_cast( @@ -445,44 +618,69 @@ index 2869ee6fb7..bbdff026a4 100644 + update.offset_axes & ~0x1ff || update.wear_offset_axes & ~0x1ff || + !comment_end || + memchr(update.comment, '\n', comment_length) || -+ memchr(update.comment, '\r', comment_length)) return -1; ++ memchr(update.comment, '\r', comment_length)) { ++ return refuse_tool_update(update.toolno, "the request is not valid"); ++ } + if ((update.fields & EMC_TOOL_UPDATE_DIAMETER) && -+ (!isfinite(update.diameter) || update.diameter < 0.0)) return -1; -+ if ((update.fields & EMC_TOOL_UPDATE_FRONTANGLE) && !isfinite(update.frontangle)) return -1; -+ if ((update.fields & EMC_TOOL_UPDATE_BACKANGLE) && !isfinite(update.backangle)) return -1; ++ (!isfinite(update.diameter) || update.diameter < 0.0)) { ++ return refuse_tool_update(update.toolno, "invalid diameter"); ++ } ++ if (((update.fields & EMC_TOOL_UPDATE_FRONTANGLE) && !isfinite(update.frontangle)) || ++ ((update.fields & EMC_TOOL_UPDATE_BACKANGLE) && !isfinite(update.backangle))) { ++ return refuse_tool_update(update.toolno, "invalid angle"); ++ } + for (int axis = 0; axis < 9; ++axis) { -+ if ((update.offset_axes & (1 << axis)) && -+ !isfinite(*pose_axes(update.offset, axis))) return -1; -+ if ((update.wear_offset_axes & (1 << axis)) && -+ !isfinite(*pose_axes(update.wear_offset, axis))) return -1; ++ if (((update.offset_axes & (1 << axis)) && ++ !isfinite(*pose_axes(update.offset, axis))) || ++ ((update.wear_offset_axes & (1 << axis)) && ++ !isfinite(*pose_axes(update.wear_offset, axis)))) { ++ return refuse_tool_update(update.toolno, "invalid offset"); ++ } + } + + CANON_TOOL_TABLE previous[CANON_POCKETS_MAX]; + CANON_TOOL_TABLE table[CANON_POCKETS_MAX]; + int previous_last = 0; -+ if (tooldata_snapshot(previous, &previous_last)) return -1; ++ if (tooldata_snapshot(previous, &previous_last)) { ++ return refuse_tool_update(update.toolno, "the tool table is not available"); ++ } + memcpy(table, previous, sizeof(table)); + int last = previous_last; + int idx = find_tool(table, last, update.toolno, random_toolchanger); + const bool creating = idx < 0; -+ if (creating && !(update.fields & EMC_TOOL_UPDATE_POCKET)) return -1; ++ if (creating && !(update.fields & EMC_TOOL_UPDATE_POCKET)) { ++ return refuse_tool_update(update.toolno, ++ "it is not in the tool table and no pocket was given"); ++ } + + int destination = idx; + if (update.fields & EMC_TOOL_UPDATE_POCKET) { -+ if (update.pocket <= 0 || update.pocket >= CANON_POCKETS_MAX) return -1; ++ if (update.pocket <= 0 || update.pocket >= CANON_POCKETS_MAX) { ++ return refuse_tool_update(update.toolno, "pocket number out of range"); ++ } + for (int other = 1; other <= last; ++other) { + if (other != idx && table[other].toolno >= 0 && -+ table[other].pocketno == update.pocket) return -1; ++ table[other].pocketno == update.pocket) { ++ return refuse_tool_update(update.toolno, "another tool has that pocket"); ++ } + } + const bool active = update.toolno == emcioStatus.tool.toolInSpindle || + idx == 0 || idx == emcioStatus.tool.pocketPrepped || -+ (iocontrol_data.tool_prepare && idx == iocontrol_data.tool_prep_index) || -+ iocontrol_data.tool_change; -+ if (!creating && table[idx].pocketno != update.pocket && active) return -1; ++ (hal_get_bool(iocontrol_data->tool_prepare) && idx == hal_get_si32(iocontrol_data->tool_prep_index)) || ++ hal_get_bool(iocontrol_data->tool_change); ++ if (!creating && table[idx].pocketno != update.pocket && active) { ++ return refuse_tool_update(update.toolno, ++ "its pocket can't change while it is in use"); ++ } + if (random_toolchanger) { + destination = update.pocket; -+ if (destination != idx && table[destination].toolno >= 0) return -1; -+ if (!creating && destination != idx && active) return -1; ++ if (destination != idx && table[destination].toolno >= 0) { ++ return refuse_tool_update(update.toolno, "another tool has that pocket"); ++ } ++ if (!creating && destination != idx && active) { ++ return refuse_tool_update(update.toolno, ++ "its pocket can't change while it is in use"); ++ } + } + } + if (creating && !random_toolchanger) { @@ -495,7 +693,9 @@ index 2869ee6fb7..bbdff026a4 100644 + const bool random_spindle_update = + random_toolchanger && !creating && idx == 0 && destination == 0; + if (destination < 0 || destination >= CANON_POCKETS_MAX || -+ (destination == 0 && !random_spindle_update)) return -1; ++ (destination == 0 && !random_spindle_update)) { ++ return refuse_tool_update(update.toolno, "the tool table has no room for it"); ++ } + + CANON_TOOL_TABLE entry = creating ? tooldata_entry_init() : table[idx]; + entry.toolno = update.toolno; @@ -521,41 +721,52 @@ index 2869ee6fb7..bbdff026a4 100644 + if (tooldata_save_snapshot(tooltable_filename, table, last)) { + (void)tooldata_save_snapshot(tooltable_filename, previous, + previous_last); -+ return -1; ++ return refuse_tool_update(update.toolno, "the tool table could not be saved"); + } + if (tooldata_replace(table, last)) { + (void)tooldata_save_snapshot(tooltable_filename, previous, + previous_last); -+ return -1; ++ return refuse_tool_update(update.toolno, "the tool table could not be updated"); + } + return 0; +} + +int Task::emcToolDelete(int toolno) +{ -+ if (!tooltable_filename || toolno <= 0 || -+ toolno == emcioStatus.tool.toolInSpindle) return -1; ++ if (!tooltable_filename || toolno <= 0) { ++ return refuse_tool_delete(toolno, "the request is not valid"); ++ } ++ if (toolno == emcioStatus.tool.toolInSpindle) { ++ return refuse_tool_delete(toolno, "it is in the spindle"); ++ } + CANON_TOOL_TABLE previous[CANON_POCKETS_MAX]; + CANON_TOOL_TABLE table[CANON_POCKETS_MAX]; + int previous_last = 0; -+ if (tooldata_snapshot(previous, &previous_last)) return -1; ++ if (tooldata_snapshot(previous, &previous_last)) { ++ return refuse_tool_delete(toolno, "the tool table is not available"); ++ } + memcpy(table, previous, sizeof(table)); + int last = previous_last; + const int idx = find_tool(table, last, toolno, random_toolchanger); -+ if (idx <= 0 || idx == emcioStatus.tool.pocketPrepped || -+ (iocontrol_data.tool_prepare && idx == iocontrol_data.tool_prep_index) || -+ iocontrol_data.tool_change) return -1; ++ if (idx <= 0) { ++ return refuse_tool_delete(toolno, "it is not in the tool table"); ++ } ++ if (idx == emcioStatus.tool.pocketPrepped || ++ (hal_get_bool(iocontrol_data->tool_prepare) && idx == hal_get_si32(iocontrol_data->tool_prep_index)) || ++ hal_get_bool(iocontrol_data->tool_change)) { ++ return refuse_tool_delete(toolno, "a tool change is using it"); ++ } + table[idx] = tooldata_entry_init(); + while (last > 0 && table[last].toolno < 0) --last; + if (tooldata_save_snapshot(tooltable_filename, table, last)) { + (void)tooldata_save_snapshot(tooltable_filename, previous, + previous_last); -+ return -1; ++ return refuse_tool_delete(toolno, "the tool table could not be saved"); + } + if (tooldata_replace(table, last)) { + (void)tooldata_save_snapshot(tooltable_filename, previous, + previous_last); -+ return -1; ++ return refuse_tool_delete(toolno, "the tool table could not be updated"); + } + return 0; +} @@ -564,10 +775,10 @@ index 2869ee6fb7..bbdff026a4 100644 { int idx; diff --git a/src/emc/task/taskclass.hh b/src/emc/task/taskclass.hh -index 5e32a1a65d..dced9adeea 100644 +index 509f11f..6077e19 100644 --- a/src/emc/task/taskclass.hh +++ b/src/emc/task/taskclass.hh -@@ -74,6 +74,8 @@ public: +@@ -75,6 +75,8 @@ public: virtual int emcToolLoadToolTable(const char *file); virtual int emcToolUnload(); virtual int emcToolSetNumber(int number); @@ -576,18 +787,27 @@ index 5e32a1a65d..dced9adeea 100644 int iocontrol_hal_init(void); void reload_tool_number(int toolno); -@@ -88,8 +90,7 @@ public: - hal_comp iocontrol; +@@ -82,6 +84,7 @@ public: + void run(); + int read_tool_inputs(void); + void hal_init_pins(void); ++ void tool_table_loaded(void); + + EMC_IO_STAT &emcioStatus; + int random_toolchanger {0}; +@@ -89,8 +92,8 @@ public: + int comp_id; const char *ini_filename; const char *tooltable_filename {}; - char db_program[LINELEN] {}; - tooldb_t db_mode {tooldb_t::DB_NOTUSED}; + bool unsupported_db_program {false}; ++ bool have_tool_table {false}; // a table has loaded since startup int tool_status; }; diff --git a/src/emc/tooldata/tooldata.hh b/src/emc/tooldata/tooldata.hh -index b0f0a756ce..19c0592b15 100644 +index db3e6b7..24ab424 100644 --- a/src/emc/tooldata/tooldata.hh +++ b/src/emc/tooldata/tooldata.hh @@ -58,6 +58,8 @@ void tooldata_reset(void); @@ -599,13 +819,26 @@ index b0f0a756ce..19c0592b15 100644 // ignore_zero_values:1 for file writes // :0 for use with tooldata_db_notify() -@@ -74,8 +76,14 @@ void tooldata_set_db(tooldb_t mode); +@@ -76,8 +78,27 @@ void tooldata_set_db(tooldb_t mode); //---------------------------------------------------------- int tooldata_load(const char *filename); ++// stage a table file without publishing it; *refused_lines tells whether ++// lines were refused as too long (see tooldata_set_refused_lines) +int tooldata_load_snapshot(const char *filename, + CANON_TOOL_TABLE *table, -+ int *last_index); ++ int *last_index, ++ bool *refused_lines); ++// the published table was loaded with refused lines, or the table file ++// did not load: saves are refused until that file loads without them ++void tooldata_set_refused_lines(bool refused); ++// what tooldata_load_snapshot() last read is what the table file holds: a ++// save is refused while the file holds anything else (no file is fine) ++void tooldata_adopt_loaded_file(void); ++ ++// whether two tables would be written to a table file identically ++bool tooldata_tables_match(const CANON_TOOL_TABLE *a, int last_a, ++ const CANON_TOOL_TABLE *b, int last_b); int tooldata_save(const char *filename); +int tooldata_save_snapshot(const char *filename, @@ -615,22 +848,28 @@ index b0f0a756ce..19c0592b15 100644 //---------------------------------------------------------- //mmap specific diff --git a/src/emc/tooldata/tooldata_common.cc b/src/emc/tooldata/tooldata_common.cc -index 4e9651c86f..cbb7299eff 100644 +index ceefe9b..0695af8 100644 --- a/src/emc/tooldata/tooldata_common.cc +++ b/src/emc/tooldata/tooldata_common.cc -@@ -23,6 +23,11 @@ +@@ -21,10 +21,17 @@ + ** along with this program; if not, write to the Free Software + ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ ++#include ++#include + #include #include #include +#include +#include -+#include + #include +#include +#include - #include ++#include #include "tooldata.hh" -@@ -32,6 +37,25 @@ static bool is_random_toolchanger = 0; + #define UNEXPECTED_MSG fprintf(stderr,"UNEXPECTED %s %d\n",__FILE__,__LINE__); +@@ -33,6 +40,25 @@ static bool is_random_toolchanger = 0; static int nonrandom_idx = 0; // 'fakepocket' counter static bool add_init_initialized = 0; static tooldb_t db_mode = DB_NOTUSED; @@ -656,7 +895,31 @@ index 4e9651c86f..cbb7299eff 100644 void tooldata_init(bool random_toolchanger) { -@@ -211,7 +235,7 @@ int tooldata_read_entry(const char *input_line) +@@ -92,12 +118,19 @@ int tooldata_read_entry(const char *input_line) + offset = empty.offset; + wear_offset = empty.wear_offset; + +- char* saveptr; +- buff = strtok_r(work_line, ";", &saveptr); +- if (strlen(buff) <=1) { +- //fprintf(stderr,"skip blankline %s\n",__FILE__); ++ // the line ends at its newline, or a CRLF file's carriage return and ++ // newline; a line of only blanks or only a comment holds no tool ++ size_t end = strlen(work_line); ++ while (end > 0 && (work_line[end - 1] == '\n' || work_line[end - 1] == '\r')) { ++ work_line[--end] = 0; ++ } ++ const size_t first = strspn(work_line, " \t"); ++ if (work_line[first] == 0 || work_line[first] == ';') { + return 0; + } ++ ++ char* saveptr; ++ buff = strtok_r(work_line, ";", &saveptr); + comment = strtok_r(NULL, "\n", &saveptr); + + token = strtok_r(buff, " ", &saveptr); +@@ -206,7 +239,7 @@ int tooldata_read_entry(const char *input_line) if (valid) { CANON_TOOL_TABLE tdata = tooldata_entry_init(); // verify no prior tool in pocket @@ -665,7 +928,7 @@ index 4e9651c86f..cbb7299eff 100644 if (is_random_toolchanger && tdata.toolno != -1) { fprintf(stderr,"WARNING: Attempt to assign multiple toolno.s to pocket %d\n",realpocket); fprintf(stderr," %s %s()\n",__FILE__,__FUNCTION__); -@@ -238,7 +262,7 @@ int tooldata_read_entry(const char *input_line) +@@ -233,7 +266,7 @@ int tooldata_read_entry(const char *input_line) ); } } @@ -674,41 +937,140 @@ index 4e9651c86f..cbb7299eff 100644 UNEXPECTED_MSG; } } else { -@@ -312,27 +336,15 @@ void tooldata_format_toolline (int idx, - return; +@@ -323,50 +356,130 @@ int tooldata_format_toolline (int idx, + return 0; } // tooldata_format_toolline() +-// The last table file loaded had a line refused as too long: that tool is +-// not in memory, so writing the table back would delete the user's line. ++// The table file the table in memory was loaded from had a line refused (too ++// long), or did not load at all: what it holds is not all in memory, so ++// writing the table back would delete the user's lines. + static bool table_has_refused_lines = false; + -int tooldata_load(const char *filename) -+int tooldata_load_snapshot(const char *filename, -+ CANON_TOOL_TABLE *staged, -+ int *last_index) ++void tooldata_set_refused_lines(bool refused) { - FILE *fp; - char input_line[CANON_TOOL_ENTRY_LEN]; - char orig_line[CANON_TOOL_ENTRY_LEN]; +- FILE *fp; +- char input_line[CANON_TOOL_ENTRY_LEN]; +- char orig_line[CANON_TOOL_ENTRY_LEN]; ++ table_has_refused_lines = refused; ++} - if (db_mode == DB_ACTIVE) { //expect data loaded from db - if (tooldata_db_getall()) { - fprintf(stderr, - "\ntooldata_load: Failed to load tooldata from database\n\n"); - db_mode = DB_NOTUSED; -- return -1; ++// What the table file should hold: the bytes read when it was loaded or ++// written by the last save, or no file at all. A file holding anything else ++// has changes the table in memory lacks. Bytes are compared rather than size ++// and timestamps, which miss an edit within the timestamp granularity and ++// change on a mere touch; after a save the bytes are known without looking ++// at the file, so the save's own rename is never taken for an edit. ++static bool table_file_known = false; ++static bool table_file_exists = false; ++static std::string table_file_content; ++static std::string last_read_content; // of the last tooldata_load_snapshot() ++ ++// 0 with the whole file in *content, else -1 with errno set ++static int read_whole_file(const char *filename, std::string *content) ++{ ++ FILE *fp = fopen(filename, "r"); ++ if (!fp) return -1; ++ content->clear(); ++ char buffer[4096]; ++ size_t count; ++ while ((count = fread(buffer, 1, sizeof(buffer), fp)) > 0) { ++ content->append(buffer, count); ++ } ++ const int read_error = ferror(fp) ? (errno ? errno : EIO) : 0; ++ fclose(fp); ++ if (read_error) { ++ errno = read_error; ++ return -1; ++ } ++ return 0; ++} ++ ++void tooldata_adopt_loaded_file(void) ++{ ++ table_file_known = true; ++ table_file_exists = true; ++ table_file_content = last_read_content; ++} ++ ++// Whether a save would lose nothing: the file holds what is expected, or ++// there is no file. One that cannot be read may hold anything. ++static bool table_file_as_expected(const char *filename) ++{ ++ if (!table_file_known) return true; ++ std::string current; ++ if (read_whole_file(filename, ¤t)) return errno == ENOENT; ++ return table_file_exists && current == table_file_content; ++} ++ ++// The file a save has to replace: filename with symbolic links followed, so ++// that the links stay. A link may point to a file not there yet. ++static int resolve_table_file(const char *filename, std::string *resolved) ++{ ++ std::string path(filename); ++ for (int depth = 0; depth < 40; ++depth) { ++ char target[PATH_MAX]; ++ const ssize_t length = readlink(path.c_str(), target, sizeof(target)); ++ if (length < 0) { ++ if (errno != EINVAL && errno != ENOENT) return -1; ++ *resolved = path; ++ return 0; ++ } ++ if ((size_t)length == sizeof(target)) { ++ errno = ENAMETOOLONG; + return -1; - } - return 0; -- } -- ++ } ++ const std::string link(target, length); ++ const auto slash = path.find_last_of('/'); ++ if (link[0] == '/' || slash == std::string::npos) { ++ path = link; ++ } else { ++ path = path.substr(0, slash + 1) + link; ++ } + } ++ errno = ELOOP; ++ return -1; ++} + - if(!filename) return -1; -- ++int tooldata_load_snapshot(const char *filename, ++ CANON_TOOL_TABLE *staged, ++ int *last_index, ++ bool *refused_lines) ++{ ++ FILE *fp = NULL; ++ char input_line[CANON_TOOL_ENTRY_LEN]; ++ char orig_line[CANON_TOOL_ENTRY_LEN]; + - // clear out tool table - // (Set vars to indicate no tool in pocket): - tooldata_reset(); -+ if (!filename || !staged || !last_index || db_mode == DB_ACTIVE) return -1; ++ if (!filename || !staged || !last_index || !refused_lines || ++ db_mode == DB_ACTIVE) return -1; - // open tool table file - if (NULL == (fp = fopen(filename, "r"))) { -@@ -341,14 +353,15 @@ int tooldata_load(const char *filename) +- // open tool table file +- if (NULL == (fp = fopen(filename, "r"))) { ++ // the file is read once, so that the lines parsed are exactly the bytes ++ // tooldata_adopt_loaded_file() remembers ++ std::string content; ++ if (read_whole_file(filename, &content)) { + fprintf(stderr, "%s, %d: Failed to open tool table file '%s': %s\n", + __FILE__, __LINE__, filename, strerror(errno)); return -1; } ++ if (!content.empty() && ++ NULL == (fp = fmemopen(content.data(), content.size(), "r"))) { ++ return -1; ++ } - // after initializing all available pockets, - // subsequent read from filename will update the last_index @@ -722,11 +1084,25 @@ index 4e9651c86f..cbb7299eff 100644 const int nonrandom_start_idx = 1; // when reading file start at 0 tooldata_add_init(nonrandom_start_idx); +- table_has_refused_lines = false; ++ bool refused = false; + int lineno = 0; +- while (!feof(fp)) { + int load_failed = 0; - while (!feof(fp)) { ++ while (fp && !feof(fp)) { // for nonrandom machines, just read the tools into pockets 1..n // no matter their tool numbers. NB leave the spindle pocket 0 -@@ -361,38 +374,62 @@ int tooldata_load(const char *filename) + // unchanged/empty. +@@ -383,7 +496,7 @@ int tooldata_load(const char *filename) + while ((c = fgetc(fp)) != EOF && c != '\n') {} + fprintf(stderr, "File: %s line %d: tool line longer than %d characters refused\n", + filename, lineno, CANON_TOOL_LINE_MAX); +- table_has_refused_lines = true; ++ refused = true; + continue; + } + strcpy(orig_line, input_line); +@@ -391,37 +504,79 @@ int tooldata_load(const char *filename) // parse and store one line from tool table file int entry_idx = tooldata_read_entry(input_line); if (entry_idx <0) { @@ -756,16 +1132,17 @@ index 4e9651c86f..cbb7299eff 100644 } } // while - // close the file +- // close the file - fclose(fp); -- -+ if (ferror(fp) || fclose(fp)) load_failed = 1; ++ if (fp && (ferror(fp) || fclose(fp))) load_failed = 1; + load_staging_table = nullptr; + if (load_failed) return -1; + *last_index = load_staging_last_index; - return 0; ++ *refused_lines = refused; ++ last_read_content = std::move(content); ++ return 0; +} // tooldata_load_snapshot() -+ + +int tooldata_load(const char *filename) +{ + if (db_mode == DB_ACTIVE) { //expect data loaded from db @@ -779,41 +1156,55 @@ index 4e9651c86f..cbb7299eff 100644 + } + CANON_TOOL_TABLE staged[CANON_POCKETS_MAX]; + int last_index = 0; -+ if (tooldata_load_snapshot(filename, staged, &last_index)) return -1; -+ return tooldata_replace(staged, last_index); ++ bool refused_lines = false; ++ if (tooldata_load_snapshot(filename, staged, &last_index, &refused_lines) || ++ tooldata_replace(staged, last_index)) { ++ // a table file that did not load is kept as it is until one loads: ++ // the table in memory does not hold it (a missing one may be made) ++ struct stat existing; ++ if (filename && stat(filename, &existing) == 0) { ++ tooldata_set_refused_lines(true); ++ } else if (filename) { ++ table_file_known = true; ++ table_file_exists = false; ++ table_file_content.clear(); ++ } ++ return -1; ++ } ++ tooldata_adopt_loaded_file(); ++ tooldata_set_refused_lines(refused_lines); + return 0; } // tooldata_load() --static void write_tool_line(FILE* fp,int idx) -+static int write_tool_line(FILE* fp, int idx, const CANON_TOOL_TABLE *table) +-// Append idx's tool line to table; -1 if it is too long to write. +-static int write_tool_line(std::string &table,int idx) ++// Append idx's tool line from table, or from the table in memory if table ++// is NULL; -1 if it is too long to write. ++static int write_tool_line(std::string *out, int idx, const CANON_TOOL_TABLE *table) { CANON_TOOL_TABLE tdata; -- if (tooldata_get(&tdata,idx) != IDX_OK) {return;} +- if (tooldata_get(&tdata,idx) != IDX_OK) {return 0;} + if (table) { + tdata = table[idx]; + } else if (tooldata_get(&tdata,idx) != IDX_OK) { + return -1; + } if (db_mode == DB_ACTIVE && idx != 0 ) { -- return; -+ return 0; + return 0; } - - if (tdata.toolno != -1) { -@@ -400,49 +437,60 @@ static void write_tool_line(FILE* fp,int idx) - tooldata_format_toolline (idx, - 1, // ignore_zero_values - tdata,theline); -- fprintf(fp,"%s",theline); -+ if (fprintf(fp,"%s",theline) < 0) return -1; +@@ -433,63 +588,114 @@ static int write_tool_line(std::string &table,int idx) + tdata,theline)) { + return -1; + } +- table += theline; ++ out->append(theline); } -- return; -+ return 0; + return 0; } // write_tool_line() -int tooldata_save(const char *filename) -+int tooldata_save_snapshot(const char *filename, -+ const CANON_TOOL_TABLE *table, -+ int last_index) ++bool tooldata_tables_match(const CANON_TOOL_TABLE *a, int last_a, ++ const CANON_TOOL_TABLE *b, int last_b) { - int idx; - FILE *fp; @@ -833,72 +1224,139 @@ index 4e9651c86f..cbb7299eff 100644 - if (filename[0] == 0) { - UNEXPECTED_MSG; - } +- if (table_has_refused_lines) { +- fprintf(stderr, "%s: not saved: lines refused when it was loaded " +- "would be lost; shorten them and reload the tool table\n", +- filename); +- return -1; +- } +- } +- +- // format every line first: a tool whose line is too long leaves the +- // file as it was rather than written without that tool +- std::string table; +- if (db_mode == DB_ACTIVE) { +- int spindle_idx = 0; +- if (write_tool_line(table,spindle_idx)) {return -1;} +- } else { +- start_idx = is_random_toolchanger ? 0 : 1; +- for (idx = start_idx; idx < CANON_POCKETS_MAX; idx++) { +- if (write_tool_line(table,idx)) {return -1;} +- } ++ const int last = last_a > last_b ? last_a : last_b; ++ for (int idx = is_random_toolchanger ? 0 : 1; idx <= last; ++idx) { ++ char line_a[CANON_TOOL_ENTRY_LEN] = {0}; ++ char line_b[CANON_TOOL_ENTRY_LEN] = {0}; ++ if (idx <= last_a && a[idx].toolno != -1 && ++ tooldata_format_toolline(idx, 1, a[idx], line_a)) return false; ++ if (idx <= last_b && b[idx].toolno != -1 && ++ tooldata_format_toolline(idx, 1, b[idx], line_b)) return false; ++ if (strcmp(line_a, line_b)) return false; + } ++ return true; ++} + +- // open tool table file +- if (NULL == (fp = fopen(filename, "w"))) { +- fprintf(stderr, "%s, %d: Failed to open tool table file '%s': %s\n", +- __FILE__, __LINE__, filename, strerror(errno)); ++int tooldata_save_snapshot(const char *filename, ++ const CANON_TOOL_TABLE *table, ++ int last_index) ++{ + if (!filename || !filename[0] || !table || last_index < 0 || + last_index >= CANON_POCKETS_MAX || db_mode == DB_ACTIVE) return -1; -+ std::string temporary = std::string(filename) + ".tmp.XXXXXX"; ++ if (table_has_refused_lines) { ++ fprintf(stderr, "%s: not saved: lines refused when it was loaded " ++ "would be lost; correct them and reload the tool table\n", ++ filename); + return -1; + } +- int written = fputs(table.c_str(), fp); +- if (fclose(fp) != 0 || written == EOF) { +- fprintf(stderr, "%s, %d: Failed to write tool table file '%s': %s\n", +- __FILE__, __LINE__, filename, strerror(errno)); ++ // a tool whose line is too long fails the save, and the file stays as ++ // it was: the table goes to a temporary file renamed over it only when ++ // every line has been written ++ std::string content; ++ for (int idx = is_random_toolchanger ? 0 : 1; ++ idx <= last_index; ++idx) { ++ if (write_tool_line(&content, idx, table)) return -1; ++ } ++ // the rename replaces the real file, not a link leading to it ++ std::string target; ++ if (resolve_table_file(filename, &target)) { ++ fprintf(stderr, "%s: not saved: %s\n", filename, strerror(errno)); + return -1; + } +- return 0; ++ std::string temporary = target + ".tmp.XXXXXX"; + int fd = mkstemp(temporary.data()); + if (fd < 0) return -1; + struct stat existing{}; -+ if (stat(filename, &existing) == 0) (void)fchmod(fd, existing.st_mode & 0777); ++ if (stat(target.c_str(), &existing) == 0) (void)fchmod(fd, existing.st_mode & 0777); + FILE *fp = fdopen(fd, "w"); + if (!fp) { close(fd); unlink(temporary.c_str()); return -1; } + int result = 0; -+ for (int idx = is_random_toolchanger ? 0 : 1; -+ idx <= last_index; ++idx) { -+ if (write_tool_line(fp, idx, table)) { result = -1; break; } - } -- -- // open tool table file -- if (NULL == (fp = fopen(filename, "w"))) { -- fprintf(stderr, "%s, %d: Failed to open tool table file '%s': %s\n", -- __FILE__, __LINE__, filename, strerror(errno)); -- return -1; ++ if (fwrite(content.data(), 1, content.size(), fp) != content.size()) result = -1; + if (!result && fflush(fp)) result = -1; + if (!result && fsync(fd)) result = -1; + if (fclose(fp)) result = -1; -+ if (!result && rename(temporary.c_str(), filename)) result = -1; ++ // checked last, to leave the least time for a change to slip in ++ if (!result && !table_file_as_expected(target.c_str())) { ++ fprintf(stderr, "%s: not saved: the file changed since it was loaded " ++ "or saved; reload the tool table\n", filename); ++ result = -1; ++ } ++ if (!result && rename(temporary.c_str(), target.c_str())) result = -1; + if (!result) { -+ const std::string path(filename); -+ const auto slash = path.find_last_of('/'); ++ table_file_known = true; ++ table_file_exists = true; ++ table_file_content = std::move(content); ++ const auto slash = target.find_last_of('/'); + const std::string parent = slash == std::string::npos ? "." : -+ (slash == 0 ? "/" : path.substr(0, slash)); ++ (slash == 0 ? "/" : target.substr(0, slash)); + const int dirfd = open(parent.c_str(), O_RDONLY | O_DIRECTORY); + if (dirfd < 0 || fsync(dirfd)) result = -1; + if (dirfd >= 0 && close(dirfd)) result = -1; - } ++ } + if (result) unlink(temporary.c_str()); + return result; -+} //tooldata_save() - + } //tooldata_save() ++ +int tooldata_save(const char *filename) +{ - if (db_mode == DB_ACTIVE) { -- int spindle_idx = 0; -- write_tool_line(fp,spindle_idx); -- } else { -- start_idx = is_random_toolchanger ? 0 : 1; -- for (idx = start_idx; idx < CANON_POCKETS_MAX; idx++) { -- write_tool_line(fp,idx); -- } ++ if (db_mode == DB_ACTIVE) { + if (!is_random_toolchanger) return 0; ++ // format the line first: one too long leaves the file as it was ++ CANON_TOOL_TABLE tdata; ++ char theline[CANON_TOOL_ENTRY_LEN] = {0}; ++ if (tooldata_get(&tdata, 0) != IDX_OK) return -1; ++ if (tdata.toolno != -1 && ++ tooldata_format_toolline(0, 1, tdata, theline)) return -1; + FILE *fp = fopen(DB_SPINDLE_SAVE, "w"); + if (!fp) return -1; -+ int result = write_tool_line(fp, 0, NULL); ++ int result = fputs(theline, fp) == EOF ? -1 : 0; + if (!result && fflush(fp)) result = -1; + if (!result && fsync(fileno(fp))) result = -1; + if (fclose(fp)) result = -1; + return result; - } -- fclose(fp); -- return 0; --} //tooldata_save() ++ } ++ // filename == NULL happens without ini entry [EMCIO]TOOL_TABLE ++ // and a Task::emcToolSetOffset is performed. ++ if (!filename) { ++ fprintf(stderr, "%s: No filename. Are you missing INI-entry [EMCIO]TOOL_TABLE?\n", ++ __PRETTY_FUNCTION__); ++ return -1; ++ } + CANON_TOOL_TABLE table[CANON_POCKETS_MAX]; + int last_index = 0; + if (tooldata_snapshot(table, &last_index)) return -1; + return tooldata_save_snapshot(filename, table, last_index); +} diff --git a/src/emc/tooldata/tooldata_mmap.cc b/src/emc/tooldata/tooldata_mmap.cc -index 45d0c2e7c2..0e3a27389d 100644 +index d13d877..71b417b 100644 --- a/src/emc/tooldata/tooldata_mmap.cc +++ b/src/emc/tooldata/tooldata_mmap.cc @@ -22,6 +22,7 @@ @@ -909,18 +1367,17 @@ index 45d0c2e7c2..0e3a27389d 100644 #include #include #include "config.h" -@@ -39,6 +40,10 @@ static int creator_fd; +@@ -48,6 +49,9 @@ static bool mmap_is_creator = false; static char filename[LINELEN] = {}; - static char* tool_mmap_base = 0; + static char* tool_mmap_base = NULL; static EMC_TOOL_STAT const *toolstat; +static dev_t mapped_device; +static ino_t mapped_inode; -+static bool creator_mapping; +static std::mutex mapping_mutex; typedef struct { rtapi_mutex_t mutex; -@@ -114,6 +119,8 @@ static void tool_mmap_mutex_give() +@@ -130,6 +134,8 @@ static void tool_mmap_mutex_give() bool tool_mmap_is_random_toolchanger(void) { @@ -929,7 +1386,7 @@ index 45d0c2e7c2..0e3a27389d 100644 bool ans = 0; tool_mmap_mutex_get(); tooldata_header_t *hptr = HPTR(); -@@ -127,6 +134,7 @@ bool tool_mmap_is_random_toolchanger(void) +@@ -143,6 +149,7 @@ bool tool_mmap_is_random_toolchanger(void) int tool_mmap_creator(EMC_TOOL_STAT const * ptr,int random_toolchanger) { static int inited=0; @@ -937,7 +1394,7 @@ index 45d0c2e7c2..0e3a27389d 100644 if (inited) { fprintf(stderr,"Error: tool_mmap_creator already called BYE\n"); -@@ -156,6 +164,12 @@ int tool_mmap_creator(EMC_TOOL_STAT const * ptr,int random_toolchanger) +@@ -172,6 +179,11 @@ int tool_mmap_creator(EMC_TOOL_STAT const * ptr,int random_toolchanger) perror("tool_mmap_creator(): mmap fail"); exit(EXIT_FAILURE); } @@ -946,11 +1403,24 @@ index 45d0c2e7c2..0e3a27389d 100644 + mapped_device = mapping_stat.st_dev; + mapped_inode = mapping_stat.st_ino; + } -+ creator_mapping = true; tooldata_header_t *hptr = HPTR(); hptr->is_random_toolchanger = random_toolchanger; -@@ -168,9 +182,22 @@ int tool_mmap_creator(EMC_TOOL_STAT const * ptr,int random_toolchanger) +@@ -183,12 +195,34 @@ int tool_mmap_creator(EMC_TOOL_STAT const * ptr,int random_toolchanger) + tool_mmap_mutex_give(); return 0; + } // tool_mmap_creator(); + ++// drop a user mapping whose file has gone or been replaced ++static void tool_mmap_user_unmap() ++{ ++ munmap(tool_mmap_base, TOOL_MMAP_SIZE); ++ tool_mmap_base = nullptr; ++ if (mmap_fd >= 0) { ++ close(mmap_fd); ++ mmap_fd = -1; ++ } ++} ++ //typ: milltask, guis (emcmodule,emcsh,...), halui int tool_mmap_user() { @@ -960,24 +1430,22 @@ index 45d0c2e7c2..0e3a27389d 100644 + const std::lock_guard mapping_lock(mapping_mutex); + struct stat path_stat; + if (stat(tool_mmap_fname(), &path_stat)) { -+ if (tool_mmap_base && !creator_mapping) { -+ munmap(tool_mmap_base, TOOL_MMAP_SIZE); -+ tool_mmap_base = 0; ++ if (tool_mmap_base && !mmap_is_creator) { ++ tool_mmap_user_unmap(); + } + return -1; + } + if (tool_mmap_base && -+ (creator_mapping || (mapped_device == path_stat.st_dev && ++ (mmap_is_creator || (mapped_device == path_stat.st_dev && + mapped_inode == path_stat.st_ino))) return 0; + if (tool_mmap_base) { -+ munmap(tool_mmap_base, TOOL_MMAP_SIZE); -+ tool_mmap_base = 0; ++ tool_mmap_user_unmap(); + } int fd = open(tool_mmap_fname(), TOOL_MMAP_USER_OPEN_FLAGS, TOOL_MMAP_MODE); -@@ -187,6 +214,12 @@ int tool_mmap_user() - tool_mmap_base = (char*)0; +@@ -205,6 +239,12 @@ int tool_mmap_user() + tool_mmap_base = (char*)NULL; return(-1); } + struct stat opened_stat; @@ -986,17 +1454,16 @@ index 45d0c2e7c2..0e3a27389d 100644 + close(fd); + return -1; + } - tool_mmap_base = (char*)mmap(0, TOOL_MMAP_SIZE, PROT_READ|PROT_WRITE, + tool_mmap_base = (char*)mmap(NULL, TOOL_MMAP_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); -@@ -195,12 +228,16 @@ int tool_mmap_user() +@@ -213,12 +253,15 @@ int tool_mmap_user() perror("tool_mmap_user(): mmap fail"); exit(EXIT_FAILURE); } + mapped_device = opened_stat.st_dev; + mapped_inode = opened_stat.st_ino; -+ creator_mapping = false; - close(fd); + mmap_fd = fd; return 0; } //tool_mmap_user() @@ -1006,24 +1473,16 @@ index 45d0c2e7c2..0e3a27389d 100644 if (!tool_mmap_base) { return; } // flush mmapped file to filesystem if (msync(tool_mmap_base, TOOL_MMAP_SIZE, MS_SYNC) == -1) { -@@ -211,6 +248,7 @@ void tool_mmap_close() - perror("tool_mmap_close(): munmapfail"); - exit(EXIT_FAILURE); - } -+ tool_mmap_base = 0; - if( unlink(tool_mmap_fname() )) { - perror("tool_mmap_close(): unlink fail"); - } -@@ -219,6 +257,8 @@ void tool_mmap_close() +@@ -249,6 +292,8 @@ void tool_mmap_close() void tooldata_last_index_set(int idx) //force last_index { + const std::lock_guard mapping_lock(mapping_mutex); -+ if (!creator_mapping) { UNEXPECTED_MSG; return; } ++ if (!mmap_is_creator) { UNEXPECTED_MSG; return; } tool_mmap_mutex_get(); tooldata_header_t *hptr = HPTR(); if (idx < 0 || idx >= CANON_POCKETS_MAX) { -@@ -232,19 +272,20 @@ void tooldata_last_index_set(int idx) //force last_index +@@ -262,19 +307,20 @@ void tooldata_last_index_set(int idx) //force last_index int tooldata_last_index_get(void) { @@ -1046,20 +1505,20 @@ index 45d0c2e7c2..0e3a27389d 100644 + const std::lock_guard mapping_lock(mapping_mutex); toolidx_t ret; - if (!tool_mmap_base) { -+ if (!tool_mmap_base || !creator_mapping) { ++ if (!tool_mmap_base || !mmap_is_creator) { fprintf(stderr,"%5d tooldata_put() no tool_mmap_base\n",getpid()); return IDX_FAIL; } -@@ -277,6 +318,8 @@ toolidx_t tooldata_put(struct CANON_TOOL_TABLE tdata,int idx) +@@ -307,6 +353,8 @@ toolidx_t tooldata_put(struct CANON_TOOL_TABLE tdata,int idx) void tooldata_reset() { + const std::lock_guard mapping_lock(mapping_mutex); -+ if (!creator_mapping) { UNEXPECTED_MSG; return; } ++ if (!mmap_is_creator) { UNEXPECTED_MSG; return; } CANON_TOOL_TABLE initdata = tooldata_entry_init(); tool_mmap_mutex_get(); int idx; -@@ -289,9 +332,9 @@ void tooldata_reset() +@@ -319,9 +367,9 @@ void tooldata_reset() toolidx_t tooldata_get(CANON_TOOL_TABLE* pdata, int idx) { @@ -1071,7 +1530,7 @@ index 45d0c2e7c2..0e3a27389d 100644 } if (idx < 0 || idx >= CANON_POCKETS_MAX) { // ui programs may query for nonexistent idx values -@@ -310,6 +353,8 @@ toolidx_t tooldata_get(CANON_TOOL_TABLE* pdata, int idx) +@@ -340,6 +388,8 @@ toolidx_t tooldata_get(CANON_TOOL_TABLE* pdata, int idx) int tooldata_find_index_for_tool(int toolno) { @@ -1080,7 +1539,7 @@ index 45d0c2e7c2..0e3a27389d 100644 tooldata_header_t *hptr = HPTR(); tool_mmap_mutex_get(); int idx; -@@ -332,3 +377,33 @@ int tooldata_find_index_for_tool(int toolno) +@@ -362,3 +412,33 @@ int tooldata_find_index_for_tool(int toolno) tool_mmap_mutex_give(); return foundidx; } // tooldata_find_index_for_tool() @@ -1101,7 +1560,7 @@ index 45d0c2e7c2..0e3a27389d 100644 +int tooldata_replace(const CANON_TOOL_TABLE *table, int last_index) +{ + const std::lock_guard mapping_lock(mapping_mutex); -+ if (!tool_mmap_base || !creator_mapping || !table || last_index < 0 || ++ if (!tool_mmap_base || !mmap_is_creator || !table || last_index < 0 || + last_index >= CANON_POCKETS_MAX || tool_mmap_mutex_get()) { + return -1; + } @@ -1115,7 +1574,7 @@ index 45d0c2e7c2..0e3a27389d 100644 + return 0; +} diff --git a/src/emc/tooldata/tooldata_nml.cc b/src/emc/tooldata/tooldata_nml.cc -index f33392574a..a7ee61e380 100644 +index f333925..a7ee61e 100644 --- a/src/emc/tooldata/tooldata_nml.cc +++ b/src/emc/tooldata/tooldata_nml.cc @@ -102,3 +102,19 @@ int tooldata_find_index_for_tool(int toolno) @@ -1139,7 +1598,7 @@ index f33392574a..a7ee61e380 100644 + return 0; +} diff --git a/tests/toolchanger/reload-tool/non-random/test-ui.py b/tests/toolchanger/reload-tool/non-random/test-ui.py -index 7bff305516..aa4b127bbd 100755 +index fca46c3..445e5ee 100755 --- a/tests/toolchanger/reload-tool/non-random/test-ui.py +++ b/tests/toolchanger/reload-tool/non-random/test-ui.py @@ -67,6 +67,20 @@ c.home(-1) @@ -1164,7 +1623,7 @@ index 7bff305516..aa4b127bbd 100755 # diff --git a/tests/toolchanger/reload-tool/random/test-ui.py b/tests/toolchanger/reload-tool/random/test-ui.py -index 7e5fc520ec..a41638f7fc 100755 +index 22509af..628ff13 100755 --- a/tests/toolchanger/reload-tool/random/test-ui.py +++ b/tests/toolchanger/reload-tool/random/test-ui.py @@ -67,6 +67,8 @@ c.home(-1) @@ -1181,3 +1640,12 @@ index 7e5fc520ec..a41638f7fc 100755 sys.exit(0) - +diff --git a/tests/tooldb/db-g10-offset/skip b/tests/tooldb/db-g10-offset/skip +new file mode 100644 +index 0000000..730d8c3 +--- /dev/null ++++ b/tests/tooldb/db-g10-offset/skip +@@ -0,0 +1,3 @@ ++This test needs an [EMCIO]DB_PROGRAM, which task refuses in this patched ++build ("emc: own transactional tool CRUD in task"): tool data must come ++from a file-backed [EMCIO]TOOL_TABLE. diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index b305ad05..b53a173e 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -3,33 +3,57 @@ From: Dariusz Majnert Date: Wed, 2 Sep 2026 11:36:57 +0200 Subject: [PATCH] rs274ngc: add composable executor stdglue +Ported to v2.10.0-pre2. HalExecutor uses the Python hal module's +hal.Type and hal.Dir names (the HAL_BIT/HAL_S32/HAL_U32 spellings now +only exist as deprecated aliases). Its pins are bool, sint and uint, +which are 64 bits wide, so the opcode range is the 64-bit signed range +and request IDs wrap within 64 bits, still skipping zero. The +install-headless Makefile hunk is dropped: that target no longer exists +and a --disable-gui install already includes stdglue.py. + +Generators are also closed when Interp::init() discards an active call +stack (EMC_TASK_PLAN_INIT), which does not go through unwind_call(). +When the unwind starts inside the generator itself, for example M2 or a +failing call run through self.execute(), the generator cannot be closed +while it runs; the close is deferred until it yields or returns, and +pycall() then returns the unwind status (INTERP_EXIT or an error) +instead of continuing the unwound call. --- - docs/src/remap/remap.adoc | 127 ++++++++++ - nc_files/remap_lib/python-stdglue/stdglue.py | 253 ++++++++++++++++++- - src/Makefile | 3 + - src/emc/rs274ngc/interp_internal.hh | 1 + - src/emc/rs274ngc/interp_python.cc | 24 ++ - src/emc/rs274ngc/interp_python.hh | 3 + - src/emc/rs274ngc/rs274ngc_pre.cc | 1 + - tests/remap/executor/checkresult | 5 + - tests/remap/executor/remap.py | 52 ++++ - tests/remap/executor/test-ui.py | 177 +++++++++++++ - tests/remap/executor/test.ini | 95 +++++++ - tests/remap/executor/test.sh | 8 + - tests/remap/executor/toplevel.py | 18 ++ - 13 files changed, 765 insertions(+), 2 deletions(-) - create mode 100755 tests/remap/executor/checkresult - create mode 100644 tests/remap/executor/remap.py - create mode 100755 tests/remap/executor/test-ui.py - create mode 100644 tests/remap/executor/test.ini - create mode 100755 tests/remap/executor/test.sh - create mode 100644 tests/remap/executor/toplevel.py + docs/src/config/python-interface.adoc | 3 +- + docs/src/remap/remap.adoc | 130 ++++++++ + nc_files/remap_lib/python-stdglue/stdglue.py | 280 +++++++++++++++++- + src/emc/nml_intf/emc.hh | 3 +- + src/emc/rs274ngc/interp_internal.hh | 7 + + src/emc/rs274ngc/interp_python.cc | 76 ++++- + src/emc/rs274ngc/interp_python.hh | 7 + + src/emc/rs274ngc/interp_setup.cc | 1 + + src/emc/rs274ngc/interpmodule.cc | 7 + + src/emc/rs274ngc/rs274ngc_pre.cc | 9 + + src/emc/task/emctask.cc | 12 + + src/emc/task/emctaskmain.cc | 55 +++- + src/emc/task/task.hh | 4 + + src/emc/usr_intf/axis/extensions/emcmodule.cc | 1 + + 14 files changed, 580 insertions(+), 15 deletions(-) +diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc +index 1c871cf..2131b07 100644 +--- a/docs/src/config/python-interface.adoc ++++ b/docs/src/config/python-interface.adoc +@@ -219,7 +219,8 @@ see <> for an example. + another subsystem runs to its end first, and Abort is the way out. One of + `HOLD_WAIT_NONE`, `HOLD_WAIT_HOMING` (a queued `G28.2`), `HOLD_WAIT_IO` (a + tool change or other I/O command), `HOLD_WAIT_SYSTEM_COMMAND` (a user +- `M100`-`M199` program). ++ `M100`-`M199` program), `HOLD_WAIT_EXECUTOR` (a request started by an ++ executor remap). + + *interpreter_errcode*:: '(returns integer)' - + current RS274NGC interpreter return code. One of diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index 218062048c..b263f1e959 100644 +index 75e2a09..642e4c7 100644 --- a/docs/src/remap/remap.adoc +++ b/docs/src/remap/remap.adoc -@@ -1576,6 +1576,133 @@ For a slightly more advanced example, see `tests/remap/predefined-named-params`. +@@ -1576,6 +1576,136 @@ For a slightly more advanced example, see `tests/remap/predefined-named-params`. Since many remapping tasks are very similar, I've started collecting working prolog and epilog routines in a single Python module. These can currently be found in 'ncfiles/remap_lib/python-stdglue/stdglue.py' and provide the following routines: @@ -42,7 +66,8 @@ index 218062048c..b263f1e959 100644 +machine configuration still defines each remap and supplies the endpoint that +performs the request. + -+`executor_transact` begins one request, waits cooperatively, releases a ++`executor_transact` first waits until the moves and commands queued before ++it have finished, then begins one request, waits cooperatively, releases a +terminal request, cancels it on timeout or interpreter abort, and returns an +`ExecutorResponse` without deciding whether the response is acceptable. +`executor_execute` adds the common policy: only `EXECUTOR_SUCCEEDED` continues @@ -120,7 +145,7 @@ index 218062048c..b263f1e959 100644 + self.tailstock = remap.HalExecutor(self, "tailstock", component) + + if component is not None: -+ component.newpin("machine-specific", hal.HAL_BIT, hal.HAL_OUT) ++ component.newpin("machine-specific", hal.Type.BOOL, hal.Dir.OUT) + component.ready() + self.remap_hal = component +---- @@ -132,39 +157,41 @@ index 218062048c..b263f1e959 100644 +|Pin |Type |Direction |Meaning + +|`remap.executor.chuck.request-id` -+|u32 |out |Nonzero identifier of the current request ++|uint |out |Nonzero identifier of the current request + +|`remap.executor.chuck.opcode` -+|s32 |out |Integer request passed to `begin` ++|sint |out |Integer request passed to `begin` + +|`remap.executor.chuck.request` -+|bit |out |The request is active ++|bool |out |The request is active + +|`remap.executor.chuck.cancel` -+|bit |out |The request was abandoned and must be cancelled ++|bool |out |The request was abandoned and must be cancelled + +|`remap.executor.chuck.response-id` -+|u32 |in |Identifier of the terminal response ++|uint |in |Identifier of the terminal response + +|`remap.executor.chuck.state` -+|s32 |in |Responder state ++|sint |in |Responder state + +|`remap.executor.chuck.result` -+|s32 |in |Machine-defined terminal result or diagnostic code ++|sint |in |Machine-defined terminal result or diagnostic code +|=== + +HAL states are `0` unavailable, `1` idle, `2` accepted, `3` running, `4` +succeeded, `5` failed, and `6` cancelled. To complete a request, the responder +first writes the terminal state and result, then copies `request-id` to +`response-id` as the commit marker. Matching IDs prevent stale responses from -+completing a later request. `cancel` remains asserted until the next request -+so realtime logic cannot miss a short userspace pulse. ++completing a later request. Request IDs increase by one for each request and ++wrap within the 64-bit `uint` range, skipping zero. `cancel` remains ++asserted until the next request so realtime logic cannot miss a short ++userspace pulse. + === T: +prepare_prolog+ and +prepare_epilog+ These wrap a NGC procedure for T__x__ Tool Prepare. diff --git a/nc_files/remap_lib/python-stdglue/stdglue.py b/nc_files/remap_lib/python-stdglue/stdglue.py -index a3b93019af..4b49e0beeb 100644 +index 8457e40..0991d4f 100644 --- a/nc_files/remap_lib/python-stdglue/stdglue.py +++ b/nc_files/remap_lib/python-stdglue/stdglue.py @@ -16,6 +16,9 @@ @@ -177,7 +204,7 @@ index a3b93019af..4b49e0beeb 100644 import emccanon from interpreter import * from emccanon import MESSAGE -@@ -40,6 +43,254 @@ def build_hal(self): +@@ -40,6 +43,281 @@ def build_hal(self): except Exception as e: print(e) @@ -196,6 +223,9 @@ index a3b93019af..4b49e0beeb 100644 +EXECUTOR_STATE_CANCELLED = 6 + +_EXECUTOR_DEFAULT_TIMEOUT = 10.0 ++_HAL_SINT_MIN = -(1 << 63) ++_HAL_SINT_MAX = (1 << 63) - 1 ++_HAL_UINT_MAX = (1 << 64) - 1 +_EXECUTOR_POLL_INTERVAL = 0.01 + + @@ -233,6 +263,13 @@ index a3b93019af..4b49e0beeb 100644 + terminal response and cancelled on timeout, interpreter error, or abort. + """ + ++ # With cutter radius compensation on, the move before this call is still ++ # held in the compensation queue, so the request would start before it. ++ if self.cutter_comp_side: ++ raise ValueError( ++ "executor requests cannot run with cutter radius compensation on" ++ ) ++ + if not self.task: + return ExecutorResponse(EXECUTOR_SUCCEEDED) + @@ -243,6 +280,14 @@ index a3b93019af..4b49e0beeb 100644 + if not math.isfinite(timeout) or timeout <= 0.0: + raise ValueError("executor timeout must be finite and greater than zero") + ++ # In AUTO the interpreter runs ahead of motion. Wait until everything ++ # queued before this call has finished, so the request starts in program ++ # order and not while earlier moves are still running. FINISH() first ++ # sends a move canon still holds for blending; the resynchronisation that ++ # follows the yield would otherwise drop it. ++ emccanon.FINISH() ++ yield INTERP_EXECUTE_FINISH ++ + operation = None + finalized = False + try: @@ -270,9 +315,14 @@ index a3b93019af..4b49e0beeb 100644 + operation.release() + return response + ++ # The request has started, so a Stop or Pause lets it run to its ++ # end: this tells task to keep polling while it holds. ++ self.executor_poll_pending = True + emccanon.DWELL(min(_EXECUTOR_POLL_INTERVAL, remaining)) + yield INTERP_EXECUTE_FINISH + finally: ++ # The request has ended; nothing is polled any more. ++ self.executor_poll_pending = False + if operation is not None and not finalized: + finalized = True + operation.cancel() @@ -333,13 +383,15 @@ index a3b93019af..4b49e0beeb 100644 + + import hal + -+ component.newpin(self._prefix + "request-id", hal.HAL_U32, hal.HAL_OUT) -+ component.newpin(self._prefix + "opcode", hal.HAL_S32, hal.HAL_OUT) -+ component.newpin(self._prefix + "request", hal.HAL_BIT, hal.HAL_OUT) -+ component.newpin(self._prefix + "cancel", hal.HAL_BIT, hal.HAL_OUT) -+ component.newpin(self._prefix + "response-id", hal.HAL_U32, hal.HAL_IN) -+ component.newpin(self._prefix + "state", hal.HAL_S32, hal.HAL_IN) -+ component.newpin(self._prefix + "result", hal.HAL_S32, hal.HAL_IN) ++ out = hal.Dir.OUT ++ pin_in = hal.Dir.IN ++ component.newpin(self._prefix + "request-id", hal.Type.UINT, out) ++ component.newpin(self._prefix + "opcode", hal.Type.SINT, out) ++ component.newpin(self._prefix + "request", hal.Type.BOOL, out) ++ component.newpin(self._prefix + "cancel", hal.Type.BOOL, out) ++ component.newpin(self._prefix + "response-id", hal.Type.UINT, pin_in) ++ component.newpin(self._prefix + "state", hal.Type.SINT, pin_in) ++ component.newpin(self._prefix + "result", hal.Type.SINT, pin_in) + + component[self._prefix + "request-id"] = 0 + component[self._prefix + "opcode"] = 0 @@ -356,11 +408,13 @@ index a3b93019af..4b49e0beeb 100644 + opcode = int(request) + except (TypeError, ValueError): + raise ValueError("HAL executor request must be an integer opcode") -+ if opcode < -2147483648 or opcode > 2147483647: -+ raise ValueError("HAL executor opcode is outside the s32 range") ++ if opcode < _HAL_SINT_MIN or opcode > _HAL_SINT_MAX: ++ raise ValueError("HAL executor opcode is outside the sint range") + ++ # Request IDs increase by one per request and wrap within the 64-bit ++ # unsigned pin, skipping zero, which means no request. + request_id = self._next_request_id -+ self._next_request_id = (request_id + 1) & 0xFFFFFFFF ++ self._next_request_id = (request_id + 1) & _HAL_UINT_MAX + if self._next_request_id == 0: + self._next_request_id = 1 + @@ -432,59 +486,97 @@ index a3b93019af..4b49e0beeb 100644 # REMAP=S prolog=setspeed_prolog ngc=setspeed epilog=setspeed_epilog # exposed parameter: # -@@ -655,5 +906,3 @@ def tool_probe_m6(self, **words): +@@ -655,5 +933,3 @@ def tool_probe_m6(self, **words): self.set_errormsg("tool_probe_m6 remap error." ) yield INTERP_ERROR - - -diff --git a/src/Makefile b/src/Makefile -index 35c77b38ac..fa06ec5664 100644 ---- a/src/Makefile -+++ b/src/Makefile -@@ -711,6 +711,7 @@ install-headless-dirs: - $(DESTDIR)$(bindir) $(DESTDIR)$(libdir) $(DESTDIR)/$(libdir)/linuxcnc \ - $(DESTDIR)$(includedir)/linuxcnc $(DESTDIR)$(tcldir) \ - $(DESTDIR)$(tcldir)/msgs $(DESTDIR)$(datadir)/linuxcnc/hallib \ -+ $(DESTDIR)$(ncfilesdir)/remap_lib/python-stdglue \ - $(DESTDIR)$(mandir)/man1 $(DESTDIR)$(mandir)/man3 $(DESTDIR)$(mandir)/man9 +diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh +index d035390..67c8d34 100644 +--- a/src/emc/nml_intf/emc.hh ++++ b/src/emc/nml_intf/emc.hh +@@ -247,7 +247,8 @@ enum class EMC_TASK_HOLD_WAIT { + NONE = 0, + HOMING = 1, // a queued G28.2 homing cycle + IO = 2, // a tool change or other I/O controller command +- SYSTEM_COMMAND = 3 // a user M100-M199 program ++ SYSTEM_COMMAND = 3, // a user M100-M199 program ++ EXECUTOR = 4 // a request started by an executor remap (stdglue) + }; - install-headless: install-headless-dirs -@@ -735,6 +736,8 @@ install-headless: install-headless-dirs - ../lib/python/hal.py ../lib/python/linuxcnc_util.py ../lib/python/nf.py \ - ../lib/python/pyhal.py ../lib/python/raster.py ../lib/python/tooldb.py $(DESTDIR)$(SITEPY) - $(FILE) ../lib/python/rs274/*.py $(DESTDIR)$(SITEPY)/rs274 -+ $(FILE) ../nc_files/remap_lib/python-stdglue/stdglue.py \ -+ $(DESTDIR)$(ncfilesdir)/remap_lib/python-stdglue - ifneq ($(BUILD_MANPAGES),no) - $(FILE) ../docs/man/man1/*.1 $(DESTDIR)$(mandir)/man1 - $(FILE) $(wildcard ../docs/man/man3/*.3) $(DESTDIR)$(mandir)/man3 + // types for motion control diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh -index fed82a67d8..e7e3497d34 100644 +index 210b4db..692b6e9 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh -@@ -594,6 +594,7 @@ struct pycontext { +@@ -620,6 +620,9 @@ struct pycontext { pycontext(const struct pycontext &); pycontext &operator=(const struct pycontext &); ~pycontext(); -+ void close_generator(); ++ // Close a Python remap generator whose call frame is being unwound. ++ // unwind_status is the status that caused the unwind. ++ void close_generator(int unwind_status); pycontext_impl *impl; }; +@@ -797,6 +800,10 @@ struct setup + bool kins_by_g43_4; // G43.4 selected the kinematics, for G49 to undo + bool toolchange_flag; // flag indicating we just had a tool change + bool home_flag; // flag indicating a G28.2 homing cycle just ran ++ // An executor remap (stdglue) polls a request it has started; task keeps ++ // running the remap while a Stop or Pause holds. Task clears it before ++ // each read, and the remap sets it again for as long as it polls. ++ bool executor_poll_pending; + int input_index; // channel queried + bool input_digital; // input queried was digital (false=analog) + bool cutter_comp_firstmove; // this is the first comp move diff --git a/src/emc/rs274ngc/interp_python.cc b/src/emc/rs274ngc/interp_python.cc -index f8217637fc..6d304503b8 100644 +index e3f8b60..ffcbf6f 100644 --- a/src/emc/rs274ngc/interp_python.cc +++ b/src/emc/rs274ngc/interp_python.cc -@@ -151,6 +151,8 @@ int Interp::pycall(setup_pointer /*settings*/, - frame->pystuff.impl->py_return_type = RET_STOPITERATION; +@@ -99,6 +99,19 @@ bool Interp::is_pycallable(setup_pointer /*settings*/, + return python_plugin->is_callable(module,funcname); + } + ++// The call stack was unwound while this frame's generator was running. Close ++// it now that it has yielded or finished, and return the status of the ++// unwind so that the caller does not continue the unwound call. ++static int finish_unwound_generator(context_pointer frame) ++{ ++ int unwind_status = frame->pystuff.impl->close_status; ++ ++ frame->pystuff.close_generator(unwind_status); ++ if (unwind_status == INTERP_EXIT) ++ return INTERP_EXIT; ++ return unwind_status > INTERP_MIN_ERROR ? unwind_status : INTERP_ERROR; ++} ++ + // all parameters to/results from Python calls go through the callframe, which looks a bit awkward + // the reason is not to expose boost.python through the interpreter public interface + int Interp::pycall(setup_pointer /*settings*/, +@@ -151,13 +164,19 @@ int Interp::pycall(setup_pointer /*settings*/, bp::handle_exception(); PyErr_Clear(); + logPy("pycall: call generator - StopIteration exception"); ++ if (frame->pystuff.impl->close_pending) ++ return finish_unwound_generator(frame); + frame->pystuff.impl->generator_next = bp::object(); + frame->pystuff.impl->generator = bp::object(); - logPy("pycall: call generator - StopIteration exception"); return INTERP_OK; } else { -@@ -194,6 +196,7 @@ int Interp::pycall(setup_pointer /*settings*/, + msg = handle_pyerror(); + bp::handle_exception(); + PyErr_Clear(); + logPy("pycall: call generator - exception: %s",msg.c_str()); +- ++ if (frame->pystuff.impl->close_pending) ++ (void) finish_unwound_generator(frame); ++ + ERS("exception during generator call: %s", msg.c_str()); + } + } else +@@ -193,11 +212,24 @@ int Interp::pycall(setup_pointer /*settings*/, // a generator was returned. This must have been the first time call to a handler // which contains a yield. Extract next() method. @@ -492,16 +584,58 @@ index f8217637fc..6d304503b8 100644 frame->pystuff.impl->generator_next = bp::getattr(retval, "__next__"); // and call it for the first time. // Expect execution up to first 'yield INTERP_EXECUTE_FINISH'. -@@ -299,3 +302,24 @@ pycontext &pycontext::operator=(const pycontext &other) { +- frame->pystuff.impl->py_returned_int = bp::extract(frame->pystuff.impl->generator_next()); +- frame->pystuff.impl->py_return_type = RET_YIELD; ++ try { ++ frame->pystuff.impl->py_returned_int = bp::extract(frame->pystuff.impl->generator_next()); ++ frame->pystuff.impl->py_return_type = RET_YIELD; ++ } catch (bp::error_already_set &) { ++ if (!PyErr_ExceptionMatches(PyExc_StopIteration)) ++ throw; ++ // A generator that returns before its first yield ends ++ // normally, as it does after a later one (for example an ++ // executor helper in preview, where nothing is run). ++ PyErr_Clear(); ++ frame->pystuff.impl->py_return_type = RET_STOPITERATION; ++ frame->pystuff.impl->generator_next = bp::object(); ++ frame->pystuff.impl->generator = bp::object(); ++ } + } else if (PyUnicode_Check(retval.ptr())) { + // returning a string sets the interpreter error message and aborts + char *msg = bp::extract(retval); +@@ -264,6 +296,11 @@ int Interp::pycall(setup_pointer /*settings*/, + bp::handle_exception(); + PyErr_Clear(); + } ++ if (frame->pystuff.impl->close_pending) { ++ int unwind_status = finish_unwound_generator(frame); ++ if (!py_exception) ++ return unwind_status; ++ } + if (py_exception) { + ERM("pycall: %s.%s:\n%s", module ? module:"", funcname, msg.c_str()); + status = INTERP_ERROR; +@@ -298,3 +335,36 @@ pycontext &pycontext::operator=(const pycontext &other) { impl = new pycontext_impl(*other.impl); return *this; } + -+void pycontext::close_generator() ++void pycontext::close_generator(int unwind_status) +{ + if (!impl->generator.ptr() || impl->generator.ptr() == Py_None) + return; + ++ // An unwind started from inside the generator itself (a nested ++ // self.execute() that fails or reaches M2/M30) cannot close it while it ++ // runs, and must not drop the references the running call relies on. ++ bp::object running = PyGen_Check(impl->generator.ptr()) ++ ? bp::object(impl->generator.attr("gi_running")) : bp::object(false); ++ if (PyObject_IsTrue(running.ptr()) == 1) { ++ impl->close_pending = true; ++ impl->close_status = unwind_status; ++ return; ++ } ++ + try { + impl->generator.attr("close")(); + } catch (bp::error_already_set &) { @@ -516,421 +650,274 @@ index f8217637fc..6d304503b8 100644 + + impl->generator_next = bp::object(); + impl->generator = bp::object(); ++ impl->close_pending = false; +} diff --git a/src/emc/rs274ngc/interp_python.hh b/src/emc/rs274ngc/interp_python.hh -index 3fcf26ba20..66155d9945 100644 +index 3fcf26b..baedeab 100644 --- a/src/emc/rs274ngc/interp_python.hh +++ b/src/emc/rs274ngc/interp_python.hh -@@ -10,6 +10,9 @@ struct pycontext_impl { +@@ -10,6 +10,13 @@ struct pycontext_impl { int py_return_type; // type of Python return value - enum retopts double py_returned_double; int py_returned_int; + // Keep the generator itself so abort can close it and run Python finally + // blocks before the remap context is discarded. + boost::python::object generator; ++ // The call stack was unwound while the generator was running, so it ++ // could not be closed then. pycall() closes it once control returns. ++ bool close_pending = false; ++ int close_status = 0; // generator object next method as returned if Python function contained a yield statement boost::python::object generator_next; }; +diff --git a/src/emc/rs274ngc/interp_setup.cc b/src/emc/rs274ngc/interp_setup.cc +index 7ac607b..061952a 100644 +--- a/src/emc/rs274ngc/interp_setup.cc ++++ b/src/emc/rs274ngc/interp_setup.cc +@@ -121,6 +121,7 @@ setup::setup() : + kins_by_g43_4(false), + toolchange_flag(0), + home_flag(0), ++ executor_poll_pending(false), + input_index(0), + input_digital(0), + cutter_comp_firstmove(0), +diff --git a/src/emc/rs274ngc/interpmodule.cc b/src/emc/rs274ngc/interpmodule.cc +index 1597ec1..5fe4623 100644 +--- a/src/emc/rs274ngc/interpmodule.cc ++++ b/src/emc/rs274ngc/interpmodule.cc +@@ -316,6 +316,12 @@ static inline bool get_speed_override (Interp &interp, int spindle) { + static inline void set_speed_override(Interp &interp, int spindle, bool value) { + interp._setup.speed_override[spindle] = value; + } ++static inline bool get_executor_poll_pending (Interp &interp) { ++ return interp._setup.executor_poll_pending; ++} ++static inline void set_executor_poll_pending(Interp &interp, bool value) { ++ interp._setup.executor_poll_pending = value; ++} + static inline bool get_toolchange_flag (Interp &interp) { + return interp._setup.toolchange_flag; + } +@@ -941,6 +947,7 @@ BOOST_PYTHON_MODULE(interpreter) { + .add_property("probe_flag", &get_probe_flag, &set_probe_flag) + .add_property("speed_override", &get_speed_override, &set_speed_override) + .add_property("toolchange_flag", &get_toolchange_flag, &set_toolchange_flag) ++ .add_property("executor_poll_pending", &get_executor_poll_pending, &set_executor_poll_pending) + .add_property("u_current", &get_u_current, &set_u_current) + .add_property("AA_axis_offset", &get_AA_axis_offset, &set_AA_axis_offset) + .add_property("AA_current", &get_AA_current, &set_AA_current) diff --git a/src/emc/rs274ngc/rs274ngc_pre.cc b/src/emc/rs274ngc/rs274ngc_pre.cc -index a4ef597412..55b048cad7 100644 +index 2ea3ba1..85dd055 100644 --- a/src/emc/rs274ngc/rs274ngc_pre.cc +++ b/src/emc/rs274ngc/rs274ngc_pre.cc -@@ -1688,6 +1688,7 @@ int Interp::unwind_call(int status, const char *file, int line, const char *func +@@ -1246,7 +1246,12 @@ int Interp::init() + //_setup.feed_hold set in Interp::synch + + // initialization stuff for subroutines and control structures ++ // A re-init can drop an active call stack without unwind_call(); still ++ // close any Python remap generators so their finally blocks run. ++ for (; _setup.call_level > 0; _setup.call_level--) ++ _setup.sub_context[_setup.call_level].pystuff.close_generator(INTERP_OK); + _setup.call_level = 0; ++ _setup.executor_poll_pending = false; + _setup.call_stack_id = 0; + _setup.defining_sub = 0; + _setup.skipping_o = NULL; +@@ -1757,9 +1762,13 @@ int Interp::unwind_call(int status, const char *file, int line, const char *func + logDebug("unwind_call: call_level=%d status=%s from %s %s:%d", + _setup.call_level, interp_status(status), function, file, line); + ++ // the remap that polled is gone ++ _setup.executor_poll_pending = false; ++ for(; _setup.call_level > 0; _setup.call_level--) { int i; context * sub = _setup.sub_context + _setup.call_level - 1; -+ _setup.sub_context[_setup.call_level].pystuff.close_generator(); ++ _setup.sub_context[_setup.call_level].pystuff.close_generator(status); free_named_parameters(&_setup.sub_context[_setup.call_level]); if(sub->subName) { logDebug("unwind_call leaving sub '%s'", sub->subName); -diff --git a/tests/remap/executor/checkresult b/tests/remap/executor/checkresult -new file mode 100755 -index 0000000000..7fda8799ba ---- /dev/null -+++ b/tests/remap/executor/checkresult -@@ -0,0 +1,5 @@ -+#!/bin/sh -+ -+set -e -+test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 4 -+grep -q '^executor remap scenarios complete$' "$1" -diff --git a/tests/remap/executor/remap.py b/tests/remap/executor/remap.py -new file mode 100644 -index 0000000000..0198feb3fc ---- /dev/null -+++ b/tests/remap/executor/remap.py -@@ -0,0 +1,52 @@ -+from stdglue import * -+ -+ -+def m10_execute(self, **words): -+ yield from executor_execute(self, self.chuck, request=0) -+ -+ -+def m11_execute(self, **words): -+ yield from executor_execute(self, self.chuck, request=1, timeout=0.2) -+ -+ -+def m20_transact(self, **words): -+ response = yield from executor_transact(self, self.tailstock, request=7) -+ if not self.task: -+ return -+ self.executor_component["raw-result"] = response.result -+ -+ -+def m21_non_hal(self, **words): -+ response = yield from executor_execute(self, self.memory_executor, request=41) -+ if not self.task: -+ return -+ if self.memory_executor.last_operation.released: -+ self.executor_component["transport-result"] = response.result -+ -+ -+class MemoryExecutor: -+ name = "memory" -+ -+ def begin(self, request): -+ self.last_operation = MemoryOperation(request) -+ return self.last_operation -+ -+ -+class MemoryOperation: -+ def __init__(self, request): -+ self.request = request -+ self.polls = 0 -+ self.released = False -+ self.cancelled = False -+ -+ def poll(self): -+ self.polls += 1 -+ if self.polls == 1: -+ return None -+ return ExecutorResponse(EXECUTOR_SUCCEEDED, result=self.request + 1) -+ -+ def release(self): -+ self.released = True -+ -+ def cancel(self): -+ self.cancelled = True -diff --git a/tests/remap/executor/test-ui.py b/tests/remap/executor/test-ui.py -new file mode 100755 -index 0000000000..fb9b77b2dc ---- /dev/null -+++ b/tests/remap/executor/test-ui.py -@@ -0,0 +1,177 @@ -+#!/usr/bin/env python3 -+ -+import os -+import sys -+import time -+ -+import hal -+import linuxcnc -+ -+ -+def fail(message): -+ print(message) -+ sys.exit(1) -+ -+ -+def wait_for(predicate, message, timeout=5.0): -+ start = time.time() -+ while time.time() - start < timeout: -+ status.poll() -+ if predicate(): -+ return -+ time.sleep(0.01) -+ fail(message) -+ -+ -+def wait_complete(message, timeout=5.0): -+ if command.wait_complete(timeout) != linuxcnc.RCS_DONE: -+ fail(message) -+ -+ -+def pin_value(name): -+ try: -+ return hal.get_value(name) -+ except RuntimeError: -+ return None -+ -+ -+def wait_request(executor, opcode): -+ prefix = "remap.executor.%s." % executor -+ wait_for( -+ lambda: hal.get_value(prefix + "request"), -+ "executor request was not asserted", -+ ) -+ request_id = int(hal.get_value(prefix + "request-id")) -+ if request_id == 0: -+ fail("executor used reserved request ID zero") -+ if int(hal.get_value(prefix + "opcode")) != opcode: -+ fail("executor published the wrong opcode") -+ if hal.get_value(prefix + "cancel"): -+ fail("executor cancel was asserted for a new request") -+ return prefix, request_id -+ -+ -+def respond(prefix, request_id, state, result): -+ hal.set_p(prefix + "state", str(state)) -+ hal.set_p(prefix + "result", str(result)) -+ hal.set_p(prefix + "response-id", str(request_id)) -+ -+ -+def assert_released(prefix): -+ wait_for( -+ lambda: not hal.get_value(prefix + "request"), -+ "completed executor request was not released", -+ ) -+ if hal.get_value(prefix + "cancel"): -+ fail("completed executor request was cancelled") -+ -+ -+command = linuxcnc.command() -+status = linuxcnc.stat() -+test_component = hal.component("executor-test-ui") -+test_component.ready() -+ -+wait_for( -+ lambda: status.task_state == linuxcnc.STATE_ESTOP, -+ "LinuxCNC did not initialize", -+) -+ -+for pin in ( -+ "remap.executor.chuck.request-id", -+ "remap.executor.chuck.response-id", -+ "remap.executor.tailstock.request-id", -+ "remap.owner-marker", -+): -+ wait_for( -+ lambda pin=pin: pin_value(pin) is not None, -+ "missing caller-owned executor component pin %s" % pin, -+ ) -+ -+if not hal.get_value("remap.owner-marker"): -+ fail("executor endpoint did not share its caller-owned HAL component") -+ -+command.state(linuxcnc.STATE_ESTOP_RESET) -+command.state(linuxcnc.STATE_ON) -+wait_complete("machine did not turn on") -+command.mode(linuxcnc.MODE_MDI) -+wait_complete("machine did not enter MDI") -+ -+scenario = os.environ["EXECUTOR_SCENARIO"] -+ -+if scenario == "success": -+ command.mdi("M10") -+ prefix, first_id = wait_request("chuck", 0) -+ respond(prefix, first_id, 4, 0) -+ wait_complete("successful executor request did not complete") -+ assert_released(prefix) -+ -+ command.mdi("M11") -+ prefix, second_id = wait_request("chuck", 1) -+ if second_id != first_id + 1: -+ fail("executor request IDs were not monotonic") -+ respond(prefix, second_id, 4, 7) -+ wait_complete("second successful executor request did not complete") -+ assert_released(prefix) -+ -+ command.mdi("M20") -+ prefix, request_id = wait_request("tailstock", 7) -+ respond(prefix, request_id, 5, 42) -+ wait_complete("raw executor transaction did not return to its remap") -+ assert_released(prefix) -+ if int(hal.get_value("remap.raw-result")) != 42: -+ fail("custom remap did not receive the raw executor result") -+ -+ command.mdi("M21") -+ wait_complete("non-HAL executor transport did not complete") -+ if int(hal.get_value("remap.transport-result")) != 42: -+ fail("executor helper required a HAL transport") -+ -+elif scenario == "failure": -+ command.mdi("M10") -+ prefix, request_id = wait_request("chuck", 0) -+ respond(prefix, request_id, 5, 42) -+ wait_for( -+ lambda: not hal.get_value(prefix + "request"), -+ "failed executor request was not released", -+ ) -+ if hal.get_value(prefix + "cancel"): -+ fail("terminal executor failure was incorrectly cancelled") -+ -+elif scenario == "timeout": -+ command.mdi("M11") -+ prefix, timed_out_id = wait_request("chuck", 1) -+ wait_for( -+ lambda: hal.get_value(prefix + "cancel") -+ and not hal.get_value(prefix + "request"), -+ "timed-out executor request was not cancelled", -+ timeout=2.0, -+ ) -+ -+ command.abort() -+ wait_complete("timeout recovery abort did not complete") -+ command.mdi("M10") -+ prefix, next_id = wait_request("chuck", 0) -+ respond(prefix, timed_out_id, 4, 0) -+ time.sleep(0.1) -+ if not hal.get_value(prefix + "request"): -+ fail("a stale response completed the next executor request") -+ respond(prefix, next_id, 4, 0) -+ wait_complete("request following a timeout did not complete") -+ assert_released(prefix) -+ -+elif scenario == "abort": -+ command.mdi("M10") -+ prefix, unused_request_id = wait_request("chuck", 0) -+ command.abort() -+ wait_complete("abort command did not complete") -+ wait_for( -+ lambda: hal.get_value(prefix + "cancel") -+ and not hal.get_value(prefix + "request"), -+ "aborted executor request was not cancelled", -+ ) -+ -+else: -+ fail("unknown executor scenario %s" % scenario) -+ -+print("executor remap scenario ok: %s" % scenario) -+sys.exit(0) -diff --git a/tests/remap/executor/test.ini b/tests/remap/executor/test.ini -new file mode 100644 -index 0000000000..c3ee45b9ca ---- /dev/null -+++ b/tests/remap/executor/test.ini -@@ -0,0 +1,95 @@ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0x0 -+ -+[DISPLAY] -+DISPLAY = ./test-ui.py -+ -+[RS274NGC] -+PARAMETER_FILE = sim.var -+REMAP = M10 modalgroup=10 python=m10_execute -+REMAP = M11 modalgroup=10 python=m11_execute -+REMAP = M20 modalgroup=10 python=m20_transact -+REMAP = M21 modalgroup=10 python=m21_non_hal -+ -+[PYTHON] -+TOPLEVEL = toplevel.py -+PATH_PREPEND = . -+PATH_APPEND = ../../../nc_files/remap_lib/python-stdglue/ -+ -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4.0 -+BASE_PERIOD = 0 -+SERVO_PERIOD = 1000000 -+ -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 -+ -+[HAL] -+HALFILE = ../remap-io/core_sim.hal -+ -+[TRAJ] -+NO_FORCE_HOMING = 1 -+AXES = 3 -+COORDINATES = X Y Z -+LINEAR_UNITS = mm -+ANGULAR_UNITS = degree -+DEFAULT_LINEAR_VELOCITY = 1 -+MAX_LINEAR_VELOCITY = 4 -+ -+[EMCIO] -+TOOL_TABLE = ../remap-io/simpockets.tbl -+ -+[KINS] -+KINEMATICS = trivkins -+JOINTS = 3 -+ -+[AXIS_X] -+MIN_LIMIT = -40 -+MAX_LIMIT = 40 -+MAX_VELOCITY = 4 -+MAX_ACCELERATION = 1000 -+ -+[JOINT_0] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 4 -+MAX_ACCELERATION = 1000 -+MIN_LIMIT = -40 -+MAX_LIMIT = 40 -+FERROR = 0.05 -+MIN_FERROR = 0.01 -+ -+[AXIS_Y] -+MIN_LIMIT = -40 -+MAX_LIMIT = 40 -+MAX_VELOCITY = 4 -+MAX_ACCELERATION = 1000 -+ -+[JOINT_1] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 4 -+MAX_ACCELERATION = 1000 -+MIN_LIMIT = -40 -+MAX_LIMIT = 40 -+FERROR = 0.05 -+MIN_FERROR = 0.01 -+ -+[AXIS_Z] -+MIN_LIMIT = -40 -+MAX_LIMIT = 40 -+MAX_VELOCITY = 4 -+MAX_ACCELERATION = 1000 -+ -+[JOINT_2] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 4 -+MAX_ACCELERATION = 1000 -+MIN_LIMIT = -40 -+MAX_LIMIT = 40 -+FERROR = 0.05 -+MIN_FERROR = 0.01 -diff --git a/tests/remap/executor/test.sh b/tests/remap/executor/test.sh -new file mode 100755 -index 0000000000..4d496c4c58 ---- /dev/null -+++ b/tests/remap/executor/test.sh -@@ -0,0 +1,8 @@ -+#!/bin/bash -e -+ -+for scenario in success failure timeout abort; do -+ echo "Running executor remap scenario: ${scenario}" -+ EXECUTOR_SCENARIO="${scenario}" linuxcnc -r test.ini -+done -+ -+echo "executor remap scenarios complete" -diff --git a/tests/remap/executor/toplevel.py b/tests/remap/executor/toplevel.py -new file mode 100644 -index 0000000000..1b41cf6b50 ---- /dev/null -+++ b/tests/remap/executor/toplevel.py -@@ -0,0 +1,18 @@ -+import hal -+import remap +diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc +index 90cc136..d2634e9 100644 +--- a/src/emc/task/emctask.cc ++++ b/src/emc/task/emctask.cc +@@ -514,6 +514,18 @@ int emcTaskPlanIsWait() + return waitFlag; + } + ++bool emcTaskPlanExecutorPollPending() ++{ ++ return _is && _is->executor_poll_pending; ++} + ++void emcTaskPlanClearExecutorPoll() ++{ ++ if (_is) { ++ _is->executor_poll_pending = false; ++ } ++} + -+def __init__(self): -+ remap.init_stdglue(self) -+ component = hal.component("remap") if self.task else None -+ self.chuck = remap.HalExecutor(self, "chuck", component) -+ self.tailstock = remap.HalExecutor(self, "tailstock", component) -+ self.memory_executor = remap.MemoryExecutor() + int emcTaskPlanClearWait() + { + waitFlag = 0; +diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc +index 6c57192..0d3448c 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -577,7 +577,12 @@ extern int emcTaskMopup(); + + void readahead_reading(void) + { +- if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE) { ++ // While a Stop or Pause holds, only an executor remap polling a request ++ // it has started runs, until the request ends; nothing past it is read. ++ const bool held = ++ emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE || ++ emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED; ++ if (held && !emcTaskPlanExecutorPollPending()) { + return; + } + int readRetval; +@@ -596,6 +601,11 @@ interpret_again: + goto interpret_again; + } + } else { ++ if (held && !emcTaskPlanExecutorPollPending()) { ++ return; ++ } ++ // a remap still polling sets it again ++ emcTaskPlanClearExecutorPoll(); + readRetval = emcTaskPlanRead(); + /*! \todo MGS FIXME + This if() actually evaluates to if (readRetval != INTERP_OK)... +@@ -633,8 +643,18 @@ interpret_again: + // the discarded commands may include a tool + // offset canon already took on + CANON_RESYNC_TOOL_OFFSET(); +- emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, +- "interpreter error"); ++ if (held) { ++ // An executor request failed while Stop ++ // or Pause held the program. Held motion ++ // would never let the program finish, so ++ // end it like an execution error, which ++ // also clears the Stop state. ++ emcStatus->task.execState = ++ EMC_TASK_EXEC::ERROR; ++ } else { ++ emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, ++ "interpreter error"); ++ } + } else if (execRetval == -1 + || execRetval == INTERP_EXIT ) { + emcStatus->task.interpState = +@@ -766,11 +786,14 @@ static void mdi_execute_hook(void) + return; + } + +- // determine when a MDI command actually finishes normally. ++ // determine when a MDI command actually finishes normally. One that ++ // finishes while paused (an executor request runs to its end) is ++ // reported done after Resume, so the Pause holds until then. + if (interp_list.len() == 0 && + emcTaskCommand == NULL && + emcStatus->task.execState == EMC_TASK_EXEC::DONE && + emcStatus->task.interpState != EMC_TASK_INTERP::IDLE && ++ emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED && + emcStatus->motion.traj.queue == 0 && + emcStatus->io.status == RCS_STATUS::DONE && + !mdi_execute_wait && +@@ -880,6 +903,10 @@ static bool emcTaskStopAllowsIssue(const NMLmsg *cmd) + return !reinterpret_cast(cmd)->now; + case EMC_MOTION_SET_AOUT_TYPE: + return !reinterpret_cast(cmd)->now; ++ case EMC_TRAJ_DELAY_TYPE: ++ case EMC_TASK_PLAN_SYNCH_TYPE: ++ // The poll of an executor request already under way. ++ return emcTaskPlanExecutorPollPending(); + default: + return false; + } +@@ -1024,6 +1051,9 @@ static void emcTaskStopResume() + */ + static EMC_TASK_HOLD_WAIT emcTaskHoldWait() + { ++ if (emcTaskPlanExecutorPollPending()) { ++ return EMC_TASK_HOLD_WAIT::EXECUTOR; ++ } + if (emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_HOMING) { + return EMC_TASK_HOLD_WAIT::HOMING; + } +@@ -1728,6 +1758,9 @@ static int emcTaskPlan(void) + + } // switch (type) in ON, AUTO, PAUSED + ++ // an executor request under way is polled while paused ++ readahead_reading(); + -+ if component is not None: -+ component.newpin("owner-marker", hal.HAL_BIT, hal.HAL_OUT) -+ component.newpin("raw-result", hal.HAL_S32, hal.HAL_OUT) -+ component.newpin("transport-result", hal.HAL_S32, hal.HAL_OUT) -+ component["owner-marker"] = True -+ component.ready() -+ self.executor_component = component + break; // EMC_TASK_INTERP::PAUSED + + case EMC_TASK_INTERP::WAITING: +@@ -2892,8 +2925,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + retval = -1; + break; + } +- // track interpState also during MDI - it might be an oword sub call +- emcStatus->task.interpState = EMC_TASK_INTERP::READING; ++ // track interpState also during MDI - it might be an oword sub call; ++ // an executor request polled while paused keeps the Pause ++ if (emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED) { ++ emcStatus->task.interpState = EMC_TASK_INTERP::READING; ++ } + + if (execute_msg->command[0] != 0) { + char * command = execute_msg->command; +@@ -3295,7 +3331,8 @@ static int emcTaskExecute(void) + case EMC_TASK_EXEC::DONE: + STEPPING_CHECK(); + if (!emcStatus->motion.traj.queueFull && +- emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED && ++ (emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED || ++ emcTaskPlanExecutorPollPending()) && + emcStatus->task.stopState != EMC_TASK_STOP_STATE::STOPPED && + emcStatus->task.stopState != EMC_TASK_STOP_STATE::STARTING) { + if (NULL == emcTaskCommand) { +@@ -3601,7 +3638,9 @@ static int emcTaskExecute(void) + + case EMC_TASK_EXEC::WAITING_FOR_DELAY: + STEPPING_CHECK(); +- if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE) { ++ // an executor's poll dwell is not frozen: its request is still running ++ if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && ++ !emcTaskPlanExecutorPollPending()) { + if (taskExecDelayStopTime <= 0.0) { + taskExecDelayStopTime = etime(); + } +diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh +index 79dbeb6..ea3bdc8 100644 +--- a/src/emc/task/task.hh ++++ b/src/emc/task/task.hh +@@ -39,6 +39,10 @@ int emcTaskSetState(EMC_TASK_STATE state); + int emcTaskPlanInit(); + int emcTaskPlanSetWait(); + int emcTaskPlanIsWait(); ++// An executor remap polls a request it has started (see interp setup ++// executor_poll_pending); cleared before each interpreter read. ++bool emcTaskPlanExecutorPollPending(); ++void emcTaskPlanClearExecutorPoll(); + int emcTaskPlanClearWait(); + int emcTaskPlanSynch(); + int emcTaskPlanSetOptionalStop(bool state); +diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc +index 6a0b6d7..74edfa0 100644 +--- a/src/emc/usr_intf/axis/extensions/emcmodule.cc ++++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc +@@ -3425,6 +3425,7 @@ PyMODINIT_FUNC PyInit_linuxcnc(void) + PyModule_AddIntConstant(m, "HOLD_WAIT_HOMING", (int)EMC_TASK_HOLD_WAIT::HOMING); + PyModule_AddIntConstant(m, "HOLD_WAIT_IO", (int)EMC_TASK_HOLD_WAIT::IO); + PyModule_AddIntConstant(m, "HOLD_WAIT_SYSTEM_COMMAND", (int)EMC_TASK_HOLD_WAIT::SYSTEM_COMMAND); ++ PyModule_AddIntConstant(m, "HOLD_WAIT_EXECUTOR", (int)EMC_TASK_HOLD_WAIT::EXECUTOR); + PyModule_AddIntConstant(m, "STOP_STOPPING", (int)EMC_TASK_STOP_STATE::STOPPING); + PyModule_AddIntConstant(m, "STOP_STOPPED", (int)EMC_TASK_STOP_STATE::STOPPED); + PyModule_AddIntConstant(m, "STOP_STARTING", (int)EMC_TASK_STOP_STATE::STARTING); diff --git a/linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch b/linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch index 02878942..963e57a1 100644 --- a/linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch +++ b/linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch @@ -4,31 +4,17 @@ Date: Wed, 2 Sep 2026 15:31:24 +0200 Subject: [PATCH] fix(spindle): publish modal CSS maximum in status --- - src/emc/task/emccanon.cc | 4 +- - src/emc/task/emctaskmain.cc | 2 +- - src/emc/task/taskintf.cc | 2 +- - src/emc/usr_intf/axis/extensions/emcmodule.cc | 1 + - tests/css-status/README | 6 ++ - tests/css-status/checkresult | 4 ++ - tests/css-status/core_sim.hal | 10 +++ - tests/css-status/test-ui.py | 61 +++++++++++++++++++ - tests/css-status/test.ini | 55 +++++++++++++++++ - tests/css-status/test.sh | 4 ++ - tests/css-status/tool.tbl | 0 - 11 files changed, 146 insertions(+), 3 deletions(-) - create mode 100644 tests/css-status/README - create mode 100755 tests/css-status/checkresult - create mode 100644 tests/css-status/core_sim.hal - create mode 100755 tests/css-status/test-ui.py - create mode 100644 tests/css-status/test.ini - create mode 100755 tests/css-status/test.sh - create mode 100644 tests/css-status/tool.tbl + src/emc/task/emccanon.cc | 4 +++- + src/emc/task/emctaskmain.cc | 2 +- + src/emc/task/taskintf.cc | 2 +- + src/emc/usr_intf/axis/extensions/emcmodule.cc | 1 + + 4 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc -index ad1352a7d4..9f36a8de8e 100644 +index 513c932..d6e8437 100644 --- a/src/emc/task/emccanon.cc +++ b/src/emc/task/emccanon.cc -@@ -3027,7 +3027,9 @@ void SPINDLE_RETRACT_TRAVERSE() +@@ -2868,7 +2868,9 @@ void SPINDLE_RETRACT_TRAVERSE() } void SET_SPINDLE_MODE(int spindle, double css_max) { @@ -40,10 +26,10 @@ index ad1352a7d4..9f36a8de8e 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 0be1c528c2..59021c7dcb 100644 +index 0d3448c..fd0335e 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -918,7 +918,7 @@ static void emcTaskStopProgress() +@@ -1084,7 +1084,7 @@ static void emcTaskStopProgress() bool spindle_output_active = false; for (int s = 0; s < emcStatus->motion.traj.spindles; ++s) { const auto &status = emcStatus->motion.spindle[s]; @@ -53,10 +39,10 @@ index 0be1c528c2..59021c7dcb 100644 stop_spindles[s].running = spindle_running; stop_spindles[s].speed = status.speed; diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index 4796832331..d88c727d52 100644 +index 3328659..aa63ab4 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -2046,7 +2046,7 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ +@@ -2184,7 +2184,7 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ for (s = 0; s < num_spindles; s++){ stat[s].spindle_override_enabled = enables & SS_ENABLED; @@ -66,10 +52,10 @@ index 4796832331..d88c727d52 100644 stat[s].feedback = emcmotStatus.spindle_status[s].spindleSpeedIn * 60.0; stat[s].brake = emcmotStatus.spindle_status[s].brake; diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index bd747787e4..03437fbce2 100644 +index 74edfa0..af63368 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1458,6 +1458,7 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { +@@ -1463,6 +1463,7 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { F2("override_enabled", spindle_override_enabled); F(speed); F(feedback); @@ -77,182 +63,3 @@ index bd747787e4..03437fbce2 100644 F2("override", spindle_scale); F(homed); F(orient_state); -diff --git a/tests/css-status/README b/tests/css-status/README -new file mode 100644 -index 0000000000..66ad330dd7 ---- /dev/null -+++ b/tests/css-status/README -@@ -0,0 +1,6 @@ -+Verify CSS maximum spindle speed status follows the active G96/G97 mode. -+ -+The regression enters G96 while the spindle is stopped, checks that the D -+word is published through spindle status, verifies M5 does not discard that -+modal limit, and checks that G97 clears it. It also verifies that spindle -+`enabled` follows the explicit on/off state rather than a nonzero CSS limit. -diff --git a/tests/css-status/checkresult b/tests/css-status/checkresult -new file mode 100755 -index 0000000000..56f319c1fe ---- /dev/null -+++ b/tests/css-status/checkresult -@@ -0,0 +1,4 @@ -+#!/bin/sh -+set -e -+ -+grep -q '^CSS status scenario ok$' "$1" -diff --git a/tests/css-status/core_sim.hal b/tests/css-status/core_sim.hal -new file mode 100644 -index 0000000000..e244f001df ---- /dev/null -+++ b/tests/css-status/core_sim.hal -@@ -0,0 +1,10 @@ -+loadrt trivkins -+loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 num_joints=1 num_spindles=1 -+ -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+ -+net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in -+ -+setp spindle.0.at-speed true -diff --git a/tests/css-status/test-ui.py b/tests/css-status/test-ui.py -new file mode 100755 -index 0000000000..2372f6c89e ---- /dev/null -+++ b/tests/css-status/test-ui.py -@@ -0,0 +1,61 @@ -+#!/usr/bin/env python3 -+ -+import math -+import sys -+import time -+ -+import linuxcnc -+ -+ -+def fail(message): -+ print(message) -+ sys.exit(1) -+ -+ -+def wait_complete(message, timeout=10.0): -+ if command.wait_complete(timeout) != linuxcnc.RCS_DONE: -+ fail(message) -+ status.poll() -+ -+ -+def assert_css_maximum(expected, message): -+ status.poll() -+ actual = status.spindle[0]["css_maximum"] -+ if not math.isclose(actual, expected, abs_tol=0.001): -+ fail("%s: expected %.3f, got %.3f" % (message, expected, actual)) -+ -+ -+command = linuxcnc.command() -+status = linuxcnc.stat() -+ -+deadline = time.time() + 10.0 -+while time.time() < deadline: -+ status.poll() -+ if status.task_state == linuxcnc.STATE_ESTOP: -+ break -+ time.sleep(0.02) -+else: -+ fail("LinuxCNC did not initialize") -+ -+command.state(linuxcnc.STATE_ESTOP_RESET) -+command.state(linuxcnc.STATE_ON) -+wait_complete("machine did not turn on") -+ -+command.mode(linuxcnc.MODE_MDI) -+wait_complete("machine did not enter MDI") -+ -+command.mdi("G96 S100 D2111") -+wait_complete("G96 command did not complete") -+assert_css_maximum(2111.0, "G96 did not publish its D word") -+if status.spindle[0]["enabled"]: -+ fail("G96 reported a stopped spindle as running") -+ -+command.mdi("M5") -+wait_complete("M5 command did not complete") -+assert_css_maximum(2111.0, "M5 discarded the modal CSS maximum") -+ -+command.mdi("G97") -+wait_complete("G97 command did not complete") -+assert_css_maximum(0.0, "G97 did not clear the CSS maximum") -+ -+print("CSS status scenario ok") -diff --git a/tests/css-status/test.ini b/tests/css-status/test.ini -new file mode 100644 -index 0000000000..61ccf6bc64 ---- /dev/null -+++ b/tests/css-status/test.ini -@@ -0,0 +1,55 @@ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0x0 -+ -+[DISPLAY] -+DISPLAY = ./test-ui.py -+ -+[RS274NGC] -+PARAMETER_FILE = sim.var -+ -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4.0 -+BASE_PERIOD = 0 -+SERVO_PERIOD = 1000000 -+ -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 -+ -+[HAL] -+HALFILE = core_sim.hal -+ -+[TRAJ] -+NO_FORCE_HOMING = 1 -+AXES = 1 -+COORDINATES = X -+SPINDLES = 1 -+LINEAR_UNITS = mm -+ANGULAR_UNITS = degree -+DEFAULT_LINEAR_VELOCITY = 10 -+MAX_LINEAR_VELOCITY = 50 -+ -+[EMCIO] -+TOOL_TABLE = tool.tbl -+ -+[KINS] -+KINEMATICS = trivkins coordinates=X -+JOINTS = 1 -+ -+[AXIS_X] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+ -+[JOINT_0] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -diff --git a/tests/css-status/test.sh b/tests/css-status/test.sh -new file mode 100755 -index 0000000000..13436c16b1 ---- /dev/null -+++ b/tests/css-status/test.sh -@@ -0,0 +1,4 @@ -+#!/bin/sh -+set -e -+ -+linuxcnc -r test.ini -diff --git a/tests/css-status/tool.tbl b/tests/css-status/tool.tbl -new file mode 100644 -index 0000000000..e69de29bb2 diff --git a/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch b/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch index d1d7dd23..fd1f0edf 100644 --- a/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch +++ b/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch @@ -4,30 +4,12 @@ Date: Fri, 4 Sep 2026 15:26:24 +0200 Subject: [PATCH] rs274ngc: pass spindle selectors to remaps --- - docs/src/remap/remap.adoc | 12 +++++++++-- - src/emc/rs274ngc/interp_remap.cc | 15 +++++++++---- - tests/remap/dollar-argspec/README | 1 + - tests/remap/dollar-argspec/expected | 29 ++++++++++++++++++++++++++ - tests/remap/dollar-argspec/m501.ngc | 9 ++++++++ - tests/remap/dollar-argspec/m502.ngc | 5 +++++ - tests/remap/dollar-argspec/remap.py | 10 +++++++++ - tests/remap/dollar-argspec/test.ini | 18 ++++++++++++++++ - tests/remap/dollar-argspec/test.ngc | 11 ++++++++++ - tests/remap/dollar-argspec/test.sh | 3 +++ - tests/remap/dollar-argspec/toplevel.py | 1 + - 11 files changed, 108 insertions(+), 6 deletions(-) - create mode 100644 tests/remap/dollar-argspec/README - create mode 100644 tests/remap/dollar-argspec/expected - create mode 100644 tests/remap/dollar-argspec/m501.ngc - create mode 100644 tests/remap/dollar-argspec/m502.ngc - create mode 100644 tests/remap/dollar-argspec/remap.py - create mode 100644 tests/remap/dollar-argspec/test.ini - create mode 100644 tests/remap/dollar-argspec/test.ngc - create mode 100755 tests/remap/dollar-argspec/test.sh - create mode 100644 tests/remap/dollar-argspec/toplevel.py + docs/src/remap/remap.adoc | 12 ++++++++++-- + src/emc/rs274ngc/interp_remap.cc | 15 +++++++++++---- + 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index b263f1e959..5bb208e611 100644 +index 642e4c7..e332924 100644 --- a/docs/src/remap/remap.adoc +++ b/docs/src/remap/remap.adoc @@ -324,7 +324,7 @@ there is the somewhat easier way of <`:: The `>` (greater-than) character specifies that the current feed must be greater than zero, diff --git a/src/emc/rs274ngc/interp_remap.cc b/src/emc/rs274ngc/interp_remap.cc -index c33df5a316..b13bdc0a5e 100644 +index 286ee98..cf192c1 100644 --- a/src/emc/rs274ngc/interp_remap.cc +++ b/src/emc/rs274ngc/interp_remap.cc -@@ -206,6 +206,7 @@ int Interp::convert_remapped_code(block_pointer /*block*/, +@@ -204,6 +204,7 @@ int Interp::convert_remapped_code(block_pointer /*block*/, // 4. handle '>' as to require a positive feed. // 5. handle '^' as to require a positive speed. // 6. handle 'N' as to add the line number. @@ -70,7 +52,7 @@ index c33df5a316..b13bdc0a5e 100644 // // return INTERP_ERROR and propagate appropriate message if any errors so far // else return INTERP_OK -@@ -332,6 +333,10 @@ int Interp::add_parameters(setup_pointer settings, +@@ -330,6 +331,10 @@ int Interp::add_parameters(setup_pointer settings, case 'x' : PARAM('x',"x",block->x_flag,block->x_number); break; case 'y' : PARAM('y',"y",block->y_flag,block->y_number); break; case 'z' : PARAM('z',"z",block->z_flag,block->z_number); break; @@ -81,7 +63,7 @@ index c33df5a316..b13bdc0a5e 100644 case '-' : break; // ignore - backwards compatibility default: ; } -@@ -367,10 +372,12 @@ int Interp::add_parameters(setup_pointer settings, +@@ -365,10 +370,12 @@ int Interp::add_parameters(setup_pointer settings, } // ^...require positive speed @@ -97,7 +79,7 @@ index c33df5a316..b13bdc0a5e 100644 } else { tail += "S>0,"; -@@ -461,7 +468,7 @@ int Interp::parse_remap(const char *inistring, int lineno) +@@ -459,7 +466,7 @@ int Interp::parse_remap(const char *inistring, int lineno) } if (!strncasecmp(kw,"argspec",kwlen)) { size_t pos = strspn (arg, @@ -106,144 +88,3 @@ index c33df5a316..b13bdc0a5e 100644 if (pos != strlen(arg)) { Error("argspec: illegal word '%c' - %d:REMAP = %s", arg[pos],lineno,inistring); -diff --git a/tests/remap/dollar-argspec/README b/tests/remap/dollar-argspec/README -new file mode 100644 -index 0000000000..3758b4fb8d ---- /dev/null -+++ b/tests/remap/dollar-argspec/README -@@ -0,0 +1 @@ -+Exercise passing the optional $ spindle selector to Python and NGC remaps. -diff --git a/tests/remap/dollar-argspec/expected b/tests/remap/dollar-argspec/expected -new file mode 100644 -index 0000000000..518d1fe2f7 ---- /dev/null -+++ b/tests/remap/dollar-argspec/expected -@@ -0,0 +1,29 @@ -+ -+ N..... USE_LENGTH_UNITS(CANON_UNITS_MM) -+ N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_XY_ROTATION(0.0000) -+ N..... SET_FEED_REFERENCE(CANON_XYZ) -+ N..... ON_RESET() -+ Python P=0 spindle=omitted -+ Python P=1 spindle=1 -+ Python P=2 spindle=-1 -+ N..... MESSAGE(" NGC spindle omitted") -+ N..... MESSAGE(" NGC spindle=2.000000") -+ N..... MESSAGE(" positional n_args=2.000000 P=7.000000 spindle=1.000000") -+ N..... SET_SPINDLE_SPEED(0, 1000.0000) -+ N..... SET_SPINDLE_SPEED(1, 2000.0000) -+ Python spindle=0 speed=1000 -+ Python spindle=1 speed=2000 -+ N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ N..... SET_XY_ROTATION(0.0000) -+ N..... SET_FEED_MODE(0, 0) -+ N..... SET_FEED_RATE(0.0000) -+ N..... STOP_SPINDLE_TURNING(0) -+ N..... SET_SPINDLE_MODE(0 0.0000) -+ N..... STOP_SPINDLE_TURNING(1) -+ N..... SET_SPINDLE_MODE(1 0.0000) -+ N..... STOP_SPINDLE_TURNING(2) -+ N..... SET_SPINDLE_MODE(2 0.0000) -+ N..... PROGRAM_END() -+ N..... ON_RESET() -diff --git a/tests/remap/dollar-argspec/m501.ngc b/tests/remap/dollar-argspec/m501.ngc -new file mode 100644 -index 0000000000..e5495df885 ---- /dev/null -+++ b/tests/remap/dollar-argspec/m501.ngc -@@ -0,0 +1,9 @@ -+o sub -+o100 if [EXISTS[#]] -+ (debug, NGC spindle=#) -+o100 else -+ (debug, NGC spindle omitted) -+o100 endif -+o endsub -+m2 -+% -diff --git a/tests/remap/dollar-argspec/m502.ngc b/tests/remap/dollar-argspec/m502.ngc -new file mode 100644 -index 0000000000..600c9a95f4 ---- /dev/null -+++ b/tests/remap/dollar-argspec/m502.ngc -@@ -0,0 +1,5 @@ -+o sub -+(debug, positional n_args=# P=#1 spindle=#2) -+o endsub -+m2 -+% -diff --git a/tests/remap/dollar-argspec/remap.py b/tests/remap/dollar-argspec/remap.py -new file mode 100644 -index 0000000000..95f0e7b8e9 ---- /dev/null -+++ b/tests/remap/dollar-argspec/remap.py -@@ -0,0 +1,10 @@ -+def m500(self, **words): -+ spindle = words.get("spindle", "omitted") -+ if spindle != "omitted": -+ spindle = int(spindle) -+ print("M500 Python P={} spindle={}".format(int(words["p"]), spindle)) -+ -+ -+def m503(self, **words): -+ spindle = int(words.get("spindle", 0)) -+ print("M503 Python spindle={} speed={}".format(spindle, int(words["s"]))) -diff --git a/tests/remap/dollar-argspec/test.ini b/tests/remap/dollar-argspec/test.ini -new file mode 100644 -index 0000000000..36abfcbc62 ---- /dev/null -+++ b/tests/remap/dollar-argspec/test.ini -@@ -0,0 +1,18 @@ -+[EMC] -+DEBUG=0 -+ -+[RS274NGC] -+SUBROUTINE_PATH = . -+LOG_LEVEL=0 -+OWORD_NARGS = 1 -+REMAP=M500 py=m500 modalgroup=10 argspec=P$ -+REMAP=M501 ngc=m501 modalgroup=10 argspec=$ -+REMAP=M502 ngc=m502 modalgroup=10 argspec=@P$ -+REMAP=M503 py=m503 modalgroup=10 argspec=^$ -+ -+[TRAJ] -+SPINDLES=3 -+ -+[PYTHON] -+PATH_PREPEND=. -+TOPLEVEL=toplevel.py -diff --git a/tests/remap/dollar-argspec/test.ngc b/tests/remap/dollar-argspec/test.ngc -new file mode 100644 -index 0000000000..b47556494a ---- /dev/null -+++ b/tests/remap/dollar-argspec/test.ngc -@@ -0,0 +1,11 @@ -+M500 P0 -+M500 P1 $1 -+M500 P2 $-1 -+M501 -+M501 $2 -+M502 P7 $1 -+S1000 -+S2000 $1 -+M503 -+M503 $1 -+M2 -diff --git a/tests/remap/dollar-argspec/test.sh b/tests/remap/dollar-argspec/test.sh -new file mode 100755 -index 0000000000..7a389520fa ---- /dev/null -+++ b/tests/remap/dollar-argspec/test.sh -@@ -0,0 +1,3 @@ -+#!/bin/bash -+rs274 -i test.ini -n 0 -g test.ngc 2>&1 | awk '{$1=""; print}' -+exit "${PIPESTATUS[0]}" -diff --git a/tests/remap/dollar-argspec/toplevel.py b/tests/remap/dollar-argspec/toplevel.py -new file mode 100644 -index 0000000000..0dc38fa2a6 ---- /dev/null -+++ b/tests/remap/dollar-argspec/toplevel.py -@@ -0,0 +1 @@ -+import remap diff --git a/linuxcnc-patches/0016-motion-joint-target-preparation.patch b/linuxcnc-patches/0016-motion-joint-target-preparation.patch index ca06d249..133217ad 100644 --- a/linuxcnc-patches/0016-motion-joint-target-preparation.patch +++ b/linuxcnc-patches/0016-motion-joint-target-preparation.patch @@ -4,26 +4,18 @@ Date: Thu, 17 Sep 2026 17:40:12 +0200 Subject: [PATCH] motion-joint-target-preparation --- - src/emc/motion/axis.c | 7 +- - src/emc/motion/control.c | 166 ++++++++++++++--------- - src/emc/motion/mot_priv.h | 9 ++ - src/emc/motion/simple_tp.c | 11 ++ - src/emc/motion/simple_tp.h | 2 + - tests/motion-target-preparation/README | 1 + - tests/motion-target-preparation/expected | 0 - tests/motion-target-preparation/test.py | 90 ++++++++++++ - tests/motion-target-preparation/test.sh | 3 + - 9 files changed, 219 insertions(+), 70 deletions(-) - create mode 100644 tests/motion-target-preparation/README - create mode 100644 tests/motion-target-preparation/expected - create mode 100644 tests/motion-target-preparation/test.py - create mode 100755 tests/motion-target-preparation/test.sh + src/emc/motion/axis.c | 7 +- + src/emc/motion/control.c | 166 ++++++++++++++++++++++--------------- + src/emc/motion/mot_priv.h | 9 ++ + src/emc/motion/simple_tp.c | 11 +++ + src/emc/motion/simple_tp.h | 2 + + 5 files changed, 125 insertions(+), 70 deletions(-) diff --git a/src/emc/motion/axis.c b/src/emc/motion/axis.c -index 25b74309be..ba87f42442 100644 +index 4cc5503..e814320 100644 --- a/src/emc/motion/axis.c +++ b/src/emc/motion/axis.c -@@ -451,11 +451,8 @@ void axis_sync_teleop_tp_to_carte_pos(int extfactor, double *pcmd_p[]) +@@ -452,11 +452,8 @@ void axis_sync_teleop_tp_to_carte_pos(int extfactor, double *pcmd_p[]) // synced curr_pos the next time simple_tp_update integrates one // cycle of motion. for (n = 0; n < EMCMOT_MAX_AXIS; n++) { @@ -38,10 +30,10 @@ index 25b74309be..ba87f42442 100644 } diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 040e534653..8ed2cb3882 100644 +index 75a9f1c..f22ab9b 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1178,9 +1178,83 @@ static void handle_jjogwheels(void) +@@ -1257,9 +1257,83 @@ static void handle_jjogwheels(void) first_pass = 0; } @@ -126,7 +118,7 @@ index 040e534653..8ed2cb3882 100644 emcmot_joint_t *joint; double positions[EMCMOT_MAX_JOINTS]; double vel_lim; -@@ -1353,40 +1427,21 @@ static void get_pos_cmds(long period) +@@ -1444,40 +1518,21 @@ static void get_pos_cmds(long period) ext_offset_coord_limit = 0; } @@ -179,7 +171,7 @@ index 040e534653..8ed2cb3882 100644 /* there is data in the interpolators */ /* run interpolation */ for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1434,39 +1489,20 @@ static void get_pos_cmds(long period) +@@ -1525,39 +1580,20 @@ static void get_pos_cmds(long period) /* the next position then gets run through the inverse kins, to compute the next positions of the joints */ @@ -234,10 +226,10 @@ index 040e534653..8ed2cb3882 100644 /* END OF OUTPUT KINS */ diff --git a/src/emc/motion/mot_priv.h b/src/emc/motion/mot_priv.h -index 5eba0f6711..2050ad51a3 100644 +index 954de98..6e02b16 100644 --- a/src/emc/motion/mot_priv.h +++ b/src/emc/motion/mot_priv.h -@@ -347,4 +347,13 @@ int joint_is_lockable(int joint_num); +@@ -352,4 +352,13 @@ extern void emcmotApplyPendingPlannerType(void); #define SET_JOINT_FAULT_FLAG(joint,fl) if (fl) (joint)->flag |= EMCMOT_JOINT_FAULT_BIT; else (joint)->flag &= ~EMCMOT_JOINT_FAULT_BIT; @@ -252,7 +244,7 @@ index 5eba0f6711..2050ad51a3 100644 + #endif /* MOT_PRIV_H */ diff --git a/src/emc/motion/simple_tp.c b/src/emc/motion/simple_tp.c -index 64ffc4f35e..0f9ff04e33 100644 +index 64ffc4f..0f9ff04 100644 --- a/src/emc/motion/simple_tp.c +++ b/src/emc/motion/simple_tp.c @@ -18,6 +18,17 @@ @@ -274,7 +266,7 @@ index 64ffc4f35e..0f9ff04e33 100644 { if(tp->max_jerk <= 0.0001 || GET_TRAJ_PLANNER_TYPE() == 0){ diff --git a/src/emc/motion/simple_tp.h b/src/emc/motion/simple_tp.h -index 26f1a64b48..c4b10cd20d 100644 +index 26f1a64..c4b10cd 100644 --- a/src/emc/motion/simple_tp.h +++ b/src/emc/motion/simple_tp.h @@ -97,6 +97,8 @@ extern "C" { @@ -286,118 +278,3 @@ index 26f1a64b48..c4b10cd20d 100644 extern void simple_tp_update(simple_tp_t *tp, double period); extern void simple_tp_update_normal(simple_tp_t *tp, double period); extern void simple_scurve_tp_update(simple_tp_t *tp, double period); -diff --git a/tests/motion-target-preparation/README b/tests/motion-target-preparation/README -new file mode 100644 -index 0000000000..99955caa22 ---- /dev/null -+++ b/tests/motion-target-preparation/README -@@ -0,0 +1 @@ -+Compiles production target preparation with deterministic inverse-kinematics doubles and the real cubic implementation. Checks that inverse-kinematics and interpolation failures cannot partially update the joint command vector. No runtime or realtime privileges are required. -diff --git a/tests/motion-target-preparation/expected b/tests/motion-target-preparation/expected -new file mode 100644 -index 0000000000..e69de29bb2 -diff --git a/tests/motion-target-preparation/test.py b/tests/motion-target-preparation/test.py -new file mode 100644 -index 0000000000..1fa2553aa3 ---- /dev/null -+++ b/tests/motion-target-preparation/test.py -@@ -0,0 +1,90 @@ -+import os -+import re -+from pathlib import Path -+import subprocess -+import tempfile -+root = Path(__file__).resolve().parents[2] -+source = (root / 'src/emc/motion/control.c').read_text() -+def function(name, source=source): -+ start = re.search(r'^(?:static )?(?:int|void) ' + name + r'\(', source, re.M).start() -+ brace = source.index('{', start) -+ depth = 1 -+ end = brace + 1 -+ while depth: -+ depth += (source[end] == '{') - (source[end] == '}') -+ end += 1 -+ return source[start:end] -+preamble = r""" -+#include -+#include -+#include -+#include "cubic.h" -+#define _(s) s -+#define reportError(...) ((void)0) -+#define NO_OF_KINS_JOINTS 3 -+typedef struct { double x; } EmcPose; -+typedef struct { -+ double coarse_pos; -+ CUBIC_STRUCT cubic; -+} emcmot_joint_t; -+static emcmot_joint_t joints[3]; -+typedef int KINEMATICS_FORWARD_FLAGS; -+static int iflags, fflags; -+static int ik_result; -+static double solution[3]; -+static int kinematicsInverse(const EmcPose *p, double *out, int *i, int *f) { -+ *f = *f + 1; -+ memcpy(out, solution, sizeof(solution)); return ik_result; -+} -+""" -+# The second patch supplies additional lifecycle/held-reference test fixtures. -+extension = Path(__file__).with_name('availability-fixture.h') -+if extension.exists(): preamble += extension.read_text() -+main = r""" -+int main(void) { -+ double positions[3]; CUBIC_STRUCT staged[3]; EmcPose pose = {0}; -+ for (int n=0; n<3; n++) { -+ cubicInit(&joints[n].cubic); -+ cubicSetSegmentTime(&joints[n].cubic, .004); -+ cubicSetInterpolationRate(&joints[n].cubic, 4); -+ joints[n].coarse_pos = 20+n; -+ solution[n] = n; -+ } -+ unsigned char before[sizeof(joints)]; memcpy(before, joints, sizeof(joints)); -+ fflags = 10; -+ ik_result = -1; -+ assert(prepare_joint_targets(&pose, positions, staged) != 0); -+ assert(fflags == 10); -+ ik_result = 0; -+ solution[2] = NAN; -+ assert(prepare_joint_targets(&pose, positions, staged) != 0); -+ assert(memcmp(before, joints, sizeof(joints)) == 0); -+ assert(fflags == 10); -+ solution[2] = 2; -+ assert(prepare_joint_targets(&pose, positions, staged) == 0); -+ assert(memcmp(before, joints, sizeof(joints)) == 0); -+ assert(fflags == 11); -+ assert(positions[0] == 0 && positions[1] == 1 && positions[2] == 2); -+ joints[2].cubic.configured = 0; -+ memcpy(before, joints, sizeof(joints)); -+ assert(prepare_joint_targets(&pose, positions, staged) != 0); -+ assert(memcmp(before, joints, sizeof(joints)) == 0); -+ assert(fflags == 11); -+ joints[2].cubic.configured = joints[0].cubic.configured; -+#ifdef TEST_AVAILABILITY -+ test_availability(&pose, positions, staged); -+#endif -+} -+""" -+with tempfile.TemporaryDirectory() as tmp: -+ tmp = Path(tmp) -+ # Only the math header is shimmed; cubic.c is compiled unchanged. -+ (tmp/'rtapi_math.h').write_text('#include \n') -+ text = preamble + '\n' + function('prepare_joint_targets') -+ extra = Path(__file__).with_name('availability-cases.h') -+ if extra.exists(): text += '\n' + extra.read_text() -+ (tmp/'test.c').write_text(text + '\n' + main) -+ subprocess.run([os.environ.get('CC', 'cc'), '-std=c99', '-I'+str(tmp), -+ '-I'+str(root/'src/emc/kinematics'), '-I'+str(root/'src/emc/motion'), str(tmp/'test.c'), -+ str(root/'src/emc/kinematics/cubic.c'), '-lm', '-o', str(tmp/'test')], check=True) -+ subprocess.run([str(tmp/'test')], check=True) -diff --git a/tests/motion-target-preparation/test.sh b/tests/motion-target-preparation/test.sh -new file mode 100755 -index 0000000000..0cd44bb027 ---- /dev/null -+++ b/tests/motion-target-preparation/test.sh -@@ -0,0 +1,3 @@ -+#!/bin/sh -+set -eu -+python3 test.py diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index aa640cd5..029ef878 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -3,113 +3,68 @@ From: Dariusz Majnert Date: Thu, 17 Sep 2026 18:00:42 +0200 Subject: [PATCH] runtime-joint-and-spindle-availability +Ported to v2.10.0-pre2. Differences from the patch on the old base: + +Acquisition of an unhomed joint still homes it automatically and reports +AVAILABLE only after homing succeeds, but the homing now runs through the +queued home cycle upstream built for G28.2 instead of the patch's own +homing wait. After the hardware ACK, motion enters HOMING and waits for +task's home request. Task issues it as a queued EMC_JOINT_HOME (FREE dip, +EXEC_WAITING_FOR_HOMING, start timeout, completion from motion's +homing_active, restoration of the prior trajectory mode) and then waits +for the acquisition to complete. Motion accepts that one JOINT_HOME for +the acquiring joint, starts it from a stationary FREE joint, and publishes +AVAILABLE or a homing fault in the servo cycle in which homing ends. + +Removed from the old patch: motion clearing coord/teleop itself and +restoring the saved motion state on completion (return_motion_state), and +motion's own homing start timeout. Abort, E-stop and Machine Off cancel +the acquisition homing as they cancel a G28.2 homing wait. + +HAL pins use the pin API of v2.10.0-pre2. + +The interpreter wait release on PLAN_SYNCH, which the patch added for +direct requests and stale waits, now skips an MDI line that still owns +the wait (mdi_execute_wait); on v2.10.0-pre2 the unconditional release +left such a line READING forever (seen in tests/tool-wear-abort after +E-stop). tests/interp/m98m99/12-M99-endless-main-program expectations +gain the availability configuration and reordered ABORT, as in the +other motion-logger tests. --- - docs/src/config/ini-config.adoc | 31 + - docs/src/config/python-interface.adoc | 26 + + docs/src/config/ini-config.adoc | 33 + + docs/src/config/python-interface.adoc | 29 +- docs/src/man/man9/motion.9.adoc | 26 + src/emc/ini/inijoint.cc | 36 +- src/emc/ini/inispindle.cc | 29 + src/emc/ini/linuxcnc_check_ini.py | 7 +- src/emc/motion-logger/motion-logger.c | 22 + src/emc/motion/axis.c | 2 +- - src/emc/motion/command.c | 356 ++++++++++- - src/emc/motion/control.c | 551 ++++++++++++++++-- + src/emc/motion/command.c | 376 +++++++++++- + src/emc/motion/control.c | 575 ++++++++++++++++-- + src/emc/motion/homing.h | 4 +- src/emc/motion/mot_priv.h | 21 + - src/emc/motion/motion.c | 16 + - src/emc/motion/motion.h | 61 +- + src/emc/motion/motion.c | 19 + + src/emc/motion/motion.h | 66 +- src/emc/nml_intf/emc.cc | 29 + - src/emc/nml_intf/emc.hh | 11 + + src/emc/nml_intf/emc.hh | 19 +- src/emc/nml_intf/emc_nml.hh | 29 + src/emc/nml_intf/emcops.cc | 10 +- src/emc/task/emctask.cc | 1 + - src/emc/task/emctaskmain.cc | 206 ++++++- + src/emc/task/emctaskmain.cc | 308 +++++++++- src/emc/task/task.hh | 1 + - src/emc/task/taskintf.cc | 94 ++- - src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + + src/emc/task/taskintf.cc | 112 +++- + src/emc/usr_intf/axis/extensions/emcmodule.cc | 25 + + .../expected.motion-logger | 17 +- .../basic/expected.builtin-startup.in | 16 +- .../mountaindew/expected.motion-logger | 11 +- .../expected.motion-logger.in | 9 +- - tests/motion-target-preparation/README | 6 +- - .../availability-cases.h | 21 + - .../availability-fixture.h | 5 + - tests/motion-target-preparation/test.py | 57 ++ - .../.gitignore | 2 + - tests/runtime-availability-regressions/README | 20 + - .../runtime-availability-regressions/base.ini | 94 +++ - .../checkresult | 5 + - .../runtime-availability-regressions/core.hal | 17 + - .../dwell.ngc | 4 + - .../extra.hal | 17 + - .../extra.ini.in | 16 + - .../fault.ini.in | 13 + - .../fixture.py | 75 +++ - .../joghome.ini.in | 6 + - .../record_abort.ngc | 6 + - .../sequence.ini.in | 6 + - .../runtime-availability-regressions/tail.hal | 30 + - .../tail.ini.in | 7 + - .../test-ui.py | 192 ++++++ - .../test.ini.in | 3 + - .../runtime-availability-regressions/test.sh | 34 ++ - .../runtime-availability-regressions/tool.tbl | 1 + - .../runtime-availability-regressions/xzc.hal | 12 + - .../xzc.ini.in | 17 + - tests/runtime-availability/.gitignore | 2 + - tests/runtime-availability/README | 8 + - tests/runtime-availability/base.ini | 99 ++++ - tests/runtime-availability/checkresult | 4 + - tests/runtime-availability/core_sim.hal | 17 + - tests/runtime-availability/initial-ui.py | 58 ++ - tests/runtime-availability/initial.ini.in | 9 + - tests/runtime-availability/make-fixtures.py | 34 ++ - tests/runtime-availability/paused.ngc | 3 + - tests/runtime-availability/test-ui.py | 297 ++++++++++ - tests/runtime-availability/test.ini.in | 3 + - tests/runtime-availability/test.sh | 5 + - tests/runtime-availability/tool.tbl | 0 - 63 files changed, 2748 insertions(+), 82 deletions(-) - create mode 100644 tests/motion-target-preparation/availability-cases.h - create mode 100644 tests/motion-target-preparation/availability-fixture.h - create mode 100644 tests/runtime-availability-regressions/.gitignore - create mode 100644 tests/runtime-availability-regressions/README - create mode 100644 tests/runtime-availability-regressions/base.ini - create mode 100755 tests/runtime-availability-regressions/checkresult - create mode 100644 tests/runtime-availability-regressions/core.hal - create mode 100644 tests/runtime-availability-regressions/dwell.ngc - create mode 100644 tests/runtime-availability-regressions/extra.hal - create mode 100644 tests/runtime-availability-regressions/extra.ini.in - create mode 100644 tests/runtime-availability-regressions/fault.ini.in - create mode 100644 tests/runtime-availability-regressions/fixture.py - create mode 100644 tests/runtime-availability-regressions/joghome.ini.in - create mode 100644 tests/runtime-availability-regressions/record_abort.ngc - create mode 100644 tests/runtime-availability-regressions/sequence.ini.in - create mode 100644 tests/runtime-availability-regressions/tail.hal - create mode 100644 tests/runtime-availability-regressions/tail.ini.in - create mode 100755 tests/runtime-availability-regressions/test-ui.py - create mode 100644 tests/runtime-availability-regressions/test.ini.in - create mode 100755 tests/runtime-availability-regressions/test.sh - create mode 100644 tests/runtime-availability-regressions/tool.tbl - create mode 100644 tests/runtime-availability-regressions/xzc.hal - create mode 100644 tests/runtime-availability-regressions/xzc.ini.in - create mode 100644 tests/runtime-availability/.gitignore - create mode 100644 tests/runtime-availability/README - create mode 100644 tests/runtime-availability/base.ini - create mode 100755 tests/runtime-availability/checkresult - create mode 100644 tests/runtime-availability/core_sim.hal - create mode 100755 tests/runtime-availability/initial-ui.py - create mode 100644 tests/runtime-availability/initial.ini.in - create mode 100644 tests/runtime-availability/make-fixtures.py - create mode 100644 tests/runtime-availability/paused.ngc - create mode 100755 tests/runtime-availability/test-ui.py - create mode 100644 tests/runtime-availability/test.ini.in - create mode 100755 tests/runtime-availability/test.sh - create mode 100644 tests/runtime-availability/tool.tbl + 27 files changed, 1728 insertions(+), 104 deletions(-) diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc -index de598c529d..cdb1333971 100644 +index 2d7a99e..e93f55a 100644 --- a/docs/src/config/ini-config.adoc +++ b/docs/src/config/ini-config.adoc -@@ -1210,6 +1210,30 @@ These parameters are Homing related, for a better explanation read the <> for an example. + `HOLD_WAIT_NONE`, `HOLD_WAIT_HOMING` (a queued `G28.2`), `HOLD_WAIT_IO` (a + tool change or other I/O command), `HOLD_WAIT_SYSTEM_COMMAND` (a user + `M100`-`M199` program), `HOLD_WAIT_EXECUTOR` (a request started by an +- executor remap). ++ executor remap), `HOLD_WAIT_AVAILABILITY` (a joint or spindle availability ++ handshake waiting for its acknowledgment). + + *interpreter_errcode*:: '(returns integer)' - + current RS274NGC interpreter return code. One of +@@ -455,6 +456,9 @@ print("Joint 1 homed: ", s.joint[1]["homed"]) For each joint, the following dictionary keys are available: @@ -168,7 +135,7 @@ index 1a61affaff..c9270ce7fe 100644 *backlash*:: '(returns float)' - Backlash in machine units. configuration parameter, reflects `[JOINT___n__]BACKLASH`. -@@ -520,6 +523,9 @@ For each joint, the following dictionary keys are available: +@@ -529,6 +533,9 @@ For each joint, the following dictionary keys are available: [[sec:the-spindle-dictionary]] === The `spindle` dictionary @@ -178,7 +145,7 @@ index 1a61affaff..c9270ce7fe 100644 *brake*:: '(returns integer)' - value of the spindle brake flag. -@@ -763,6 +769,26 @@ c.tool_offset(toolno, z_offset, x_offset, diameter, frontangle, backangle, orie +@@ -774,6 +781,26 @@ c.tool_offset(toolno, z_offset, x_offset, diameter, frontangle, backangle, orie `set_optional_stop(int)`:: set optional stop on/off @@ -206,10 +173,10 @@ index 1a61affaff..c9270ce7fe 100644 set spindle override enabled. Defaults to spindle 0. diff --git a/docs/src/man/man9/motion.9.adoc b/docs/src/man/man9/motion.9.adoc -index 43859fcef1..5881e97529 100644 +index 4d2c184..bcf8c31 100644 --- a/docs/src/man/man9/motion.9.adoc +++ b/docs/src/man/man9/motion.9.adoc -@@ -375,6 +375,20 @@ Note: Pins marked *(DEBUG)* serve as debugging aids and are subject to change or +@@ -386,6 +386,20 @@ Note: Pins marked *(DEBUG)* serve as debugging aids and are subject to change or TRUE if the amplifier for this joint should be enabled. **joint.**_N_**.amp-fault-in** IN BIT:: Should be driven TRUE if an external fault is detected with the amplifier for this joint. @@ -230,7 +197,7 @@ index 43859fcef1..5881e97529 100644 **joint.**_N_**.backlash-corr** OUT FLOAT *(DEBUG)*:: Backlash or screw compensation raw value. **joint.**_N_**.backlash-filt** OUT FLOAT *(DEBUG)*:: -@@ -482,6 +496,18 @@ Example: loadrt motmod ... **unlock_joints_mask=**0x38 creates unlock pins for j +@@ -493,6 +507,18 @@ Example: loadrt motmod ... **unlock_joints_mask=**0x38 creates unlock pins for j **spindle.**_M_**.amp-fault-in** IN BIT:: Should be driven TRUE if an external fault is detected with the amplifier for this spindle. @@ -250,7 +217,7 @@ index 43859fcef1..5881e97529 100644 Motion will pause until this pin is TRUE, under the following conditions: Before the first feed move after each spindle start or speed change; diff --git a/src/emc/ini/inijoint.cc b/src/emc/ini/inijoint.cc -index 37dff22f62..48c61d7852 100644 +index 295cc34..0e3a1d7 100644 --- a/src/emc/ini/inijoint.cc +++ b/src/emc/ini/inijoint.cc @@ -11,6 +11,7 @@ @@ -261,7 +228,7 @@ index 37dff22f62..48c61d7852 100644 #include #include "nml_intf/emc.hh" -@@ -139,9 +140,26 @@ static int loadJoint(int joint, const IniFile &ini) +@@ -143,9 +144,26 @@ static int loadJoint(int joint, const IniFile &ini) // Sequence defaults to an unrealizable and positive sequence so that // joints with unspecified HOME_SEQUENCE= will not be homed in home-all @@ -288,8 +255,8 @@ index 37dff22f62..48c61d7852 100644 + } if (0 != emcJointSetHomingParams(joint, home, offset, final_vel, search_vel, latch_vel, - use_index, -@@ -149,7 +167,7 @@ static int loadJoint(int joint, const IniFile &ini) + search_dist, latch_dist, +@@ -154,7 +172,7 @@ static int loadJoint(int joint, const IniFile &ini) ignore_limits, is_shared, sequence, @@ -298,7 +265,7 @@ index 37dff22f62..48c61d7852 100644 locking_idxer, abs_encoder)) { print_dbg_config("emcJointSetHomingParams"); -@@ -187,10 +205,20 @@ static int loadJoint(int joint, const IniFile &ini) +@@ -192,10 +210,20 @@ static int loadJoint(int joint, const IniFile &ini) } } @@ -322,7 +289,7 @@ index 37dff22f62..48c61d7852 100644 return -1; } diff --git a/src/emc/ini/inispindle.cc b/src/emc/ini/inispindle.cc -index 7438ae02bc..ad815f8df0 100644 +index ecbfcab..f87dca5 100644 --- a/src/emc/ini/inispindle.cc +++ b/src/emc/ini/inispindle.cc @@ -14,6 +14,7 @@ @@ -375,7 +342,7 @@ index 7438ae02bc..ad815f8df0 100644 } diff --git a/src/emc/ini/linuxcnc_check_ini.py b/src/emc/ini/linuxcnc_check_ini.py -index d780715b90..eba42b648d 100755 +index d780715..eba42b6 100755 --- a/src/emc/ini/linuxcnc_check_ini.py +++ b/src/emc/ini/linuxcnc_check_ini.py @@ -251,8 +251,10 @@ def check_bools(): @@ -401,10 +368,10 @@ index d780715b90..eba42b648d 100755 # # Integer checks also include a range check diff --git a/src/emc/motion-logger/motion-logger.c b/src/emc/motion-logger/motion-logger.c -index 051ca3eff0..ae7c8d3f6e 100644 +index 24d0fea..f5f508f 100644 --- a/src/emc/motion-logger/motion-logger.c +++ b/src/emc/motion-logger/motion-logger.c -@@ -645,6 +645,28 @@ int main(int argc, char* argv[]) { +@@ -639,6 +639,28 @@ int main(int argc, char* argv[]) { log_print("SET_SPINDLE_PARAMS, %.2e, %.2e, %.2e, %.2e\n", c->maxLimit, c->min_pos_speed, c->minLimit, c->max_neg_speed); break; @@ -434,10 +401,10 @@ index 051ca3eff0..ae7c8d3f6e 100644 log_print("SET_SPINDLESYNC sync=%06f, flags=0x%08x\n", c->spindlesync, c->flags); break; diff --git a/src/emc/motion/axis.c b/src/emc/motion/axis.c -index ba87f42442..1be690a25c 100644 +index e814320..029af60 100644 --- a/src/emc/motion/axis.c +++ b/src/emc/motion/axis.c -@@ -397,7 +397,7 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo +@@ -398,7 +398,7 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo } if (!motion_teleop_flag) { axis->teleop_tp.enable = 0; @@ -445,15 +412,32 @@ index ba87f42442..1be690a25c 100644 + continue; } if (!motion_enable_flag) { continue; } - if ( *(axis_data->ajog_enable) == 0 ) { continue; } + if (!hal_get_bool(axis_data->ajog_enable)) { continue; } diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index c166af652b..a18acd066f 100644 +index 0347123..072bb70 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -80,6 +80,38 @@ extern int motion_num_spindles; +@@ -80,6 +80,16 @@ extern int motion_num_spindles; static int rehomeAll; ++/* Task requests acquisition homing through its queued home cycle. */ ++static int availability_home_requested(int joint_num) ++{ ++ const availability_status_t *a; ++ if (joint_num < 0 || joint_num >= ALL_JOINTS) return 0; ++ a = &emcmotStatus->joint_status[joint_num].availability; ++ return a->controlled && a->state == EMCMOT_AVAILABILITY_HOMING && ++ a->phase == AVAIL_PHASE_WAIT_HOME_REQUEST; ++} ++ + /* ===== BEGIN PLANNER_SWITCH_DEFER (reversible) ===================================== + * Deferred PLANNER_TYPE switching. Switching 0<->1 mid-motion causes an acceleration + * discontinuity (the very thing the S-curve planner exists to avoid), so a switch +@@ -115,6 +125,38 @@ void emcmotApplyPendingPlannerType(void) + } + /* ===== END PLANNER_SWITCH_DEFER ==================================================== */ + +int availability_transition_busy(void) +{ + int n; @@ -489,7 +473,7 @@ index c166af652b..a18acd066f 100644 /* limits_ok() returns 1 if none of the hard limits are set, 0 if any are set. Called on a linear and circular move. */ STATIC int limits_ok(void) -@@ -492,6 +524,40 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -523,6 +565,43 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) return; } } @@ -502,7 +486,10 @@ index c166af652b..a18acd066f 100644 + case EMCMOT_SET_CIRCLE: + case EMCMOT_PROBE: + case EMCMOT_RIGID_TAP: ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ return; + case EMCMOT_JOINT_HOME: ++ if (availability_home_requested(joint_num)) break; + emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; + return; + default: break; @@ -530,15 +517,15 @@ index c166af652b..a18acd066f 100644 switch (emcmotCommand->command) { case EMCMOT_ABORT: /* abort motion */ -@@ -503,6 +569,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -534,6 +613,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) does yet), and if in free mode, it disables the free mode traj planners which stops joint motion */ rtapi_print_msg(RTAPI_MSG_DBG, "ABORT"); + availability_cancel(0); - /* check for coord or free space motion active */ - if (GET_MOTION_TELEOP_FLAG()) { - axis_jog_abort_all(0); -@@ -525,6 +592,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + /* the override release is queued behind the cycle, drop it here */ + emcmotStatus->enables_new &= ~SS_LOCKED; + /* End a resumable Stop in every mode: one issued during a queued +@@ -582,6 +662,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) } } } @@ -546,7 +533,7 @@ index c166af652b..a18acd066f 100644 SET_MOTION_ERROR_FLAG(0); /* clear joint errors (regardless of mode) */ for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -551,6 +619,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -613,6 +694,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) /* abort one joint number or axis number */ /* can happen at any time */ rtapi_print_msg(RTAPI_MSG_DBG, "JOG_ABORT: %i", joint_num); @@ -558,7 +545,7 @@ index c166af652b..a18acd066f 100644 if (GET_MOTION_TELEOP_FLAG()) { /* tell teleop planner to stop */ if ((emcmotCommand->axis >= 0) && (emcmotCommand->axis < EMCMOT_MAX_AXIS)) { -@@ -585,6 +658,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -647,6 +733,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_COORD: @@ -569,7 +556,7 @@ index c166af652b..a18acd066f 100644 /* change the mode to coordinated axis motion */ /* can be done at any time */ /* this code doesn't actually make the transition, it merely -@@ -607,6 +684,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -669,6 +759,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_TELEOP: @@ -580,7 +567,7 @@ index c166af652b..a18acd066f 100644 rtapi_print_msg(RTAPI_MSG_DBG, "TELEOP"); switch_to_teleop_mode(); break; -@@ -679,10 +760,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -743,10 +837,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) case EMCMOT_UPDATE_JOINT_HOMING_PARAMS: rtapi_print_msg(RTAPI_MSG_DBG, "UPDATE_JOINT_HOMING_PARAMS"); rtapi_print_msg(RTAPI_MSG_DBG, " %d", joint_num); @@ -599,7 +586,7 @@ index c166af652b..a18acd066f 100644 update_joint_homing_params(joint_num, emcmotCommand->offset, emcmotCommand->home, -@@ -795,6 +883,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -859,6 +960,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) SET_JOINT_ERROR_FLAG(joint, 1); break; } @@ -612,9 +599,9 @@ index c166af652b..a18acd066f 100644 + break; + } // cannot jog if jog-inhibit is TRUE - if (*(emcmot_hal_data->jog_inhibit)){ + if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); -@@ -864,6 +960,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -928,6 +1037,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) SET_JOINT_ERROR_FLAG(joint, 1); break; } @@ -627,9 +614,9 @@ index c166af652b..a18acd066f 100644 + break; + } // cannot jog if jog-inhibit is TRUE - if (*(emcmot_hal_data->jog_inhibit)){ + if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); -@@ -944,6 +1048,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1008,6 +1125,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) SET_JOINT_ERROR_FLAG(joint, 1); break; } @@ -642,9 +629,9 @@ index c166af652b..a18acd066f 100644 + break; + } // cannot jog if jog-inhibit is TRUE - if (*(emcmot_hal_data->jog_inhibit)){ + if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); -@@ -1007,6 +1119,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1071,6 +1196,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_SET_SPINDLESYNC: @@ -662,7 +649,7 @@ index c166af652b..a18acd066f 100644 tpSetSpindleSync(&emcmotInternal->coord_tp, emcmotCommand->spindle, emcmotCommand->spindlesync, emcmotCommand->flags); break; -@@ -1380,6 +1503,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1511,6 +1647,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) controller cycle (it *will* be honored) */ rtapi_print_msg(RTAPI_MSG_DBG, "DISABLE"); emcmotInternal->enabling = 0; @@ -670,7 +657,7 @@ index c166af652b..a18acd066f 100644 if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { emcmotInternal->teleoperating = 0; emcmotInternal->coordinating = 0; -@@ -1392,10 +1516,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1523,10 +1660,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) /* set the emcmotInternal->enabling flag to defer enable until controller cycle */ rtapi_print_msg(RTAPI_MSG_DBG, "ENABLE"); @@ -678,7 +665,7 @@ index c166af652b..a18acd066f 100644 + * Repeated On must neither release resources nor restart a scan. */ + if (GET_MOTION_ENABLE_FLAG() || emcmotInternal->enabling || + emcmotInternal->availability_machine_on) break; - if ( *(emcmot_hal_data->enable) == 0 ) { + if ( !hal_get_bool(emcmot_hal_data->enable) ) { reportError(_("can't enable motion, enable input is false")); } else { - emcmotInternal->enabling = 1; @@ -688,7 +675,7 @@ index c166af652b..a18acd066f 100644 if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { emcmotInternal->teleoperating = 0; emcmotInternal->coordinating = 0; -@@ -1412,6 +1542,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1543,6 +1686,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (joint == 0) { break; } @@ -702,7 +689,7 @@ index c166af652b..a18acd066f 100644 SET_JOINT_ACTIVE_FLAG(joint, 1); break; -@@ -1424,6 +1561,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1555,6 +1705,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (joint == 0) { break; } @@ -716,29 +703,40 @@ index c166af652b..a18acd066f 100644 SET_JOINT_ACTIVE_FLAG(joint, 0); break; -@@ -1435,6 +1579,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1566,6 +1723,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) rtapi_print_msg(RTAPI_MSG_DBG, "JOINT_HOME"); rtapi_print_msg(RTAPI_MSG_DBG, " %d", joint_num); + if (joint_num >= 0 && -+ emcmotStatus->joint_status[joint_num].availability.controlled) { ++ emcmotStatus->joint_status[joint_num].availability.controlled && ++ !availability_home_requested(joint_num)) { + reportError(_("availability-controlled joint %d is homed only during acquisition"), + joint_num); + emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; + break; + } - if (emcmotStatus->motion_state != EMCMOT_MOTION_FREE) { - /* can't home unless in free mode */ - reportError(_("must be in joint mode to home")); -@@ -1452,7 +1603,6 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + /* Normally homing requires free (joint) mode. The queued G28.2 path + * (emctaskmain EMC_TASK_EXEC::WAITING_FOR_HOMING) dips motion into + * FREE before issuing this command; while that transition is still +@@ -1598,9 +1763,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (!GET_MOTION_ENABLE_FLAG()) { break; } -- ++ emcmotInternal->home_request_command = emcmotCommand->commandNum; ++ if (availability_home_requested(joint_num)) { ++ /* Availability starts it from a stationary FREE joint. */ ++ emcmotStatus->joint_status[joint_num].availability.phase = ++ AVAIL_PHASE_WAIT_FREE; ++ break; ++ } + // Negative joint_num specifies homeall do_home_joint(joint_num); ++ emcmotInternal->home_started_command = emcmotCommand->commandNum; break; -@@ -1468,6 +1618,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + + case EMCMOT_JOINT_UNHOME: +@@ -1614,6 +1787,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) return; } @@ -765,7 +763,7 @@ index c166af652b..a18acd066f 100644 // For configs that require homing and have joints configured as VOLATILE_HOME // 'get_allhomed()' will change from TRUE to FALSE. If that happens we need to // switch motion mode to 'free'. -@@ -1486,6 +1656,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1632,6 +1825,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; @@ -858,14 +856,14 @@ index c166af652b..a18acd066f 100644 + break; + } + if (emcmotCommand->available && !get_homed(joint_num) && -+ *(emcmot_hal_data->homing_inhibit)) { ++ hal_get_bool(emcmot_hal_data->homing_inhibit)) { + reportError(_("Homing denied by motion.homing-inhibit joint=%d\n"), + joint_num); + emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; + break; + } + if (emcmotCommand->available) { -+ if (!GET_MOTION_ENABLE_FLAG() || !*emcmot_hal_data->enable) { ++ if (!GET_MOTION_ENABLE_FLAG() || !hal_get_bool(emcmot_hal_data->enable)) { + emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; + break; + } @@ -912,7 +910,7 @@ index c166af652b..a18acd066f 100644 + break; + } + if (emcmotCommand->available) { -+ if (!GET_MOTION_ENABLE_FLAG() || !*emcmot_hal_data->enable) { ++ if (!GET_MOTION_ENABLE_FLAG() || !hal_get_bool(emcmot_hal_data->enable)) { + emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; + break; + } @@ -926,7 +924,7 @@ index c166af652b..a18acd066f 100644 case EMCMOT_CLEAR_PROBE_FLAGS: rtapi_print_msg(RTAPI_MSG_DBG, "CLEAR_PROBE_FLAGS"); emcmotStatus->probing = 0; -@@ -1673,8 +1997,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1828,6 +2175,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -936,11 +934,9 @@ index c166af652b..a18acd066f 100644 + break; + } for (n = s0; n<=s1; n++){ -- - if (*(emcmot_hal_data->spindle[n].spindle_orient)) - rtapi_print_msg(RTAPI_MSG_DBG, "SPINDLE_ORIENT cancelled by SPINDLE_ON\n"); - if (*(emcmot_hal_data->spindle[n].spindle_locked)) -@@ -1761,8 +2089,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + + if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) +@@ -1933,8 +2285,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -954,7 +950,7 @@ index c166af652b..a18acd066f 100644 if (n > emcmotConfig->numSpindles){ rtapi_print_msg(RTAPI_MSG_ERR, "spindle number <%d> too high in M19",n); break; -@@ -1812,6 +2144,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1984,6 +2340,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -965,7 +961,7 @@ index c166af652b..a18acd066f 100644 for (n = s0; n<=s1; n++){ if (emcmotStatus->spindle_status[n].speed > 0) { emcmotStatus->spindle_status[n].speed += emcmotStatus->spindle_status[n].increment; -@@ -1836,6 +2172,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -2008,6 +2368,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -976,7 +972,7 @@ index c166af652b..a18acd066f 100644 for (n = s0; n<=s1; n++){ if (emcmotStatus->spindle_status[n].speed > emcmotStatus->spindle_status[n].increment) { emcmotStatus->spindle_status[n].speed -= emcmotStatus->spindle_status[n].increment; -@@ -1882,8 +2222,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -2054,8 +2418,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -991,10 +987,10 @@ index c166af652b..a18acd066f 100644 } break; diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 8ed2cb3882..722c58545d 100644 +index f22ab9b..7f55169 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -46,6 +46,9 @@ static int switchkins_type = 0; +@@ -45,6 +45,9 @@ static int switchkins_type = 0; /* kinematics flags */ KINEMATICS_FORWARD_FLAGS fflags = 0; KINEMATICS_INVERSE_FLAGS iflags = 0; @@ -1004,15 +1000,16 @@ index 8ed2cb3882..722c58545d 100644 /*! \todo FIXME - debugging - uncomment the following line to log changes in JOINT_FLAG and MOTION_FLAG */ -@@ -87,6 +90,7 @@ static double *pcmd_p[EMCMOT_MAX_AXIS]; +@@ -90,6 +93,8 @@ static unsigned char prev_enables = 0; emcmotStatus structure. */ static void process_inputs(void); +static void process_availability(void); ++static void finish_availability_homing(void); /* 'joint_jog_abort_all()' if either jog-stop or jog-stop-immediate become True while jogging then the jog will abort. -@@ -248,6 +252,7 @@ void emcmotController(void *arg, long period) +@@ -251,6 +256,7 @@ void emcmotController(void *arg, long period) read_homing_in_pins(ALL_JOINTS); handle_kinematicsSwitch(); process_inputs(); @@ -1020,16 +1017,16 @@ index 8ed2cb3882..722c58545d 100644 do_forward_kins(); process_probe_inputs(); check_for_faults(); -@@ -255,11 +260,19 @@ void emcmotController(void *arg, long period) - if (!*emcmot_hal_data->jog_inhibit) { +@@ -258,13 +264,28 @@ void emcmotController(void *arg, long period) + if (!hal_get_bool(emcmot_hal_data->jog_inhibit)) { handle_jjogwheels(); } -- if (!emcmotStatus->on_soft_limit && !*emcmot_hal_data->jog_inhibit) { // change from teleop to move off joint soft limit +- if (!emcmotStatus->on_soft_limit && !hal_get_bool(emcmot_hal_data->jog_inhibit)) { // change from teleop to move off joint soft limit - axis_handle_jogwheels(GET_MOTION_TELEOP_FLAG(), GET_MOTION_ENABLE_FLAG(), get_homing_is_active()); + /* Always consume wheel input, including while a transition inhibits motion. */ + axis_handle_jogwheels(GET_MOTION_TELEOP_FLAG(), + GET_MOTION_ENABLE_FLAG() && !availability_transition_busy() && -+ !emcmotStatus->on_soft_limit && !*emcmot_hal_data->jog_inhibit, ++ !emcmotStatus->on_soft_limit && !hal_get_bool(emcmot_hal_data->jog_inhibit), + get_homing_is_active()); + int availability_homing = 0, homing_cleanup = 0; + for (int n = 0; n < ALL_JOINTS; n++) { @@ -1039,23 +1036,48 @@ index 8ed2cb3882..722c58545d 100644 } - if ( (emcmotStatus->motion_state == EMCMOT_MOTION_FREE) - && do_homing()) { -+ if ((emcmotStatus->motion_state == EMCMOT_MOTION_FREE || homing_cleanup) -+ && do_homing() && !availability_homing && !homing_cleanup) { - switch_to_teleop_mode(); +- switch_to_teleop_mode(); ++ if (emcmotStatus->motion_state == EMCMOT_MOTION_FREE || homing_cleanup) { ++ bool all_homed_now = do_homing(); ++ /* Published here, with the homing state update_status() writes in this ++ * same cycle, so that a reader never sees the start without its effect ++ * on homing_active or homed. */ ++ emcmotStatus->home_started_command = emcmotInternal->home_started_command; ++ if (all_homed_now && !availability_homing && !homing_cleanup) { ++ switch_to_teleop_mode(); ++ } } - -@@ -440,8 +453,29 @@ static void process_inputs(void) ++ finish_availability_homing(); + + /* PLANNER_SWITCH_DEFER (reversible): apply a latched PLANNER_TYPE switch once the + * coordinated queue has gone idle. No-op unless a switch is pending + motion idle. */ +@@ -415,7 +436,14 @@ static void process_inputs(void) + hal_get_real(emcmot_hal_data->spindle[spindle_num].spindle_revs); + emcmotStatus->spindle_status[spindle_num].spindleSpeedIn = + hal_get_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_in); ++ /* A released spindle is run by its external owner. Its at-speed ++ input says nothing about this program and must not hold the ++ at-speed waits of the other spindles. */ ++ const availability_status_t *availability = ++ &emcmotStatus->spindle_status[spindle_num].availability; + emcmotStatus->spindle_status[spindle_num].at_speed = ++ (availability->controlled && ++ availability->state != EMCMOT_AVAILABILITY_AVAILABLE) || + hal_get_bool(emcmot_hal_data->spindle[spindle_num].spindle_is_atspeed); + /* Sampled every servo period for resumable Stop: a short false + between a Stop restore and at-speed would be missed by task. */ +@@ -518,8 +546,29 @@ static void process_inputs(void) joint_data = &(emcmot_hal_data->joint[joint_num]); /* point to joint data */ joint = &joints[joint_num]; + /* Interlocks must be current before availability can activate a joint. */ + /* read limit switches */ -+ if (*(joint_data->pos_lim_sw)) { ++ if (hal_get_bool(joint_data->pos_lim_sw)) { + SET_JOINT_PHL_FLAG(joint, 1); + } else { + SET_JOINT_PHL_FLAG(joint, 0); + } -+ if (*(joint_data->neg_lim_sw)) { ++ if (hal_get_bool(joint_data->neg_lim_sw)) { + SET_JOINT_NHL_FLAG(joint, 1); + } else { + SET_JOINT_NHL_FLAG(joint, 0); @@ -1063,7 +1085,7 @@ index 8ed2cb3882..722c58545d 100644 + joint->on_pos_limit = GET_JOINT_PHL_FLAG(joint); + joint->on_neg_limit = GET_JOINT_NHL_FLAG(joint); + /* read amp fault input */ -+ if (*(joint_data->amp_fault)) { ++ if (hal_get_bool(joint_data->amp_fault)) { + SET_JOINT_FAULT_FLAG(joint, 1); + } else { + SET_JOINT_FAULT_FLAG(joint, 0); @@ -1075,17 +1097,17 @@ index 8ed2cb3882..722c58545d 100644 continue; } /* copy data from HAL to joint structure */ -@@ -489,25 +523,7 @@ static void process_inputs(void) +@@ -567,25 +616,7 @@ static void process_inputs(void) SET_JOINT_FERROR_FLAG(joint, 0); } - /* read limit switches */ -- if (*(joint_data->pos_lim_sw)) { +- if (hal_get_bool(joint_data->pos_lim_sw)) { - SET_JOINT_PHL_FLAG(joint, 1); - } else { - SET_JOINT_PHL_FLAG(joint, 0); - } -- if (*(joint_data->neg_lim_sw)) { +- if (hal_get_bool(joint_data->neg_lim_sw)) { - SET_JOINT_NHL_FLAG(joint, 1); - } else { - SET_JOINT_NHL_FLAG(joint, 0); @@ -1093,7 +1115,7 @@ index 8ed2cb3882..722c58545d 100644 - joint->on_pos_limit = GET_JOINT_PHL_FLAG(joint); - joint->on_neg_limit = GET_JOINT_NHL_FLAG(joint); - /* read amp fault input */ -- if (*(joint_data->amp_fault)) { +- if (hal_get_bool(joint_data->amp_fault)) { - SET_JOINT_FAULT_FLAG(joint, 1); - } else { - SET_JOINT_FAULT_FLAG(joint, 0); @@ -1102,7 +1124,7 @@ index 8ed2cb3882..722c58545d 100644 } // a fault was signalled during a spindle-orient in progress -@@ -551,6 +567,394 @@ static void process_inputs(void) +@@ -629,6 +660,401 @@ static void process_inputs(void) } } @@ -1111,14 +1133,12 @@ index 8ed2cb3882..722c58545d 100644 +{ + a->target_available = 0; + a->phase = AVAIL_PHASE_IDLE; -+ a->return_motion_state = EMCMOT_MOTION_FREE; +} + +void availability_begin(availability_status_t *a, int runtime) +{ + a->target_available = 1; + a->phase = runtime ? AVAIL_PHASE_RUNTIME_ACK : AVAIL_PHASE_INITIAL_ACK; -+ a->return_motion_state = EMCMOT_MOTION_FREE; + a->fault = EMCMOT_AVAILABILITY_FAULT_NONE; + a->transition_started = etime(); + /* A fault must first observe ACK low before issuing a fresh request. */ @@ -1138,7 +1158,7 @@ index 8ed2cb3882..722c58545d 100644 + a->fault = fault; + a->state = EMCMOT_AVAILABILITY_DISABLING; + a->transition_started = etime(); -+ *emcmot_hal_data->joint[n].availability_request = 0; ++ hal_set_bool(emcmot_hal_data->joint[n].availability_request, 0); + motion_cancel_joint(n); +} + @@ -1164,17 +1184,17 @@ index 8ed2cb3882..722c58545d 100644 + a->fault = fault; + a->state = EMCMOT_AVAILABILITY_DISABLING; + a->transition_started = etime(); -+ *emcmot_hal_data->spindle[n].availability_request = 0; ++ hal_set_bool(emcmot_hal_data->spindle[n].availability_request, 0); + s->state = 0; + s->speed = 0; + s->brake = 0; + s->locked = 0; + s->orient_state = EMCMOT_ORIENT_NONE; + s->spindle_index_enable = 0; -+ *emcmot_hal_data->spindle[n].spindle_index_enable = 0; ++ hal_set_bool(emcmot_hal_data->spindle[n].spindle_index_enable, 0); + old_motion_index[n] = old_hal_index[n] = 0; -+ *emcmot_hal_data->spindle[n].spindle_orient = 0; -+ *emcmot_hal_data->spindle[n].spindle_locked = 0; ++ hal_set_bool(emcmot_hal_data->spindle[n].spindle_orient, 0); ++ hal_set_bool(emcmot_hal_data->spindle[n].spindle_locked, 0); +} + +void availability_cancel(int all) @@ -1235,7 +1255,7 @@ index 8ed2cb3882..722c58545d 100644 +{ + const availability_status_t *a = &emcmotStatus->joint_status[n].availability; + const emcmot_joint_t *joint = &joints[n]; -+ double feedback = *emcmot_hal_data->joint[n].motor_pos_fb; ++ double feedback = hal_get_real(emcmot_hal_data->joint[n].motor_pos_fb); + double expected = a->held_position + joint->backlash_filt + joint->motor_offset; + double tolerance = joint->min_ferror; + return isfinite(feedback) && isfinite(expected) && isfinite(tolerance) && @@ -1248,10 +1268,11 @@ index 8ed2cb3882..722c58545d 100644 +static bool availability_start_homing(int n) +{ + emcmot_joint_t *joint = &joints[n]; -+ double motor = *emcmot_hal_data->joint[n].motor_pos_fb; ++ double motor = hal_get_real(emcmot_hal_data->joint[n].motor_pos_fb); + double position = motor - joint->backlash_filt - joint->motor_offset; + if (!isfinite(motor) || !isfinite(position)) return false; + do_home_joint(n); ++ emcmotInternal->home_started_command = emcmotInternal->home_request_command; + joint->motor_pos_fb = motor; + joint->pos_fb = joint->pos_cmd = joint->coarse_pos = position; + joint->free_tp.curr_pos = joint->free_tp.pos_cmd = @@ -1270,31 +1291,38 @@ index 8ed2cb3882..722c58545d 100644 +static void availability_complete_joint(int n) +{ + availability_status_t *a = &emcmotStatus->joint_status[n].availability; -+ motion_state_t restore = a->return_motion_state; + a->phase = AVAIL_PHASE_IDLE; -+ a->return_motion_state = EMCMOT_MOTION_FREE; + a->state = EMCMOT_AVAILABILITY_AVAILABLE; -+ if (restore == EMCMOT_MOTION_COORD) emcmotInternal->coordinating = 1; -+ if (restore == EMCMOT_MOTION_TELEOP) switch_to_teleop_mode(); +} + -+static void availability_finish_homing(int n) ++/* Runs right after do_homing(), so the cycle that ends acquisition homing also ++ * publishes its result. Task's queued home cycle observes homing_active fall ++ * and restores the trajectory mode only once the joint is AVAILABLE. */ ++static void finish_availability_homing(void) +{ -+ availability_complete_joint(n); ++ int n; ++ for (n = 0; n < ALL_JOINTS; n++) { ++ availability_status_t *a = &emcmotStatus->joint_status[n].availability; ++ if (!a->controlled || a->state != EMCMOT_AVAILABILITY_HOMING || ++ a->phase != AVAIL_PHASE_WAIT_HOME_FINISH || !get_home_is_idle(n)) ++ continue; ++ if (get_homed(n)) availability_complete_joint(n); ++ else set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_FAILED); ++ } +} + +static void process_availability(void) +{ + int n; + double now = etime(); -+ if (!*emcmot_hal_data->enable && ++ if (!hal_get_bool(emcmot_hal_data->enable) && + (emcmotInternal->availability_machine_on || GET_MOTION_ENABLE_FLAG())) + availability_cancel(1); + + for (n = 0; n < ALL_JOINTS; n++) { + availability_status_t *a = &emcmotStatus->joint_status[n].availability; + joint_hal_t *hal = &emcmot_hal_data->joint[n]; -+ int ack = !!*hal->availability_ack; ++ int ack = hal_get_bool(hal->availability_ack); + if (!a->controlled) { + a->state = EMCMOT_AVAILABILITY_AVAILABLE; + } else switch (a->state) { @@ -1302,16 +1330,17 @@ index 8ed2cb3882..722c58545d 100644 + if (ack) set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_UNEXPECTED); + break; + case EMCMOT_AVAILABILITY_ENABLING: -+ if (ack && !*hal->availability_request) { ++ if (ack && !hal_get_bool(hal->availability_request)) { + set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_STALE_HIGH); + break; + } + if (ack) { + if (!get_homed(n) && a->phase == AVAIL_PHASE_RUNTIME_ACK) { -+ a->return_motion_state = emcmotStatus->motion_state; -+ emcmotInternal->coordinating = emcmotInternal->teleoperating = 0; ++ /* Task homes the joint through its queued home cycle, ++ * which also owns the FREE dip and mode restoration. */ + a->state = EMCMOT_AVAILABILITY_HOMING; -+ a->phase = AVAIL_PHASE_WAIT_FREE; ++ a->phase = AVAIL_PHASE_WAIT_HOME_REQUEST; ++ a->transition_started = now; + } else { + if (!validate_joint_position(n)) { + set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_POSITION_MISMATCH); @@ -1325,28 +1354,28 @@ index 8ed2cb3882..722c58545d 100644 + set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACQUIRE_TIMEOUT); + break; + case EMCMOT_AVAILABILITY_HOMING: ++ /* The home must start within the timeout. Task holds its home ++ * request while the program is paused or stopped, so that time ++ * does not count. */ ++ if (a->phase != AVAIL_PHASE_WAIT_HOME_FINISH && emcmotStatus->paused) ++ a->transition_started = now; + if (!ack) { + set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); ++ } else if (a->phase != AVAIL_PHASE_WAIT_HOME_FINISH && ++ hal_get_bool(emcmot_hal_data->homing_inhibit)) { ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_ABORTED); ++ } else if (a->phase != AVAIL_PHASE_WAIT_HOME_FINISH && ++ now - a->transition_started >= a->timeout) { ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_FAILED); + } else if (a->phase == AVAIL_PHASE_WAIT_FREE) { ++ /* Task's home request was accepted; it has dipped motion ++ * into FREE. Completion is finish_availability_homing(). */ + if (emcmotStatus->motion_state != EMCMOT_MOTION_FREE) break; -+ if (*emcmot_hal_data->homing_inhibit) { -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_ABORTED); -+ break; -+ } + if (!availability_start_homing(n)) { + set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_FAILED); + break; + } -+ a->phase = AVAIL_PHASE_WAIT_HOME_START; -+ a->transition_started = now; -+ } else if (a->phase == AVAIL_PHASE_WAIT_HOME_START) { -+ if (get_homing(n)) a->phase = AVAIL_PHASE_WAIT_HOME_FINISH; -+ else if (get_homed(n) && get_home_is_idle(n)) availability_finish_homing(n); -+ else if (now - a->transition_started >= a->timeout) -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_FAILED); -+ } else if (get_home_is_idle(n)) { -+ if (get_homed(n)) availability_finish_homing(n); -+ else set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_FAILED); ++ a->phase = AVAIL_PHASE_WAIT_HOME_FINISH; + } + break; + case EMCMOT_AVAILABILITY_AVAILABLE: @@ -1409,27 +1438,27 @@ index 8ed2cb3882..722c58545d 100644 + break; + case EMCMOT_AVAILABILITY_FAULT: break; + } -+ *hal->availability_request = a->controlled && a->target_available && ++ hal_set_bool(hal->availability_request, a->controlled && a->target_available && + (a->state == EMCMOT_AVAILABILITY_ENABLING || -+ a->state == EMCMOT_AVAILABILITY_HOMING || a->state == EMCMOT_AVAILABILITY_AVAILABLE); ++ a->state == EMCMOT_AVAILABILITY_HOMING || a->state == EMCMOT_AVAILABILITY_AVAILABLE)); + if (a->controlled && a->phase == AVAIL_PHASE_WAIT_SETTLED) -+ *hal->availability_request = 1; -+ *hal->available = a->state == EMCMOT_AVAILABILITY_AVAILABLE; -+ *hal->availability_state = a->state; -+ *hal->availability_fault = !!a->fault; -+ *hal->availability_fault_code = a->fault; ++ hal_set_bool(hal->availability_request, 1); ++ hal_set_bool(hal->available, a->state == EMCMOT_AVAILABILITY_AVAILABLE); ++ hal_set_sint(hal->availability_state, a->state); ++ hal_set_bool(hal->availability_fault, !!a->fault); ++ hal_set_sint(hal->availability_fault_code, a->fault); + } + for (n = 0; n < emcmotConfig->numSpindles; n++) { + availability_status_t *a = &emcmotStatus->spindle_status[n].availability; + spindle_hal_t *hal = &emcmot_hal_data->spindle[n]; -+ int ack = !!*hal->availability_ack; ++ int ack = hal_get_bool(hal->availability_ack); + if (!a->controlled) a->state = EMCMOT_AVAILABILITY_AVAILABLE; + else switch (a->state) { + case EMCMOT_AVAILABILITY_DISABLED: + if (ack) set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_UNEXPECTED); + break; + case EMCMOT_AVAILABILITY_ENABLING: -+ if (ack && !*hal->availability_request) { ++ if (ack && !hal_get_bool(hal->availability_request)) { + set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_STALE_HIGH); + break; + } @@ -1459,12 +1488,12 @@ index 8ed2cb3882..722c58545d 100644 + break; + case EMCMOT_AVAILABILITY_FAULT: break; + } -+ *hal->availability_request = a->controlled && a->target_available && -+ (a->state == EMCMOT_AVAILABILITY_ENABLING || a->state == EMCMOT_AVAILABILITY_AVAILABLE); -+ *hal->available = a->state == EMCMOT_AVAILABILITY_AVAILABLE; -+ *hal->availability_state = a->state; -+ *hal->availability_fault = !!a->fault; -+ *hal->availability_fault_code = a->fault; ++ hal_set_bool(hal->availability_request, a->controlled && a->target_available && ++ (a->state == EMCMOT_AVAILABILITY_ENABLING || a->state == EMCMOT_AVAILABILITY_AVAILABLE)); ++ hal_set_bool(hal->available, a->state == EMCMOT_AVAILABILITY_AVAILABLE); ++ hal_set_sint(hal->availability_state, a->state); ++ hal_set_bool(hal->availability_fault, !!a->fault); ++ hal_set_sint(hal->availability_fault_code, a->fault); + } + if (emcmotInternal->availability_machine_on) { + for (n = 0; n < ALL_JOINTS; n++) { @@ -1486,7 +1515,7 @@ index 8ed2cb3882..722c58545d 100644 + break; + } + if (emcmotInternal->availability_resource == emcmotConfig->numSpindles) { -+ if (*emcmot_hal_data->enable) { ++ if (hal_get_bool(emcmot_hal_data->enable)) { + emcmotInternal->availability_machine_on = 0; + emcmotInternal->enabling = 1; + } else availability_cancel(1); @@ -1497,7 +1526,7 @@ index 8ed2cb3882..722c58545d 100644 static void joint_jog_abort_all(bool immediate) { int jNum; -@@ -613,7 +1017,7 @@ static void do_forward_kins(void) +@@ -691,7 +1117,7 @@ static void do_forward_kins(void) at the traj rate */ double joint_pos[EMCMOT_MAX_JOINTS] = {0,}; @@ -1506,7 +1535,7 @@ index 8ed2cb3882..722c58545d 100644 emcmot_joint_t *joint; /* copy joint position feedback to local array */ -@@ -795,7 +1199,9 @@ static void check_for_faults(void) +@@ -873,7 +1299,9 @@ static void check_for_faults(void) } /* check for spindle ampfifier errors */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1517,7 +1546,7 @@ index 8ed2cb3882..722c58545d 100644 reportError(_("spindle %d amplifier fault"), spindle_num); emcmotInternal->enabling = 0; } -@@ -867,6 +1273,7 @@ static void set_operating_mode(void) +@@ -945,6 +1373,7 @@ static void set_operating_mode(void) /* check for disabling */ if (!emcmotInternal->enabling && GET_MOTION_ENABLE_FLAG()) { @@ -1525,7 +1554,7 @@ index 8ed2cb3882..722c58545d 100644 /* clear out the motion emcmotInternal->coord_tp and interpolators */ tpClear(&emcmotInternal->coord_tp); for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -921,8 +1328,9 @@ static void set_operating_mode(void) +@@ -999,8 +1428,9 @@ static void set_operating_mode(void) } } SET_MOTION_ENABLE_FLAG(1); @@ -1537,7 +1566,7 @@ index 8ed2cb3882..722c58545d 100644 } /* check for entering teleop mode */ -@@ -950,7 +1358,7 @@ static void set_operating_mode(void) +@@ -1028,7 +1458,7 @@ static void set_operating_mode(void) /* Initialize things to do when starting teleop mode. */ SET_MOTION_TELEOP_FLAG(1); SET_MOTION_COORD_FLAG(0); @@ -1546,25 +1575,25 @@ index 8ed2cb3882..722c58545d 100644 kinematicsForward(positions, &emcmotStatus->carte_pos_cmd, &fflags, &iflags); // entering teleop (INPOS), remove ext offsets -@@ -994,7 +1402,7 @@ static void set_operating_mode(void) +@@ -1072,7 +1502,7 @@ static void set_operating_mode(void) emcmotStatus->overrideLimitMask = 0; SET_MOTION_COORD_FLAG(1); SET_MOTION_TELEOP_FLAG(0); - SET_MOTION_ERROR_FLAG(0); + if (!emcmotInternal->availability_motion_error) { SET_MOTION_ERROR_FLAG(0); } } else { - /* not in position-- don't honor mode change */ - emcmotInternal->coordinating = 0; -@@ -1014,7 +1422,7 @@ static void set_operating_mode(void) + /* not in position-- defer the mode change; the request stays + pending and is honored when motion comes to rest */ +@@ -1092,7 +1522,7 @@ static void set_operating_mode(void) } SET_MOTION_COORD_FLAG(0); SET_MOTION_TELEOP_FLAG(0); - SET_MOTION_ERROR_FLAG(0); + if (!emcmotInternal->availability_motion_error) { SET_MOTION_ERROR_FLAG(0); } } else { - /* not in position-- don't honor mode change */ - emcmotInternal->coordinating = 1; -@@ -1049,10 +1457,17 @@ static void handle_jjogwheels(void) + /* not in position-- defer the mode change; the request stays + pending and is honored when motion comes to rest */ +@@ -1127,10 +1557,17 @@ static void handle_jjogwheels(void) /* point to joint data */ joint_data = &(emcmot_hal_data->joint[joint_num]); joint = &joints[joint_num]; @@ -1576,7 +1605,7 @@ index 8ed2cb3882..722c58545d 100644 + emcmotStatus->joint_status[joint_num].availability.state != EMCMOT_AVAILABILITY_AVAILABLE) { + /* Discard wheel movement while ownership is external so it cannot + become a delayed jog when acquisition completes. */ -+ joint->old_jjog_counts = *(joint_data->jjog_counts); ++ joint->old_jjog_counts = hal_get_sint(joint_data->jjog_counts); + continue; + } + if (!GET_JOINT_ACTIVE_FLAG(joint)) { @@ -1585,8 +1614,8 @@ index 8ed2cb3882..722c58545d 100644 + } // disallow accel bogus fractions - if ( (*(joint_data->jjog_accel_fraction) > 1) -@@ -1066,6 +1481,7 @@ static void handle_jjogwheels(void) + rtapi_real jjog_accel_fraction = hal_get_real(joint_data->jjog_accel_fraction); +@@ -1145,6 +1582,7 @@ static void handle_jjogwheels(void) delta = new_jjog_counts - joint->old_jjog_counts; /* save value for next time */ joint->old_jjog_counts = new_jjog_counts; @@ -1594,7 +1623,7 @@ index 8ed2cb3882..722c58545d 100644 /* initialization complete */ if ( first_pass ) { continue; -@@ -1197,6 +1613,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, +@@ -1276,6 +1714,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, reportError(_("kinematicsInverse gave non-finite joint location on joint %d"), n); return -1; } @@ -1611,7 +1640,7 @@ index 8ed2cb3882..722c58545d 100644 cubics[n] = joints[n].cubic; if (cubicNeedNextPoint(&cubics[n]) && cubicAddPoint(&cubics[n], positions[n]) != 0) { -@@ -1286,7 +1712,10 @@ static void get_pos_cmds(long period) +@@ -1365,7 +1813,10 @@ static void get_pos_cmds(long period) for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { /* point to joint struct */ joint = &joints[joint_num]; @@ -1623,7 +1652,7 @@ index 8ed2cb3882..722c58545d 100644 /* if joint is not active, skip it */ continue; } -@@ -1430,8 +1859,7 @@ static void get_pos_cmds(long period) +@@ -1521,8 +1972,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1633,7 +1662,7 @@ index 8ed2cb3882..722c58545d 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1492,8 +1920,7 @@ static void get_pos_cmds(long period) +@@ -1583,8 +2033,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1643,7 +1672,7 @@ index 8ed2cb3882..722c58545d 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1504,6 +1931,8 @@ static void get_pos_cmds(long period) +@@ -1595,6 +2044,8 @@ static void get_pos_cmds(long period) &joint->vel_cmd, &joint->acc_cmd, &joint->jerk_cmd); } @@ -1652,7 +1681,7 @@ index 8ed2cb3882..722c58545d 100644 /* END OF OUTPUT KINS */ -@@ -1520,10 +1949,13 @@ static void get_pos_cmds(long period) +@@ -1611,10 +2062,13 @@ static void get_pos_cmds(long period) case EMCMOT_MOTION_DISABLED: /* set position commands to match feedbacks, this avoids disturbances and/or following errors when enabling */ @@ -1667,7 +1696,7 @@ index 8ed2cb3882..722c58545d 100644 /* save old command */ joint->pos_cmd = joint->pos_fb; /* set joint velocity and acceleration to zero */ -@@ -1911,8 +2343,6 @@ static void output_to_hal(void) +@@ -2002,8 +2456,6 @@ static void output_to_hal(void) double inch_mult; emcmot_joint_t *joint; joint_hal_t *joint_data; @@ -1675,8 +1704,8 @@ index 8ed2cb3882..722c58545d 100644 - static int old_hal_index[EMCMOT_MAX_SPINDLES] = {0}; /* output machine info to HAL for scoping, etc */ - *(emcmot_hal_data->motion_enabled) = GET_MOTION_ENABLE_FLAG(); -@@ -1954,6 +2384,9 @@ static void output_to_hal(void) + hal_set_bool(emcmot_hal_data->motion_enabled, GET_MOTION_ENABLE_FLAG()); +@@ -2045,6 +2497,9 @@ static void output_to_hal(void) for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ double speed; @@ -1686,97 +1715,111 @@ index 8ed2cb3882..722c58545d 100644 if(emcmotStatus->spindle_status[spindle_num].css_factor) { double denom = fabs(emcmotStatus->spindle_status[spindle_num].xoffset - emcmotStatus->carte_pos_cmd.tran.x); -@@ -1988,16 +2421,22 @@ static void output_to_hal(void) +@@ -2079,14 +2534,22 @@ static void output_to_hal(void) } } + if (!spindle_available) speed = 0.0; + if (!spindle_available) { -+ *(emcmot_hal_data->spindle[spindle_num].spindle_orient) = 0; -+ *(emcmot_hal_data->spindle[spindle_num].spindle_locked) = 0; ++ hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_orient, 0); ++ hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_locked, 0); + } - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out) = speed; - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps) = speed/60.; - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_abs) = fabs(speed); - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps_abs) = fabs(speed / 60); -- *(emcmot_hal_data->spindle[spindle_num].spindle_on) = -- ((emcmotStatus->spindle_status[spindle_num].state) !=0) ? 1 : 0; -- *(emcmot_hal_data->spindle[spindle_num].spindle_forward) = (speed > 0) ? 1 : 0; -- *(emcmot_hal_data->spindle[spindle_num].spindle_reverse) = (speed < 0) ? 1 : 0; -+ *(emcmot_hal_data->spindle[spindle_num].spindle_on) = -+ spindle_available && emcmotStatus->spindle_status[spindle_num].state != 0; -+ *(emcmot_hal_data->spindle[spindle_num].spindle_forward) = spindle_available && speed > 0; -+ *(emcmot_hal_data->spindle[spindle_num].spindle_reverse) = spindle_available && speed < 0; - *(emcmot_hal_data->spindle[spindle_num].spindle_brake) = -- (emcmotStatus->spindle_status[spindle_num].brake != 0) ? 1 : 0; + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out, speed); + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps, speed/60.); + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_abs, fabs(speed)); + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_out_rps_abs, fabs(speed / 60)); +- hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_on, (emcmotStatus->spindle_status[spindle_num].state) != 0); +- hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_forward, speed > 0); +- hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_reverse, speed < 0); +- hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_brake, emcmotStatus->spindle_status[spindle_num].brake != 0); ++ hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_on, ++ spindle_available && emcmotStatus->spindle_status[spindle_num].state != 0); ++ hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_forward, spindle_available && speed > 0); ++ hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_reverse, spindle_available && speed < 0); ++ hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_brake, + spindle_available && -+ emcmotStatus->spindle_status[spindle_num].brake != 0; ++ emcmotStatus->spindle_status[spindle_num].brake != 0); // What is this for? Docs don't say - *(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps) = - emcmotStatus->spindle_status[spindle_num].speed / 60.; -@@ -2054,6 +2493,13 @@ static void output_to_hal(void) + hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps, + emcmotStatus->spindle_status[spindle_num].speed / 60.); +@@ -2147,6 +2610,13 @@ static void output_to_hal(void) /* two way handshaking for the spindle encoder */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ + availability_status_t *a = &emcmotStatus->spindle_status[spindle_num].availability; + if (a->controlled && a->state != EMCMOT_AVAILABILITY_AVAILABLE) { + emcmotStatus->spindle_status[spindle_num].spindle_index_enable = 0; -+ *emcmot_hal_data->spindle[spindle_num].spindle_index_enable = 0; ++ hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable, 0); + old_motion_index[spindle_num] = old_hal_index[spindle_num] = 0; + continue; + } if(emcmotStatus->spindle_status[spindle_num].spindle_index_enable && !old_motion_index[spindle_num]) { - *emcmot_hal_data->spindle[spindle_num].spindle_index_enable = 1; -@@ -2096,7 +2542,14 @@ static void output_to_hal(void) - *(joint_data->motor_pos_cmd) = joint->motor_pos_cmd; - *(joint_data->joint_pos_cmd) = joint->pos_cmd; - *(joint_data->joint_pos_fb) = joint->pos_fb; -- *(joint_data->amp_enable) = GET_JOINT_ENABLE_FLAG(joint); + hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable, 1); +@@ -2189,7 +2659,14 @@ static void output_to_hal(void) + hal_set_real(joint_data->motor_pos_cmd, joint->motor_pos_cmd); + hal_set_real(joint_data->joint_pos_cmd, joint->pos_cmd); + hal_set_real(joint_data->joint_pos_fb, joint->pos_fb); +- hal_set_bool(joint_data->amp_enable, GET_JOINT_ENABLE_FLAG(joint)); + availability_status_t *availability = + &emcmotStatus->joint_status[joint_num].availability; -+ *(joint_data->amp_enable) = GET_JOINT_ENABLE_FLAG(joint) && ++ hal_set_bool(joint_data->amp_enable, GET_JOINT_ENABLE_FLAG(joint) && + (availability->state == + EMCMOT_AVAILABILITY_AVAILABLE || + availability->state == EMCMOT_AVAILABILITY_HOMING || + (availability->state == EMCMOT_AVAILABILITY_DISABLING && -+ availability->phase == AVAIL_PHASE_WAIT_SETTLED)); - - *(joint_data->coarse_pos_cmd) = joint->coarse_pos; - *(joint_data->joint_vel_cmd) = joint->vel_cmd; ++ availability->phase == AVAIL_PHASE_WAIT_SETTLED))); + + hal_set_real(joint_data->coarse_pos_cmd, joint->coarse_pos); + hal_set_real(joint_data->joint_vel_cmd, joint->vel_cmd); +diff --git a/src/emc/motion/homing.h b/src/emc/motion/homing.h +index b6a51c4..af883eb 100644 +--- a/src/emc/motion/homing.h ++++ b/src/emc/motion/homing.h +@@ -77,7 +77,9 @@ bool do_homing(void); //return 1 if allhomed + void write_homing_out_pins(int njoints); + + // responses to EMCMOT_JOINT_HOME message: +-// jno == -1 requests home-all (start the homing sequence). ++// jno == -1 requests home-all (start the homing sequence). By the end of the ++// next do_homing() the home must be reported by get_homing_is_active() or be ++// finished: task takes an inactive module to mean the home has ended. + void do_home_joint(int jno); + // per-joint controls + // Abort an in-progress homing of joint jno. diff --git a/src/emc/motion/mot_priv.h b/src/emc/motion/mot_priv.h -index 2050ad51a3..631c146ee2 100644 +index 6e02b16..e5b8373 100644 --- a/src/emc/motion/mot_priv.h +++ b/src/emc/motion/mot_priv.h @@ -70,6 +70,13 @@ typedef struct { - hal_bit_t *spindle_is_oriented; /* in: orientation completed */ - hal_s32_t *spindle_orient_fault; /* in: error code of failed operation */ - -+ hal_bit_t *availability_request; -+ hal_bit_t *availability_ack; -+ hal_bit_t *available; -+ hal_s32_t *availability_state; -+ hal_bit_t *availability_fault; -+ hal_s32_t *availability_fault_code; + hal_bool_t spindle_is_oriented; /* in: orientation completed */ + hal_sint_t spindle_orient_fault; /* in: error code of failed operation */ + ++ hal_bool_t availability_request; ++ hal_bool_t availability_ack; ++ hal_bool_t available; ++ hal_sint_t availability_state; ++ hal_bool_t availability_fault; ++ hal_sint_t availability_fault_code; + } spindle_hal_t; typedef struct { @@ -106,6 +113,13 @@ typedef struct { - hal_bit_t *amp_fault; /* RPI: amp fault input */ - hal_bit_t *amp_enable; /* WPI: amp enable output */ - -+ hal_bit_t *availability_request; -+ hal_bit_t *availability_ack; -+ hal_bit_t *available; -+ hal_s32_t *availability_state; -+ hal_bit_t *availability_fault; -+ hal_s32_t *availability_fault_code; + hal_bool_t amp_fault; /* RPI: amp fault input */ + hal_bool_t amp_enable; /* WPI: amp enable output */ + ++ hal_bool_t availability_request; ++ hal_bool_t availability_ack; ++ hal_bool_t available; ++ hal_sint_t availability_state; ++ hal_bool_t availability_fault; ++ hal_sint_t availability_fault_code; + - hal_bit_t *unlock; /* WPI: command that axis should unlock for rotation */ - hal_bit_t *is_unlocked; /* RPI: axis is currently unlocked */ + hal_bool_t unlock; /* WPI: command that axis should unlock for rotation */ + hal_bool_t is_unlocked; /* RPI: axis is currently unlocked */ -@@ -356,4 +370,11 @@ typedef enum { +@@ -361,4 +375,11 @@ typedef enum { motion_joint_release_state_t motion_joint_release_state(int joint_num); void motion_cancel_joint(int joint_num); @@ -1789,36 +1832,49 @@ index 2050ad51a3..631c146ee2 100644 + #endif /* MOT_PRIV_H */ diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c -index 7f81108901..87f1a06205 100644 +index 067711a..8993290 100644 --- a/src/emc/motion/motion.c +++ b/src/emc/motion/motion.c -@@ -735,6 +735,12 @@ static int export_spindle(int num, spindle_hal_t * addr){ - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->spindle_revs), mot_comp_id, "spindle.%d.revs", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->spindle_speed_in), mot_comp_id, "spindle.%d.speed-in", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->spindle_is_atspeed), mot_comp_id, "spindle.%d.at-speed", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->availability_request), mot_comp_id, "spindle.%d.availability-request", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->availability_ack), mot_comp_id, "spindle.%d.availability-ack", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->available), mot_comp_id, "spindle.%d.available", num)) != 0) return retval; -+ if ((retval = hal_pin_s32_newf(HAL_OUT, &(addr->availability_state), mot_comp_id, "spindle.%d.availability-state", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->availability_fault), mot_comp_id, "spindle.%d.availability-fault", num)) != 0) return retval; -+ if ((retval = hal_pin_s32_newf(HAL_OUT, &(addr->availability_fault_code), mot_comp_id, "spindle.%d.availability-fault-code", num)) != 0) return retval; - *(addr->spindle_is_atspeed) = 1; +@@ -739,6 +739,12 @@ static int export_spindle(int num, spindle_hal_t * addr){ + /* Default 1: an unwired at-speed pin must never block motion. Do not + change to 0 or machines without at-speed wired would idle forever. */ + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->spindle_is_atspeed), 1, "spindle.%d.at-speed", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->availability_request), 0, "spindle.%d.availability-request", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->availability_ack), 0, "spindle.%d.availability-ack", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->available), 0, "spindle.%d.available", num)); ++ CALL_CHECK(hal_pin_new_sint(mot_comp_id, HAL_OUT, &(addr->availability_state), 0, "spindle.%d.availability-state", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->availability_fault), 0, "spindle.%d.availability-fault", num)); ++ CALL_CHECK(hal_pin_new_sint(mot_comp_id, HAL_OUT, &(addr->availability_fault_code), 0, "spindle.%d.availability-fault-code", num)); /* restore saved message level */ rtapi_set_msg_level(msg); -@@ -763,6 +769,12 @@ static int export_joint(int num, joint_hal_t * addr) - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->neg_lim_sw), mot_comp_id, "joint.%d.neg-lim-sw-in", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->amp_enable), mot_comp_id, "joint.%d.amp-enable-out", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->amp_fault), mot_comp_id, "joint.%d.amp-fault-in", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->availability_request), mot_comp_id, "joint.%d.availability-request", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->availability_ack), mot_comp_id, "joint.%d.availability-ack", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->available), mot_comp_id, "joint.%d.available", num)) != 0) return retval; -+ if ((retval = hal_pin_s32_newf(HAL_OUT, &(addr->availability_state), mot_comp_id, "joint.%d.availability-state", num)) != 0) return retval; -+ if ((retval = hal_pin_bit_newf(HAL_OUT, &(addr->availability_fault), mot_comp_id, "joint.%d.availability-fault", num)) != 0) return retval; -+ if ((retval = hal_pin_s32_newf(HAL_OUT, &(addr->availability_fault_code), mot_comp_id, "joint.%d.availability-fault-code", num)) != 0) return retval; - if ((retval = hal_pin_s32_newf(HAL_IN, &(addr->jjog_counts), mot_comp_id, "joint.%d.jog-counts", num)) != 0) return retval; - if ((retval = hal_pin_bit_newf(HAL_IN, &(addr->jjog_enable), mot_comp_id, "joint.%d.jog-enable", num)) != 0) return retval; - if ((retval = hal_pin_float_newf(HAL_IN, &(addr->jjog_scale), mot_comp_id, "joint.%d.jog-scale", num)) != 0) return retval; -@@ -917,6 +929,8 @@ static int init_comm_buffers(void) + return 0; +@@ -764,6 +770,12 @@ static int export_joint(int num, joint_hal_t * addr) + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->neg_lim_sw), 0, "joint.%d.neg-lim-sw-in", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->amp_enable), 0, "joint.%d.amp-enable-out", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->amp_fault), 0, "joint.%d.amp-fault-in", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->availability_request), 0, "joint.%d.availability-request", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->availability_ack), 0, "joint.%d.availability-ack", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->available), 0, "joint.%d.available", num)); ++ CALL_CHECK(hal_pin_new_sint(mot_comp_id, HAL_OUT, &(addr->availability_state), 0, "joint.%d.availability-state", num)); ++ CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_OUT, &(addr->availability_fault), 0, "joint.%d.availability-fault", num)); ++ CALL_CHECK(hal_pin_new_sint(mot_comp_id, HAL_OUT, &(addr->availability_fault_code), 0, "joint.%d.availability-fault-code", num)); + CALL_CHECK(hal_pin_new_sint(mot_comp_id, HAL_IN, &(addr->jjog_counts), 0, "joint.%d.jog-counts", num)); + CALL_CHECK(hal_pin_new_bool(mot_comp_id, HAL_IN, &(addr->jjog_enable), 0, "joint.%d.jog-enable", num)); + CALL_CHECK(hal_pin_new_real(mot_comp_id, HAL_IN, &(addr->jjog_scale), 0.0, "joint.%d.jog-scale", num)); +@@ -870,9 +882,12 @@ static int init_comm_buffers(void) + emcmotStatus->commandEcho = 0; + emcmotStatus->commandNumEcho = 0; + emcmotStatus->commandStatus = 0; ++ emcmotStatus->home_started_command = 0; + + /* init more stuff */ + emcmotInternal->head = 0; ++ emcmotInternal->home_request_command = 0; ++ emcmotInternal->home_started_command = 0; + emcmotConfig->head = 0; + + emcmotStatus->motionFlag = 0; +@@ -927,6 +942,8 @@ static int init_comm_buffers(void) for (spindle_num = 0; spindle_num < EMCMOT_MAX_SPINDLES; spindle_num++){ emcmotStatus->spindle_status[spindle_num].scale = 1.0; emcmotStatus->spindle_status[spindle_num].speed = 0.0; @@ -1827,7 +1883,7 @@ index 7f81108901..87f1a06205 100644 } axis_init_all(); -@@ -936,6 +950,8 @@ static int init_comm_buffers(void) +@@ -946,6 +963,8 @@ static int init_comm_buffers(void) joint->min_ferror = 0.01; joint->max_ferror = 1.0; joint->backlash = 0.0; @@ -1837,12 +1893,12 @@ index 7f81108901..87f1a06205 100644 joint->comp.entries = 0; joint->comp.entry = &(joint->comp.array[0]); diff --git a/src/emc/motion/motion.h b/src/emc/motion/motion.h -index dfc990f853..fd934976e2 100644 +index ad391e1..bed4351 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h -@@ -183,6 +183,10 @@ extern "C" { - EMCMOT_SET_AXIS_JERK_LIMIT, /* set the max axis jerk */ +@@ -180,6 +180,10 @@ extern "C" { + EMCMOT_SELECT_KINS_TYPE, /* select the switchkins type (G12.1) */ EMCMOT_SET_SPINDLE_PARAMS, /* One command to set all spindle params */ + EMCMOT_SET_JOINT_AVAILABILITY_CONFIG, + EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG, @@ -1851,8 +1907,8 @@ index dfc990f853..fd934976e2 100644 } cmd_code_t; -@@ -277,6 +281,10 @@ extern "C" { - struct state_tag_t tag; +@@ -280,6 +284,10 @@ extern "C" { + int switchkins_type; /* switchkins type requested by G12.1 */ int g76_pass_id; /* internal G76 pass ownership, zero otherwise */ int g76_pass_clearance;/* 1: clearance retract, 2: approach endpoint */ + int availability_control; @@ -1862,7 +1918,7 @@ index dfc990f853..fd934976e2 100644 } emcmot_command_t; /*! \todo FIXME - these packed bits might be replaced with chars -@@ -357,7 +365,6 @@ Suggestion: Split this in to an Error and a Status flag register.. +@@ -360,7 +368,6 @@ Suggestion: Split this in to an Error and a Status flag register.. #define EMCMOT_JOINT_MIN_HARD_LIMIT_BIT 0x0020 #define EMCMOT_JOINT_FERROR_BIT 0x0040 #define EMCMOT_JOINT_FAULT_BIT 0x0080 @@ -1870,7 +1926,7 @@ index dfc990f853..fd934976e2 100644 /*! \todo FIXME - the terms "teleop", "coord", and "free" are poorly documented. This is my feeble attempt to understand exactly what they mean. -@@ -425,6 +432,53 @@ Suggestion: Split this in to an Error and a Status flag register.. +@@ -428,6 +435,52 @@ Suggestion: Split this in to an Error and a Status flag register.. EMCMOT_ORIENT_FAULTED, } orient_state_t; @@ -1900,8 +1956,8 @@ index dfc990f853..fd934976e2 100644 + AVAIL_PHASE_IDLE, + AVAIL_PHASE_INITIAL_ACK, + AVAIL_PHASE_RUNTIME_ACK, ++ AVAIL_PHASE_WAIT_HOME_REQUEST, /* task issues the queued home */ + AVAIL_PHASE_WAIT_FREE, -+ AVAIL_PHASE_WAIT_HOME_START, + AVAIL_PHASE_WAIT_HOME_FINISH, + AVAIL_PHASE_WAIT_SETTLED, + AVAIL_PHASE_CANCEL_HOME, @@ -1914,7 +1970,6 @@ index dfc990f853..fd934976e2 100644 + int target_available; + availability_phase_t phase; + double held_position; /* logical command, fixed throughout release */ -+ motion_state_t return_motion_state; + availability_state_t state; + availability_fault_t fault; + double timeout; @@ -1924,7 +1979,7 @@ index dfc990f853..fd934976e2 100644 /* flags for enabling spindle scaling, feed scaling, adaptive feed, and feed hold */ -@@ -510,6 +564,7 @@ Suggestion: Split this in to an Error and a Status flag register.. +@@ -514,6 +567,7 @@ Suggestion: Split this in to an Error and a Status flag register.. EMCMOT_JOINT_FLAG flag; /* see above for bit details */ bool homed; bool homing; @@ -1932,7 +1987,7 @@ index dfc990f853..fd934976e2 100644 double pos_cmd; /* commanded joint position */ double pos_fb; /* position feedback, comp removed */ -@@ -556,6 +611,7 @@ Suggestion: Split this in to an Error and a Status flag register.. +@@ -564,6 +618,7 @@ Suggestion: Split this in to an Error and a Status flag register.. double home_search_vel; int home_sequence; double increment; @@ -1940,21 +1995,34 @@ index dfc990f853..fd934976e2 100644 } spindle_status_t; typedef struct { -@@ -763,6 +819,9 @@ typedef struct emcmot_internal_t { +@@ -691,6 +746,10 @@ Suggestion: Split this in to an Error and a Status flag register.. + Aggregate: stays true across the gap between + HOME_SEQUENCE groups, when every joint's per-joint + .homing flag is momentarily false. */ ++ int home_started_command; /* commandNum of the last EMCMOT_JOINT_HOME that ++ started a home, published once do_homing() has run ++ after the start. With homing_active false, a home ++ this new has finished, however briefly it ran. */ + + int switchkins_seq; /* echoes the config counter once acted on */ + int switchkins_type; /* switchkins type now in force */ +@@ -790,6 +849,11 @@ typedef struct emcmot_internal_t { int enabling; /* starts up disabled */ int coordinating; /* starts up in free mode */ int teleoperating; /* starts up in free mode */ + int availability_motion_error; /* acknowledged by Abort or enable */ + int availability_machine_on; /* serialized initial acquisitions */ + int availability_resource; /* serialized initial spindle acquisitions */ ++ int home_request_command; /* commandNum of the last accepted home request */ ++ int home_started_command; /* the same, once its home has been started */ int overriding; /* non-zero means we've initiated an joint move while overriding limits */ TP_STRUCT coord_tp; /* coordinated mode planner */ diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index 7663c33f7e..c40c9dbe5e 100644 +index 61fa3b6..54d973c 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -61,6 +61,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) +@@ -59,6 +59,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) case EMC_JOINT_UNHOME_TYPE: ((EMC_JOINT_UNHOME *) buffer)->update(cms); break; @@ -1964,7 +2032,7 @@ index 7663c33f7e..c40c9dbe5e 100644 case EMC_JOG_CONT_TYPE: ((EMC_JOG_CONT *) buffer)->update(cms); break; -@@ -160,6 +163,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) +@@ -158,6 +161,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) case EMC_SPINDLE_OFF_TYPE: ((EMC_SPINDLE_OFF *) buffer)->update(cms); break; @@ -1974,7 +2042,7 @@ index 7663c33f7e..c40c9dbe5e 100644 case EMC_SPINDLE_ON_TYPE: ((EMC_SPINDLE_ON *) buffer)->update(cms); break; -@@ -375,6 +381,8 @@ const char *emc_symbol_lookup(uint32_t type) +@@ -376,6 +382,8 @@ const char *emc_symbol_lookup(uint32_t type) return "EMC_JOINT_HOME"; case EMC_JOINT_UNHOME_TYPE: return "EMC_JOINT_UNHOME"; @@ -1983,7 +2051,7 @@ index 7663c33f7e..c40c9dbe5e 100644 case EMC_JOG_CONT_TYPE: return "EMC_JOG_CONT"; case EMC_JOG_INCR_TYPE: -@@ -445,6 +453,8 @@ const char *emc_symbol_lookup(uint32_t type) +@@ -446,6 +454,8 @@ const char *emc_symbol_lookup(uint32_t type) return "EMC_SPINDLE_INCREASE"; case EMC_SPINDLE_OFF_TYPE: return "EMC_SPINDLE_OFF"; @@ -1992,7 +2060,7 @@ index 7663c33f7e..c40c9dbe5e 100644 case EMC_SPINDLE_ON_TYPE: return "EMC_SPINDLE_ON"; case EMC_SPINDLE_SPEED_TYPE: -@@ -702,6 +712,13 @@ void EMC_SPINDLE_CMD_MSG::update(CMS * cms) +@@ -705,6 +715,13 @@ void EMC_SPINDLE_CMD_MSG::update(CMS * cms) cms->update(_spindle); } @@ -2006,7 +2074,7 @@ index 7663c33f7e..c40c9dbe5e 100644 /* * NML/CMS Update function for EMC_TRAJ_DELAY * Automatically generated by NML CodeGen Java Applet. -@@ -1089,6 +1106,9 @@ void EMC_SPINDLE_STAT::update(CMS * cms) +@@ -1097,6 +1114,9 @@ void EMC_SPINDLE_STAT::update(CMS * cms) cms->update(spindle_override_enabled); cms->update(at_speed); cms->update(homed); @@ -2016,7 +2084,7 @@ index 7663c33f7e..c40c9dbe5e 100644 } /* -@@ -1337,6 +1357,15 @@ void EMC_JOINT_STAT::update(CMS * cms) +@@ -1349,6 +1369,15 @@ void EMC_JOINT_STAT::update(CMS * cms) cms->update(minHardLimit); cms->update(maxHardLimit); cms->update(overrideLimits); @@ -2033,7 +2101,7 @@ index 7663c33f7e..c40c9dbe5e 100644 /* diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index 0dca92c7e0..32ca6fbaa0 100644 +index 67c8d34..94d6a19 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -74,6 +74,7 @@ struct PM_CARTESIAN; @@ -2044,7 +2112,7 @@ index 0dca92c7e0..32ca6fbaa0 100644 #define EMC_JOINT_STAT_TYPE ((NMLTYPE) 198) #define EMC_AXIS_STAT_TYPE ((NMLTYPE) 199) -@@ -180,6 +181,7 @@ struct PM_CARTESIAN; +@@ -181,6 +182,7 @@ struct PM_CARTESIAN; #define EMC_SPINDLE_SPEED_TYPE ((NMLTYPE) 1316) #define EMC_SPINDLE_ORIENT_TYPE ((NMLTYPE) 1317) #define EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE ((NMLTYPE) 1318) @@ -2052,7 +2120,29 @@ index 0dca92c7e0..32ca6fbaa0 100644 #define EMC_SPINDLE_STAT_TYPE ((NMLTYPE) 1399) -@@ -340,6 +342,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); +@@ -248,7 +250,8 @@ enum class EMC_TASK_HOLD_WAIT { + HOMING = 1, // a queued G28.2 homing cycle + IO = 2, // a tool change or other I/O controller command + SYSTEM_COMMAND = 3, // a user M100-M199 program +- EXECUTOR = 4 // a request started by an executor remap (stdglue) ++ EXECUTOR = 4, // a request started by an executor remap (stdglue) ++ AVAILABILITY = 5 // an M54/M55 or direct availability handshake + }; + + // types for motion control +@@ -342,6 +345,11 @@ extern int emcJointSetMaxAcceleration(int joint, double acc); + extern int emcJointInit(int joint); + extern int emcJointHalt(int joint); + extern int emcJointHome(int joint); ++// motion command number of the last emcJointHome() ++extern int emcJointHomeCommand(); ++// command number of the newest home motion has started, as of the last ++// emcMotionUpdate() ++extern int emcJointHomeStartedCommand(); + extern int emcJointUnhome(int joint); + extern int emcJointActivate(int joint); + extern int emcJointDeactivate(int joint); +@@ -354,6 +362,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); extern int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints); @@ -2063,7 +2153,7 @@ index 0dca92c7e0..32ca6fbaa0 100644 extern int emcJointSetMaxJerk(int joint, double jerk); -@@ -451,6 +457,11 @@ extern int emcSpindleBrakeRelease(int spindle); +@@ -483,6 +495,11 @@ extern int emcSpindleBrakeRelease(int spindle); extern int emcSpindleBrakeEngage(int spindle); extern int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles); @@ -2076,10 +2166,10 @@ index 0dca92c7e0..32ca6fbaa0 100644 // implementation functions for EMC_COOLANT types diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index 225b549d38..ac4d322a92 100644 +index e4a04b1..feab3fb 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -351,6 +351,17 @@ class EMC_JOINT_UNHOME:public EMC_JOINT_CMD_MSG { +@@ -356,6 +356,17 @@ class EMC_JOINT_UNHOME:public EMC_JOINT_CMD_MSG { void update(CMS * cms); }; @@ -2097,7 +2187,7 @@ index 225b549d38..ac4d322a92 100644 class EMC_JOG_CONT:public EMC_JOG_CMD_MSG { public: EMC_JOG_CONT() -@@ -501,6 +512,9 @@ class EMC_JOINT_STAT:public EMC_JOINT_STAT_MSG { +@@ -506,6 +517,9 @@ class EMC_JOINT_STAT:public EMC_JOINT_STAT_MSG { unsigned char minHardLimit; // non-zero means min hard limit exceeded unsigned char maxHardLimit; // non-zero means max hard limit exceeded unsigned char overrideLimits; // non-zero means limits are overridden @@ -2107,7 +2197,7 @@ index 225b549d38..ac4d322a92 100644 }; // declarations for EMC_TRAJ classes -@@ -1148,6 +1162,9 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { +@@ -1190,6 +1204,9 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { bool spindle_override_enabled; bool at_speed; bool homed; @@ -2117,8 +2207,8 @@ index 225b549d38..ac4d322a92 100644 }; class EMC_MOTION_STAT:public EMC_MOTION_STAT_MSG { -@@ -1904,6 +1921,18 @@ class EMC_SPINDLE_OFF:public EMC_SPINDLE_CMD_MSG { - int spindle; // the spindle to be turned off +@@ -2002,6 +2019,18 @@ class EMC_SPINDLE_OFF:public EMC_SPINDLE_CMD_MSG { + int wait_for_spindle_at_speed; // wait for at-speed (spindle stopped) before next feed }; +class EMC_SPINDLE_SET_AVAILABILITY:public EMC_SPINDLE_CMD_MSG { @@ -2137,10 +2227,10 @@ index 225b549d38..ac4d322a92 100644 public: EMC_SPINDLE_INCREASE() diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc -index 6d91ef1bd0..6215d7d68c 100644 +index 6010ecb..72fd7d4 100644 --- a/src/emc/nml_intf/emcops.cc +++ b/src/emc/nml_intf/emcops.cc -@@ -50,7 +50,10 @@ EMC_JOINT_STAT::EMC_JOINT_STAT() +@@ -58,7 +58,10 @@ EMC_JOINT_STAT::EMC_JOINT_STAT() maxSoftLimit(0), minHardLimit(0), maxHardLimit(0), @@ -2152,7 +2242,7 @@ index 6d91ef1bd0..6215d7d68c 100644 { } -@@ -198,7 +201,10 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() +@@ -216,7 +219,10 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() orient_fault(0), spindle_override_enabled(OFF), at_speed(OFF), @@ -2165,10 +2255,10 @@ index 6d91ef1bd0..6215d7d68c 100644 } diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index e0fe4e3616..ac4a55781b 100644 +index d2634e9..f889dd3 100644 --- a/src/emc/task/emctask.cc +++ b/src/emc/task/emctask.cc -@@ -234,6 +234,7 @@ void emcTaskQueueTaskPlanSynchCmd() +@@ -245,6 +245,7 @@ void emcTaskQueueTaskPlanSynchCmd() int emcTaskAbort() { @@ -2177,10 +2267,10 @@ index e0fe4e3616..ac4a55781b 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 59021c7dcb..1314163557 100644 +index fd0335e..900c430 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -169,6 +169,60 @@ volatile int done; +@@ -171,6 +171,61 @@ volatile int done; static int emctask_shutdown(void); extern void backtrace(int signo); int _task = 1; // control preview behaviour when remapping @@ -2193,6 +2283,7 @@ index 59021c7dcb..1314163557 100644 + bool available = false; + bool cancelled = false; + bool failed = false; ++ bool home_issued = false; +} availability_pending; + +void emcTaskCancelAvailability() @@ -2241,7 +2332,7 @@ index 59021c7dcb..1314163557 100644 static int joints = 0; uint64_t task_beat = 0; // Task's main loop heartbeat counter -@@ -180,8 +234,13 @@ extern void setup_signal_handlers(); // backtrace, gdb-in-new-window supportx +@@ -182,8 +237,13 @@ extern void setup_signal_handlers(); // backtrace, gdb-in-new-window supportx int all_homed(void) { for (int i = 0; i < emcStatus->motion.traj.joints; i++) { @@ -2257,7 +2348,59 @@ index 59021c7dcb..1314163557 100644 } return 1; } -@@ -836,6 +895,13 @@ static bool emcTaskArmSingleStep() +@@ -436,21 +496,27 @@ static EMC_TRAJ_SET_SPINDLESYNC *emcTrajSetSpindlesyncMsg; + // per-channel-homing problem. + static int homingWaitJoint = -1; // joint (-1 = all) we're waiting on + static bool homingWaiting = false; // true while EMC_TASK_EXEC::WAITING_FOR_HOMING is active +-static bool homingStarted = false; // true once we've observed .homing go true at least once ++static bool homingStarted = false; // true once motion has reported the home as started ++static int homingCommand = 0; // motion command number of the issued home + static double homingIssueTime = 0.0; // etime() when issued, for the start-timeout below + // Some motion-side guards (e.g. "must be in joint mode to home", + // motion.homing-inhibit, already-homing) reject with reportError() and a + // bare return, without setting commandStatus to a failure -- so a rejected + // home can look identical to an accepted one at the retval/NML level. Give +-// it this long to actually start (.homing go true) before treating it as +-// rejected; once started, there is no further timeout (real homing cycles +-// vary widely in duration, same as a GUI just watching .homing/.homed). ++// it this long to actually start before treating it as rejected; once started, ++// there is no further timeout (real homing cycles vary widely in duration, same ++// as a GUI just watching .homing/.homed). Motion reports the start by command ++// number, because a home can begin and end between two status reads. + static const double HOMING_START_TIMEOUT = 2.0; + static EMC_TRAJ_MODE homingPriorMode = EMC_TRAJ_MODE::FREE; // mode to restore on success + // Task mode in effect when the queued home was issued. While motion is dipped + // into FREE, determineMode() reports MANUAL, so resumable Stop uses this to + // recognise a G28.2 that belongs to an AUTO program. + static EMC_TASK_MODE homingPriorTaskMode = EMC_TASK_MODE::MANUAL; ++// Set when an acquisition home failed to start: motion refuses mode changes ++// while the acquisition is in transition, so homingPriorMode is restored once ++// the abort that follows has cancelled it. ++static bool homingRestoreAfterAvailability = false; + // True only while emcTaskExecute() is issuing a command taken off the + // interp_list. emcTaskIssueCommand() serves both that queued path and the + // immediate commands emcTaskPlan() sends straight through (the GUI's Home +@@ -462,6 +528,19 @@ static EMC_TASK_MODE homingPriorTaskMode = EMC_TASK_MODE::MANUAL; + // an immediate home keeps its original pass-through behaviour. + static bool issuingQueuedCommand = false; + ++// Undo the FREE dip of a home that never started. ++static void emcTaskRestoreHomingMode() ++{ ++ if (homingPriorMode == EMC_TRAJ_MODE::FREE) { ++ return; ++ } ++ if (availability_pending.active) { ++ homingRestoreAfterAvailability = true; ++ } else { ++ emcTrajSetMode(homingPriorMode); ++ } ++} ++ + static EMC_SPINDLE_SPEED *spindle_speed_msg; + static EMC_SPINDLE_ORIENT *spindle_orient_msg; + static EMC_SPINDLE_WAIT_ORIENT_COMPLETE *wait_spindle_orient_complete_msg; +@@ -951,6 +1030,13 @@ static bool emcTaskArmSingleStep() return true; } @@ -2271,7 +2414,27 @@ index 59021c7dcb..1314163557 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1029,6 +1095,31 @@ static int emcTaskPlan(void) +@@ -1063,6 +1149,19 @@ static EMC_TASK_HOLD_WAIT emcTaskHoldWait() + if (emcStatus->io.status == RCS_STATUS::EXEC) { + return EMC_TASK_HOLD_WAIT::IO; + } ++ // A joint or spindle handshake waits for its acknowledgment. The ++ // acquisition home of an unhomed joint is not part of it: like a queued ++ // G28.2 it starts only after Resume, and once started it is HOMING. ++ const auto &op = availability_pending; ++ if (op.active && !op.cancelled) { ++ int state = op.spindle ++ ? emcStatus->motion.spindle[op.index].availability_state ++ : emcStatus->motion.joint[op.index].availability_state; ++ if (state == EMCMOT_AVAILABILITY_ENABLING || ++ state == EMCMOT_AVAILABILITY_DISABLING) { ++ return EMC_TASK_HOLD_WAIT::AVAILABILITY; ++ } ++ } + return EMC_TASK_HOLD_WAIT::NONE; + } + +@@ -1210,6 +1309,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2303,7 +2466,7 @@ index 59021c7dcb..1314163557 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -@@ -1047,6 +1138,36 @@ static int emcTaskPlan(void) +@@ -1233,6 +1357,36 @@ static int emcTaskPlan(void) return 0; } @@ -2340,7 +2503,7 @@ index 59021c7dcb..1314163557 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1559,9 +1680,7 @@ static int emcTaskPlan(void) +@@ -1745,9 +1899,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2351,7 +2514,7 @@ index 59021c7dcb..1314163557 100644 break; // otherwise we can't handle it -@@ -1824,6 +1943,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -2013,6 +2165,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) case EMC_TRAJ_CLEAR_PROBE_TRIPPED_FLAG_TYPE: // and this case EMC_AUX_INPUT_WAIT_TYPE: case EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE: @@ -2360,7 +2523,31 @@ index 59021c7dcb..1314163557 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -1993,6 +2114,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2219,10 +2373,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + emcTrajSetMode(EMC_TRAJ_MODE::FREE); + } + homingWaitJoint = target_joint; ++ homingRestoreAfterAvailability = false; + homingStarted = false; + homingIssueTime = etime(); + homingWaiting = true; + retval = emcJointHome(target_joint); ++ homingCommand = emcJointHomeCommand(); + if (retval != 0) { + // emcJointHome() rejected the request outright (e.g. an + // invalid joint number) -- homing will never start, so the +@@ -2232,9 +2388,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + // from it) stays stuck at FREE/MANUAL until the operator + // manually cycles mode again. + homingWaiting = false; +- if (homingPriorMode != EMC_TRAJ_MODE::FREE) { +- emcTrajSetMode(homingPriorMode); +- } ++ emcTaskRestoreHomingMode(); + } + } + break; +@@ -2248,6 +2402,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2385,8 +2572,8 @@ index 59021c7dcb..1314163557 100644 case EMC_JOG_CONT_TYPE: jog_cont_msg = reinterpret_cast(cmd); retval = emcJogCont(jog_cont_msg->joint_or_axis, -@@ -2334,6 +2473,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) - retval = emcSpindleOff(spindle_off_msg->spindle); +@@ -2615,6 +2787,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + retval = emcSpindleOff(spindle_off_msg->spindle, spindle_off_msg->wait_for_spindle_at_speed); break; + case EMC_SPINDLE_SET_AVAILABILITY_TYPE: { @@ -2412,7 +2599,7 @@ index 59021c7dcb..1314163557 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -2777,7 +2936,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3074,7 +3266,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2420,12 +2607,14 @@ index 59021c7dcb..1314163557 100644 + availability_completion() != EMC_TASK_EXEC::DONE) return -1; retval = emcTaskPlanSynch(); + availability_pending.active = false; -+ if (emcStatus->task.interpState == EMC_TASK_INTERP::IDLE) ++ // An MDI line still waiting for its queue to drain owns the wait. ++ if (emcStatus->task.interpState == EMC_TASK_INTERP::IDLE && ++ !mdi_execute_wait) + emcTaskPlanClearWait(); if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -2887,6 +3051,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3189,6 +3388,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2437,7 +2626,7 @@ index 59021c7dcb..1314163557 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -2958,6 +3127,12 @@ static int emcTaskExecute(void) +@@ -3271,6 +3475,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2450,15 +2639,42 @@ index 59021c7dcb..1314163557 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3067,11 +3242,32 @@ static int emcTaskExecute(void) +@@ -3399,11 +3609,59 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: + if (availability_pending.active) { + auto completion = availability_completion(); ++ auto &op = availability_pending; ++ if (completion == EMC_TASK_EXEC::WAITING_FOR_MOTION && ++ !op.cancelled && !op.spindle && op.available && !op.home_issued && ++ emcStatus->motion.joint[op.index].availability_state == ++ EMCMOT_AVAILABILITY_HOMING) { ++ // Like a queued G28.2, the home does not start while the ++ // program is paused or stopped; it starts after Resume. ++ if (emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED || ++ emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE) ++ break; ++ // Acquisition homes an unhomed joint through the queued G28.2 ++ // home cycle: FREE dip, WAITING_FOR_HOMING, mode restore. ++ EMC_JOINT_HOME home; ++ home.joint = op.index; ++ op.home_issued = true; ++ issuingQueuedCommand = true; ++ int home_retval = emcTaskIssueCommand(&home); ++ issuingQueuedCommand = false; ++ emcStatus->task.execState = home_retval == 0 && homingWaiting ++ ? EMC_TASK_EXEC::WAITING_FOR_HOMING : EMC_TASK_EXEC::ERROR; ++ break; ++ } + if (completion == EMC_TASK_EXEC::WAITING_FOR_MOTION) break; + if (availability_pending.cancelled) { + availability_pending.active = false; ++ if (homingRestoreAfterAvailability) { ++ homingRestoreAfterAvailability = false; ++ if (emcStatus->task.state == EMC_TASK_STATE::ON) ++ emcTrajSetMode(homingPriorMode); ++ } + emcStatus->task.execState = EMC_TASK_EXEC::DONE; + retval = availability_pending.failed ? -1 : 0; + break; @@ -2483,8 +2699,56 @@ index 59021c7dcb..1314163557 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } +@@ -3531,12 +3789,17 @@ static int emcTaskExecute(void) + homingStarted = true; + break; // still running; no timeout once started (see HOMING_START_TIMEOUT comment) + } ++ // A home that ended between two status reads was never seen active ++ // (absolute encoder, HOME_NO_REHOME on a homed joint, nothing to ++ // move), but motion reports that it started. ++ if (emcJointHomeStartedCommand() - homingCommand >= 0) { ++ homingStarted = true; ++ } + if (!homingStarted) { +- // Never observed homing go active: motion silently rejected +- // it (a guard like "must be in joint mode", or +- // motion.homing-inhibit, reports an operator error but does +- // not fail the NML command -- see emcJointHome's caller), +- // or this is the same task cycle it was issued in. Give it ++ // Not started: motion silently rejected it (a guard like "must ++ // be in joint mode", or motion.homing-inhibit, reports an ++ // operator error but does not fail the NML command -- see ++ // emcJointHome's caller), or it has not got there yet. Give it + // HOMING_START_TIMEOUT before concluding it was rejected. + if (etime() - homingIssueTime < HOMING_START_TIMEOUT) { + break; +@@ -3548,11 +3811,8 @@ static int emcTaskExecute(void) + emcTaskEager = 1; + homingWaiting = false; + // Nothing physically moved, so it's safe to restore the +- // mode immediately instead of leaving the machine parked +- // in FREE. +- if (homingPriorMode != EMC_TRAJ_MODE::FREE) { +- emcTrajSetMode(homingPriorMode); +- } ++ // mode instead of leaving the machine parked in FREE. ++ emcTaskRestoreHomingMode(); + break; + } + // It ran and has now stopped; did it reach the expected end state? +@@ -3618,7 +3878,9 @@ static int emcTaskExecute(void) + "coordinated motion until every joint is homed")); + emcStatus->task.execState = EMC_TASK_EXEC::ERROR; + } else if (success) { +- emcStatus->task.execState = EMC_TASK_EXEC::DONE; ++ // An availability acquisition still owns its completion. ++ emcStatus->task.execState = availability_pending.active ++ ? EMC_TASK_EXEC::WAITING_FOR_MOTION : EMC_TASK_EXEC::DONE; + if (homingPriorMode != EMC_TRAJ_MODE::FREE) { + emcTrajSetMode(homingPriorMode); + } diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh -index 79dbeb68bc..223886ebb2 100644 +index ea3bdc8..4a7089e 100644 --- a/src/emc/task/task.hh +++ b/src/emc/task/task.hh @@ -34,6 +34,7 @@ int emcTaskInit(); @@ -2496,10 +2760,41 @@ index 79dbeb68bc..223886ebb2 100644 int emcTaskSetState(EMC_TASK_STATE state); int emcTaskPlanInit(); diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index d88c727d52..ca5c4dc3a2 100644 +index aa63ab4..27418ce 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -990,6 +990,10 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) +@@ -799,6 +799,9 @@ int emcJointOverrideLimits(int joint) + return usrmotWriteEmcmotCommand(&emcmotCommand); + } + ++static int jointHomeCommand = 0; ++static int jointHomeStartedCommand = 0; ++ + int emcJointHome(int joint) + { + // Range-check against the machine's *configured* joint count, not against +@@ -835,7 +838,19 @@ int emcJointHome(int joint) + emcmotCommand.command = EMCMOT_JOINT_HOME; + emcmotCommand.joint = joint; + +- return usrmotWriteEmcmotCommand(&emcmotCommand); ++ int retval = usrmotWriteEmcmotCommand(&emcmotCommand); ++ jointHomeCommand = emcmotCommand.commandNum; ++ return retval; ++} ++ ++int emcJointHomeCommand() ++{ ++ return jointHomeCommand; ++} ++ ++int emcJointHomeStartedCommand() ++{ ++ return jointHomeStartedCommand; + } + + int emcJointUnhome(int joint) +@@ -1035,6 +1050,10 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) stat[joint_num].maxHardLimit = (joint->flag & EMCMOT_JOINT_MAX_HARD_LIMIT_BIT ? 1 : 0); stat[joint_num].overrideLimits = !!(emcmotStatus.overrideLimitMask); // one @@ -2510,7 +2805,7 @@ index d88c727d52..ca5c4dc3a2 100644 // for // all -@@ -1015,6 +1019,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) +@@ -1060,6 +1079,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) return 0; } @@ -2544,7 +2839,7 @@ index d88c727d52..ca5c4dc3a2 100644 // EMC_TRAJ functions int emcTrajSetJoints(int joints) -@@ -1839,9 +1870,11 @@ int emcMotionInit() +@@ -1918,9 +1964,11 @@ int emcMotionInit() int emcMotionHalt() { @@ -2557,7 +2852,7 @@ index d88c727d52..ca5c4dc3a2 100644 r1 = -1; for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { if (0 == emcJointHalt(t)) { -@@ -1854,7 +1887,7 @@ int emcMotionHalt() +@@ -1933,7 +1981,7 @@ int emcMotionHalt() r4 = emcPositionSave(); r5 = ini_hal_exit(); @@ -2566,7 +2861,7 @@ index d88c727d52..ca5c4dc3a2 100644 } int emcMotionAbort() -@@ -1864,6 +1897,8 @@ int emcMotionAbort() +@@ -1943,6 +1991,8 @@ int emcMotionAbort() int r3 = 0; int t; @@ -2575,7 +2870,7 @@ index d88c727d52..ca5c4dc3a2 100644 r1 = -1; for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { if (0 == emcJogAbort(t)) { -@@ -1871,8 +1906,6 @@ int emcMotionAbort() +@@ -1950,8 +2000,6 @@ int emcMotionAbort() } } @@ -2584,7 +2879,7 @@ index d88c727d52..ca5c4dc3a2 100644 return (r1 == 0 && r2 == 0 && r3 == 0) ? 0 : -1; } -@@ -2057,10 +2090,42 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ +@@ -2195,10 +2243,42 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ stat[s].css_factor = emcmotStatus.spindle_status[s].css_factor; stat[s].css_xoffset = emcmotStatus.spindle_status[s].xoffset; stat[s].at_speed = emcmotStatus.spindle_status[s].at_speed; @@ -2627,7 +2922,15 @@ index d88c727d52..ca5c4dc3a2 100644 int emcMotionUpdate(EMC_MOTION_STAT * stat) { int r1, r2, r3, r4; -@@ -2133,6 +2198,18 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) +@@ -2280,6 +2360,7 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) + + stat->jogging_active = emcmotStatus.jogging_active; + stat->homing_active = emcmotStatus.homing_active; ++ jointHomeStartedCommand = emcmotStatus.home_started_command; + stat->numExtraJoints = emcmotStatus.numExtraJoints; + + // set the status flag +@@ -2288,6 +2369,18 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) // FIXME-AJ: joints not axes for (joint = 0; joint < stat->traj.joints; joint++) { @@ -2646,7 +2949,7 @@ index d88c727d52..ca5c4dc3a2 100644 if (stat->joint[joint].status == RCS_STATUS::ERROR) { error = 1; break; -@@ -2142,6 +2219,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) +@@ -2297,6 +2390,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) break; } } @@ -2663,10 +2966,10 @@ index d88c727d52..ca5c4dc3a2 100644 error = 1; } else if (stat->traj.status == RCS_STATUS::EXEC) { diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index 03437fbce2..28ee76096f 100644 +index af63368..25b240e 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1414,6 +1414,9 @@ static PyObject *Stat_joint_one(pyStatChannel *s, int jointno) { +@@ -1419,6 +1419,9 @@ static PyObject *Stat_joint_one(pyStatChannel *s, int jointno) { F2("min_hard_limit", minHardLimit); F2("max_hard_limit", maxHardLimit); F2("override_limits", overrideLimits); @@ -2676,7 +2979,7 @@ index 03437fbce2..28ee76096f 100644 return res; } #undef F -@@ -1463,6 +1466,9 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { +@@ -1468,6 +1471,9 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { F(homed); F(orient_state); F(orient_fault); @@ -2686,7 +2989,7 @@ index 03437fbce2..28ee76096f 100644 return res; } #undef F -@@ -2021,6 +2027,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { +@@ -2064,6 +2070,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { return Py_None; } @@ -2707,7 +3010,7 @@ index 03437fbce2..28ee76096f 100644 // jog(JOG_STOP, jjogmode, ja_value) // jog(JOG_CONTINUOUS, jjogmode, ja_value, speed) // jog(JOG_INCREMENT, jjogmode, ja_value, speed, increment) -@@ -2407,6 +2427,10 @@ static PyMethodDef Command_methods[] = { +@@ -2450,6 +2470,10 @@ static PyMethodDef Command_methods[] = { "JOINT can be a valid joint number (0-9), or -1 to home all joints.\n" }, {"unhome", (PyCFunction)unhome, METH_VARARGS, NULL}, @@ -2718,11 +3021,144 @@ index 03437fbce2..28ee76096f 100644 {"jog", (PyCFunction)jog, METH_VARARGS, "jog(JOG_CONTINUOUS, joint_flag, index, speed)\n" "jog(JOG_INCREMENT, joint_flag, index, speed, increment)\n" +@@ -3427,6 +3451,7 @@ PyMODINIT_FUNC PyInit_linuxcnc(void) + PyModule_AddIntConstant(m, "HOLD_WAIT_IO", (int)EMC_TASK_HOLD_WAIT::IO); + PyModule_AddIntConstant(m, "HOLD_WAIT_SYSTEM_COMMAND", (int)EMC_TASK_HOLD_WAIT::SYSTEM_COMMAND); + PyModule_AddIntConstant(m, "HOLD_WAIT_EXECUTOR", (int)EMC_TASK_HOLD_WAIT::EXECUTOR); ++ PyModule_AddIntConstant(m, "HOLD_WAIT_AVAILABILITY", (int)EMC_TASK_HOLD_WAIT::AVAILABILITY); + PyModule_AddIntConstant(m, "STOP_STOPPING", (int)EMC_TASK_STOP_STATE::STOPPING); + PyModule_AddIntConstant(m, "STOP_STOPPED", (int)EMC_TASK_STOP_STATE::STOPPED); + PyModule_AddIntConstant(m, "STOP_STARTING", (int)EMC_TASK_STOP_STATE::STARTING); +diff --git a/tests/interp/m98m99/12-M99-endless-main-program/expected.motion-logger b/tests/interp/m98m99/12-M99-endless-main-program/expected.motion-logger +index aebc5e1..71f8701 100644 +--- a/tests/interp/m98m99/12-M99-endless-main-program/expected.motion-logger ++++ b/tests/interp/m98m99/12-M99-endless-main-program/expected.motion-logger +@@ -19,6 +19,7 @@ SET_JOINT_HOMING_PARAMS joint=0, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=0, vel=4 + SET_JOINT_ACC_LIMIT joint=0, acc=1000 + SET_JOINT_JERK_LIMIT joint=0, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=0, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=0 + SET_JOINT_BACKLASH joint=1, backlash=0 + SET_JOINT_POSITION_LIMITS joint=1, min=-40, max=0 +@@ -29,6 +30,7 @@ SET_JOINT_HOMING_PARAMS joint=1, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=1, vel=4 + SET_JOINT_ACC_LIMIT joint=1, acc=1000 + SET_JOINT_JERK_LIMIT joint=1, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=1, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=1 + SET_JOINT_BACKLASH joint=2, backlash=0 + SET_JOINT_POSITION_LIMITS joint=2, min=-4, max=0 +@@ -39,6 +41,7 @@ SET_JOINT_HOMING_PARAMS joint=2, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=2, vel=4 + SET_JOINT_ACC_LIMIT joint=2, acc=1000 + SET_JOINT_JERK_LIMIT joint=2, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=2, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=2 + SET_JOINT_BACKLASH joint=3, backlash=0 + SET_JOINT_POSITION_LIMITS joint=3, min=-40, max=0 +@@ -49,6 +52,7 @@ SET_JOINT_HOMING_PARAMS joint=3, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=3, vel=4 + SET_JOINT_ACC_LIMIT joint=3, acc=1000 + SET_JOINT_JERK_LIMIT joint=3, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=3, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=3 + SET_JOINT_BACKLASH joint=4, backlash=0 + SET_JOINT_POSITION_LIMITS joint=4, min=-40, max=0 +@@ -59,6 +63,7 @@ SET_JOINT_HOMING_PARAMS joint=4, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=4, vel=4 + SET_JOINT_ACC_LIMIT joint=4, acc=1000 + SET_JOINT_JERK_LIMIT joint=4, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=4, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=4 + SET_JOINT_BACKLASH joint=5, backlash=0 + SET_JOINT_POSITION_LIMITS joint=5, min=-4, max=0 +@@ -69,6 +74,7 @@ SET_JOINT_HOMING_PARAMS joint=5, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=5, vel=4 + SET_JOINT_ACC_LIMIT joint=5, acc=1000 + SET_JOINT_JERK_LIMIT joint=5, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=5, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=5 + SET_JOINT_BACKLASH joint=6, backlash=0 + SET_JOINT_POSITION_LIMITS joint=6, min=-40, max=0 +@@ -79,6 +85,7 @@ SET_JOINT_HOMING_PARAMS joint=6, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=6, vel=4 + SET_JOINT_ACC_LIMIT joint=6, acc=1000 + SET_JOINT_JERK_LIMIT joint=6, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=6, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=6 + SET_JOINT_BACKLASH joint=7, backlash=0 + SET_JOINT_POSITION_LIMITS joint=7, min=-40, max=0 +@@ -89,6 +96,7 @@ SET_JOINT_HOMING_PARAMS joint=7, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=7, vel=4 + SET_JOINT_ACC_LIMIT joint=7, acc=1000 + SET_JOINT_JERK_LIMIT joint=7, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=7, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=7 + SET_JOINT_BACKLASH joint=8, backlash=0 + SET_JOINT_POSITION_LIMITS joint=8, min=-4, max=0 +@@ -99,6 +107,7 @@ SET_JOINT_HOMING_PARAMS joint=8, offset=0 home=0, final_vel=-1, search_vel=0, la + SET_JOINT_VEL_LIMIT joint=8, vel=4 + SET_JOINT_ACC_LIMIT joint=8, acc=1000 + SET_JOINT_JERK_LIMIT joint=8, jerk=0 ++SET_JOINT_AVAILABILITY_CONFIG joint=8, controlled=0, timeout=5, volatile_home=0 + JOINT_ACTIVATE joint=8 + SET_AXIS_POSITION_LIMITS axis=0, min=-40, max=0 + SET_AXIS_POSITION_LIMITS axis=0, min=-40, max=40 +@@ -155,6 +164,8 @@ SET_AXIS_ACC_LIMIT axis=8, acc=1000 + SET_AXIS_LOCKING_JOINT axis=8, locking_joint=-1 + SET_AXIS_JERK_LIMIT axis=8, jerk=0 + SET_SPINDLE_PARAMS, 1.00e+99, 0.00e+00, -1.00e+99, 0.00e+00 ++SET_SPINDLE_AVAILABILITY_CONFIG spindle=0, controlled=0, initial_available=1, timeout=5 ++ABORT + JOG_ABORT joint=0 + JOG_ABORT joint=1 + JOG_ABORT joint=2 +@@ -171,11 +182,11 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + SPINDLE_OFF + DISABLE + JOINT_UNHOME joint=-2 + FREE ++ABORT + JOG_ABORT joint=0 + JOG_ABORT joint=1 + JOG_ABORT joint=2 +@@ -192,11 +203,11 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + SPINDLE_OFF + SS_ENABLE + ENABLE + COORD ++ABORT + JOG_ABORT joint=0 + JOG_ABORT joint=1 + JOG_ABORT joint=2 +@@ -213,7 +224,6 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + SET_LINE x=1, y=0, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=19, motion_type=2, vel=0.666667, ini_maxvel=4, acc=1000, turn=-1 + SET_LINE x=1, y=-4, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=26, motion_type=2, vel=0.666667, ini_maxvel=4, acc=1000, turn=-1 + SET_LINE x=5, y=-4, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=21, motion_type=2, vel=0.666667, ini_maxvel=4, acc=1000, turn=-1 +@@ -225,4 +235,5 @@ SET_LINE x=1, y=-4, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=26, motion_type=2, vel + SET_LINE x=5, y=-4, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=21, motion_type=2, vel=0.666667, ini_maxvel=4, acc=1000, turn=-1 + SET_SPINDLESYNC sync=0.000000, flags=0x00000000 + SPINDLE_OFF ++ABORT + DISABLE diff --git a/tests/motion-logger/basic/expected.builtin-startup.in b/tests/motion-logger/basic/expected.builtin-startup.in -index d8bd807543..8ed60094c8 100644 +index 2296018..f3e53c9 100644 --- a/tests/motion-logger/basic/expected.builtin-startup.in +++ b/tests/motion-logger/basic/expected.builtin-startup.in -@@ -18,6 +18,7 @@ SET_JOINT_HOMING_PARAMS joint=0, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -19,6 +19,7 @@ SET_JOINT_HOMING_PARAMS joint=0, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=0, vel=4 SET_JOINT_ACC_LIMIT joint=0, acc=1000 SET_JOINT_JERK_LIMIT joint=0, jerk=0 @@ -2730,7 +3166,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=0 SET_JOINT_BACKLASH joint=1, backlash=0 SET_JOINT_POSITION_LIMITS joint=1, min=-40, max=0 -@@ -28,6 +29,7 @@ SET_JOINT_HOMING_PARAMS joint=1, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -29,6 +30,7 @@ SET_JOINT_HOMING_PARAMS joint=1, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=1, vel=4 SET_JOINT_ACC_LIMIT joint=1, acc=1000 SET_JOINT_JERK_LIMIT joint=1, jerk=0 @@ -2738,7 +3174,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=1 SET_JOINT_BACKLASH joint=2, backlash=0 SET_JOINT_POSITION_LIMITS joint=2, min=-4, max=0 -@@ -38,6 +40,7 @@ SET_JOINT_HOMING_PARAMS joint=2, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -39,6 +41,7 @@ SET_JOINT_HOMING_PARAMS joint=2, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=2, vel=4 SET_JOINT_ACC_LIMIT joint=2, acc=1000 SET_JOINT_JERK_LIMIT joint=2, jerk=0 @@ -2746,7 +3182,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=2 SET_JOINT_BACKLASH joint=3, backlash=0 SET_JOINT_POSITION_LIMITS joint=3, min=-40, max=0 -@@ -48,6 +51,7 @@ SET_JOINT_HOMING_PARAMS joint=3, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -49,6 +52,7 @@ SET_JOINT_HOMING_PARAMS joint=3, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=3, vel=4 SET_JOINT_ACC_LIMIT joint=3, acc=1000 SET_JOINT_JERK_LIMIT joint=3, jerk=0 @@ -2754,7 +3190,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=3 SET_JOINT_BACKLASH joint=4, backlash=0 SET_JOINT_POSITION_LIMITS joint=4, min=-40, max=0 -@@ -58,6 +62,7 @@ SET_JOINT_HOMING_PARAMS joint=4, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -59,6 +63,7 @@ SET_JOINT_HOMING_PARAMS joint=4, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=4, vel=4 SET_JOINT_ACC_LIMIT joint=4, acc=1000 SET_JOINT_JERK_LIMIT joint=4, jerk=0 @@ -2762,7 +3198,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=4 SET_JOINT_BACKLASH joint=5, backlash=0 SET_JOINT_POSITION_LIMITS joint=5, min=-4, max=0 -@@ -68,6 +73,7 @@ SET_JOINT_HOMING_PARAMS joint=5, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -69,6 +74,7 @@ SET_JOINT_HOMING_PARAMS joint=5, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=5, vel=4 SET_JOINT_ACC_LIMIT joint=5, acc=1000 SET_JOINT_JERK_LIMIT joint=5, jerk=0 @@ -2770,7 +3206,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=5 SET_JOINT_BACKLASH joint=6, backlash=0 SET_JOINT_POSITION_LIMITS joint=6, min=-40, max=0 -@@ -78,6 +84,7 @@ SET_JOINT_HOMING_PARAMS joint=6, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -79,6 +85,7 @@ SET_JOINT_HOMING_PARAMS joint=6, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=6, vel=4 SET_JOINT_ACC_LIMIT joint=6, acc=1000 SET_JOINT_JERK_LIMIT joint=6, jerk=0 @@ -2778,7 +3214,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=6 SET_JOINT_BACKLASH joint=7, backlash=0 SET_JOINT_POSITION_LIMITS joint=7, min=-40, max=0 -@@ -88,6 +95,7 @@ SET_JOINT_HOMING_PARAMS joint=7, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -89,6 +96,7 @@ SET_JOINT_HOMING_PARAMS joint=7, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=7, vel=4 SET_JOINT_ACC_LIMIT joint=7, acc=1000 SET_JOINT_JERK_LIMIT joint=7, jerk=0 @@ -2786,7 +3222,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=7 SET_JOINT_BACKLASH joint=8, backlash=0 SET_JOINT_POSITION_LIMITS joint=8, min=-4, max=0 -@@ -98,6 +106,7 @@ SET_JOINT_HOMING_PARAMS joint=8, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -99,6 +107,7 @@ SET_JOINT_HOMING_PARAMS joint=8, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=8, vel=4 SET_JOINT_ACC_LIMIT joint=8, acc=1000 SET_JOINT_JERK_LIMIT joint=8, jerk=0 @@ -2794,7 +3230,7 @@ index d8bd807543..8ed60094c8 100644 JOINT_ACTIVATE joint=8 SET_AXIS_POSITION_LIMITS axis=0, min=-40, max=0 SET_AXIS_POSITION_LIMITS axis=0, min=-40, max=40 -@@ -154,6 +163,8 @@ SET_AXIS_ACC_LIMIT axis=8, acc=1000 +@@ -155,6 +164,8 @@ SET_AXIS_ACC_LIMIT axis=8, acc=1000 SET_AXIS_LOCKING_JOINT axis=8, locking_joint=-1 SET_AXIS_JERK_LIMIT axis=8, jerk=0 SET_SPINDLE_PARAMS, 1.00e+99, 0.00e+00, -1.00e+99, 0.00e+00 @@ -2803,7 +3239,7 @@ index d8bd807543..8ed60094c8 100644 JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -170,11 +181,11 @@ JOG_ABORT joint=12 +@@ -171,11 +182,11 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 @@ -2816,7 +3252,7 @@ index d8bd807543..8ed60094c8 100644 JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -191,7 +202,6 @@ JOG_ABORT joint=12 +@@ -192,7 +203,6 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 @@ -2824,7 +3260,7 @@ index d8bd807543..8ed60094c8 100644 SPINDLE_OFF # -@@ -207,6 +217,7 @@ ENABLE +@@ -209,6 +219,7 @@ ENABLE # COORD @@ -2832,16 +3268,16 @@ index d8bd807543..8ed60094c8 100644 JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -223,4 +234,3 @@ JOG_ABORT joint=12 +@@ -225,4 +236,3 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 -ABORT diff --git a/tests/motion-logger/mountaindew/expected.motion-logger b/tests/motion-logger/mountaindew/expected.motion-logger -index ba0b740b38..eec29d9b93 100644 +index c52ea95..f5b60ef 100644 --- a/tests/motion-logger/mountaindew/expected.motion-logger +++ b/tests/motion-logger/mountaindew/expected.motion-logger -@@ -18,6 +18,7 @@ SET_JOINT_HOMING_PARAMS joint=0, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -19,6 +19,7 @@ SET_JOINT_HOMING_PARAMS joint=0, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=0, vel=400 SET_JOINT_ACC_LIMIT joint=0, acc=1000 SET_JOINT_JERK_LIMIT joint=0, jerk=0 @@ -2849,7 +3285,7 @@ index ba0b740b38..eec29d9b93 100644 JOINT_ACTIVATE joint=0 SET_JOINT_BACKLASH joint=1, backlash=0 SET_JOINT_POSITION_LIMITS joint=1, min=-40, max=0 -@@ -28,6 +29,7 @@ SET_JOINT_HOMING_PARAMS joint=1, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -29,6 +30,7 @@ SET_JOINT_HOMING_PARAMS joint=1, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=1, vel=400 SET_JOINT_ACC_LIMIT joint=1, acc=1000 SET_JOINT_JERK_LIMIT joint=1, jerk=0 @@ -2857,7 +3293,7 @@ index ba0b740b38..eec29d9b93 100644 JOINT_ACTIVATE joint=1 SET_JOINT_BACKLASH joint=2, backlash=0 SET_JOINT_POSITION_LIMITS joint=2, min=-40, max=0 -@@ -38,6 +40,7 @@ SET_JOINT_HOMING_PARAMS joint=2, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -39,6 +41,7 @@ SET_JOINT_HOMING_PARAMS joint=2, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=2, vel=400 SET_JOINT_ACC_LIMIT joint=2, acc=1000 SET_JOINT_JERK_LIMIT joint=2, jerk=0 @@ -2865,7 +3301,7 @@ index ba0b740b38..eec29d9b93 100644 JOINT_ACTIVATE joint=2 SET_AXIS_POSITION_LIMITS axis=0, min=-40, max=0 SET_AXIS_POSITION_LIMITS axis=0, min=-40, max=40 -@@ -58,6 +61,8 @@ SET_AXIS_ACC_LIMIT axis=2, acc=1000 +@@ -59,6 +62,8 @@ SET_AXIS_ACC_LIMIT axis=2, acc=1000 SET_AXIS_LOCKING_JOINT axis=2, locking_joint=-1 SET_AXIS_JERK_LIMIT axis=2, jerk=0 SET_SPINDLE_PARAMS, 1.00e+99, 0.00e+00, -1.00e+99, 0.00e+00 @@ -2874,7 +3310,7 @@ index ba0b740b38..eec29d9b93 100644 JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -74,11 +79,11 @@ JOG_ABORT joint=12 +@@ -75,11 +80,11 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 @@ -2887,19 +3323,20 @@ index ba0b740b38..eec29d9b93 100644 JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -95,10 +100,10 @@ JOG_ABORT joint=12 +@@ -96,11 +101,11 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 -ABORT SPINDLE_OFF + SS_ENABLE ENABLE COORD +ABORT JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -115,7 +120,6 @@ JOG_ABORT joint=12 +@@ -117,7 +122,6 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 @@ -2907,17 +3344,17 @@ index ba0b740b38..eec29d9b93 100644 SET_LINE x=2, y=0, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=4, motion_type=2, vel=0.666667, ini_maxvel=400, acc=1000, turn=-1 SET_LINE x=3, y=0, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=5, motion_type=2, vel=0.666667, ini_maxvel=400, acc=1000, turn=-1 SET_LINE x=3, y=4, z=0, a=0, b=0, c=0, u=0, v=0, w=0, id=6, motion_type=2, vel=0.666667, ini_maxvel=400, acc=1000, turn=-1 -@@ -128,4 +132,5 @@ SET_LINE x=0, y=1, z=0.5, a=0, b=0, c=0, u=0, v=0, w=0, id=5, motion_type=1, vel +@@ -130,4 +134,5 @@ SET_LINE x=0, y=1, z=0.5, a=0, b=0, c=0, u=0, v=0, w=0, id=5, motion_type=1, vel SET_LINE x=0, y=0, z=0.5, a=0, b=0, c=0, u=0, v=0, w=0, id=6, motion_type=1, vel=400, ini_maxvel=400, acc=1000, turn=-1 SET_SPINDLESYNC sync=0.000000, flags=0x00000000 SPINDLE_OFF +ABORT DISABLE diff --git a/tests/motion-logger/startup-gcode-abort/expected.motion-logger.in b/tests/motion-logger/startup-gcode-abort/expected.motion-logger.in -index cc3abee97d..0a520173b9 100644 +index 8bef6b8..5741c00 100644 --- a/tests/motion-logger/startup-gcode-abort/expected.motion-logger.in +++ b/tests/motion-logger/startup-gcode-abort/expected.motion-logger.in -@@ -23,6 +23,7 @@ SET_JOINT_HOMING_PARAMS joint=0, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -24,6 +24,7 @@ SET_JOINT_HOMING_PARAMS joint=0, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=0, vel=4 SET_JOINT_ACC_LIMIT joint=0, acc=1000 SET_JOINT_JERK_LIMIT joint=0, jerk=0 @@ -2925,7 +3362,7 @@ index cc3abee97d..0a520173b9 100644 JOINT_ACTIVATE joint=0 SET_JOINT_BACKLASH joint=1, backlash=0 SET_JOINT_POSITION_LIMITS joint=1, min=-40, max=0 -@@ -33,6 +34,7 @@ SET_JOINT_HOMING_PARAMS joint=1, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -34,6 +35,7 @@ SET_JOINT_HOMING_PARAMS joint=1, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=1, vel=4 SET_JOINT_ACC_LIMIT joint=1, acc=1000 SET_JOINT_JERK_LIMIT joint=1, jerk=0 @@ -2933,7 +3370,7 @@ index cc3abee97d..0a520173b9 100644 JOINT_ACTIVATE joint=1 SET_JOINT_BACKLASH joint=2, backlash=0 SET_JOINT_POSITION_LIMITS joint=2, min=-4, max=0 -@@ -43,6 +45,7 @@ SET_JOINT_HOMING_PARAMS joint=2, offset=0 home=0, final_vel=-1, search_vel=0, la +@@ -44,6 +46,7 @@ SET_JOINT_HOMING_PARAMS joint=2, offset=0 home=0, final_vel=-1, search_vel=0, la SET_JOINT_VEL_LIMIT joint=2, vel=4 SET_JOINT_ACC_LIMIT joint=2, acc=1000 SET_JOINT_JERK_LIMIT joint=2, jerk=0 @@ -2941,7 +3378,7 @@ index cc3abee97d..0a520173b9 100644 JOINT_ACTIVATE joint=2 SET_AXIS_POSITION_LIMITS axis=0, min=-40, max=0 -@@ -84,6 +87,8 @@ SET_AXIS_LOCKING_JOINT axis=2, locking_joint=-1 +@@ -85,6 +88,8 @@ SET_AXIS_LOCKING_JOINT axis=2, locking_joint=-1 SET_AXIS_JERK_LIMIT axis=2, jerk=0 SET_SPINDLE_PARAMS, 1.00e+99, 0.00e+00, -1.00e+99, 0.00e+00 @@ -2950,7 +3387,7 @@ index cc3abee97d..0a520173b9 100644 JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -100,7 +105,6 @@ JOG_ABORT joint=12 +@@ -101,7 +106,6 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 @@ -2958,7 +3395,7 @@ index cc3abee97d..0a520173b9 100644 SPINDLE_OFF DISABLE JOINT_UNHOME joint=-2 -@@ -121,6 +125,7 @@ FREE +@@ -122,6 +126,7 @@ FREE # The test UI immediately sent an Abort. # @@ -2966,1442 +3403,12 @@ index cc3abee97d..0a520173b9 100644 JOG_ABORT joint=0 JOG_ABORT joint=1 JOG_ABORT joint=2 -@@ -154,6 +159,6 @@ JOG_ABORT joint=12 +@@ -155,7 +160,7 @@ JOG_ABORT joint=12 JOG_ABORT joint=13 JOG_ABORT joint=14 JOG_ABORT joint=15 -ABORT SPINDLE_OFF + SS_ENABLE +ABORT DISABLE -diff --git a/tests/motion-target-preparation/README b/tests/motion-target-preparation/README -index 99955caa22..7958c18d67 100644 ---- a/tests/motion-target-preparation/README -+++ b/tests/motion-target-preparation/README -@@ -1 +1,5 @@ --Compiles production target preparation with deterministic inverse-kinematics doubles and the real cubic implementation. Checks that inverse-kinematics and interpolation failures cannot partially update the joint command vector. No runtime or realtime privileges are required. -+Compiles production target preparation with deterministic inverse-kinematics -+doubles and the real cubic implementation. Checks that inverse-kinematics, -+interpolation, and unavailable-joint target failures cannot partially update -+the joint command vector. Also checks the isolated legacy activation guard. -+No runtime or realtime privileges are required. -diff --git a/tests/motion-target-preparation/availability-cases.h b/tests/motion-target-preparation/availability-cases.h -new file mode 100644 -index 0000000000..00099d2dfa ---- /dev/null -+++ b/tests/motion-target-preparation/availability-cases.h -@@ -0,0 +1,21 @@ -+static void test_availability(EmcPose *pose, double *positions, CUBIC_STRUCT *staged) { -+ availability_status_t *a = &status.joint_status[2].availability; -+ a->controlled = 1; a->held_position = 2; -+ unsigned char before[sizeof(joints)]; memcpy(before, joints, sizeof(joints)); -+ int saved_fflags = fflags; -+ solution[0] = 10; solution[2] = 3; -+ assert(prepare_joint_targets(pose, positions, staged) != 0); -+ assert(memcmp(before, joints, sizeof(joints)) == 0); -+ assert(fflags == saved_fflags); -+ solution[2] = 2; -+ assert(prepare_joint_targets(pose, positions, staged) == 0); -+ assert(fflags == saved_fflags + 1); -+ assert(positions[0] == 10 && positions[2] == 2); -+ for (int n=1; n<100; n++) { -+ solution[2] = 2 + n*1e-10; -+ int result = prepare_joint_targets(pose, positions, staged); -+ if (n <= 9) { assert(result == 0); assert(positions[2] == 2); } -+ if (n >= 11) assert(result != 0); -+ assert(a->held_position == 2); -+ } -+} -diff --git a/tests/motion-target-preparation/availability-fixture.h b/tests/motion-target-preparation/availability-fixture.h -new file mode 100644 -index 0000000000..dd4b2be8dd ---- /dev/null -+++ b/tests/motion-target-preparation/availability-fixture.h -@@ -0,0 +1,5 @@ -+#define TEST_AVAILABILITY 1 -+#define EMCMOT_AVAILABILITY_AVAILABLE 3 -+typedef struct { int controlled, state; double held_position; } availability_status_t; -+static struct { EmcPose carte_pos_cmd; int overrideLimitMask; struct { availability_status_t availability; } joint_status[3]; } status; -+#define emcmotStatus (&status) -diff --git a/tests/motion-target-preparation/test.py b/tests/motion-target-preparation/test.py -index 1fa2553aa3..8ac9a8043d 100644 ---- a/tests/motion-target-preparation/test.py -+++ b/tests/motion-target-preparation/test.py -@@ -88,3 +88,60 @@ with tempfile.TemporaryDirectory() as tmp: - '-I'+str(root/'src/emc/kinematics'), '-I'+str(root/'src/emc/motion'), str(tmp/'test.c'), - str(root/'src/emc/kinematics/cubic.c'), '-lm', '-o', str(tmp/'test')], check=True) - subprocess.run([str(tmp/'test')], check=True) -+ -+# Exercise the production legacy activation command handlers in every lifecycle -+# state: controlled joints must retain ACTIVE and all lifecycle fields on error. -+command_source = (root / 'src/emc/motion/command.c').read_text() -+start = command_source.index('\tcase EMCMOT_JOINT_ACTIVATE:') -+end = command_source.index('\tcase EMCMOT_JOINT_HOME:', start) -+activation_cases = command_source[start:end] -+activation_test = r""" -+#include -+#include -+#define _(s) s -+#define reportError(...) ((void)0) -+#define rtapi_print_msg(...) ((void)0) -+#define SET_JOINT_ACTIVE_FLAG(j, v) ((j)->active = (v)) -+enum { EMCMOT_JOINT_ACTIVATE, EMCMOT_JOINT_DEACTIVATE, -+ EMCMOT_COMMAND_INVALID_COMMAND }; -+typedef struct { int active; } joint_t; -+static struct { -+ int commandStatus; -+ struct { struct { int controlled, state, phase; } availability; } joint_status[1]; -+} status, *emcmotStatus = &status; -+static void command(int cmd, joint_t *joint) { -+ int joint_num = 0; -+ switch (cmd) { -+""" + activation_cases + r""" -+ } -+} -+int main(void) { -+ for (int state = 0; state <= 5; ++state) -+ for (int active = 0; active <= 1; ++active) -+ for (int cmd = 0; cmd <= 1; ++cmd) { -+ joint_t joint = {active}; -+ status.joint_status[0].availability.controlled = 1; -+ status.joint_status[0].availability.state = state; -+ status.joint_status[0].availability.phase = 42; -+ status.commandStatus = 0; -+ command(cmd, &joint); -+ assert(joint.active == active); -+ assert(status.commandStatus == EMCMOT_COMMAND_INVALID_COMMAND); -+ assert(status.joint_status[0].availability.state == state); -+ assert(status.joint_status[0].availability.phase == 42); -+ } -+ joint_t joint = {0}; -+ status.joint_status[0].availability.controlled = 0; -+ status.commandStatus = 0; -+ command(EMCMOT_JOINT_ACTIVATE, &joint); -+ assert(joint.active == 1 && status.commandStatus == 0); -+ command(EMCMOT_JOINT_DEACTIVATE, &joint); -+ assert(joint.active == 0 && status.commandStatus == 0); -+} -+""" -+with tempfile.TemporaryDirectory() as directory: -+ source_file = Path(directory) / 'activation.c' -+ binary = Path(directory) / 'activation' -+ source_file.write_text(activation_test) -+ subprocess.run(['cc', '-Wall', '-Werror', str(source_file), '-o', str(binary)], check=True) -+ subprocess.run([str(binary)], check=True) -diff --git a/tests/runtime-availability-regressions/.gitignore b/tests/runtime-availability-regressions/.gitignore -new file mode 100644 -index 0000000000..425d52b6e7 ---- /dev/null -+++ b/tests/runtime-availability-regressions/.gitignore -@@ -0,0 +1,2 @@ -+/*.ini -+!/base.ini -diff --git a/tests/runtime-availability-regressions/README b/tests/runtime-availability-regressions/README -new file mode 100644 -index 0000000000..e1bde102e6 ---- /dev/null -+++ b/tests/runtime-availability-regressions/README -@@ -0,0 +1,20 @@ -+Production-path availability regressions. Each case starts LinuxCNC with POSIX -+simulation and uses its NML command/status channels and real HAL servo thread. -+The amplifier and homing latches run after motion-controller every servo cycle. -+Select individual cases with AVAILABILITY_REGRESSION_CASES for mutation checks. -+The extra-joint case verifies configuration rejection before Machine On because -+no external posthome command ownership/completion contract is supported. -+The fault case records EMC_ABORT_MOTION_OR_IO_RCS_ERROR through the standard -+ON_ABORT_COMMAND hook, distinguishing error handling from a machine-off abort -+without polling transient status. The sequence case verifies that an -+availability-controlled joint cannot define a Home All sequence. -+ -+INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local -+*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before -+launching an individual case directly. @unset explicitly removes an inherited -+key. Generated INIs are ignored; edit the base or the case override instead. -+Handoff regressions cover abort during a spindle index wait followed by release -+and reacquisition (including a fresh encoder handshake), X/Z/C Machine Off/On -+while released C feedback moves externally, and JOG_STOP during acknowledgment -+and volatile acquisition homing waits. Released motion state remains frozen -+while the raw HAL feedback pin stays live. -diff --git a/tests/runtime-availability-regressions/base.ini b/tests/runtime-availability-regressions/base.ini -new file mode 100644 -index 0000000000..71f455ae57 ---- /dev/null -+++ b/tests/runtime-availability-regressions/base.ini -@@ -0,0 +1,94 @@ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0 -+[DISPLAY] -+DISPLAY = ./test-ui.py -+[RS274NGC] -+PARAMETER_FILE = sim.var -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4 -+SERVO_PERIOD = 1000000 -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 -+[HAL] -+HALFILE = core.hal -+[TRAJ] -+NO_FORCE_HOMING = 1 -+COORDINATES = XYZ -+SPINDLES = 1 -+LINEAR_UNITS = mm -+ANGULAR_UNITS = degree -+DEFAULT_LINEAR_VELOCITY = 10 -+MAX_LINEAR_VELOCITY = 50 -+[EMCIO] -+TOOL_TABLE = tool.tbl -+[KINS] -+KINEMATICS = trivkins coordinates=XYZ -+JOINTS = 3 -+[AXIS_X] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+[AXIS_Y] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+[AXIS_Z] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+[JOINT_0] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+HOME_SEARCH_VEL = 0 -+HOME_LATCH_VEL = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+AVAILABILITY_CONTROL = 1 -+AVAILABILITY_TIMEOUT = 5 -+VOLATILE_HOME = 0 -+[JOINT_1] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+HOME_SEARCH_VEL = 0 -+HOME_LATCH_VEL = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+AVAILABILITY_CONTROL = 1 -+AVAILABILITY_TIMEOUT = 5 -+VOLATILE_HOME = 0 -+[JOINT_2] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+HOME_SEQUENCE = 0 -+HOME_SEARCH_VEL = 0 -+HOME_LATCH_VEL = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+AVAILABILITY_CONTROL = 0 -+AVAILABILITY_TIMEOUT = 5 -+VOLATILE_HOME = 0 -+[SPINDLE_0] -+AVAILABILITY_CONTROL = 1 -+INITIAL_AVAILABILITY = 0 -+AVAILABILITY_TIMEOUT = 5 -diff --git a/tests/runtime-availability-regressions/checkresult b/tests/runtime-availability-regressions/checkresult -new file mode 100755 -index 0000000000..153f94a5fc ---- /dev/null -+++ b/tests/runtime-availability-regressions/checkresult -@@ -0,0 +1,5 @@ -+#!/bin/sh -+set -eu -+for scenario in ${AVAILABILITY_REGRESSION_CASES:-fault wheel tail amp power index jogstop joghome extra sequence}; do -+ grep -q "^availability regression $scenario ok$" "$1" -+done -diff --git a/tests/runtime-availability-regressions/core.hal b/tests/runtime-availability-regressions/core.hal -new file mode 100644 -index 0000000000..7e0cffcfb7 ---- /dev/null -+++ b/tests/runtime-availability-regressions/core.hal -@@ -0,0 +1,17 @@ -+loadrt trivkins coordinates=XYZ -+loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_spindles=1 -+loadrt mux2 count=1 -+addf mux2.0 servo-thread -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net Ycmd joint.1.motor-pos-cmd => mux2.0.in0 -+net Yfb mux2.0.out => joint.1.motor-pos-fb -+net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb -+net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in -+setp spindle.0.at-speed true -+loadrt flipflop count=5 -+addf flipflop.0 servo-thread -+addf flipflop.1 servo-thread -+net amp-seen joint.1.amp-enable-out => flipflop.0.set -+net other-home-seen joint.2.homing => flipflop.1.set -diff --git a/tests/runtime-availability-regressions/dwell.ngc b/tests/runtime-availability-regressions/dwell.ngc -new file mode 100644 -index 0000000000..b69d67a192 ---- /dev/null -+++ b/tests/runtime-availability-regressions/dwell.ngc -@@ -0,0 +1,4 @@ -+G90 G94 -+G4 P1 -+M64 P0 -+M2 -diff --git a/tests/runtime-availability-regressions/extra.hal b/tests/runtime-availability-regressions/extra.hal -new file mode 100644 -index 0000000000..36c2c7ee86 ---- /dev/null -+++ b/tests/runtime-availability-regressions/extra.hal -@@ -0,0 +1,17 @@ -+loadrt trivkins coordinates=XY kinstype=B -+loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_extrajoints=1 num_spindles=1 -+loadrt mux2 count=1 -+addf mux2.0 servo-thread -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net Ycmd joint.1.motor-pos-cmd => mux2.0.in0 -+net Yfb mux2.0.out => joint.1.motor-pos-fb -+net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb -+net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in -+setp spindle.0.at-speed true -+loadrt flipflop count=2 -+addf flipflop.0 servo-thread -+addf flipflop.1 servo-thread -+net amp-seen joint.1.amp-enable-out => flipflop.0.set -+net other-home-seen joint.2.homing => flipflop.1.set -diff --git a/tests/runtime-availability-regressions/extra.ini.in b/tests/runtime-availability-regressions/extra.ini.in -new file mode 100644 -index 0000000000..5048be901a ---- /dev/null -+++ b/tests/runtime-availability-regressions/extra.ini.in -@@ -0,0 +1,16 @@ -+# Case-specific overrides; unspecified values come from FIXTURE.BASE. -+[FIXTURE] -+BASE = base.ini -+ -+[HAL] -+HALFILE = extra.hal -+ -+[TRAJ] -+COORDINATES = XY -+ -+[KINS] -+KINEMATICS = trivkins coordinates=XY kinstype=B -+ -+[JOINT_2] -+HOME_SEQUENCE = @unset -+AVAILABILITY_CONTROL = 1 -diff --git a/tests/runtime-availability-regressions/fault.ini.in b/tests/runtime-availability-regressions/fault.ini.in -new file mode 100644 -index 0000000000..b39d68b962 ---- /dev/null -+++ b/tests/runtime-availability-regressions/fault.ini.in -@@ -0,0 +1,13 @@ -+# Case-specific overrides; unspecified values come from FIXTURE.BASE. -+[FIXTURE] -+BASE = base.ini -+ -+[RS274NGC] -+SUBROUTINE_PATH = . -+ON_ABORT_COMMAND = O call -+ -+[JOINT_0] -+AVAILABILITY_CONTROL = 0 -+ -+[JOINT_1] -+AVAILABILITY_CONTROL = 0 -diff --git a/tests/runtime-availability-regressions/fixture.py b/tests/runtime-availability-regressions/fixture.py -new file mode 100644 -index 0000000000..ef0f630d93 ---- /dev/null -+++ b/tests/runtime-availability-regressions/fixture.py -@@ -0,0 +1,75 @@ -+#!/usr/bin/env python3 -+import os -+import time -+import hal -+import linuxcnc -+ -+h = hal.component('availability-regression') -+h.ready() -+c = linuxcnc.command() -+s = linuxcnc.stat() -+e = linuxcnc.error_channel() -+errors = [] -+case = os.environ.get('AVAILABILITY_REGRESSION_CASE', 'extra') -+ -+def pin(name, value): -+ hal.set_p(name, str(value)) -+ -+def wait(predicate, message, timeout=8): -+ until = time.monotonic() + timeout -+ while time.monotonic() < until: -+ s.poll() -+ while (error := e.poll()) is not None: -+ errors.append(error) -+ if predicate(): -+ return -+ time.sleep(.005) -+ raise AssertionError(f'{case}: {message}: task={s.task_state} ' -+ f'interp={s.interp_state} exec={s.exec_state} errors={errors}') -+ -+def settle(seconds=.1): -+ until = time.monotonic() + seconds -+ wait(lambda: time.monotonic() >= until, 'settle') -+ -+def done(): -+ assert c.wait_complete(8) == linuxcnc.RCS_DONE, (case, errors) -+ s.poll() -+ -+def acquire(resource): -+ kind, number = resource.split('.') -+ getattr(c, f'set_{kind}_availability')(int(number), True) -+ wait(lambda: hal.get_value(resource + '.availability-request'), 'acquire ' + resource) -+ pin(resource + '.availability-ack', 1) -+ done() -+ -+def release(resource): -+ kind, number = resource.split('.') -+ getattr(c, f'set_{kind}_availability')(int(number), False) -+ wait(lambda: not hal.get_value(resource + '.availability-request'), 'release ' + resource) -+ pin(resource + '.availability-ack', 0) -+ done() -+ -+def run(name): -+ c.mode(linuxcnc.MODE_AUTO); done() -+ c.program_open(os.path.abspath(name)); done() -+ c.auto(linuxcnc.AUTO_RUN, 0) -+ -+wait(lambda: s.task_state == linuxcnc.STATE_ESTOP, 'startup') -+if case == 'extra': -+ raise AssertionError('unsupported extra-joint configuration reached UI') -+c.state(linuxcnc.STATE_ESTOP_RESET); done() -+c.state(linuxcnc.STATE_ON); done() -+c.teleop_enable(0); done() -+if case != 'fault': -+ acquire('joint.0') -+if case not in ('fault', 'joghome'): -+ acquire('joint.1') -+if case == 'joghome': -+ c.set_joint_availability(1, True) -+ wait(lambda: hal.get_value('joint.1.availability-request'), 'runtime acquisition') -+ pin('joint.1.availability-ack', 1) -+ wait(lambda: hal.get_value('joint.1.index-enable'), 'runtime homing index') -+ pin('joint.1.index-enable', 0) -+ done() -+c.home(2); done() -+wait(lambda: s.homed[2], 'home ordinary joint') -diff --git a/tests/runtime-availability-regressions/joghome.ini.in b/tests/runtime-availability-regressions/joghome.ini.in -new file mode 100644 -index 0000000000..949adc122d ---- /dev/null -+++ b/tests/runtime-availability-regressions/joghome.ini.in -@@ -0,0 +1,6 @@ -+[FIXTURE] -+BASE = base.ini -+[JOINT_1] -+VOLATILE_HOME = 1 -+HOME_USE_INDEX = YES -+HOME_LATCH_VEL = 1 -diff --git a/tests/runtime-availability-regressions/record_abort.ngc b/tests/runtime-availability-regressions/record_abort.ngc -new file mode 100644 -index 0000000000..5ca302ff7f ---- /dev/null -+++ b/tests/runtime-availability-regressions/record_abort.ngc -@@ -0,0 +1,6 @@ -+o sub -+(LOGAPPEND,abort-reasons.log) -+(LOG,#1) -+(LOGCLOSE) -+o endsub -+M2 -diff --git a/tests/runtime-availability-regressions/sequence.ini.in b/tests/runtime-availability-regressions/sequence.ini.in -new file mode 100644 -index 0000000000..3786b1533f ---- /dev/null -+++ b/tests/runtime-availability-regressions/sequence.ini.in -@@ -0,0 +1,6 @@ -+# Availability-controlled joints are referenced only by individual acquisition. -+[FIXTURE] -+BASE = base.ini -+ -+[JOINT_1] -+HOME_SEQUENCE = 1 -diff --git a/tests/runtime-availability-regressions/tail.hal b/tests/runtime-availability-regressions/tail.hal -new file mode 100644 -index 0000000000..c9eea9dd0c ---- /dev/null -+++ b/tests/runtime-availability-regressions/tail.hal -@@ -0,0 +1,30 @@ -+source core.hal -+# Observe the interpolation tail every servo cycle, after motion-controller. -+# Tail: the axis planner stopped but the joint interpolator still has velocity. -+loadrt near count=2 -+loadrt not count=2 -+loadrt and2 count=3 -+addf near.0 servo-thread -+addf near.1 servo-thread -+addf not.0 servo-thread -+addf and2.0 servo-thread -+addf and2.1 servo-thread -+addf not.1 servo-thread -+addf and2.2 servo-thread -+addf flipflop.2 servo-thread -+addf flipflop.3 servo-thread -+addf flipflop.4 servo-thread -+setp near.0.difference 1e-12 -+setp near.1.difference 1e-12 -+net axis-velocity axis.y.teleop-vel-cmd => near.0.in1 -+net joint-velocity joint.1.vel-cmd => near.1.in1 -+net axis-stopped near.0.out => and2.0.in0 -+net joint-stopped near.1.out => not.0.in -+net joint-moving not.0.out => and2.0.in1 -+net interpolation-tail and2.0.out => flipflop.2.set and2.1.in0 -+net motion-inpos motion.in-position => and2.1.in1 -+net premature-inpos and2.1.out => flipflop.3.set -+net amp-seen => not.1.in -+net amplifier-off not.1.out => and2.2.in0 -+net joint-owned joint.1.availability-request => and2.2.in1 -+net premature-amplifier-off and2.2.out => flipflop.4.set -diff --git a/tests/runtime-availability-regressions/tail.ini.in b/tests/runtime-availability-regressions/tail.ini.in -new file mode 100644 -index 0000000000..cdf6f940c4 ---- /dev/null -+++ b/tests/runtime-availability-regressions/tail.ini.in -@@ -0,0 +1,7 @@ -+# TELEOP release: latch the real servo-cycle tail and upstream INPOS during it. -+[FIXTURE] -+BASE = base.ini -+[HAL] -+HALFILE = tail.hal -+[JOINT_1] -+BACKLASH = 0.4 -diff --git a/tests/runtime-availability-regressions/test-ui.py b/tests/runtime-availability-regressions/test-ui.py -new file mode 100755 -index 0000000000..468b03b6f2 ---- /dev/null -+++ b/tests/runtime-availability-regressions/test-ui.py -@@ -0,0 +1,192 @@ -+#!/usr/bin/env python3 -+from fixture import * -+from pathlib import Path -+ -+if case == 'power': -+ release('joint.1') -+ pin('mux2.0.in1', 180); pin('mux2.0.sel', 1) -+ wait(lambda: abs(hal.get_value('joint.1.motor-pos-fb') - 180) < 1e-6, -+ 'live released C HAL feedback') -+ settle() -+ assert abs(s.actual_position[5]) < 1e-9 -+ assert abs(s.joint_position[1]) < 1e-9 -+ c.state(linuxcnc.STATE_OFF) -+ wait(lambda: not hal.get_value('joint.0.availability-request'), 'Machine Off release') -+ pin('joint.0.availability-ack', 0) -+ done(); settle() -+ assert abs(s.position[5]) < 1e-9, s.position -+ assert abs(hal.get_value('joint.1.pos-cmd')) < 1e-9 -+ c.state(linuxcnc.STATE_ON); done() -+ acquire('joint.0') -+ c.mode(linuxcnc.MODE_MDI); done() -+ c.mdi('G0 X2 Z3'); done() -+ assert abs(s.position[0] - 2) < 1e-6 and abs(s.position[2] - 3) < 1e-6 -+ assert abs(s.position[5]) < 1e-9 -+ assert abs(s.actual_position[5]) < 1e-9 -+ -+elif case == 'index': -+ acquire('spindle.0') -+ c.mode(linuxcnc.MODE_MDI); done() -+ c.mdi('M3 S60'); done() -+ c.mdi('G33 Z1 K1') -+ wait(lambda: hal.get_value('spindle.0.index-enable'), 'first index wait') -+ c.abort(); done(); settle() -+ c.mode(linuxcnc.MODE_MANUAL); done() -+ release('spindle.0') -+ assert not hal.get_value('spindle.0.index-enable'), 'index latch survived release' -+ assert not hal.get_value('spindle.0.on') -+ assert hal.get_value('spindle.0.speed-out') == 0 -+ pin('spindle.0.index-enable', 1) -+ settle() -+ assert not hal.get_value('spindle.0.index-enable'), 'index latch reasserted while released' -+ acquire('spindle.0') -+ assert not hal.get_value('spindle.0.index-enable') -+ c.mode(linuxcnc.MODE_MDI); done() -+ c.mdi('M3 S60'); done() -+ c.mdi('G33 Z1 K1') -+ wait(lambda: hal.get_value('spindle.0.index-enable'), 'fresh index edge after reacquire') -+ pin('spindle.0.index-enable', 0) -+ settle() -+ assert not hal.get_value('spindle.0.index-enable'), 'encoder index handshake failed' -+ c.abort(); done() -+ -+elif case in ('jogstop', 'joghome'): -+ release('joint.1') -+ c.teleop_enable(0); done() -+ c.set_joint_availability(1, True) -+ wait(lambda: hal.get_value('joint.1.availability-request'), 'acquisition waiting for ACK') -+ c.jog(linuxcnc.JOG_STOP, 1, 1) -+ settle() -+ assert hal.get_value('joint.1.availability-request'), 'jog stop canceled acquisition' -+ pin('joint.1.availability-ack', 1) -+ if case == 'joghome': -+ wait(lambda: hal.get_value('joint.1.index-enable'), 'acquisition homing index') -+ c.jog(linuxcnc.JOG_STOP, 1, 1) -+ settle() -+ assert hal.get_value('joint.1.index-enable'), 'jog stop canceled acquisition homing' -+ assert hal.get_value('joint.1.availability-request') -+ pin('joint.1.index-enable', 0) -+ done() -+ wait(lambda: s.joint[1]['available'], 'acquisition completed after jog stop') -+ -+elif case == 'fault': -+ acquire('spindle.0') -+ run('dwell.ngc') -+ wait(lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY and -+ s.motion_mode == linuxcnc.TRAJ_MODE_COORD, 'coordinated dwell') -+ assert s.spindle[0]['availability_state'] == 3 -+ Path('abort-reasons.log').unlink(missing_ok=True) -+ pin('spindle.0.availability-ack', 0) -+ wait(lambda: s.interp_state == linuxcnc.INTERP_IDLE, 'task abort') -+ settle(1.3) -+ assert not hal.get_value('motion.digital-out-00'), 'program continued after ACK loss' -+ assert not s.enabled -+ reasons = [float(line) for line in Path('abort-reasons.log').read_text().splitlines()] -+ assert 3 in reasons, f'task did not handle motion RCS_ERROR: {reasons}' -+ # The resource fault stays visible, but acknowledged motion errors must -+ # not prevent a deliberate release, re-enable and new program. -+ c.abort(); done() -+ for resource in ('spindle.0',): -+ pin(resource + '.availability-ack', 0) -+ settle() -+ c.mode(linuxcnc.MODE_MANUAL); done() -+ for resource in ('spindle.0',): -+ release(resource) -+ c.state(linuxcnc.STATE_ON); done() -+ acquire('spindle.0') -+ run('dwell.ngc'); done() -+ wait(lambda: bool(hal.get_value('motion.digital-out-00')), 'deliberate recovery') -+ -+elif case == 'wheel': -+ c.teleop_enable(1); done() -+ pin('axis.x.jog-enable', 1) -+ pin('axis.x.jog-scale', .1) -+ for cancel in (False, True): -+ before = hal.get_value('joint.0.pos-cmd') -+ c.set_spindle_availability(0, True) -+ wait(lambda: hal.get_value('spindle.0.availability-request'), 'wheel ACK wait') -+ counts = hal.get_value('axis.x.jog-counts') -+ pin('axis.x.jog-counts', counts + 10) -+ settle() -+ assert hal.get_value('joint.0.pos-cmd') == before -+ if cancel: -+ c.abort(); done() -+ else: -+ pin('spindle.0.availability-ack', 1); done() -+ settle(.3) -+ assert abs(hal.get_value('joint.0.pos-cmd') - before) < 1e-9, 'delayed inhibited wheel jog' -+ pin('axis.x.jog-counts', counts + 11) -+ wait(lambda: abs(hal.get_value('joint.0.pos-cmd') - before - .1) < 1e-6, -+ 'fresh wheel count') -+ if not cancel: -+ release('spindle.0') -+ -+elif case == 'jointwheel': -+ c.teleop_enable(0); done() -+ release('joint.1') -+ pin('joint.1.jog-enable', 1) -+ pin('joint.1.jog-scale', .1) -+ before = hal.get_value('joint.1.pos-cmd') -+ counts = hal.get_value('joint.1.jog-counts') -+ pin('joint.1.jog-counts', counts + 10) -+ settle() -+ acquire('joint.1') -+ settle(.3) -+ assert abs(hal.get_value('joint.1.pos-cmd') - before) < 1e-9, \ -+ 'unavailable joint replayed stale wheel counts' -+ pin('joint.1.jog-counts', counts + 11) -+ wait(lambda: abs(hal.get_value('joint.1.pos-cmd') - before - .1) < 1e-6, -+ 'fresh joint wheel count') -+ wait(lambda: s.inpos, 'FREE jog completion') -+ release('joint.1') -+ assert not s.joint[1]['availability_fault'], 'FREE-mode release faulted' -+ -+elif case == 'tail': -+ c.teleop_enable(1); done() -+ # Release may begin after logical motion finishes, but it must keep the -+ # hardware request asserted until interpolation and compensation settle. -+ for increment in (.01, .019): -+ before = hal.get_value('joint.1.pos-cmd') -+ for latch in (2, 3, 4): pin(f'flipflop.{latch}.reset', 1) -+ settle() -+ for latch in (2, 3, 4): pin(f'flipflop.{latch}.reset', 0) -+ c.jog(linuxcnc.JOG_INCREMENT, 0, 1, 1, increment) -+ wait(lambda: abs(s.joint_position[1] - before - increment) < 1e-6 -+ and hal.get_value('motion.in-position'), 'TELEOP endpoint') -+ # Task admission observes NML completion after the servo endpoint. -+ done() -+ assert hal.get_value('flipflop.2.out'), 'TELEOP interpolation tail not exercised' -+ assert hal.get_value('flipflop.3.out'), 'upstream INPOS did not precede interpolation completion' -+ c.set_joint_availability(1, False) -+ wait(lambda: not hal.get_value('joint.1.availability-request'), 'settled release') -+ assert not hal.get_value('flipflop.4.out'), \ -+ 'amplifier disabled before release tail settled' -+ held = hal.get_value('joint.1.pos-cmd') -+ settle(.02) -+ assert abs(hal.get_value('joint.1.backlash-vel')) < 1e-12 -+ assert abs(hal.get_value('joint.1.backlash-corr') - -+ hal.get_value('joint.1.backlash-filt')) < 1e-12 -+ pin('joint.1.availability-ack', 0); done() -+ x = s.joint_position[0] -+ c.jog(linuxcnc.JOG_INCREMENT, 0, 0, 1, .01) -+ wait(lambda: abs(s.joint_position[0] - x - .01) < 1e-6 -+ and hal.get_value('motion.in-position'), 'unrelated TELEOP move') -+ settle() -+ assert abs(hal.get_value('joint.1.pos-cmd') - held) < 1e-12, 'released TELEOP joint moved' -+ acquire('joint.1') -+ -+elif case == 'amp': -+ release('joint.1') -+ pin('joint.1.amp-fault-in', 1) -+ pin('flipflop.0.reset', 1); settle() -+ pin('flipflop.0.reset', 0) -+ c.set_joint_availability(1, True) -+ wait(lambda: hal.get_value('joint.1.availability-request'), 'faulted acquisition') -+ pin('joint.1.availability-ack', 1) -+ wait(lambda: not s.enabled, 'fault inhibit') -+ settle() -+ assert not hal.get_value('flipflop.0.out'), 'amp-enable pulsed with amp-fault asserted' -+ -+else: -+ raise AssertionError('unknown scenario ' + case) -+print(f'availability regression {case} ok') -diff --git a/tests/runtime-availability-regressions/test.ini.in b/tests/runtime-availability-regressions/test.ini.in -new file mode 100644 -index 0000000000..67dab70a3d ---- /dev/null -+++ b/tests/runtime-availability-regressions/test.ini.in -@@ -0,0 +1,3 @@ -+# Case-specific overrides; unspecified values come from FIXTURE.BASE. -+[FIXTURE] -+BASE = base.ini -diff --git a/tests/runtime-availability-regressions/test.sh b/tests/runtime-availability-regressions/test.sh -new file mode 100755 -index 0000000000..e2dc178445 ---- /dev/null -+++ b/tests/runtime-availability-regressions/test.sh -@@ -0,0 +1,34 @@ -+#!/bin/sh -+set -eu -+python3 ../runtime-availability/make-fixtures.py -+for scenario in ${AVAILABILITY_REGRESSION_CASES:-fault wheel jointwheel tail amp power index jogstop joghome extra sequence}; do -+ ini=test.ini -+ case "$scenario" in -+ fault) ini=fault.ini ;; -+ tail) ini=tail.ini ;; -+ power) ini=xzc.ini ;; -+ joghome) ini=joghome.ini ;; -+ extra) -+ # Unsupported ownership must fail configuration, before Machine On. -+ if linuxcnc -r extra.ini >extra.log 2>&1; then -+ cat extra.log -+ echo 'extra-joint configuration unexpectedly accepted' >&2 -+ exit 1 -+ fi -+ cat extra.log -+ grep -q 'JOINT_2: availability configuration rejected' extra.log -+ echo 'availability regression extra ok' -+ continue ;; -+ sequence) -+ if linuxcnc -r sequence.ini >sequence.log 2>&1; then -+ cat sequence.log -+ echo 'availability HOME_SEQUENCE configuration unexpectedly accepted' >&2 -+ exit 1 -+ fi -+ cat sequence.log -+ grep -q 'JOINT_1: HOME_SEQUENCE cannot be used with AVAILABILITY_CONTROL' sequence.log -+ echo 'availability regression sequence ok' -+ continue ;; -+ esac -+ AVAILABILITY_REGRESSION_CASE=$scenario linuxcnc -r "$ini" -+done -diff --git a/tests/runtime-availability-regressions/tool.tbl b/tests/runtime-availability-regressions/tool.tbl -new file mode 100644 -index 0000000000..a5800196af ---- /dev/null -+++ b/tests/runtime-availability-regressions/tool.tbl -@@ -0,0 +1 @@ -+T1 P1 Z0 ; test -diff --git a/tests/runtime-availability-regressions/xzc.hal b/tests/runtime-availability-regressions/xzc.hal -new file mode 100644 -index 0000000000..5c7ef3f3f2 ---- /dev/null -+++ b/tests/runtime-availability-regressions/xzc.hal -@@ -0,0 +1,12 @@ -+loadrt trivkins coordinates=XCZ -+loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_spindles=1 -+loadrt mux2 count=1 -+addf mux2.0 servo-thread -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net Ccmd joint.1.motor-pos-cmd => mux2.0.in0 -+net Cfb mux2.0.out => joint.1.motor-pos-fb -+net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb -+net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in -+setp spindle.0.at-speed true -diff --git a/tests/runtime-availability-regressions/xzc.ini.in b/tests/runtime-availability-regressions/xzc.ini.in -new file mode 100644 -index 0000000000..ada9398601 ---- /dev/null -+++ b/tests/runtime-availability-regressions/xzc.ini.in -@@ -0,0 +1,17 @@ -+[FIXTURE] -+BASE = base.ini -+[TRAJ] -+COORDINATES = XCZ -+[KINS] -+KINEMATICS = trivkins coordinates=XCZ -+[HAL] -+HALFILE = xzc.hal -+[AXIS_C] -+MIN_LIMIT = -360 -+MAX_LIMIT = 360 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+[JOINT_1] -+TYPE = ANGULAR -+MIN_LIMIT = -360 -+MAX_LIMIT = 360 -diff --git a/tests/runtime-availability/.gitignore b/tests/runtime-availability/.gitignore -new file mode 100644 -index 0000000000..425d52b6e7 ---- /dev/null -+++ b/tests/runtime-availability/.gitignore -@@ -0,0 +1,2 @@ -+/*.ini -+!/base.ini -diff --git a/tests/runtime-availability/README b/tests/runtime-availability/README -new file mode 100644 -index 0000000000..bdfd8cc4e3 ---- /dev/null -+++ b/tests/runtime-availability/README -@@ -0,0 +1,8 @@ -+Userspace POSIX simulation: actual target enforcement, released-joint MDI eligibility, late ACK cancellation, held-position validation, and homing abort cleanup. -+Cancellation waits for actual homing velocity and checks stationary completion and reacquisition. -+Direct admission rejects dwell/queued MDI and paused AUTO, overlaps (including no-ops and other resources), and interpretation/jogging before completion. With forced homing enabled, Home All skips unavailable controlled joints, first acquisition homes an unhomed nonvolatile joint, and controlled joints reject user HOME/UNHOME outside acquisition. Later nonvolatile acquisition preserves a matching held position and rejects changed or non-finite feedback without publishing availability. Volatile acquisition accepts arbitrary unavailable movement only through successful homing. Abort during ACK wait and moving homing cannot be revived by late ACK; later reacquisition succeeds. -+ -+INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local -+*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before -+launching an individual case directly. @unset explicitly removes an inherited -+key. Generated INIs are ignored; edit the base or the case override instead. -diff --git a/tests/runtime-availability/base.ini b/tests/runtime-availability/base.ini -new file mode 100644 -index 0000000000..c8e0eab3d2 ---- /dev/null -+++ b/tests/runtime-availability/base.ini -@@ -0,0 +1,99 @@ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0x0 -+ -+[DISPLAY] -+DISPLAY = ./test-ui.py -+ -+[RS274NGC] -+PARAMETER_FILE = sim.var -+ -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4.0 -+BASE_PERIOD = 0 -+SERVO_PERIOD = 1000000 -+ -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 -+ -+[HAL] -+HALFILE = core_sim.hal -+ -+[TRAJ] -+NO_FORCE_HOMING = 0 -+AXES = 3 -+COORDINATES = XYZ -+SPINDLES = 1 -+LINEAR_UNITS = mm -+ANGULAR_UNITS = degree -+DEFAULT_LINEAR_VELOCITY = 10 -+MAX_LINEAR_VELOCITY = 50 -+ -+[EMCIO] -+TOOL_TABLE = tool.tbl -+ -+[KINS] -+KINEMATICS = trivkins coordinates=XYZ -+JOINTS = 3 -+ -+[AXIS_X] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+ -+[JOINT_0] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+ -+HOME_SEQUENCE = 0 -+HOME_SEARCH_VEL = 0 -+HOME_LATCH_VEL = 0 -+[AXIS_Y] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+[AXIS_Z] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+[JOINT_1] -+TYPE = LINEAR -+HOME = 0 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+AVAILABILITY_CONTROL = 1 -+AVAILABILITY_TIMEOUT = 2 -+VOLATILE_HOME = 0 -+[JOINT_2] -+TYPE = LINEAR -+HOME = 0 -+HOME_SEARCH_VEL = 1 -+HOME_LATCH_VEL = 0.1 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+AVAILABILITY_CONTROL = 1 -+AVAILABILITY_TIMEOUT = 2 -+VOLATILE_HOME = 1 -+[SPINDLE_0] -+AVAILABILITY_CONTROL = 1 -+INITIAL_AVAILABILITY = 0 -+AVAILABILITY_TIMEOUT = 2 -diff --git a/tests/runtime-availability/checkresult b/tests/runtime-availability/checkresult -new file mode 100755 -index 0000000000..12624ae5b8 ---- /dev/null -+++ b/tests/runtime-availability/checkresult -@@ -0,0 +1,4 @@ -+#!/bin/sh -+set -e -+grep -q "^runtime availability scenarios ok$" "$1" -+grep -q "^initial availability scenarios ok$" "$1" -diff --git a/tests/runtime-availability/core_sim.hal b/tests/runtime-availability/core_sim.hal -new file mode 100644 -index 0000000000..62edf534b6 ---- /dev/null -+++ b/tests/runtime-availability/core_sim.hal -@@ -0,0 +1,17 @@ -+loadrt trivkins coordinates=XYZ -+loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_spindles=1 -+loadrt mux2 count=2 -+addf mux2.0 servo-thread -+addf mux2.1 servo-thread -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net Ycmd joint.1.motor-pos-cmd => mux2.0.in0 -+net Yfb mux2.0.out => joint.1.motor-pos-fb -+net Zcmd joint.2.motor-pos-cmd => mux2.1.in0 -+net Zfb mux2.1.out => joint.2.motor-pos-fb -+net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in -+setp spindle.0.at-speed true -+loadrt flipflop count=1 -+addf flipflop.0 servo-thread -+net enable-seen motion.motion-enabled => flipflop.0.set -diff --git a/tests/runtime-availability/initial-ui.py b/tests/runtime-availability/initial-ui.py -new file mode 100755 -index 0000000000..1c30ffabdd ---- /dev/null -+++ b/tests/runtime-availability/initial-ui.py -@@ -0,0 +1,58 @@ -+#!/usr/bin/env python3 -+import time -+import linuxcnc -+import hal -+h = hal.component('initial-availability-test'); h.ready() -+c = linuxcnc.command(); s = linuxcnc.stat() -+def wait(fn, msg): -+ end = time.monotonic() + 8 -+ while time.monotonic() < end: -+ s.poll() -+ if fn(): return -+ time.sleep(.005) -+ raise AssertionError(msg) -+def pin(n, v): hal.set_p(n, str(v)) -+wait(lambda: s.task_state == linuxcnc.STATE_ESTOP, 'startup') -+c.state(linuxcnc.STATE_ESTOP_RESET); c.wait_complete(3) -+c.state(linuxcnc.STATE_ON) -+wait(lambda: hal.get_value('spindle.0.availability-request'), 'initial request') -+pin('motion.enable', 0) -+pin('spindle.0.availability-ack', 1) -+time.sleep(.05); s.poll() -+assert not s.enabled and not hal.get_value('flipflop.0.out') -+assert not hal.get_value('spindle.0.available') -+pin('spindle.0.availability-ack', 0) -+c.state(linuxcnc.STATE_OFF); c.wait_complete(3) -+c.set_spindle_availability(0, False); c.wait_complete(3) -+pin('motion.enable', 1) -+c.state(linuxcnc.STATE_ON) -+wait(lambda: hal.get_value('spindle.0.availability-request'), 'retry request') -+c.abort() -+wait(lambda: not hal.get_value('spindle.0.availability-request'), 'abort request') -+pin('spindle.0.availability-ack', 1) -+time.sleep(.05); s.poll() -+assert not s.enabled and not hal.get_value('flipflop.0.out') -+pin('spindle.0.availability-ack', 0) -+c.state(linuxcnc.STATE_OFF); c.wait_complete(3) -+c.set_spindle_availability(0, False); c.wait_complete(3) -+c.state(linuxcnc.STATE_ON) -+wait(lambda: hal.get_value('spindle.0.availability-request'), 'initial spindle request') -+# Repeated On while the initial scan is already pending must not restart it. -+c.state(linuxcnc.STATE_ON) -+time.sleep(.02) -+assert hal.get_value('spindle.0.availability-request') -+pin('spindle.0.availability-ack', 1) -+assert c.wait_complete(5) == linuxcnc.RCS_DONE -+wait(lambda: s.enabled, 'machine on') -+assert not s.joint[1]['available'] and not s.joint[2]['available'] -+# Initial availability is startup policy, not a permanent ownership requirement. -+c.set_spindle_availability(0, False) -+wait(lambda: not hal.get_value('spindle.0.availability-request'), 'release initial spindle') -+pin('spindle.0.availability-ack', 0) -+assert c.wait_complete(5) == linuxcnc.RCS_DONE -+c.state(linuxcnc.STATE_ON) -+assert c.wait_complete(5) == linuxcnc.RCS_DONE -+time.sleep(.1); s.poll() -+assert s.enabled and not s.spindle[0]['available'] -+assert not hal.get_value('spindle.0.availability-request') -+print('initial availability scenarios ok') -diff --git a/tests/runtime-availability/initial.ini.in b/tests/runtime-availability/initial.ini.in -new file mode 100644 -index 0000000000..3b9c37cc3b ---- /dev/null -+++ b/tests/runtime-availability/initial.ini.in -@@ -0,0 +1,9 @@ -+# Case-specific overrides; unspecified values come from FIXTURE.BASE. -+[FIXTURE] -+BASE = base.ini -+ -+[DISPLAY] -+DISPLAY = ./initial-ui.py -+ -+[SPINDLE_0] -+INITIAL_AVAILABILITY = 1 -diff --git a/tests/runtime-availability/make-fixtures.py b/tests/runtime-availability/make-fixtures.py -new file mode 100644 -index 0000000000..3e7e61f92e ---- /dev/null -+++ b/tests/runtime-availability/make-fixtures.py -@@ -0,0 +1,34 @@ -+#!/usr/bin/env python3 -+"""Materialize local *.ini.in cases from a shared base and explicit overrides. -+ -+Run in the suite directory (test.sh does this automatically). @unset removes -+an inherited key; all other strings are copied verbatim. Paths remain relative -+to the suite, just as in the original standalone fixtures. -+""" -+import configparser -+from pathlib import Path -+ -+ -+def read(path): -+ ini = configparser.ConfigParser(interpolation=None) -+ ini.optionxform = str -+ with path.open() as stream: -+ ini.read_file(stream) -+ return ini -+ -+ -+for template in sorted(Path('.').glob('*.ini.in')): -+ overrides = read(template) -+ ini = read(template.parent / overrides['FIXTURE']['BASE']) -+ overrides.remove_section('FIXTURE') -+ for section in overrides.sections(): -+ if not ini.has_section(section): -+ ini.add_section(section) -+ for key, value in overrides[section].items(): -+ if value == '@unset': -+ ini.remove_option(section, key) -+ else: -+ ini[section][key] = value -+ with template.with_suffix('').open('w') as stream: -+ stream.write('# Generated by make-fixtures.py; edit the .ini.in case.\n') -+ ini.write(stream) -diff --git a/tests/runtime-availability/paused.ngc b/tests/runtime-availability/paused.ngc -new file mode 100644 -index 0000000000..c9e6f8a64f ---- /dev/null -+++ b/tests/runtime-availability/paused.ngc -@@ -0,0 +1,3 @@ -+M0 -+G90 G0 X0.5 -+M2 -diff --git a/tests/runtime-availability/test-ui.py b/tests/runtime-availability/test-ui.py -new file mode 100755 -index 0000000000..1f435daf96 ---- /dev/null -+++ b/tests/runtime-availability/test-ui.py -@@ -0,0 +1,297 @@ -+#!/usr/bin/env python3 -+import time -+import os -+import linuxcnc -+import hal -+h = hal.component("availability-test") -+h.ready() -+c = linuxcnc.command() -+s = linuxcnc.stat() -+e = linuxcnc.error_channel() -+def wait(fn, message, timeout=8): -+ end = time.monotonic() + timeout -+ while time.monotonic() < end: -+ s.poll() -+ # Expected rejection diagnostics must not fill the bounded NML error -+ # channel and block task while later scenarios wait for completion. -+ while e.poll() is not None: -+ pass -+ if fn(): return -+ time.sleep(.005) -+ raise AssertionError('%s: task=%s exec=%s joints=%r spindle=%r error=%r' % -+ (message, s.task_state, s.exec_state, -+ [(j['availability_state'], j['availability_fault']) for j in s.joint], -+ s.spindle[0], e.poll())) -+def done(): -+ assert c.wait_complete(8) == linuxcnc.RCS_DONE, "command failed: %r" % (e.poll(),) -+ s.poll() -+def pin(name, value): hal.set_p(name, str(value)) -+def manual(): -+ c.mode(linuxcnc.MODE_MANUAL); done() -+ c.teleop_enable(0); done() -+def mdi(code): c.mdi(code); done() -+def reset(): -+ c.state(linuxcnc.STATE_OFF); c.wait_complete(2) -+ for n in (1, 2): pin('joint.%d.availability-ack' % n, 0) -+ pin('spindle.0.availability-ack', 0) -+ time.sleep(.05) -+ for n in (1, 2): -+ c.set_joint_availability(n, False); c.wait_complete(2) -+ c.set_spindle_availability(0, False); c.wait_complete(2) -+ wait(lambda: all(s.joint[n]['availability_state'] == 0 for n in (1,2)), 'release') -+ pin('motion.enable', 1) -+ c.state(linuxcnc.STATE_ESTOP_RESET); done() -+ c.state(linuxcnc.STATE_ON); done() -+ manual() -+ c.home(-1); done() -+ wait(lambda: s.homed[0], 'Home All homes X') -+ assert all(not s.joint[n]['homing'] for n in (1,2)) -+ assert not s.joint[2]['homed'] -+ assert all(not hal.get_value('joint.%d.availability-request' % n) for n in (1,2)) -+wait(lambda: s.task_state == linuxcnc.STATE_ESTOP, 'startup') -+reset() -+# Motion can be DONE while task is dwelling with more MDI work queued. -+c.mode(linuxcnc.MODE_MDI); done() -+c.mdi('G4 P2') -+wait(lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY, 'active dwell') -+c.mdi('G0 X0.25') -+assert c.wait_complete(.05) == -1 -+c.mdi('G0 X0.5') -+wait(lambda: s.queued_mdi_commands > 0, 'queued MDI') -+for request in (lambda: c.set_joint_availability(1, True), -+ lambda: c.set_spindle_availability(0, True)): -+ request() -+ assert c.wait_complete(.2) == linuxcnc.RCS_ERROR, 'busy direct request queued' -+ assert not hal.get_value('joint.1.availability-request') -+ assert not hal.get_value('spindle.0.availability-request') -+wait(lambda: s.interp_state == linuxcnc.INTERP_IDLE and -+ s.exec_state == linuxcnc.EXEC_DONE, 'queued work completion') -+assert abs(s.joint_position[0] - .5) < .001 -+c.mode(linuxcnc.MODE_AUTO); done() -+c.program_open(os.path.abspath('paused.ngc')); done() -+c.auto(linuxcnc.AUTO_RUN, 0) -+wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED, 'paused AUTO') -+c.set_joint_availability(1, False) -+assert c.wait_complete(.2) == linuxcnc.RCS_ERROR, 'paused AUTO accepted direct no-op' -+c.auto(linuxcnc.AUTO_RESUME); done() -+manual() -+# All overlaps, including duplicate/no-op requests, must leave the first intact. -+c.set_spindle_availability(0, True) -+wait(lambda: hal.get_value('spindle.0.availability-request'), 'original spindle request') -+for request in (lambda: c.set_spindle_availability(0, True), -+ lambda: c.set_spindle_availability(0, False), -+ lambda: c.set_joint_availability(1, True), -+ lambda: c.set_joint_availability(1, False), -+ lambda: c.mode(linuxcnc.MODE_MDI), -+ lambda: c.jog(linuxcnc.JOG_INCREMENT, 1, 0, 1, 1)): -+ request() -+ assert c.wait_complete(.2) == linuxcnc.RCS_ERROR -+ assert hal.get_value('spindle.0.availability-request'), 'overlap canceled owner' -+ assert not hal.get_value('joint.1.availability-request') -+pin('spindle.0.availability-ack', 1) -+wait(lambda: s.spindle[0]['available'] and s.exec_state == linuxcnc.EXEC_DONE, -+ 'original request completion') -+c.set_spindle_availability(0, False) -+wait(lambda: not hal.get_value('spindle.0.availability-request'), 'spindle release') -+pin('spindle.0.availability-ack', 0); done() -+# A released spindle's amplifier may report not-ready while axes remain usable. -+pin('spindle.0.amp-fault-in', 1) -+c.mode(linuxcnc.MODE_MDI); done() -+mdi('G0 X0.75') -+assert s.enabled and abs(s.joint_position[0] - .75) < .001 -+manual() -+c.set_spindle_availability(0, True) -+wait(lambda: hal.get_value('spindle.0.availability-request'), 'faulted spindle acquire') -+assert s.enabled, 'pending spindle acquisition enabled fault checking too early' -+pin('spindle.0.availability-ack', 1) -+wait(lambda: not s.enabled, 'reacquired spindle amplifier fault did not disable motion') -+pin('spindle.0.amp-fault-in', 0) -+reset() -+# Deliberately released unhomed joints permit unrelated MDI and explicit no-op Y. -+c.mode(linuxcnc.MODE_MDI); done() -+mdi('G0 X1 Y0 Z0') -+assert abs(s.joint_position[0]-1) < .01 -+# First prohibited actual target faults the whole coordinated operation. -+c.mdi('G1 X10 Y10 F60') -+wait(lambda: s.task_state != linuxcnc.STATE_ON, 'illegal Y did not fault') -+assert abs(s.joint_position[1]) < 1e-9 -+reset() -+# Direct joint jogging is rejected; teleop uses the same actual-target guard. -+c.teleop_enable(0); done() -+wait(lambda: s.motion_mode == linuxcnc.TRAJ_MODE_FREE, "joint mode") -+c.jog(linuxcnc.JOG_INCREMENT, 1, 1, 1, 1) -+assert c.wait_complete(3) == linuxcnc.RCS_ERROR -+assert abs(s.joint_position[1]) < 1e-9 -+c.abort(); done() -+c.teleop_enable(1); done() -+wait(lambda: s.motion_mode == linuxcnc.TRAJ_MODE_TELEOP, "teleop mode") -+c.jog(linuxcnc.JOG_INCREMENT, 0, 1, 1, 1) -+wait(lambda: not s.enabled, 'illegal teleop target did not fault') -+assert abs(s.joint_position[1]) < 1e-9 -+reset() -+# Abort then late ACK cannot complete a pending acquisition. -+c.set_joint_availability(1, True) -+wait(lambda: s.joint[1]['availability_state'] == 1, 'pending acquisition') -+c.abort(); c.wait_complete(2) -+pin('joint.1.availability-ack', 1) -+time.sleep(.05); s.poll() -+assert not s.joint[1]['available'] -+assert not hal.get_value('joint.1.amp-enable-out') -+# Clear the fault explicitly after hardware ACK goes low. -+pin('joint.1.availability-ack', 0) -+c.set_joint_availability(1, False); c.wait_complete(2) -+reset() -+# Enable withdrawal followed by a late ACK revokes runtime acquisition. -+c.set_joint_availability(1, True) -+wait(lambda: s.joint[1]['availability_state'] == 1, 'second acquisition') -+pin('motion.enable', 0) -+pin('joint.1.availability-ack', 1) -+time.sleep(.05); s.poll() -+assert not s.enabled and not s.joint[1]['available'] -+pin('joint.1.availability-ack', 0) -+c.set_joint_availability(1, False); c.wait_complete(2) -+reset() -+# Establish synchronization while acquired, then clear it after release. -+c.set_spindle_availability(0, True) -+wait(lambda: hal.get_value('spindle.0.availability-request'), 'spindle request') -+pin('spindle.0.availability-ack', 1); done() -+c.mode(linuxcnc.MODE_MDI); done() -+mdi('G95 F1') -+manual() -+c.set_spindle_availability(0, False) -+wait(lambda: not hal.get_value('spindle.0.availability-request'), 'spindle release') -+pin('spindle.0.availability-ack', 0); done() -+c.mode(linuxcnc.MODE_MDI); done() -+mdi('G94') -+manual() -+# An unhomed nonvolatile joint homes on first acquisition. Ordinary individual -+# HOME/UNHOME commands cannot bypass availability ownership. -+held = hal.get_value('joint.1.pos-cmd') -+c.set_joint_availability(1, True) -+wait(lambda: hal.get_value('joint.1.availability-request'), 'request Y') -+pin('joint.1.availability-ack', 1); done() -+wait(lambda: s.joint[1]['available'] and s.joint[1]['homed'], 'home and acquire Y') -+assert abs(hal.get_value('joint.1.pos-cmd') - held) < 1e-12 -+c.home(1) -+assert c.wait_complete(3) == linuxcnc.RCS_ERROR -+c.abort(); done(); manual() -+c.unhome(1) -+assert c.wait_complete(3) == linuxcnc.RCS_ERROR -+c.unhome(-1) -+assert c.wait_complete(3) == linuxcnc.RCS_ERROR -+c.abort(); done(); manual() -+assert s.homed[0] and s.joint[1]['available'] and s.joint[1]['homed'] -+# Release freezes the logical joint and Cartesian pose. External feedback remains -+# visible at HAL, but a material mismatch rejects acquisition. -+held = hal.get_value('joint.1.pos-cmd') -+c.set_joint_availability(1, False) -+wait(lambda: not hal.get_value('joint.1.availability-request'), 'direct release') -+pin('joint.1.availability-ack', 0); done() -+pin('mux2.0.in1', hal.get_value('joint.1.motor-pos-fb') + 3) -+pin('mux2.0.sel', 1) -+time.sleep(.05); s.poll() -+assert abs(hal.get_value('joint.1.motor-pos-fb') - (held + 3)) < 1e-6 -+assert abs(s.joint_position[1] - held) < 1e-9 -+assert abs(hal.get_value('joint.1.pos-fb') - held) < 1e-9 -+c.set_joint_availability(1, True) -+wait(lambda: hal.get_value('joint.1.availability-request'), 'mismatching acquire') -+pin('joint.1.availability-ack', 1) -+wait(lambda: s.joint[1]['availability_fault'] == 8, 'position mismatch fault') -+assert not s.joint[1]['available'] -+assert not hal.get_value('joint.1.amp-enable-out') -+assert abs(hal.get_value('joint.1.pos-cmd') - held) < 1e-12 -+assert abs(s.joint_position[1] - held) < 1e-9 -+pin('joint.1.availability-ack', 0) -+pin('mux2.0.sel', 0) -+reset() -+# Runtime volatile acquisition may home, but cancellation must clean it up. -+pin('mux2.1.in1', 7); pin('mux2.1.sel', 1) -+time.sleep(.05); s.poll() -+assert abs(hal.get_value('joint.2.motor-pos-fb') - 7) < 1e-6 -+assert abs(s.joint_position[2]) < 1e-9 -+c.set_joint_availability(2, True) -+wait(lambda: hal.get_value('joint.2.availability-request'), 'request Z') -+pin('joint.2.availability-ack', 1) -+wait(lambda: s.joint[2]['availability_state'] == 2, 'hardware ACK enters homing') -+assert not s.joint[2]['available'] and not s.joint[2]['homed'] -+pin('mux2.1.sel', 0) -+for state, switch in [(7, 1), (10, 0), (12, 1)]: -+ wait(lambda: hal.get_value('joint.2.home-state') == state, 'home switch phase %d' % state) -+ assert not hal.get_value('joint.2.available') -+ assert c.wait_complete(.02) == -1, 'completed before required homing' -+ pin('joint.2.home-sw-in', switch) -+done() -+wait(lambda: s.joint[2]['available'] and s.joint[2]['homed'], 'completed home') -+c.set_joint_availability(2, False) -+wait(lambda: not hal.get_value('joint.2.availability-request'), 'release homed Z') -+pin('joint.2.availability-ack', 0); done() -+ -+# A later volatile acquisition remains unavailable until homing completes, and -+# cancellation leaves it unavailable and unreferenced. -+c.set_joint_availability(2, True) -+wait(lambda: hal.get_value('joint.2.availability-request'), 'request Z') -+pin('joint.2.availability-ack', 1) -+wait(lambda: abs(hal.get_value('joint.2.vel-cmd')) > .1, 'moving runtime home Z') -+c.set_joint_availability(2, False) -+assert c.wait_complete(.2) == linuxcnc.RCS_ERROR, 'release canceled acquisition homing' -+assert hal.get_value('joint.2.availability-request') -+c.abort() -+wait(lambda: not hal.get_value('joint.2.availability-request'), 'cancel request') -+assert c.wait_complete(.03) == -1, 'Abort completed before release ACK/cleanup' -+pin('joint.2.availability-ack', 0) -+done() -+wait(lambda: not s.joint[2]['homing'] and s.joint[2]['availability_state'] == 0, 'homing abort cleanup') -+assert not hal.get_value('joint.2.amp-enable-out') -+assert not hal.get_value('joint.2.active') -+assert s.joint[2]['inpos'], 'released joint not complete' -+wait(lambda: hal.get_value('joint.2.vel-cmd') == 0, 'homing velocity stopped') -+wait(lambda: s.state == linuxcnc.RCS_DONE, 'normal completion after cancellation') -+# Late hardware acknowledgement cannot revive cancelled homing. -+pin('joint.2.availability-ack', 1) -+time.sleep(.05); s.poll() -+assert not s.joint[2]['available'] and not hal.get_value('joint.2.amp-enable-out') -+pin('joint.2.availability-ack', 0) -+reset() -+# A fresh acquisition can complete homing and only then become available. -+pin('joint.2.home-sw-in', 0) -+c.set_joint_availability(2, True) -+wait(lambda: hal.get_value('joint.2.availability-request'), 'fresh request Z') -+pin('joint.2.availability-ack', 1) -+for state, switch in [(7, 1), (10, 0), (12, 1)]: -+ wait(lambda: hal.get_value('joint.2.home-state') == state, 'home switch phase %d' % state) -+ assert not hal.get_value('joint.2.available') -+ assert c.wait_complete(.02) == -1, 'completed before required homing' -+ pin('joint.2.home-sw-in', switch) -+done() -+wait(lambda: s.joint[2]['available'] and s.joint[2]['homed'], 'completed home') -+time.sleep(.05) -+assert abs(hal.get_value('joint.2.free-pos-cmd') - s.joint_position[2]) < 1e-5 -+# Losing an acquired ACK inhibits the actuator and propagates a fault. -+pin('joint.2.availability-ack', 0) -+wait(lambda: s.joint[2]['availability_fault'] != 0, 'ACK loss fault') -+assert not hal.get_value('joint.2.amp-enable-out') -+# A release timeout is failure, even though the actuator is already inhibited. -+reset() -+c.set_spindle_availability(0, True) -+wait(lambda: hal.get_value('spindle.0.availability-request'), 'timeout setup acquire') -+pin('spindle.0.availability-ack', 1); done() -+c.set_spindle_availability(0, False) -+assert c.wait_complete(5) == linuxcnc.RCS_ERROR, 'release timeout reported success' -+s.poll() -+assert s.spindle[0]['availability_fault'] == 3 -+# Invalid reacquisition feedback must fail explicitly, never publish AVAILABLE. -+reset() -+c.set_joint_availability(1, True) -+wait(lambda: hal.get_value('joint.1.availability-request'), 'invalid-feedback home setup') -+pin('joint.1.availability-ack', 1); done() -+assert s.joint[1]['available'] and s.joint[1]['homed'] -+c.set_joint_availability(1, False) -+wait(lambda: not hal.get_value('joint.1.availability-request'), 'invalid-feedback release setup') -+pin('joint.1.availability-ack', 0); done() -+pin('mux2.0.in1', 'nan'); pin('mux2.0.sel', 1) -+c.set_joint_availability(1, True) -+wait(lambda: hal.get_value('joint.1.availability-request'), 'invalid-feedback request') -+pin('joint.1.availability-ack', 1) -+wait(lambda: s.joint[1]['availability_fault'] == 8, 'invalid-feedback position mismatch') -+assert not s.joint[1]['available'] and not hal.get_value('joint.1.amp-enable-out') -+print('runtime availability scenarios ok') -diff --git a/tests/runtime-availability/test.ini.in b/tests/runtime-availability/test.ini.in -new file mode 100644 -index 0000000000..67dab70a3d ---- /dev/null -+++ b/tests/runtime-availability/test.ini.in -@@ -0,0 +1,3 @@ -+# Case-specific overrides; unspecified values come from FIXTURE.BASE. -+[FIXTURE] -+BASE = base.ini -diff --git a/tests/runtime-availability/test.sh b/tests/runtime-availability/test.sh -new file mode 100755 -index 0000000000..9a17bf2443 ---- /dev/null -+++ b/tests/runtime-availability/test.sh -@@ -0,0 +1,5 @@ -+#!/bin/sh -+set -e -+python3 ../runtime-availability/make-fixtures.py -+linuxcnc -r test.ini -+linuxcnc -r initial.ini -diff --git a/tests/runtime-availability/tool.tbl b/tests/runtime-availability/tool.tbl -new file mode 100644 -index 0000000000..e69de29bb2 diff --git a/linuxcnc-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index 7e8da6e3..d9580f18 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -3,129 +3,33 @@ From: Dariusz Majnert Date: Thu, 17 Sep 2026 18:00:42 +0200 Subject: [PATCH] availability-mcodes +Ported to v2.10.0-pre2. M54 acquisition homing runs through the queued +G28.2 home cycle (see runtime-joint-and-spindle-availability), so +tests/availability-mcodes also covers Machine Off during acquisition +homing and a resumable Stop during M54 homing, which stays STOPPING until +homing ends as it does during G28.2. --- - docs/src/gcode/m-code.adoc | 40 +++++ - docs/src/remap/remap.adoc | 7 +- - src/emc/nml_intf/canon.hh | 2 + - src/emc/rs274ngc/gcodemodule.cc | 2 + - src/emc/rs274ngc/interp_array.cc | 2 +- - src/emc/rs274ngc/interp_check.cc | 24 ++- - src/emc/rs274ngc/interp_convert.cc | 11 ++ - src/emc/rs274ngc/interp_execute.cc | 4 + - src/emc/rs274ngc/interp_internal.cc | 1 + - src/emc/rs274ngc/interp_internal.hh | 7 + - src/emc/rs274ngc/interp_read.cc | 9 +- - src/emc/rs274ngc/interp_remap.cc | 2 + - src/emc/rs274ngc/recordingcanon.cc | 3 + - src/emc/sai/saicanon.cc | 5 + - src/emc/task/emccanon.cc | 18 +++ - .../.gitignore | 2 + - tests/availability-mcodes-regressions/README | 9 ++ - .../checkresult | 5 + - .../availability-mcodes-regressions/step.ngc | 6 + - .../test-ui.py | 74 +++++++++ - .../test.ini.in | 9 ++ - tests/availability-mcodes-regressions/test.sh | 6 + - tests/availability-mcodes/.gitignore | 2 + - tests/availability-mcodes/README | 9 ++ - tests/availability-mcodes/checkresult | 4 + - tests/availability-mcodes/core_sim.hal | 1 + - tests/availability-mcodes/homing.ngc | 4 + - tests/availability-mcodes/no-force.ini.in | 6 + - tests/availability-mcodes/ordered.ngc | 6 + - tests/availability-mcodes/test-ui.py | 142 ++++++++++++++++++ - tests/availability-mcodes/test.ini | 1 + - tests/availability-mcodes/test.sh | 5 + - tests/availability-mcodes/timeout.ngc | 4 + - tests/availability-mcodes/tool.tbl | 1 + - tests/availability-mcodes/unhomed.ngc | 4 + - tests/interp/availability-mcodes/README | 6 + - .../interp/availability-mcodes/bad-joint.ngc | 2 + - .../availability-mcodes/double-selector.ngc | 2 + - .../availability-mcodes/execute-status.cc | 26 ++++ - .../availability-mcodes/execute-status.py | 30 ++++ - tests/interp/availability-mcodes/expected | 0 - .../availability-mcodes/fractional-joint.ngc | 2 + - .../fractional-spindle.ngc | 2 + - .../availability-mcodes/group-spindle.ngc | 2 + - .../availability-mcodes/huge-spindle.ngc | 2 + - tests/interp/availability-mcodes/legacy54.ngc | 5 + - tests/interp/availability-mcodes/legacy55.ngc | 5 + - .../availability-mcodes/missing-selector.ngc | 2 + - .../interp/availability-mcodes/mixed-feed.ngc | 2 + - .../availability-mcodes/mixed-modal.ngc | 2 + - .../availability-mcodes/mixed-motion.ngc | 2 + - .../availability-mcodes/mixed-parameter.ngc | 2 + - .../availability-mcodes/mixed-polar.ngc | 2 + - .../availability-mcodes/mixed-speed.ngc | 2 + - .../interp/availability-mcodes/mixed-stop.ngc | 2 + - .../interp/availability-mcodes/mixed-tool.ngc | 2 + - .../interp/availability-mcodes/mixed-word.ngc | 2 + - .../negative-fractional-spindle.ngc | 2 + - .../availability-mcodes/negative-joint.ngc | 2 + - tests/interp/availability-mcodes/remap.ini | 5 + - tests/interp/availability-mcodes/remapped.ngc | 3 + - tests/interp/availability-mcodes/test.ini | 2 + - tests/interp/availability-mcodes/test.sh | 80 ++++++++++ - .../availability-mcodes/valid-joint.ngc | 3 + - .../availability-mcodes/valid-spindle.ngc | 3 + - 65 files changed, 634 insertions(+), 7 deletions(-) - create mode 100644 tests/availability-mcodes-regressions/.gitignore - create mode 100644 tests/availability-mcodes-regressions/README - create mode 100755 tests/availability-mcodes-regressions/checkresult - create mode 100644 tests/availability-mcodes-regressions/step.ngc - create mode 100755 tests/availability-mcodes-regressions/test-ui.py - create mode 100644 tests/availability-mcodes-regressions/test.ini.in - create mode 100755 tests/availability-mcodes-regressions/test.sh - create mode 100644 tests/availability-mcodes/.gitignore - create mode 100644 tests/availability-mcodes/README - create mode 100755 tests/availability-mcodes/checkresult - create mode 120000 tests/availability-mcodes/core_sim.hal - create mode 100644 tests/availability-mcodes/homing.ngc - create mode 100644 tests/availability-mcodes/no-force.ini.in - create mode 100644 tests/availability-mcodes/ordered.ngc - create mode 100755 tests/availability-mcodes/test-ui.py - create mode 120000 tests/availability-mcodes/test.ini - create mode 100755 tests/availability-mcodes/test.sh - create mode 100644 tests/availability-mcodes/timeout.ngc - create mode 120000 tests/availability-mcodes/tool.tbl - create mode 100644 tests/availability-mcodes/unhomed.ngc - create mode 100644 tests/interp/availability-mcodes/README - create mode 100644 tests/interp/availability-mcodes/bad-joint.ngc - create mode 100644 tests/interp/availability-mcodes/double-selector.ngc - create mode 100644 tests/interp/availability-mcodes/execute-status.cc - create mode 100644 tests/interp/availability-mcodes/execute-status.py - create mode 100644 tests/interp/availability-mcodes/expected - create mode 100644 tests/interp/availability-mcodes/fractional-joint.ngc - create mode 100644 tests/interp/availability-mcodes/fractional-spindle.ngc - create mode 100644 tests/interp/availability-mcodes/group-spindle.ngc - create mode 100644 tests/interp/availability-mcodes/huge-spindle.ngc - create mode 100644 tests/interp/availability-mcodes/legacy54.ngc - create mode 100644 tests/interp/availability-mcodes/legacy55.ngc - create mode 100644 tests/interp/availability-mcodes/missing-selector.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-feed.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-modal.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-motion.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-parameter.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-polar.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-speed.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-stop.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-tool.ngc - create mode 100644 tests/interp/availability-mcodes/mixed-word.ngc - create mode 100644 tests/interp/availability-mcodes/negative-fractional-spindle.ngc - create mode 100644 tests/interp/availability-mcodes/negative-joint.ngc - create mode 100644 tests/interp/availability-mcodes/remap.ini - create mode 100644 tests/interp/availability-mcodes/remapped.ngc - create mode 100644 tests/interp/availability-mcodes/test.ini - create mode 100755 tests/interp/availability-mcodes/test.sh - create mode 100644 tests/interp/availability-mcodes/valid-joint.ngc - create mode 100644 tests/interp/availability-mcodes/valid-spindle.ngc + docs/src/gcode/m-code.adoc | 41 +++++++++++++++++++++++++++++ + docs/src/remap/remap.adoc | 7 ++++- + src/emc/nml_intf/canon.hh | 2 ++ + src/emc/rs274ngc/gcodemodule.cc | 2 ++ + src/emc/rs274ngc/interp_array.cc | 2 +- + src/emc/rs274ngc/interp_check.cc | 24 ++++++++++++++--- + src/emc/rs274ngc/interp_convert.cc | 14 ++++++++++ + src/emc/rs274ngc/interp_execute.cc | 4 +++ + src/emc/rs274ngc/interp_internal.cc | 1 + + src/emc/rs274ngc/interp_internal.hh | 7 +++++ + src/emc/rs274ngc/interp_read.cc | 9 ++++++- + src/emc/rs274ngc/interp_remap.cc | 2 ++ + src/emc/sai/saicanon.cc | 5 ++++ + src/emc/task/emccanon.cc | 18 +++++++++++++ + 14 files changed, 131 insertions(+), 7 deletions(-) diff --git a/docs/src/gcode/m-code.adoc b/docs/src/gcode/m-code.adoc -index 1cb15521ad..0f3b65c8e4 100644 +index e74ef24..757bf92 100644 --- a/docs/src/gcode/m-code.adoc +++ b/docs/src/gcode/m-code.adoc -@@ -22,6 +22,7 @@ +@@ -23,6 +23,7 @@ |<> | Spindle Override Control |<> | Adaptive Feed Control |<> | Feed Stop Control @@ -133,7 +37,7 @@ index 1cb15521ad..0f3b65c8e4 100644 |<> | Set Current Tool Number |<> | Output Control |<> | Input Control -@@ -342,6 +343,45 @@ cutters and wire spark eroders but it is not limited to such applications. +@@ -411,6 +412,46 @@ cutters and wire spark eroders but it is not limited to such applications. * 'M53 P0' - disable the feed stop switch. The state of 'motion.feed-hold' will have no effect on feed when M53 is not active. @@ -161,6 +65,7 @@ index 1cb15521ad..0f3b65c8e4 100644 +comments and a line number are permitted. Motion, modal changes, other M-codes, +parameter assignments, polar coordinates, and unsupported words are rejected +before execution of block actions. Selectors must name one configured resource. ++M54 and M55 are refused while cutter radius compensation is on. + +The execution boundary is: finish preceding motion and IO, dispatch the runtime +API request, wait for its shared completion boundary or failure, then continue. @@ -180,10 +85,10 @@ index 1cb15521ad..0f3b65c8e4 100644 == M61 Set Current Tool diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index 5bb208e611..b2fd837823 100644 +index e332924..46b68ef 100644 --- a/docs/src/remap/remap.adoc +++ b/docs/src/remap/remap.adoc -@@ -1928,6 +1928,7 @@ The current set of *existing* codes open to redefinition is: +@@ -1931,6 +1931,7 @@ The current set of *existing* codes open to redefinition is: - M7 (activate coolant mist) - M8 (activate coolant flood) - M9 (deactivate coolant mist and flood) @@ -191,7 +96,7 @@ index 5bb208e611..b2fd837823 100644 - M60 (exchange pallet shuttles and then pause a running program temporarily) - M62 .. M65 (digital output control) - M66 (wait on input) -@@ -2117,7 +2118,7 @@ These M-codes are currently undefined in the current implementation of LinuxCNC +@@ -2120,7 +2121,7 @@ These M-codes are currently undefined in the current implementation of LinuxCNC |20-29 |M20 |M21 |M22 |M23 |M24 |M25 |M26 |M27 |M28 |M29 |30-39 | |M31 |M32 |M33 |M34 |M35 |M36 |M37 |M38 |M39 |40-49 |M40 |M41 |M42 |M43 |M44 |M45 |M46 |M47 | | @@ -200,7 +105,7 @@ index 5bb208e611..b2fd837823 100644 |60-69 | | | | | | | | | | |70-79 | | | | |M74 |M75 |M76 |M77 |M78 |M79 |80-89 |M80 |M81 |M82 |M83 |M84 |M85 |M86 |M87 |M88 |M89 -@@ -2126,6 +2127,10 @@ These M-codes are currently undefined in the current implementation of LinuxCNC +@@ -2129,6 +2130,10 @@ These M-codes are currently undefined in the current implementation of LinuxCNC All M-codes from `M100` to `M199` are user-defined M-codes already, and should not be remapped. @@ -212,37 +117,37 @@ index 5bb208e611..b2fd837823 100644 == A short survey of LinuxCNC program execution diff --git a/src/emc/nml_intf/canon.hh b/src/emc/nml_intf/canon.hh -index 9a41b2647f..2b6768ae16 100644 +index ee99e8e..da250ca 100644 --- a/src/emc/nml_intf/canon.hh +++ b/src/emc/nml_intf/canon.hh -@@ -640,6 +640,8 @@ rotation. If the spindle is already turning and is at a different +@@ -656,6 +656,8 @@ rotation. If the spindle is already turning and is at a different speed, change to the speed given with this command. */ - extern void STOP_SPINDLE_TURNING(int spindle); + extern void STOP_SPINDLE_TURNING(int spindle, int wait_for_atspeed = 1); +extern void SET_JOINT_AVAILABILITY(int joint, int available); +extern void SET_SPINDLE_AVAILABILITY(int spindle, int available); /* Stop the spindle from turning. If the spindle is already stopped, this command may be given, but it will have no effect. */ diff --git a/src/emc/rs274ngc/gcodemodule.cc b/src/emc/rs274ngc/gcodemodule.cc -index d97d0ac765..5a58552006 100644 +index 109cf46..699bf0d 100644 --- a/src/emc/rs274ngc/gcodemodule.cc +++ b/src/emc/rs274ngc/gcodemodule.cc -@@ -553,6 +553,8 @@ void START_SPINDLE_COUNTERCLOCKWISE(int /*spindle*/, int /*wait_for_at_speed*/) - void START_SPINDLE_CLOCKWISE(int /*spindle*/, int /*wait_for_at_speed*/) {} - void SET_SPINDLE_MODE(int /*spindle*/, double) {} - void STOP_SPINDLE_TURNING(int /*spindle*/) {} +@@ -634,6 +634,8 @@ void SET_SPINDLE_MODE(int spindle, double css_max) { + if(spindle == 0) parse_state.canon->set_spindle_mode(css_max); + } + void STOP_SPINDLE_TURNING(int /*spindle*/, int /*wait_for_at_speed*/) {} +void SET_JOINT_AVAILABILITY(int /*joint*/, int /*available*/) {} +void SET_SPINDLE_AVAILABILITY(int /*spindle*/, int /*available*/) {} - void SET_SPINDLE_SPEED(int /*spindle*/, double /*rpm*/) {} - void ORIENT_SPINDLE(int /*spindle*/, double /*d*/, int /*i*/) {} - void WAIT_SPINDLE_ORIENT_COMPLETE(int /*s*/, double /*timeout*/) {} + void SET_SPINDLE_SPEED(int spindle, double rpm) { + if(spindle == 0) parse_state.canon->set_spindle_speed(rpm); + } diff --git a/src/emc/rs274ngc/interp_array.cc b/src/emc/rs274ngc/interp_array.cc -index ba393b5b9f..606365a3bd 100644 +index a900d33..d95b187 100644 --- a/src/emc/rs274ngc/interp_array.cc +++ b/src/emc/rs274ngc/interp_array.cc @@ -151,7 +151,7 @@ const int Interp::ems[] = { - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 29 + -1, -1, -1, -1, -1, -1, 3, 3, -1, -1, // 29 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 39 -1, -1, -1, -1, -1, -1, -1, -1, 9, 9, // 49 - 9, 9, 9, 9, -1, -1, -1, -1, -1, -1, // 59 @@ -251,7 +156,7 @@ index ba393b5b9f..606365a3bd 100644 7, 7, 7, 7, -1, -1, -1, -1, -1, -1, // 79 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 89 diff --git a/src/emc/rs274ngc/interp_check.cc b/src/emc/rs274ngc/interp_check.cc -index 3b139a0ca6..4707bc5afc 100644 +index c65a3b2..219a007 100644 --- a/src/emc/rs274ngc/interp_check.cc +++ b/src/emc/rs274ngc/interp_check.cc @@ -17,6 +17,7 @@ @@ -262,7 +167,7 @@ index 3b139a0ca6..4707bc5afc 100644 #include #include #include "rs274ngc.hh" -@@ -175,6 +176,19 @@ reading. This function checks for additional errors in m_codes. +@@ -181,6 +182,19 @@ reading. This function checks for additional errors in m_codes. int Interp::check_m_codes(block_pointer block) //!< pointer to a block to be checked { @@ -282,7 +187,7 @@ index 3b139a0ca6..4707bc5afc 100644 CHKS((block->m_count > MAX_EMS), NCE_TOO_MANY_M_CODES_ON_LINE); return INTERP_OK; -@@ -268,8 +282,9 @@ int Interp::check_other_codes(block_pointer block) //!< pointer to a block +@@ -274,8 +288,9 @@ int Interp::check_other_codes(block_pointer block) //!< pointer to a block (block->g_modes[GM_SPINDLE_MODE] != G_97) && (block->m_modes[7] != 3) && (block->m_modes[7] != 4) && (block->m_modes[7] != 5) && (block->m_modes[7] != 19) && @@ -294,9 +199,9 @@ index 3b139a0ca6..4707bc5afc 100644 } if (block->e_flag) { -@@ -327,12 +342,13 @@ int Interp::check_other_codes(block_pointer block) //!< pointer to a block - (motion != G_2) && (motion != G_3) && +@@ -334,13 +349,14 @@ int Interp::check_other_codes(block_pointer block) //!< pointer to a block (motion != G_74) && (motion != G_84) && + (block->g_modes[GM_MODAL_0] != G_28_2) && (block->m_modes[9] != 50) && (block->m_modes[9] != 51) && (block->m_modes[9] != 52) && - (block->m_modes[9] != 53) && (block->m_modes[5] != 62) && (block->m_modes[5] != 63) && + (block->m_modes[9] != 53) && (block->m_modes[9] != 54) && @@ -304,22 +209,26 @@ index 3b139a0ca6..4707bc5afc 100644 (block->m_modes[5] != 64) && (block->m_modes[5] != 65) && (block->m_modes[5] != 66) && (block->m_modes[7] != 19) && (block->user_m != 1) && (block->o_type != M_98)), - _("P word with no G2 G3 G4 G10 G64 G5 G5.2 G6, G6.2, G76 G82 G86 G88 G89" + _("P word with no G2 G3 G4 G10 G12.1 G64 G5 G5.2 G6, G6.2, G76 G82 G86 G88 G89" + " G28.2" - " or M50 M51 M52 M53 M62 M63 M64 M65 M66 M98 " + " or M50 M51 M52 M53 M54 M55 M62 M63 M64 M65 M66 M98 " "or user M code to use it")); int p_value = round_to_int(block->p_number); CHKS(((motion == G_2 || motion == G_3 || (block->m_modes[7] == 19)) && diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index e0c95f83cb..1b8e7fa05b 100644 +index a823ac5..354433e 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -4249,6 +4249,17 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ +@@ -4447,6 +4447,20 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ } } +if (((block->m_modes[9] == 54) || (block->m_modes[9] == 55)) && ONCE_M(9)) { + const int available = block->m_modes[9] == 54; ++ // The comp queue still holds the previous move, which must run first. ++ CHKS((settings->cutter_comp_side != CUTTER_COMP::OFF), ++ (_("Cannot change joint or spindle availability with cutter radius compensation on"))); + FINISH(); + if (block->p_flag) + SET_JOINT_AVAILABILITY((int)block->p_number, available); @@ -333,11 +242,11 @@ index e0c95f83cb..1b8e7fa05b 100644 return convert_remapped_code(block,settings,STEP_M_10,'m', block->m_modes[10]); diff --git a/src/emc/rs274ngc/interp_execute.cc b/src/emc/rs274ngc/interp_execute.cc -index e30635d881..119b9d8a43 100644 +index 46eb9e1..6bb5760 100644 --- a/src/emc/rs274ngc/interp_execute.cc +++ b/src/emc/rs274ngc/interp_execute.cc -@@ -325,6 +325,10 @@ int Interp::execute_block(block_pointer block, //!< pointer to a block of RS27 - if (settings->toolchange_flag) +@@ -330,6 +330,10 @@ int Interp::execute_block(block_pointer block, //!< pointer to a block of RS27 + if (settings->home_flag) return (INTERP_EXECUTE_FINISH); + if ((block->m_modes[9] == 54 || block->m_modes[9] == 55) && @@ -348,10 +257,10 @@ index e30635d881..119b9d8a43 100644 write_canon_state_tag(block, settings); return INTERP_OK; diff --git a/src/emc/rs274ngc/interp_internal.cc b/src/emc/rs274ngc/interp_internal.cc -index 5d4156d983..6fe1006528 100644 +index e08e4a6..21edbb7 100644 --- a/src/emc/rs274ngc/interp_internal.cc +++ b/src/emc/rs274ngc/interp_internal.cc -@@ -287,6 +287,7 @@ int Interp::init_block(block_pointer block) //!< pointer to a block to be i +@@ -288,6 +288,7 @@ int Interp::init_block(block_pointer block) //!< pointer to a block to be i block->line_number = -1; block->n_number = -1; block->motion_to_be = -1; @@ -360,10 +269,10 @@ index 5d4156d983..6fe1006528 100644 for (n = 0; n < 11; n++) { block->m_modes[n] = -1; diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh -index e7e3497d34..a8f87b03df 100644 +index 692b6e9..8ffadca 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh -@@ -454,12 +454,19 @@ struct block_struct +@@ -479,12 +479,19 @@ struct block_struct int line_number{}; int saved_line_number{}; // value of sequence_number when a remap was encountered int motion_to_be{}; @@ -384,7 +293,7 @@ index e7e3497d34..a8f87b03df 100644 bool b_flag{}; bool c_flag{}; diff --git a/src/emc/rs274ngc/interp_read.cc b/src/emc/rs274ngc/interp_read.cc -index 24ad8d99e4..0011efae1a 100644 +index b397cc0..2480073 100644 --- a/src/emc/rs274ngc/interp_read.cc +++ b/src/emc/rs274ngc/interp_read.cc @@ -20,6 +20,7 @@ @@ -394,8 +303,8 @@ index 24ad8d99e4..0011efae1a 100644 +#include #include #include - #include -@@ -406,7 +407,11 @@ int Interp::read_dollar(char *line, //!< string: line of RS274 code being proc + #include +@@ -405,7 +406,11 @@ int Interp::read_dollar(char *line, //!< string: line of RS274 code being proc *counter = (*counter + 1); CHKS((block->dollar_flag), NCE_MULTIPLE_$_WORDS_ON_ONE_LINE); CHP(read_real_value(line, counter, &value, parameters)); @@ -408,7 +317,7 @@ index 24ad8d99e4..0011efae1a 100644 block->dollar_flag = true; return INTERP_OK; } -@@ -870,7 +875,9 @@ int Interp::read_items(block_pointer block, //!< pointer to a block being f +@@ -876,7 +881,9 @@ int Interp::read_items(block_pointer block, //!< pointer to a block being f } for (; counter < length;) { @@ -419,10 +328,10 @@ index 24ad8d99e4..0011efae1a 100644 return INTERP_OK; } diff --git a/src/emc/rs274ngc/interp_remap.cc b/src/emc/rs274ngc/interp_remap.cc -index b13bdc0a5e..a944478d8d 100644 +index cf192c1..6cfdd5c 100644 --- a/src/emc/rs274ngc/interp_remap.cc +++ b/src/emc/rs274ngc/interp_remap.cc -@@ -47,6 +47,8 @@ bool Interp::is_m_code_remappable(int m_code) +@@ -45,6 +45,8 @@ bool Interp::is_m_code_remappable(int m_code) m_code == 7 || m_code == 8 || m_code == 9 || @@ -431,25 +340,11 @@ index b13bdc0a5e..a944478d8d 100644 m_code == 60 || m_code == 61 || m_code == 62 || -diff --git a/src/emc/rs274ngc/recordingcanon.cc b/src/emc/rs274ngc/recordingcanon.cc -index 235da9b7ea..9593f45c44 100644 ---- a/src/emc/rs274ngc/recordingcanon.cc -+++ b/src/emc/rs274ngc/recordingcanon.cc -@@ -425,6 +425,9 @@ void STOP_SPINDLE_TURNING(int spindle) - recording::active().spindle_direction[spindle] = CANON_STOPPED; - } - -+void SET_JOINT_AVAILABILITY(int /*joint*/, int /*available*/) {} -+void SET_SPINDLE_AVAILABILITY(int /*spindle*/, int /*available*/) {} -+ - void USE_TOOL_LENGTH_OFFSET(const EmcPose &offset) - { - tool_offset = offset; diff --git a/src/emc/sai/saicanon.cc b/src/emc/sai/saicanon.cc -index c4703d40d8..4af879ae03 100644 +index faeae9f..a45ebab 100644 --- a/src/emc/sai/saicanon.cc +++ b/src/emc/sai/saicanon.cc -@@ -491,6 +491,11 @@ void STOP_SPINDLE_TURNING(int spindle) +@@ -497,6 +497,11 @@ void STOP_SPINDLE_TURNING(int spindle, int /*wait_for_atspeed*/) _sai._spindle_turning[spindle] = CANON_STOPPED; } @@ -462,10 +357,10 @@ index c4703d40d8..4af879ae03 100644 {PRINT("SPINDLE_RETRACT()\n");} diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc -index 9f36a8de8e..f61e55bcfa 100644 +index d6e8437..2276d89 100644 --- a/src/emc/task/emccanon.cc +++ b/src/emc/task/emccanon.cc -@@ -3091,6 +3091,24 @@ void STOP_SPINDLE_TURNING(int s) +@@ -2933,6 +2933,24 @@ void STOP_SPINDLE_TURNING(int s, int wait_for_atspeed) canon.spindle[s].dir = 0; } @@ -490,807 +385,3 @@ index 9f36a8de8e..f61e55bcfa 100644 void SPINDLE_RETRACT() { /*! \todo FIXME-- unimplemented */ -diff --git a/tests/availability-mcodes-regressions/.gitignore b/tests/availability-mcodes-regressions/.gitignore -new file mode 100644 -index 0000000000..425d52b6e7 ---- /dev/null -+++ b/tests/availability-mcodes-regressions/.gitignore -@@ -0,0 +1,2 @@ -+/*.ini -+!/base.ini -diff --git a/tests/availability-mcodes-regressions/README b/tests/availability-mcodes-regressions/README -new file mode 100644 -index 0000000000..3be13a3d4a ---- /dev/null -+++ b/tests/availability-mcodes-regressions/README -@@ -0,0 +1,9 @@ -+M54/M55 production-path regressions using the runtime API regression fixture. -+The retained G95 case rejects a feed after M55 releases its spindle, then clears -+synchronization with G94. The paused-AUTO case advances an acquired M54 barrier -+using only Single Step. Select with AVAILABILITY_MCODE_REGRESSION_CASES. -+ -+INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local -+*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before -+launching an individual case directly. @unset explicitly removes an inherited -+key. Generated INIs are ignored; edit the base or the case override instead. -diff --git a/tests/availability-mcodes-regressions/checkresult b/tests/availability-mcodes-regressions/checkresult -new file mode 100755 -index 0000000000..14417ee80d ---- /dev/null -+++ b/tests/availability-mcodes-regressions/checkresult -@@ -0,0 +1,5 @@ -+#!/bin/sh -+set -eu -+for scenario in ${AVAILABILITY_MCODE_REGRESSION_CASES:-sync step}; do -+ grep -q "^availability M-code regression $scenario ok$" "$1" -+done -diff --git a/tests/availability-mcodes-regressions/step.ngc b/tests/availability-mcodes-regressions/step.ngc -new file mode 100644 -index 0000000000..a9bcd9e28d ---- /dev/null -+++ b/tests/availability-mcodes-regressions/step.ngc -@@ -0,0 +1,6 @@ -+M54 P1 -+G91 G0 Y1 -+M64 P0 -+G0 Y1 -+M64 P1 -+M2 -diff --git a/tests/availability-mcodes-regressions/test-ui.py b/tests/availability-mcodes-regressions/test-ui.py -new file mode 100755 -index 0000000000..1cf2f53b74 ---- /dev/null -+++ b/tests/availability-mcodes-regressions/test-ui.py -@@ -0,0 +1,74 @@ -+#!/usr/bin/env python3 -+import sys -+from pathlib import Path -+sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'runtime-availability-regressions')) -+from fixture import * -+ -+if case == 'sync': -+ acquire('spindle.0') -+ c.mode(linuxcnc.MODE_MDI); done() -+ c.mdi('S1000 G95 F1'); done() -+ c.mdi('M55 $0') -+ wait(lambda: not hal.get_value('spindle.0.availability-request'), 'M55 release') -+ pin('spindle.0.availability-ack', 0); done() -+ c.mdi('G1 X1') -+ result = c.wait_complete(2) -+ assert result == linuxcnc.RCS_ERROR, 'feed inherited unavailable spindle sync' -+ assert abs(hal.get_value('joint.0.pos-cmd')) < 1e-9 -+ c.abort(); done() -+ c.mdi('G94'); done() -+ c.mdi('G0 X1'); done() -+ wait(lambda: abs(s.joint_position[0] - 1) < 1e-6, -+ 'G94 did not allow unrelated motion') -+ -+elif case == 'step': -+ release('joint.1') -+ run('step.ngc') -+ wait(lambda: hal.get_value('joint.1.availability-request'), 'M54 ACK wait') -+ c.auto(linuxcnc.AUTO_PAUSE) -+ wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED, 'AUTO pause') -+ def held_at(position, output=False): -+ assert s.enabled and s.task_mode == linuxcnc.MODE_AUTO -+ assert abs(s.joint_position[1] - position) < 1e-6 -+ assert bool(hal.get_value('motion.digital-out-00')) == output -+ assert not hal.get_value('motion.digital-out-01'), 'later output escaped Single Step' -+ -+ # Pausing at the ACK barrier must block the move and both later outputs. -+ settle(.2) -+ held_at(0) -+ assert s.interp_state == linuxcnc.INTERP_PAUSED -+ assert not s.joint[1]['available'] -+ pin('joint.1.availability-ack', 1) -+ wait(lambda: s.joint[1]['available'], 'acquisition completion') -+ settle(.2) -+ held_at(0) -+ assert s.interp_state == linuxcnc.INTERP_PAUSED -+ -+ def step(): -+ c.auto(linuxcnc.AUTO_STEP) -+ serial = c.serial -+ wait(lambda: s.echo_serial_number >= serial, 'Single Step acknowledgement') -+ settle(.2) -+ -+ # The first step clears the completion/synchronization boundary only. -+ # The next canonical motion line is waiting; neither motion nor output -+ # may escape without another explicit step. -+ step() -+ held_at(0) -+ assert s.current_line == 2, 'Single Step did not reach the first motion boundary' -+ settle(.3) -+ held_at(0) -+ -+ # Immediate M64 output carries the preceding motion's canonical line id. -+ # Step that group, then prove the next move/output group is still blocked. -+ step() -+ wait(lambda: abs(s.joint_position[1] - 1) < 1e-6 -+ and hal.get_value('motion.digital-out-00'), 'stepped motion/output group') -+ held_at(1, True) -+ assert s.current_line == 4, 'Single Step did not stop at the next motion boundary' -+ settle(.3) -+ held_at(1, True) -+ -+else: -+ raise AssertionError(case) -+print(f'availability M-code regression {case} ok') -diff --git a/tests/availability-mcodes-regressions/test.ini.in b/tests/availability-mcodes-regressions/test.ini.in -new file mode 100644 -index 0000000000..bcbcb6c01d ---- /dev/null -+++ b/tests/availability-mcodes-regressions/test.ini.in -@@ -0,0 +1,9 @@ -+# Case-specific overrides; unspecified values come from FIXTURE.BASE. -+[FIXTURE] -+BASE = ../runtime-availability-regressions/base.ini -+ -+[HAL] -+HALFILE = ../runtime-availability-regressions/core.hal -+ -+[EMCIO] -+TOOL_TABLE = ../runtime-availability-regressions/tool.tbl -diff --git a/tests/availability-mcodes-regressions/test.sh b/tests/availability-mcodes-regressions/test.sh -new file mode 100755 -index 0000000000..5ed42c86b5 ---- /dev/null -+++ b/tests/availability-mcodes-regressions/test.sh -@@ -0,0 +1,6 @@ -+#!/bin/sh -+set -eu -+python3 ../runtime-availability/make-fixtures.py -+for scenario in ${AVAILABILITY_MCODE_REGRESSION_CASES:-sync step}; do -+ AVAILABILITY_REGRESSION_CASE=$scenario linuxcnc -r test.ini -+done -diff --git a/tests/availability-mcodes/.gitignore b/tests/availability-mcodes/.gitignore -new file mode 100644 -index 0000000000..425d52b6e7 ---- /dev/null -+++ b/tests/availability-mcodes/.gitignore -@@ -0,0 +1,2 @@ -+/*.ini -+!/base.ini -diff --git a/tests/availability-mcodes/README b/tests/availability-mcodes/README -new file mode 100644 -index 0000000000..a8a62f3415 ---- /dev/null -+++ b/tests/availability-mcodes/README -@@ -0,0 +1,9 @@ -+AUTO M54/M55 barriers: prior motion drains, ACK wait, held-position validation, -+required homing wait, release wait, and failure prevents continuation. -+Runs with interpolation rate 4 and releases the joint just moved, checking a fixed command and successful unrelated motion. Home All skips unavailable availability-controlled joints; any unhomed controlled joint is homed individually inside M54 before the program may continue. Invalid but syntactically representable selectors are passed through the interpreter and rejected against authoritative task topology. A second run confirms acquisition homing with forced homing disabled, then covers direct nonvolatile reacquisition. -+Abort in AUTO during ACK wait and moving acquisition homing terminates the program. Late ACK never enables the joint or executes the following block; a new program can reacquire and home. -+ -+INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local -+*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before -+launching an individual case directly. @unset explicitly removes an inherited -+key. Generated INIs are ignored; edit the base or the case override instead. -diff --git a/tests/availability-mcodes/checkresult b/tests/availability-mcodes/checkresult -new file mode 100755 -index 0000000000..1e0aa79240 ---- /dev/null -+++ b/tests/availability-mcodes/checkresult -@@ -0,0 +1,4 @@ -+#!/bin/sh -+set -e -+grep -q "^availability M-code scenarios ok$" "$1" -+grep -q "^availability without forced homing ok$" "$1" -diff --git a/tests/availability-mcodes/core_sim.hal b/tests/availability-mcodes/core_sim.hal -new file mode 120000 -index 0000000000..563a89b098 ---- /dev/null -+++ b/tests/availability-mcodes/core_sim.hal -@@ -0,0 +1 @@ -+../runtime-availability/core_sim.hal -\ No newline at end of file -diff --git a/tests/availability-mcodes/homing.ngc b/tests/availability-mcodes/homing.ngc -new file mode 100644 -index 0000000000..ca47f56f70 ---- /dev/null -+++ b/tests/availability-mcodes/homing.ngc -@@ -0,0 +1,4 @@ -+G90 G0 X4 -+M54 P2 -+G0 X5 -+M2 -diff --git a/tests/availability-mcodes/no-force.ini.in b/tests/availability-mcodes/no-force.ini.in -new file mode 100644 -index 0000000000..12b5b7a829 ---- /dev/null -+++ b/tests/availability-mcodes/no-force.ini.in -@@ -0,0 +1,6 @@ -+# Case-specific overrides; unspecified values come from FIXTURE.BASE. -+[FIXTURE] -+BASE = ../runtime-availability/base.ini -+ -+[TRAJ] -+NO_FORCE_HOMING = 1 -diff --git a/tests/availability-mcodes/ordered.ngc b/tests/availability-mcodes/ordered.ngc -new file mode 100644 -index 0000000000..a18005598f ---- /dev/null -+++ b/tests/availability-mcodes/ordered.ngc -@@ -0,0 +1,6 @@ -+G90 G0 X1 -+M54 P1 -+G91 G0 X1 Y1 -+M55 P1 -+G90 G0 X3 -+M2 -diff --git a/tests/availability-mcodes/test-ui.py b/tests/availability-mcodes/test-ui.py -new file mode 100755 -index 0000000000..6b827943b9 ---- /dev/null -+++ b/tests/availability-mcodes/test-ui.py -@@ -0,0 +1,142 @@ -+#!/usr/bin/env python3 -+import os -+import time -+import linuxcnc -+import hal -+h = hal.component('availability-mcode-test'); h.ready() -+c = linuxcnc.command(); s = linuxcnc.stat() -+def pin(n,v): hal.set_p(n,str(v)) -+def wait(fn, message): -+ end = time.monotonic()+10 -+ while time.monotonic() .1, 'AUTO homing motion') -+ c.abort() -+ wait(lambda: not hal.get_value('joint.2.availability-request'), 'AUTO abort output') -+ pin('joint.2.availability-ack', 0) -+ done(); idle() -+ assert abs(s.joint_position[0]-4)<.001, 'Abort continued after M54' -+ pin('joint.2.availability-ack', 1) -+ time.sleep(.05); s.poll() -+ assert not s.joint[2]['available'] -+ assert not hal.get_value('joint.2.amp-enable-out') -+ assert abs(s.joint_position[0]-4)<.001, 'late ACK resumed aborted program' -+ pin('joint.2.availability-ack', 0) -+ c.state(linuxcnc.STATE_OFF); c.wait_complete(3) -+ wait(lambda: s.exec_state == linuxcnc.EXEC_DONE, 'fault cleanup') -+ for n in (1, 2): -+ c.set_joint_availability(n, False); done() -+ c.state(linuxcnc.STATE_ON); done() -+ c.mode(linuxcnc.MODE_MANUAL); done() -+ c.home(0); done() -+ wait(lambda: s.homed[0], 'rehome X after abort cleanup') -+ c.mode(linuxcnc.MODE_AUTO); done() -+# The next fresh program can acquire and home successfully. -+run('homing.ngc') -+wait(lambda: hal.get_value('joint.2.availability-request'), 'M54 home request') -+pin('joint.2.availability-ack',1) -+for state, switch in [(7,1),(10,0),(12,1)]: -+ wait(lambda: hal.get_value('joint.2.home-state') == state, 'home phase') -+ assert abs(s.joint_position[0]-4)<.001, 'continued before homing finished' -+ assert not hal.get_value('joint.2.available') -+ pin('joint.2.home-sw-in',switch) -+done(); idle() -+assert s.joint[2]['available'] and abs(s.joint_position[0]-5)<.001 -+run('timeout.ngc') -+wait(lambda: s.spindle[0]['availability_fault'] != 0, 'timeout propagation') -+assert abs(s.joint_position[0]-6)<.001, 'continued after failed acquisition' -+print('availability M-code scenarios ok') -diff --git a/tests/availability-mcodes/test.ini b/tests/availability-mcodes/test.ini -new file mode 120000 -index 0000000000..800b1b7d98 ---- /dev/null -+++ b/tests/availability-mcodes/test.ini -@@ -0,0 +1 @@ -+../runtime-availability/base.ini -\ No newline at end of file -diff --git a/tests/availability-mcodes/test.sh b/tests/availability-mcodes/test.sh -new file mode 100755 -index 0000000000..882b151895 ---- /dev/null -+++ b/tests/availability-mcodes/test.sh -@@ -0,0 +1,5 @@ -+#!/bin/sh -+set -e -+python3 ../runtime-availability/make-fixtures.py -+linuxcnc -r test.ini -+AVAILABILITY_NO_FORCE=1 linuxcnc -r no-force.ini -diff --git a/tests/availability-mcodes/timeout.ngc b/tests/availability-mcodes/timeout.ngc -new file mode 100644 -index 0000000000..8a28c6f402 ---- /dev/null -+++ b/tests/availability-mcodes/timeout.ngc -@@ -0,0 +1,4 @@ -+G90 G0 X6 -+M54 $0 -+G0 X7 -+M2 -diff --git a/tests/availability-mcodes/tool.tbl b/tests/availability-mcodes/tool.tbl -new file mode 120000 -index 0000000000..37d2571593 ---- /dev/null -+++ b/tests/availability-mcodes/tool.tbl -@@ -0,0 +1 @@ -+../runtime-availability/tool.tbl -\ No newline at end of file -diff --git a/tests/availability-mcodes/unhomed.ngc b/tests/availability-mcodes/unhomed.ngc -new file mode 100644 -index 0000000000..e5728900ed ---- /dev/null -+++ b/tests/availability-mcodes/unhomed.ngc -@@ -0,0 +1,4 @@ -+G90 G0 X1 -+M54 P1 -+G0 Y10 -+M2 -diff --git a/tests/interp/availability-mcodes/README b/tests/interp/availability-mcodes/README -new file mode 100644 -index 0000000000..6054ffdd70 ---- /dev/null -+++ b/tests/interp/availability-mcodes/README -@@ -0,0 +1,6 @@ -+Exercise the native M54/M55 joint and spindle selectors, generic standalone -+block validation, and interpreter checks limited to selector representation. -+Configured resource topology is deliberately left to task and motion. -+ -+Execute-status coverage checks zero queue-buster returns for legacy M54/M55 -+remaps and two for each built-in acquire/release program. Requires a built RIP tree. -diff --git a/tests/interp/availability-mcodes/bad-joint.ngc b/tests/interp/availability-mcodes/bad-joint.ngc -new file mode 100644 -index 0000000000..da0115cfed ---- /dev/null -+++ b/tests/interp/availability-mcodes/bad-joint.ngc -@@ -0,0 +1,2 @@ -+M54 P999999999999999 -+M2 -diff --git a/tests/interp/availability-mcodes/double-selector.ngc b/tests/interp/availability-mcodes/double-selector.ngc -new file mode 100644 -index 0000000000..a851ea0278 ---- /dev/null -+++ b/tests/interp/availability-mcodes/double-selector.ngc -@@ -0,0 +1,2 @@ -+M54 P2 $0 -+M2 -diff --git a/tests/interp/availability-mcodes/execute-status.cc b/tests/interp/availability-mcodes/execute-status.cc -new file mode 100644 -index 0000000000..554485e05a ---- /dev/null -+++ b/tests/interp/availability-mcodes/execute-status.cc -@@ -0,0 +1,26 @@ -+#include "rs274ngc.hh" -+#include "interp_return.hh" -+#include -+#include -+int _task = 0; -+InterpBase *pinterp; -+int main(int argc, char **argv) { -+ assert(argc == 4); -+ setenv("INI_FILE_NAME", argv[1], 1); -+ auto interp = pinterp = makeInterp(); -+ assert(interp->init() == INTERP_OK); -+ assert(interp->open(argv[2]) == INTERP_OK); -+ int finishes = 0; -+ for (int n = 0; n < 100; n++) { -+ int read = interp->read(); -+ assert(read == INTERP_OK); -+ int result = interp->execute(); -+ if (result == INTERP_EXIT) { -+ assert(finishes == atoi(argv[3])); -+ return 0; -+ } -+ assert(result == INTERP_OK || result == INTERP_EXECUTE_FINISH); -+ if (result == INTERP_EXECUTE_FINISH) finishes++; -+ } -+ abort(); -+} -diff --git a/tests/interp/availability-mcodes/execute-status.py b/tests/interp/availability-mcodes/execute-status.py -new file mode 100644 -index 0000000000..145e48201c ---- /dev/null -+++ b/tests/interp/availability-mcodes/execute-status.py -@@ -0,0 +1,30 @@ -+#!/usr/bin/env python3 -+"""Check actual execute return codes using the production interpreter/canon.""" -+import os -+from pathlib import Path -+import subprocess -+import tempfile -+root = Path(os.environ.get('LINUXCNC_TEST_ROOT', Path(__file__).resolve().parents[3])) -+with tempfile.TemporaryDirectory() as directory: -+ binary = str(Path(directory) / 'execute-status') -+ objects = root / 'src/objects/emc' -+ command = [os.environ.get('CXX', 'c++'), 'execute-status.cc', -+ '-I' + str(root / 'include'), -+ '-I' + str(root / 'src'), -+ '-I' + str(root / 'src/emc'), -+ '-I' + str(root / 'src/emc/nml_intf'), -+ '-I' + str(root / 'src/emc/rs274ngc'), -+ str(objects / 'sai/saicanon.o'), -+ str(objects / 'sai/dummyemcstat.o'), -+ str(objects / 'task/taskclass.o'), -+ '-L' + str(root / 'lib'), '-Wl,-rpath,' + str(root / 'lib'), -+ '-lrs274', '-llinuxcnc', '-lnml', '-llinuxcnchal', -+ '-llinuxcncini', '-lpyplugin', '-ltooldata'] -+ command += subprocess.check_output(['python3-config', '--embed', '--ldflags'], text=True).split() -+ subprocess.run(command + ['-o', binary], check=True) -+ for ini, program, finishes in [('remap.ini', 'remapped.ngc', '0'), -+ ('test.ini', 'valid-joint.ngc', '2'), -+ ('test.ini', 'valid-spindle.ngc', '2')]: -+ result = subprocess.run([binary, ini, program, finishes], capture_output=True, text=True) -+ if result.returncode: -+ raise AssertionError(f'{ini} {program}: {result.returncode}\n{result.stdout}\n{result.stderr}') -diff --git a/tests/interp/availability-mcodes/expected b/tests/interp/availability-mcodes/expected -new file mode 100644 -index 0000000000..e69de29bb2 -diff --git a/tests/interp/availability-mcodes/fractional-joint.ngc b/tests/interp/availability-mcodes/fractional-joint.ngc -new file mode 100644 -index 0000000000..e5488fbd9a ---- /dev/null -+++ b/tests/interp/availability-mcodes/fractional-joint.ngc -@@ -0,0 +1,2 @@ -+M54 P2.5 -+M2 -diff --git a/tests/interp/availability-mcodes/fractional-spindle.ngc b/tests/interp/availability-mcodes/fractional-spindle.ngc -new file mode 100644 -index 0000000000..26ff05c8a0 ---- /dev/null -+++ b/tests/interp/availability-mcodes/fractional-spindle.ngc -@@ -0,0 +1,2 @@ -+M54 $0.5 -+M2 -diff --git a/tests/interp/availability-mcodes/group-spindle.ngc b/tests/interp/availability-mcodes/group-spindle.ngc -new file mode 100644 -index 0000000000..3b2f3fbbe7 ---- /dev/null -+++ b/tests/interp/availability-mcodes/group-spindle.ngc -@@ -0,0 +1,2 @@ -+M54 $-1 -+M2 -diff --git a/tests/interp/availability-mcodes/huge-spindle.ngc b/tests/interp/availability-mcodes/huge-spindle.ngc -new file mode 100644 -index 0000000000..584fa3b719 ---- /dev/null -+++ b/tests/interp/availability-mcodes/huge-spindle.ngc -@@ -0,0 +1,2 @@ -+M54 $999999999999 -+M2 -diff --git a/tests/interp/availability-mcodes/legacy54.ngc b/tests/interp/availability-mcodes/legacy54.ngc -new file mode 100644 -index 0000000000..6947d8a6fb ---- /dev/null -+++ b/tests/interp/availability-mcodes/legacy54.ngc -@@ -0,0 +1,5 @@ -+o sub -+(msg, legacy M54 override) -+# = # -+o endsub -+M2 -diff --git a/tests/interp/availability-mcodes/legacy55.ngc b/tests/interp/availability-mcodes/legacy55.ngc -new file mode 100644 -index 0000000000..c48d1b9de1 ---- /dev/null -+++ b/tests/interp/availability-mcodes/legacy55.ngc -@@ -0,0 +1,5 @@ -+o sub -+(msg, legacy M55 override) -+# = # -+o endsub -+M2 -diff --git a/tests/interp/availability-mcodes/missing-selector.ngc b/tests/interp/availability-mcodes/missing-selector.ngc -new file mode 100644 -index 0000000000..96cb26cf60 ---- /dev/null -+++ b/tests/interp/availability-mcodes/missing-selector.ngc -@@ -0,0 +1,2 @@ -+M54 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-feed.ngc b/tests/interp/availability-mcodes/mixed-feed.ngc -new file mode 100644 -index 0000000000..1a45e38e18 ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-feed.ngc -@@ -0,0 +1,2 @@ -+M54 P2 F10 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-modal.ngc b/tests/interp/availability-mcodes/mixed-modal.ngc -new file mode 100644 -index 0000000000..dd567c47f0 ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-modal.ngc -@@ -0,0 +1,2 @@ -+M54 P2 G91 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-motion.ngc b/tests/interp/availability-mcodes/mixed-motion.ngc -new file mode 100644 -index 0000000000..a52d2d4fd1 ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-motion.ngc -@@ -0,0 +1,2 @@ -+M54 P0 G0 X10 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-parameter.ngc b/tests/interp/availability-mcodes/mixed-parameter.ngc -new file mode 100644 -index 0000000000..1054e7e0aa ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-parameter.ngc -@@ -0,0 +1,2 @@ -+M54 P2 #100=7 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-polar.ngc b/tests/interp/availability-mcodes/mixed-polar.ngc -new file mode 100644 -index 0000000000..1d22b22856 ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-polar.ngc -@@ -0,0 +1,2 @@ -+M54 P2 @1 ^45 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-speed.ngc b/tests/interp/availability-mcodes/mixed-speed.ngc -new file mode 100644 -index 0000000000..1cf09ae478 ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-speed.ngc -@@ -0,0 +1,2 @@ -+M54 P2 S500 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-stop.ngc b/tests/interp/availability-mcodes/mixed-stop.ngc -new file mode 100644 -index 0000000000..8fd4be9598 ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-stop.ngc -@@ -0,0 +1,2 @@ -+M55 $0 M2 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-tool.ngc b/tests/interp/availability-mcodes/mixed-tool.ngc -new file mode 100644 -index 0000000000..6fc9e05d67 ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-tool.ngc -@@ -0,0 +1,2 @@ -+M54 P2 T1 -+M2 -diff --git a/tests/interp/availability-mcodes/mixed-word.ngc b/tests/interp/availability-mcodes/mixed-word.ngc -new file mode 100644 -index 0000000000..37e7a2e4cb ---- /dev/null -+++ b/tests/interp/availability-mcodes/mixed-word.ngc -@@ -0,0 +1,2 @@ -+M55 P2 Q1 -+M2 -diff --git a/tests/interp/availability-mcodes/negative-fractional-spindle.ngc b/tests/interp/availability-mcodes/negative-fractional-spindle.ngc -new file mode 100644 -index 0000000000..5153e911bc ---- /dev/null -+++ b/tests/interp/availability-mcodes/negative-fractional-spindle.ngc -@@ -0,0 +1,2 @@ -+M54 $-0.5 -+M2 -diff --git a/tests/interp/availability-mcodes/negative-joint.ngc b/tests/interp/availability-mcodes/negative-joint.ngc -new file mode 100644 -index 0000000000..dea8ef76e6 ---- /dev/null -+++ b/tests/interp/availability-mcodes/negative-joint.ngc -@@ -0,0 +1,2 @@ -+M55 P-1 -+M2 -diff --git a/tests/interp/availability-mcodes/remap.ini b/tests/interp/availability-mcodes/remap.ini -new file mode 100644 -index 0000000000..3a6b2030f2 ---- /dev/null -+++ b/tests/interp/availability-mcodes/remap.ini -@@ -0,0 +1,5 @@ -+[RS274NGC] -+PARAMETER_FILE = linuxcnc.var -+SUBROUTINE_PATH = . -+REMAP=M54 modalgroup=9 argspec=Q ngc=legacy54 -+REMAP=M55 modalgroup=9 argspec=Q ngc=legacy55 -diff --git a/tests/interp/availability-mcodes/remapped.ngc b/tests/interp/availability-mcodes/remapped.ngc -new file mode 100644 -index 0000000000..2412206345 ---- /dev/null -+++ b/tests/interp/availability-mcodes/remapped.ngc -@@ -0,0 +1,3 @@ -+M54 Q12 -+M55 Q34 -+M2 -diff --git a/tests/interp/availability-mcodes/test.ini b/tests/interp/availability-mcodes/test.ini -new file mode 100644 -index 0000000000..03afbfaa99 ---- /dev/null -+++ b/tests/interp/availability-mcodes/test.ini -@@ -0,0 +1,2 @@ -+[RS274NGC] -+PARAMETER_FILE = linuxcnc.var -diff --git a/tests/interp/availability-mcodes/test.sh b/tests/interp/availability-mcodes/test.sh -new file mode 100755 -index 0000000000..c61548a3fd ---- /dev/null -+++ b/tests/interp/availability-mcodes/test.sh -@@ -0,0 +1,80 @@ -+#!/bin/bash -+set -e -+ -+output_dir=$(mktemp -d) -+trap 'rm -rf "$output_dir"' EXIT -+ -+check_valid() { -+ program=$1 -+ kind=$2 -+ selector=$3 -+ if ! rs274 -n 0 -i test.ini -g "$program" >"$output_dir/canon" 2>"$output_dir/diagnostics"; then -+ cat "$output_dir/diagnostics" >&2 -+ exit 1 -+ fi -+ # rs274 can return zero on interpreter errors. Only its normal startup -+ # message is permitted on stderr; also verify every resource operation. -+ sed '/^executing$/d; /^[[:space:]]*$/d' "$output_dir/diagnostics" >"$output_dir/errors" -+ if test -s "$output_dir/errors"; then -+ cat "$output_dir/errors" >&2 -+ exit 1 -+ fi -+ sed -nE 's/^[[:space:]]*[0-9]+[[:space:]]+N[^[:space:]]+[[:space:]]+(SET_(JOINT|SPINDLE)_AVAILABILITY\(.*\))$/\1/p' \ -+ "$output_dir/canon" >"$output_dir/actual" -+ printf 'SET_%s_AVAILABILITY(%s, 1)\nSET_%s_AVAILABILITY(%s, 0)\n' \ -+ "$kind" "$selector" "$kind" "$selector" >"$output_dir/expected" -+ diff -u "$output_dir/expected" "$output_dir/actual" -+} -+check_valid valid-joint.ngc JOINT 99 -+check_valid valid-spindle.ngc SPINDLE 99 -+ -+check_rejected() { -+ program=$1 -+ expected=$2 -+ output=$(rs274 -n 0 -i test.ini -g "$program" 2>&1) || : -+ case "$output" in -+ *"$expected"*) ;; -+ *) -+ echo "expected $program to report: $expected" >&2 -+ echo "$output" >&2 -+ exit 1 -+ ;; -+ esac -+} -+ -+check_rejected missing-selector.ngc "requires exactly one P joint selector or $ spindle selector" -+check_rejected double-selector.ngc "requires exactly one P joint selector or $ spindle selector" -+check_rejected fractional-joint.ngc "P selector must be a non-negative integer joint number" -+check_rejected group-spindle.ngc '$ selector must be a non-negative integer spindle number' -+check_rejected mixed-motion.ngc "must be the only command in its block" -+check_rejected mixed-stop.ngc "must be the only command in its block" -+check_rejected mixed-feed.ngc "must be the only command in its block" -+check_rejected mixed-speed.ngc "must be the only command in its block" -+check_rejected mixed-modal.ngc "must be the only command in its block" -+check_rejected mixed-tool.ngc "must be the only command in its block" -+check_rejected mixed-polar.ngc "Cannot use axis values without a g code that uses them" -+check_rejected mixed-parameter.ngc "must be the only command in its block" -+check_rejected mixed-word.ngc "must be the only command in its block" -+check_rejected bad-joint.ngc "P selector must be a non-negative integer joint number" -+check_rejected negative-joint.ngc "P selector must be a non-negative integer joint number" -+ -+check_rejected fractional-spindle.ngc '$ selector must be a non-negative integer spindle number' -+check_rejected negative-fractional-spindle.ngc '$ selector must be a non-negative integer spindle number' -+check_rejected huge-spindle.ngc '$ selector must be a non-negative integer spindle number' -+ -+# Legacy remaps accept their own words without built-in resource selectors. -+rs274 -n 0 -i remap.ini -g remapped.ngc >"$output_dir/remap" 2>"$output_dir/diagnostics" -+sed '/^executing$/d; /^[[:space:]]*$/d' "$output_dir/diagnostics" >"$output_dir/errors" -+if test -s "$output_dir/errors"; then -+ cat "$output_dir/errors" >&2 -+ exit 1 -+fi -+grep -q 'MESSAGE(" legacy M54 override")' "$output_dir/remap" -+grep -q 'MESSAGE(" legacy M55 override")' "$output_dir/remap" -+if grep -q 'SET_.*_AVAILABILITY' "$output_dir/remap"; then -+ cat "$output_dir/remap" >&2 -+ exit 1 -+fi -+ -+# Remaps must not inherit the built-in interpreter synchronization return. -+python3 execute-status.py -diff --git a/tests/interp/availability-mcodes/valid-joint.ngc b/tests/interp/availability-mcodes/valid-joint.ngc -new file mode 100644 -index 0000000000..d697df4d37 ---- /dev/null -+++ b/tests/interp/availability-mcodes/valid-joint.ngc -@@ -0,0 +1,3 @@ -+N10 M54 P99 (joint resource) -+N20 M55 P99 ; release -+M2 -diff --git a/tests/interp/availability-mcodes/valid-spindle.ngc b/tests/interp/availability-mcodes/valid-spindle.ngc -new file mode 100644 -index 0000000000..10632c2188 ---- /dev/null -+++ b/tests/interp/availability-mcodes/valid-spindle.ngc -@@ -0,0 +1,3 @@ -+M54 $99 -+M55 $99 -+M2 diff --git a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch index f6603e46..aa731f45 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -3,31 +3,31 @@ From: Dariusz Majnert Date: Sun, 20 Sep 2026 00:52:14 +0200 Subject: [PATCH] motion: allow concurrent individual joint homing +Differences on pre2: upstream's bounded homing moves return a joint to +the start of its move through the joints of the running sequence, which +an independent home is not part of; home_return_group() treats an +independently homed joint as its own group so its return completes and +leaves other homes alone. homecomp.comp gains the matching changes in its +skeleton and custom variants and exports get_home_sequence_is_active(), +which motmod requires. Upstream's aggregate homing_active status carries +the "active until the last joint finishes" flag to task, so a G28.2 Pn +now waits for all concurrent homes. Availability acquisition issues its +home through task's queued G28.2 path; it cannot start while any homing +is active and blocks other HOME requests while in progress, as before, +so the new concurrency checks never refuse it. --- - src/emc/motion/command.c | 12 +- - src/emc/motion/control.c | 19 +-- - src/emc/motion/homing.c | 109 +++++++------- - src/emc/motion/homing.h | 1 + - src/hal/components/homecomp.comp | 21 +-- - tests/homing-concurrent/checkresult | 3 + - tests/homing-concurrent/homing.hal | 14 ++ - tests/homing-concurrent/test-ui.py | 217 ++++++++++++++++++++++++++++ - tests/homing-concurrent/test.ini | 133 +++++++++++++++++ - tests/homing-concurrent/test.sh | 4 + - tests/homing-concurrent/tool.tbl | 0 - 11 files changed, 449 insertions(+), 84 deletions(-) - create mode 100755 tests/homing-concurrent/checkresult - create mode 100644 tests/homing-concurrent/homing.hal - create mode 100755 tests/homing-concurrent/test-ui.py - create mode 100644 tests/homing-concurrent/test.ini - create mode 100755 tests/homing-concurrent/test.sh - create mode 100644 tests/homing-concurrent/tool.tbl + src/emc/motion/command.c | 23 +++++- + src/emc/motion/control.c | 19 ++--- + src/emc/motion/homing.c | 131 +++++++++++++++++-------------- + src/emc/motion/homing.h | 7 ++ + src/hal/components/homecomp.comp | 17 ++-- + 5 files changed, 119 insertions(+), 78 deletions(-) diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index a18acd066f..f4fd73b31b 100644 +index 072bb70..b96b098 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -1596,8 +1596,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1756,10 +1756,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) joint_num); return; } @@ -45,12 +45,25 @@ index a18acd066f..f4fd73b31b 100644 + emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; return; } ++ /* A shared home switch (or a limit used as home) can be tripped ++ by another joint homing at the same time. */ ++ for (int n = 0; joint_num >= 0 && n < ALL_JOINTS; n++) { ++ if (n != joint_num && !get_home_is_idle(n) && ++ (get_home_is_exclusive(joint_num) || get_home_is_exclusive(n))) { ++ reportError(_("Cannot home joint %d while joint %d is homing (shared home or limit switch)"), ++ joint_num, n); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ return; ++ } ++ } if (!GET_MOTION_ENABLE_FLAG()) { + break; + } diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 722c58545d..a3e7a3b776 100644 +index 7f55169..c75c227 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2625,18 +2625,13 @@ static void update_status(void) +@@ -2742,18 +2742,13 @@ static void update_status(void) } #endif joint_status->flag = joint->flag; @@ -77,7 +90,7 @@ index 722c58545d..a3e7a3b776 100644 joint_status->homed = get_homed(joint_num); joint_status->pos_cmd = joint->pos_cmd; diff --git a/src/emc/motion/homing.c b/src/emc/motion/homing.c -index 13c5e6b513..2611ee8f0e 100644 +index a2b6c9b..9f36e71 100644 --- a/src/emc/motion/homing.c +++ b/src/emc/motion/homing.c @@ -64,7 +64,6 @@ void homeMotFunctions(void(*pSetRotaryUnlock)(int,int) @@ -88,7 +101,45 @@ index 13c5e6b513..2611ee8f0e 100644 HOME_SEQUENCE_DO_ONE_SEQUENCE, // valid start state HOME_SEQUENCE_START_JOINTS, // internal usage HOME_SEQUENCE_WAIT_JOINTS, // internal usage -@@ -260,6 +259,7 @@ static void do_home_all(void) +@@ -188,6 +187,13 @@ static void home_start_move(int joint_num, double vel, double dist) + joint->free_tp.enable = 1; + } // home_start_move() + ++/* An individually homed joint is not in the sequence and forms its own ++ group, so its return leaves other independently homing joints alone. */ ++static bool home_return_group(int jno, int i) ++{ ++ return H[jno].joint_in_sequence ? H[i].joint_in_sequence : i == jno; ++} ++ + /* 'home_return()' is called when a move bounded by HOME_LATCH_DIST ran + its full length without finding what it was looking for. Every joint + of the sequence stops; the joint and the joints synchronized with it +@@ -200,7 +206,7 @@ static void home_return(int jno) + int i; + + for (i = 0; i < all_joints; i++) { +- if (!H[i].joint_in_sequence) { continue; } ++ if (!home_return_group(jno, i)) { continue; } + if (H[i].home_state == HOME_IDLE) { continue; } + joints[i].free_tp.enable = 0; + if ( i == jno +@@ -215,12 +221,12 @@ static void home_return(int jno) + } // home_return() + + /* true once no joint of the sequence has a return move pending */ +-static bool home_returns_done(void) ++static bool home_returns_done(int jno) + { + int i; + + for (i = 0; i < all_joints; i++) { +- if (!H[i].joint_in_sequence) { continue; } ++ if (!home_return_group(jno, i)) { continue; } + if (H[i].home_state == HOME_RETURN_START) { return 0; } + if (H[i].home_state == HOME_RETURN_WAIT && joints[i].free_tp.active) { return 0; } + } +@@ -343,6 +349,7 @@ static void do_home_all(void) { if (!get_homing_is_active() ) { sequence_state = HOME_SEQUENCE_START; @@ -96,7 +147,7 @@ index 13c5e6b513..2611ee8f0e 100644 } } // do_home_all() -@@ -276,9 +276,11 @@ static void do_home_one_joint(int jno) +@@ -359,9 +366,11 @@ static void do_home_one_joint(int jno) } } } else { @@ -110,7 +161,7 @@ index 13c5e6b513..2611ee8f0e 100644 } // do_home_one_joint() static void set_all_unhomed(int unhome_method, motion_state_t motstate) -@@ -340,19 +342,6 @@ static void do_homing_sequence(void) +@@ -423,19 +432,6 @@ static void do_homing_sequence(void) /* nothing to do */ break; @@ -130,7 +181,7 @@ index 13c5e6b513..2611ee8f0e 100644 case HOME_SEQUENCE_DO_ONE_SEQUENCE: // Expect multiple joints with home_state==HOME_START // specified by a negative sequence -@@ -428,8 +417,6 @@ static void do_homing_sequence(void) +@@ -511,8 +507,6 @@ static void do_homing_sequence(void) return; } } @@ -139,7 +190,7 @@ index 13c5e6b513..2611ee8f0e 100644 /* Fallthrough */ case HOME_SEQUENCE_START_JOINTS: -@@ -450,8 +437,6 @@ static void do_homing_sequence(void) +@@ -533,8 +527,6 @@ static void do_homing_sequence(void) } else { /* no joints have this sequence number, we're done */ sequence_state = HOME_SEQUENCE_IDLE; @@ -148,7 +199,7 @@ index 13c5e6b513..2611ee8f0e 100644 } break; -@@ -482,7 +467,6 @@ static void do_homing_sequence(void) +@@ -565,7 +557,6 @@ static void do_homing_sequence(void) rtapi_print_msg(RTAPI_MSG_ERR, _("unknown state '%d' during homing sequence"), sequence_state); sequence_state = HOME_SEQUENCE_IDLE; @@ -156,11 +207,11 @@ index 13c5e6b513..2611ee8f0e 100644 break; } } // do_homing_sequence() -@@ -543,20 +527,12 @@ static void base_write_homing_out_pins(int njoints) +@@ -628,18 +619,11 @@ static void base_write_homing_out_pins(int njoints) one_joint_home_data_t *addr; for (jno = 0; jno < njoints; jno++) { addr = &(joint_home_data->jhd[jno]); -- if(!(*(addr->homing) && !H[jno].homing && homing_active)) { +- if(!(hal_get_bool(addr->homing) && !H[jno].homing && homing_active)) { - // Prevent race condition. - // (See also emc/motion/control.c: update_status()) - // The homing status variable turns false before homing_active state @@ -171,18 +222,16 @@ index 13c5e6b513..2611ee8f0e 100644 - // Do not update the homing status when going from homing --> not homing - // and the state machine is still active. The homing status deassertion - // must be delayed until the state machine is done. -- *(addr->homing) = H[jno].homing; -+ if (!(*(addr->homing) && !H[jno].homing && +- hal_set_bool(addr->homing, H[jno].homing); ++ if (!(hal_get_bool(addr->homing) && !H[jno].homing && + sequence_state != HOME_SEQUENCE_IDLE)) { + // Match the NML status completion gate: a sequence remains busy + // until it has observed that its joints finished. -+ *(addr->homing) = H[jno].homing; // OUT ++ hal_set_bool(addr->homing, H[jno].homing); // OUT } -- *(addr->homing) = H[jno].homing; // OUT - *(addr->homed) = H[jno].homed; // OUT - *(addr->home_state) = H[jno].home_state; // OUT - *(addr->index_enable) = H[jno].index_enable; // IO -@@ -573,9 +549,7 @@ static void base_do_home_joint(int jno) { + hal_set_bool(addr->homed, H[jno].homed); // OUT + hal_set_sint(addr->home_state, H[jno].home_state); // OUT +@@ -666,9 +650,7 @@ static void base_do_home_joint(int jno) { } static void base_do_cancel_homing(int jno) { @@ -193,7 +242,7 @@ index 13c5e6b513..2611ee8f0e 100644 H[jno].home_state = HOME_ABORT; } } -@@ -674,6 +648,10 @@ static bool base_get_homing_is_active(void) { +@@ -771,6 +753,10 @@ static bool base_get_homing_is_active(void) { return homing_active; } @@ -204,8 +253,31 @@ index 13c5e6b513..2611ee8f0e 100644 static int base_get_home_sequence(int jno) { return H[jno].home_sequence; } -@@ -1374,17 +1352,24 @@ static int base_1joint_state_machine(int joint_num) - H[joint_num].joint_in_sequence = 0; +@@ -791,6 +777,14 @@ static bool base_get_home_needs_unlock_first(int jno) { + return (H[jno].home_flags & HOME_UNLOCK_FIRST) ? 1 : 0; + } + ++static bool base_get_home_is_exclusive(int jno) { ++ // a shared home switch, or a limit switch used as the home switch ++ // (possibly wired in series with other joints' limits), can be ++ // tripped by another joint that is homing at the same time ++ if (H[jno].home_flags & HOME_ABSOLUTE_ENCODER) { return 0; } ++ return (H[jno].home_flags & (HOME_IS_SHARED | HOME_IGNORE_LIMITS)) ? 1 : 0; ++} ++ + static bool base_get_home_is_idle(int jno) { + return H[jno].home_state == HOME_IDLE ? 1 : 0; + } +@@ -1512,15 +1506,21 @@ static int base_1joint_state_machine(int joint_num) + break; + } + joint->free_tp.enable = 0; +- if (!home_returns_done()) { ++ if (!home_returns_done(joint_num)) { + break; + } + H[joint_num].home_state = HOME_ABORT; + immediate_state = 1; break; - case HOME_ABORT: @@ -221,10 +293,7 @@ index 13c5e6b513..2611ee8f0e 100644 H[i].homing = 0; H[i].homed = 0; H[i].joint_in_sequence = 0; -- joint[i].free_tp.enable = 0; -+ joints[i].free_tp.enable = 0; - H[i].home_state = HOME_IDLE; - H[i].index_enable = 0; +@@ -1530,6 +1530,7 @@ static int base_1joint_state_machine(int joint_num) } immediate_state = 1; break; @@ -232,7 +301,7 @@ index 13c5e6b513..2611ee8f0e 100644 default: /* should never get here */ -@@ -1399,31 +1384,43 @@ static int base_1joint_state_machine(int joint_num) +@@ -1544,31 +1545,43 @@ static int base_1joint_state_machine(int joint_num) return homing_flag; } // base_1joint_state_machine() @@ -291,7 +360,15 @@ index 13c5e6b513..2611ee8f0e 100644 } // base_do_homing() /*********************************************************************** -@@ -1461,6 +1458,7 @@ int get_home_sequence(int jno) { return base_get_home_sequence(jno); +@@ -1599,6 +1612,7 @@ int homing_init(int id, + bool do_homing(void) { return base_do_homing(); } + bool get_allhomed(void) { return base_get_allhomed(); } + bool get_homed(int jno) { return base_get_homed(jno); } ++bool get_home_is_exclusive(int jno) { return base_get_home_is_exclusive(jno); } + bool get_home_is_idle(int jno) { return base_get_home_is_idle(jno); } + bool get_home_is_synchronized(int jno) { return base_get_home_is_synchronized(jno); } + bool get_home_needs_unlock_first(int jno) { return base_get_home_needs_unlock_first(jno); } +@@ -1606,6 +1620,7 @@ int get_home_sequence(int jno) { return base_get_home_sequence(jno); bool get_homing(int jno) { return base_get_homing(jno); } bool get_homing_at_index_search_wait(int jno) { return base_get_homing_at_index_search_wait(jno); } bool get_homing_is_active(void) { return base_get_homing_is_active(); } @@ -299,7 +376,15 @@ index 13c5e6b513..2611ee8f0e 100644 bool get_index_enable(int jno) { return base_get_index_enable(jno); } void read_homing_in_pins(int njoints) { base_read_homing_in_pins(njoints); } -@@ -1515,6 +1513,7 @@ EXPORT_SYMBOL(get_home_sequence); +@@ -1657,6 +1672,7 @@ EXPORT_SYMBOL(homing_init); + EXPORT_SYMBOL(do_homing); + EXPORT_SYMBOL(get_allhomed); + EXPORT_SYMBOL(get_homed); ++EXPORT_SYMBOL(get_home_is_exclusive); + EXPORT_SYMBOL(get_home_is_idle); + EXPORT_SYMBOL(get_home_is_synchronized); + EXPORT_SYMBOL(get_home_needs_unlock_first); +@@ -1664,6 +1680,7 @@ EXPORT_SYMBOL(get_home_sequence); EXPORT_SYMBOL(get_homing); EXPORT_SYMBOL(get_homing_at_index_search_wait); EXPORT_SYMBOL(get_homing_is_active); @@ -308,477 +393,107 @@ index 13c5e6b513..2611ee8f0e 100644 EXPORT_SYMBOL(read_homing_in_pins); EXPORT_SYMBOL(do_home_joint); diff --git a/src/emc/motion/homing.h b/src/emc/motion/homing.h -index 0c4869de6d..409ca2547e 100644 +index af883eb..feea75c 100644 --- a/src/emc/motion/homing.h +++ b/src/emc/motion/homing.h -@@ -63,6 +63,7 @@ void set_unhomed(int jno,motion_state_t motstate); - // overall status: - bool get_allhomed(void); +@@ -98,6 +98,9 @@ bool get_allhomed(void); + // get_homing_is_active(): true while any homing sequence or per-joint + // homing state machine is in progress. bool get_homing_is_active(void); ++// get_home_sequence_is_active(): true while the HOME ALL / HOME_SEQUENCE ++// controller is running; individual joint homes do not use it. +bool get_home_sequence_is_active(void); // per-joint information: int get_home_sequence(int jno); //return s +@@ -111,6 +114,10 @@ bool get_index_enable(int jno); + // get_home_needs_unlock_first(): joint jno has HOME_UNLOCK_FIRST set + // (rotary axis must be unlocked before homing). + bool get_home_needs_unlock_first(int jno); ++// get_home_is_exclusive(): joint jno must not home while any other ++// joint is homing independently (HOME_IS_SHARED or HOME_IGNORE_LIMITS: ++// its home input may be tripped by another joint). ++bool get_home_is_exclusive(int jno); + // get_home_is_idle(): joint jno's homing state machine is HOME_IDLE. + bool get_home_is_idle(int jno); + // get_home_is_synchronized(): joint jno homes synchronized with other diff --git a/src/hal/components/homecomp.comp b/src/hal/components/homecomp.comp -index 79c4691787..74025d5e07 100644 +index 9096469..ea04e05 100644 --- a/src/hal/components/homecomp.comp +++ b/src/hal/components/homecomp.comp -@@ -258,34 +258,23 @@ void write_homing_out_pins(int njoints) +@@ -233,6 +233,7 @@ bool do_homing(void) + return completed; + } + ++bool get_home_is_exclusive(int jno) { (void)jno; return 0; } + bool get_home_is_idle(int jno) { (void)jno; return 1; } + bool get_home_is_synchronized(int jno) { (void)jno; return 0; } + bool get_home_needs_unlock_first(int jno) { (void)jno; return 0; } +@@ -240,6 +241,7 @@ int get_home_sequence(int jno) { (void)jno; return 0; } + bool get_homing(int jno) { (void)jno; return 0; } + bool get_homing_at_index_search_wait(int jno) { (void)jno; return 0; } + bool get_homing_is_active(void) { return 0; } ++bool get_home_sequence_is_active(void) { return 0; } + bool get_index_enable(int jno) { (void)jno; return 0; } + + void read_homing_in_pins(int njoints) { rd(njoints); } +@@ -343,12 +345,12 @@ void write_homing_out_pins(int njoints) + bool do_homing(void) { - int joint_num; -- int homing_flag = 0; - bool beginning_allhomed = get_allhomed(); - +- int jno, busy = 0; ++ int jno; + bool begin_all = base_get_allhomed(); + (void)base_do_homing; // replaced by this custom do_homing() do_homing_sequence(); - /* loop thru joints, treat each one individually */ - for (joint_num = 0; joint_num < all_joints; joint_num++) { -- if (!H[joint_num].joint_in_sequence) { continue; } -+ if (H[joint_num].home_state == HOME_IDLE) { continue; } - if (!GET_JOINT_ACTIVE_FLAG(&joints[joint_num])) { continue; } - - if (customH[joint_num].is_custom_homing) { - // CUSTOM joint homing state machine: -- homing_flag += custom_1joint_state_machine(joint_num); -+ custom_1joint_state_machine(joint_num); + for (jno = 0; jno < all_joints; jno++) { +- if (!H[jno].joint_in_sequence) continue; ++ if (H[jno].home_state == HOME_IDLE) continue; + if (!GET_JOINT_ACTIVE_FLAG(&joints[jno])) continue; + if (custom_data && hal_get_bool(custom_data[jno].request_custom_homing)) { + // Trivial example: mark requested joints homed at once. +@@ -357,17 +359,15 @@ bool do_homing(void) + H[jno].homing = 0; + H[jno].home_state = HOME_IDLE; } else { - // DEFAULT joint homing state machine: -- homing_flag += base_1joint_state_machine(joint_num); -+ base_1joint_state_machine(joint_num); +- busy += base_1joint_state_machine(jno); ++ base_1joint_state_machine(jno); } } -- if ( homing_flag > 0 ) { /* one or more joint is homing */ -- homing_active = 1; -- } else { /* is a homing sequence in progress? */ -- if (sequence_state == HOME_SEQUENCE_IDLE) { -- /* no, single joint only, we're done */ -- homing_active = 0; -- } -- } -- // return 1 if homing completed this period -- if (!beginning_allhomed && get_allhomed()) {homing_active=0; return 1;} +- if (busy > 0) homing_active = 1; +- else if (sequence_state == HOME_SEQUENCE_IDLE) homing_active = 0; +- if (!begin_all && base_get_allhomed()) { homing_active = 0; return 1; } - return 0; -+ return finish_homing_cycle(beginning_allhomed); ++ return finish_homing_cycle(begin_all); } - //=============================================================================== -@@ -299,6 +288,7 @@ int get_home_sequence(int jno) { return base_get_home_sequence(jno); - bool get_homing(int jno) { return base_get_homing(jno); } + bool get_allhomed(void) { return base_get_allhomed(); } + bool get_homed(int jno) { return base_get_homed(jno); } ++bool get_home_is_exclusive(int jno) { return base_get_home_is_exclusive(jno); } + bool get_home_is_idle(int jno) { return base_get_home_is_idle(jno); } + bool get_home_is_synchronized(int jno) { return base_get_home_is_synchronized(jno); } + bool get_home_needs_unlock_first(int jno) { return base_get_home_needs_unlock_first(jno); } +@@ -375,6 +375,7 @@ int get_home_sequence(int jno) { return base_get_home_sequence(jn + bool get_homing(int jno) { return base_get_homing(jno); } bool get_homing_at_index_search_wait(int jno) { return base_get_homing_at_index_search_wait(jno); } bool get_homing_is_active(void) { return base_get_homing_is_active(); } +bool get_home_sequence_is_active(void) { return base_get_home_sequence_is_active(); } bool get_index_enable(int jno) { return base_get_index_enable(jno); } void do_home_joint(int jno) { base_do_home_joint(jno); } -@@ -417,6 +407,7 @@ int get_home_sequence(int jno) { (void)jno; return 0;} - bool get_homing(int jno) { (void)jno; return 0;} - bool get_homing_at_index_search_wait(int jno) { (void)jno; return 0;} - bool get_homing_is_active() {return 0;} -+bool get_home_sequence_is_active() {return 0;} - bool get_index_enable(int jno) { (void)jno; return 0;} - void read_homing_in_pins(int njoints) { (void)njoints; return;} - void do_home_joint(int jno) { (void)jno; return;} -diff --git a/tests/homing-concurrent/checkresult b/tests/homing-concurrent/checkresult -new file mode 100755 -index 0000000000..9c14eb33b3 ---- /dev/null -+++ b/tests/homing-concurrent/checkresult -@@ -0,0 +1,3 @@ -+#!/bin/sh -+set -e -+grep -q "^concurrent homing regression passed$" "$1" -diff --git a/tests/homing-concurrent/homing.hal b/tests/homing-concurrent/homing.hal -new file mode 100644 -index 0000000000..2eeb379e69 ---- /dev/null -+++ b/tests/homing-concurrent/homing.hal -@@ -0,0 +1,14 @@ -+loadrt [KINS]KINEMATICS -+loadrt [EMCMOT]EMCMOT servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS unlock_joints_mask=31 -+ -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+ -+net joint-0-position joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net joint-1-position joint.1.motor-pos-cmd => joint.1.motor-pos-fb -+net joint-2-position joint.2.motor-pos-cmd => joint.2.motor-pos-fb -+net joint-3-position joint.3.motor-pos-cmd => joint.3.motor-pos-fb -+net joint-4-position joint.4.motor-pos-cmd => joint.4.motor-pos-fb -+ -+net estop-loop <= iocontrol.0.user-enable-out -+net estop-loop => iocontrol.0.emc-enable-in -diff --git a/tests/homing-concurrent/test-ui.py b/tests/homing-concurrent/test-ui.py -new file mode 100755 -index 0000000000..e0c65cab6d ---- /dev/null -+++ b/tests/homing-concurrent/test-ui.py -@@ -0,0 +1,217 @@ -+#!/usr/bin/env python3 -+ -+import time -+ -+import hal -+import linuxcnc -+ -+ -+HOME_IDLE = 0 -+HOME_UNLOCK_WAIT = 3 -+HOME_FINAL_MOVE_START = 20 -+HOME_LOCK_WAIT = 23 -+TIMEOUT = 5.0 -+ -+ -+command = linuxcnc.command() -+status = linuxcnc.stat() -+errors = linuxcnc.error_channel() -+component = hal.component("homing-concurrent-test") -+for joint in range(5): -+ component.newpin("is-unlocked-%d" % joint, hal.HAL_BIT, hal.HAL_OUT) -+component.newpin("joint-0-home-switch", hal.HAL_BIT, hal.HAL_OUT) -+component.ready() -+for joint in range(5): -+ signal = "homing-concurrent-test-unlocked-%d" % joint -+ hal.new_sig(signal, hal.HAL_BIT) -+ hal.connect( -+ "homing-concurrent-test.is-unlocked-%d" % joint, -+ signal, -+ ) -+ hal.connect("joint.%d.is-unlocked" % joint, signal) -+hal.new_sig("homing-concurrent-test-joint-0-home-switch", hal.HAL_BIT) -+hal.connect( -+ "homing-concurrent-test.joint-0-home-switch", -+ "homing-concurrent-test-joint-0-home-switch", -+) -+hal.connect("joint.0.home-sw-in", "homing-concurrent-test-joint-0-home-switch") -+ -+ -+def wait(predicate, description, timeout=TIMEOUT, poll_interval=0.01): -+ deadline = time.time() + timeout -+ while time.time() < deadline: -+ status.poll() -+ if predicate(): -+ return -+ time.sleep(poll_interval) -+ raise AssertionError("timeout waiting for %s" % description) -+ -+ -+def state(joint): -+ return hal.get_value("joint.%d.home-state" % joint) -+ -+ -+def homing(joint): -+ return status.joint[joint]["homing"] -+ -+ -+def issue(function, expected=linuxcnc.RCS_DONE): -+ function() -+ result = command.wait_complete(TIMEOUT) -+ assert result == expected, "command returned %s, expected %s" % (result, expected) -+ -+ -+def wait_error(fragment): -+ deadline = time.time() + TIMEOUT -+ while time.time() < deadline: -+ error = errors.poll() -+ if error is not None and fragment in error[1]: -+ return -+ time.sleep(0.01) -+ raise AssertionError("missing error containing %r" % fragment) -+ -+ -+def wait_for_start(*joints): -+ wait( -+ lambda: all(state(joint) == HOME_UNLOCK_WAIT for joint in joints), -+ "joints %s to wait for unlock" % (joints,), -+ ) -+ -+ -+def finish_joint(joint, wait_for_published_completion=True): -+ component["is-unlocked-%d" % joint] = True -+ wait(lambda: state(joint) == HOME_LOCK_WAIT, "joint %d lock wait" % joint) -+ component["is-unlocked-%d" % joint] = False -+ wait( -+ lambda: state(joint) == HOME_IDLE -+ and status.joint[joint]["homed"] -+ and (not wait_for_published_completion or not homing(joint)), -+ "joint %d homing completion" % joint, -+ ) -+ -+ -+def finish_synchronized_group(): -+ wait_for_start(3, 4) -+ component["is-unlocked-3"] = True -+ wait(lambda: state(3) == HOME_FINAL_MOVE_START, "joint 3 synchronized wait") -+ time.sleep(0.05) -+ assert state(3) == HOME_FINAL_MOVE_START -+ assert state(4) == HOME_UNLOCK_WAIT -+ component["is-unlocked-4"] = True -+ wait( -+ lambda: state(3) == HOME_LOCK_WAIT and state(4) == HOME_LOCK_WAIT, -+ "synchronized final moves", -+ ) -+ component["is-unlocked-3"] = False -+ component["is-unlocked-4"] = False -+ wait( -+ lambda: all( -+ state(joint) == HOME_IDLE -+ and status.joint[joint]["homed"] -+ and not homing(joint) -+ for joint in (3, 4) -+ ), -+ "synchronized group completion", -+ poll_interval=0.0001, -+ ) -+ -+ -+wait( -+ lambda: status.task_state == linuxcnc.STATE_ESTOP -+ and status.exec_state == linuxcnc.EXEC_DONE, -+ "LinuxCNC startup", -+ timeout=10.0, -+) -+issue(lambda: command.state(linuxcnc.STATE_ESTOP_RESET)) -+issue(lambda: command.state(linuxcnc.STATE_ON)) -+issue(lambda: command.mode(linuxcnc.MODE_MANUAL)) -+issue(lambda: command.teleop_enable(0)) -+wait(lambda: status.motion_mode == linuxcnc.TRAJ_MODE_FREE, "joint mode") -+ -+# Positive individual requests run concurrently and a third can join later. -+issue(lambda: command.home(0)) -+wait_for_start(0) -+issue(lambda: command.home(2)) -+wait_for_start(0, 2) -+issue(lambda: command.home(1)) -+wait_for_start(0, 1, 2) -+assert all(homing(joint) for joint in (0, 1, 2)) -+ -+# A duplicate request is rejected without restarting the joint. -+issue(lambda: command.home(0), linuxcnc.RCS_ERROR) -+wait_error("joint 0 is already homing") -+assert state(0) == HOME_UNLOCK_WAIT -+ -+# One joint can finish while the others continue and publish independent state. -+finish_joint(2) -+assert not homing(2) -+assert homing(0) and homing(1) -+ -+# Aborting one independent home does not cancel the other. -+issue(lambda: command.jog(linuxcnc.JOG_STOP, 1, 0)) -+wait( -+ lambda: state(0) == HOME_IDLE and not homing(0) and not status.joint[0]["homed"], -+ "joint 0 abort", -+) -+assert state(1) == HOME_UNLOCK_WAIT and homing(1) -+ -+# A per-joint homing error is also isolated from an independent home. -+component["joint-0-home-switch"] = True -+issue(lambda: command.home(0)) -+wait( -+ lambda: state(0) == HOME_IDLE and not homing(0) and not status.joint[0]["homed"], -+ "joint 0 homing error cleanup", -+) -+wait_error("Cannot home while shared home switch is closed j=0") -+assert state(1) == HOME_UNLOCK_WAIT and homing(1) -+component["joint-0-home-switch"] = False -+ -+# HOME ALL and synchronized groups cannot be mixed into independent homing. -+issue(lambda: command.home(-1), linuxcnc.RCS_ERROR) -+wait_error("Homing sequence not possible") -+issue(lambda: command.home(3), linuxcnc.RCS_ERROR) -+wait_error("Homing sequence not possible") -+ -+finish_joint(1) -+issue(lambda: command.home(0)) -+wait_for_start(0) -+finish_joint(0) -+ -+# A synchronized group must not publish completion until its sequence -+# controller can accept the next request. Leave joint 2 unhomed so completing -+# the group does not take finish_homing_cycle()'s all-homed fast path. -+issue(lambda: command.unhome(2)) -+wait(lambda: not status.joint[2]["homed"], "joint 2 unhome") -+issue(lambda: command.home(3)) -+finish_synchronized_group() -+issue(lambda: command.home(2)) -+wait_for_start(2) -+finish_joint(2) -+ -+# HOME ALL retains HOME_SEQUENCE ordering and starts the synchronized group last. -+issue(lambda: command.teleop_enable(0)) -+wait(lambda: status.motion_mode == linuxcnc.TRAJ_MODE_FREE, "joint mode for HOME ALL") -+issue(lambda: command.home(-1)) -+wait_for_start(0) -+assert all(state(joint) == HOME_IDLE for joint in (1, 2, 3, 4)) -+finish_joint(0, wait_for_published_completion=False) -+wait_for_start(1) -+assert all(state(joint) == HOME_IDLE for joint in (2, 3, 4)) -+finish_joint(1, wait_for_published_completion=False) -+wait_for_start(2) -+assert all(state(joint) == HOME_IDLE for joint in (3, 4)) -+finish_joint(2, wait_for_published_completion=False) -+finish_synchronized_group() -+wait(lambda: all(status.homed[:5]), "HOME ALL completion") -+wait( -+ lambda: status.motion_mode == linuxcnc.TRAJ_MODE_TELEOP, -+ "automatic teleop transition", -+) -+x_before_jog = status.joint_position[0] -+issue(lambda: command.jog(linuxcnc.JOG_INCREMENT, 0, 0, 1, 0.1)) -+wait( -+ lambda: abs(status.joint_position[0] - x_before_jog - 0.1) < 1e-6, -+ "axis jog after HOME ALL", -+) -+ -+print("concurrent homing regression passed") -diff --git a/tests/homing-concurrent/test.ini b/tests/homing-concurrent/test.ini -new file mode 100644 -index 0000000000..49d5777ad0 ---- /dev/null -+++ b/tests/homing-concurrent/test.ini -@@ -0,0 +1,133 @@ -+[EMC] -+VERSION = 1.1 -+MACHINE = homing-concurrent -+DEBUG = 0 -+ -+[DISPLAY] -+DISPLAY = ./test-ui.py -+ -+[RS274NGC] -+PARAMETER_FILE = sim.var -+ -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4.0 -+SERVO_PERIOD = 1000000 -+ -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 -+ -+[EMCIO] -+TOOL_TABLE = tool.tbl -+ -+[HAL] -+HALFILE = homing.hal -+ -+[TRAJ] -+AXES = 5 -+COORDINATES = XYZUV -+LINEAR_UNITS = mm -+ANGULAR_UNITS = degree -+DEFAULT_LINEAR_VELOCITY = 10 -+MAX_LINEAR_VELOCITY = 50 -+ -+[KINS] -+KINEMATICS = trivkins coordinates=XYZUV -+JOINTS = 5 -+ -+[AXIS_X] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+ -+[AXIS_Y] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+ -+[AXIS_Z] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+ -+[AXIS_U] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+ -+[AXIS_V] -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+ -+[JOINT_0] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+LOCKING_INDEXER = 1 -+HOME_IS_SHARED = 1 -+HOME_SEQUENCE = 1 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+ -+[JOINT_1] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+LOCKING_INDEXER = 1 -+HOME_SEQUENCE = 2 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+ -+[JOINT_2] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+LOCKING_INDEXER = 1 -+HOME_SEQUENCE = 3 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+ -+[JOINT_3] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+LOCKING_INDEXER = 1 -+HOME_SEQUENCE = -4 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -+ -+[JOINT_4] -+TYPE = LINEAR -+HOME = 0 -+HOME_OFFSET = 0 -+LOCKING_INDEXER = 1 -+HOME_SEQUENCE = -4 -+MAX_VELOCITY = 50 -+MAX_ACCELERATION = 500 -+MIN_LIMIT = -100 -+MAX_LIMIT = 100 -+FERROR = 1 -+MIN_FERROR = 0.25 -diff --git a/tests/homing-concurrent/test.sh b/tests/homing-concurrent/test.sh -new file mode 100755 -index 0000000000..3e0b51699c ---- /dev/null -+++ b/tests/homing-concurrent/test.sh -@@ -0,0 +1,4 @@ -+#!/bin/sh -+set -e -+rm -f sim.var sim.var.bak -+linuxcnc -r test.ini -diff --git a/tests/homing-concurrent/tool.tbl b/tests/homing-concurrent/tool.tbl -new file mode 100644 -index 0000000000..e69de29bb2 +@@ -410,6 +411,7 @@ EXPORT_SYMBOL(homing_init); + EXPORT_SYMBOL(do_homing); + EXPORT_SYMBOL(get_allhomed); + EXPORT_SYMBOL(get_homed); ++EXPORT_SYMBOL(get_home_is_exclusive); + EXPORT_SYMBOL(get_home_is_idle); + EXPORT_SYMBOL(get_home_is_synchronized); + EXPORT_SYMBOL(get_home_needs_unlock_first); +@@ -417,6 +419,7 @@ EXPORT_SYMBOL(get_home_sequence); + EXPORT_SYMBOL(get_homing); + EXPORT_SYMBOL(get_homing_at_index_search_wait); + EXPORT_SYMBOL(get_homing_is_active); ++EXPORT_SYMBOL(get_home_sequence_is_active); + EXPORT_SYMBOL(get_index_enable); + EXPORT_SYMBOL(read_homing_in_pins); + EXPORT_SYMBOL(do_home_joint); diff --git a/linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch b/linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch index ab7b2dfd..64ca089b 100644 --- a/linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch +++ b/linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch @@ -3,50 +3,39 @@ From: Dariusz Majnert Date: Tue, 22 Sep 2026 11:50:09 +0200 Subject: [PATCH] feat(motion): add native lathe power jogging +Ported to v2.10.0-pre2: the halui pins use the opaque HAL API, so +halui.power-feed.spindle is a hal_uint_t pin, as upstream converted the +other halui u32 pins. --- - docs/src/man/man1/halui.1.adoc | 28 ++++ + docs/src/man/man1/halui.1.adoc | 28 ++++++ src/Makefile | 1 + src/emc/motion-logger/Submakefile | 1 + - src/emc/motion-logger/motion-logger.c | 6 + - src/emc/motion/axis.c | 68 ++++++++- + src/emc/motion-logger/motion-logger.c | 6 ++ + src/emc/motion/axis.c | 68 ++++++++++++- src/emc/motion/axis.h | 5 +- - src/emc/motion/command.c | 27 ++++ + src/emc/motion/command.c | 29 ++++++ src/emc/motion/control.c | 9 +- src/emc/motion/mot_priv.h | 1 + - src/emc/motion/motion.c | 8 ++ + src/emc/motion/motion.c | 7 ++ src/emc/motion/motion.h | 3 + - src/emc/motion/power_jog.c | 128 +++++++++++++++++ - src/emc/motion/power_jog.h | 37 +++++ - src/emc/nml_intf/emc.cc | 14 ++ + src/emc/motion/power_jog.c | 135 ++++++++++++++++++++++++++ + src/emc/motion/power_jog.h | 37 +++++++ + src/emc/nml_intf/emc.cc | 14 +++ src/emc/nml_intf/emc.hh | 2 + - src/emc/nml_intf/emc_nml.hh | 11 ++ + src/emc/nml_intf/emc_nml.hh | 11 +++ src/emc/task/emctaskmain.cc | 8 ++ - src/emc/task/taskintf.cc | 12 ++ - src/emc/tp/sp_scurve.c | 52 +++++++ - src/emc/tp/sp_scurve.h | 7 + - src/emc/usr_intf/halui.cc | 14 ++ - src/emc/usr_intf/halui_power_feed.hh | 69 +++++++++ - tests/power-jog/.gitignore | 3 + - tests/power-jog/checkresult | 4 + - tests/power-jog/core_sim.hal | 11 ++ - tests/power-jog/test-ui.py | 199 ++++++++++++++++++++++++++ - tests/power-jog/test.ini | 69 +++++++++ - tests/power-jog/test.sh | 7 + - tests/power-jog/tool.tbl | 1 + - 29 files changed, 801 insertions(+), 4 deletions(-) + src/emc/task/taskintf.cc | 12 +++ + src/emc/tp/sp_scurve.c | 52 ++++++++++ + src/emc/tp/sp_scurve.h | 7 ++ + src/emc/usr_intf/halui.cc | 14 +++ + src/emc/usr_intf/halui_power_feed.hh | 67 +++++++++++++ + 22 files changed, 513 insertions(+), 4 deletions(-) create mode 100644 src/emc/motion/power_jog.c create mode 100644 src/emc/motion/power_jog.h create mode 100644 src/emc/usr_intf/halui_power_feed.hh - create mode 100644 tests/power-jog/.gitignore - create mode 100755 tests/power-jog/checkresult - create mode 100644 tests/power-jog/core_sim.hal - create mode 100755 tests/power-jog/test-ui.py - create mode 100644 tests/power-jog/test.ini - create mode 100755 tests/power-jog/test.sh - create mode 100644 tests/power-jog/tool.tbl diff --git a/docs/src/man/man1/halui.1.adoc b/docs/src/man/man1/halui.1.adoc -index c172f579cd..003290e96a 100644 +index c172f57..003290e 100644 --- a/docs/src/man/man1/halui.1.adoc +++ b/docs/src/man/man1/halui.1.adoc @@ -371,6 +371,34 @@ _L_ = axis letter (xyzabcuvw) @@ -85,10 +74,10 @@ index c172f579cd..003290e96a 100644 *halui.flood.is-on* bit out:: diff --git a/src/Makefile b/src/Makefile -index fa06ec5664..30d00fc7c3 100644 +index af616fb..8770900 100644 --- a/src/Makefile +++ b/src/Makefile -@@ -1275,6 +1275,7 @@ obj-m += 5axiskins.o +@@ -1251,6 +1251,7 @@ obj-m += 5axiskins.o obj-$(CONFIG_MOTMOD) += motmod.o motmod-objs := emc/kinematics/cubic.o motmod-objs += emc/motion/axis.o @@ -97,7 +86,7 @@ index fa06ec5664..30d00fc7c3 100644 motmod-objs += emc/motion/command.o motmod-objs += emc/motion/control.o diff --git a/src/emc/motion-logger/Submakefile b/src/emc/motion-logger/Submakefile -index 7b572d7c32..acdd1b532c 100644 +index 7b572d7..acdd1b5 100644 --- a/src/emc/motion-logger/Submakefile +++ b/src/emc/motion-logger/Submakefile @@ -3,6 +3,7 @@ TARGETS += ../bin/motion-logger @@ -109,10 +98,10 @@ index 7b572d7c32..acdd1b532c 100644 emc/tp/sp_scurve.c \ emc/tp/ruckig_wrapper.c diff --git a/src/emc/motion-logger/motion-logger.c b/src/emc/motion-logger/motion-logger.c -index ae7c8d3f6e..65900c1af3 100644 +index f5f508f..fc79c42 100644 --- a/src/emc/motion-logger/motion-logger.c +++ b/src/emc/motion-logger/motion-logger.c -@@ -667,6 +667,12 @@ int main(int argc, char* argv[]) { +@@ -661,6 +661,12 @@ int main(int argc, char* argv[]) { c->spindle, c->available); break; @@ -126,7 +115,7 @@ index ae7c8d3f6e..65900c1af3 100644 log_print("SET_SPINDLESYNC sync=%06f, flags=0x%08x\n", c->spindlesync, c->flags); break; diff --git a/src/emc/motion/axis.c b/src/emc/motion/axis.c -index 1be690a25c..279a577e96 100644 +index 029af60..dd8641e 100644 --- a/src/emc/motion/axis.c +++ b/src/emc/motion/axis.c @@ -5,6 +5,7 @@ @@ -213,7 +202,7 @@ index 1be690a25c..279a577e96 100644 int n; emcmot_axis_t *axis; for (n = 0; n < EMCMOT_MAX_AXIS; n++) { -@@ -391,6 +425,7 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo +@@ -392,6 +426,7 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo delta = new_ajog_counts - axis->old_ajog_counts; axis->old_ajog_counts = new_ajog_counts; if ( first_pass ) { continue; } @@ -221,7 +210,7 @@ index 1be690a25c..279a577e96 100644 if ( delta == 0 ) { //just update counts continue; -@@ -438,6 +473,7 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo +@@ -439,6 +474,7 @@ void axis_handle_jogwheels(bool motion_teleop_flag, bool motion_enable_flag, boo void axis_sync_teleop_tp_to_carte_pos(int extfactor, double *pcmd_p[]) { @@ -229,7 +218,7 @@ index 1be690a25c..279a577e96 100644 int n; // expect extfactor = -1 || 0 || +1 // -@@ -672,11 +708,38 @@ static int update_teleop_with_check(int axis_num, simple_tp_t *the_tp, double se +@@ -671,11 +707,38 @@ static int update_teleop_with_check(int axis_num, simple_tp_t *the_tp, double se return 0; } @@ -269,7 +258,7 @@ index 1be690a25c..279a577e96 100644 for (axis_num = 0; axis_num < EMCMOT_MAX_AXIS; axis_num++) { axis = &axis_array[axis_num]; -@@ -685,7 +748,8 @@ int axis_calc_motion(double servo_period) +@@ -684,7 +747,8 @@ int axis_calc_motion(double servo_period) if (axis->teleop_tp.max_vel > axis->vel_limit) { axis->teleop_tp.max_vel = axis->vel_limit; } @@ -280,7 +269,7 @@ index 1be690a25c..279a577e96 100644 } diff --git a/src/emc/motion/axis.h b/src/emc/motion/axis.h -index 5d61f0b13f..f1ce1d7e90 100644 +index 5d61f0b..f1ce1d7 100644 --- a/src/emc/motion/axis.h +++ b/src/emc/motion/axis.h @@ -18,6 +18,8 @@ bool axis_plan_external_offsets(double servo_period, bool motion_enable_flag, bo @@ -303,10 +292,10 @@ index 5d61f0b13f..f1ce1d7e90 100644 #ifdef __cplusplus diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index f4fd73b31b..70b6be49a1 100644 +index b96b098..3f5a562 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -112,6 +112,17 @@ STATIC int spindle_range_is_available(int first, int last) +@@ -157,6 +157,19 @@ STATIC int spindle_range_is_available(int first, int last) return 1; } @@ -314,8 +303,10 @@ index f4fd73b31b..70b6be49a1 100644 +{ + return GET_MOTION_ENABLE_FLAG() && GET_MOTION_TELEOP_FLAG() && + !GET_MOTION_ERROR_FLAG() && get_allhomed() && !get_homing_is_active() && -+ !availability_transition_busy() && !*emcmot_hal_data->jog_inhibit && -+ !*emcmot_hal_data->jog_stop && !*emcmot_hal_data->jog_stop_immediate && ++ !availability_transition_busy() && ++ !hal_get_bool(emcmot_hal_data->jog_inhibit) && ++ !hal_get_bool(emcmot_hal_data->jog_stop) && ++ !hal_get_bool(emcmot_hal_data->jog_stop_immediate) && + spindle >= 0 && spindle < emcmotConfig->numSpindles && + spindle_range_is_available(spindle, spindle) && + emcmotStatus->spindle_status[spindle].direction; @@ -324,7 +315,7 @@ index f4fd73b31b..70b6be49a1 100644 /* limits_ok() returns 1 if none of the hard limits are set, 0 if any are set. Called on a linear and circular move. */ STATIC int limits_ok(void) -@@ -872,6 +883,22 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -949,6 +962,22 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) joint->min_ferror = emcmotCommand->minFerror; break; @@ -348,10 +339,10 @@ index f4fd73b31b..70b6be49a1 100644 /* do a continuous jog, implemented as an incremental jog to the limit. When the user lets go of the button an abort will diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index a3e7a3b776..49983d19b5 100644 +index c75c227..f0e6a18 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1900,7 +1900,14 @@ static void get_pos_cmds(long period) +@@ -2013,7 +2013,14 @@ static void get_pos_cmds(long period) break; case EMCMOT_MOTION_TELEOP: @@ -368,10 +359,10 @@ index a3e7a3b776..49983d19b5 100644 ext_offset_coord_limit = 0; //in case was set in prior coord motion } diff --git a/src/emc/motion/mot_priv.h b/src/emc/motion/mot_priv.h -index 631c146ee2..3191b219e1 100644 +index e5b8373..a0b6ea1 100644 --- a/src/emc/motion/mot_priv.h +++ b/src/emc/motion/mot_priv.h -@@ -376,5 +376,6 @@ void availability_release_joint(int n, availability_fault_t fault); +@@ -381,5 +381,6 @@ void availability_release_joint(int n, availability_fault_t fault); void availability_release_spindle(int n, availability_fault_t fault); void availability_cancel(int all); int availability_transition_busy(void); @@ -379,10 +370,10 @@ index 631c146ee2..3191b219e1 100644 #endif /* MOT_PRIV_H */ diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c -index 87f1a06205..59f3338c66 100644 +index 8993290..43efa8c 100644 --- a/src/emc/motion/motion.c +++ b/src/emc/motion/motion.c -@@ -22,6 +22,7 @@ +@@ -23,6 +23,7 @@ #include "mot_priv.h" #include "homing.h" #include "axis.h" @@ -390,7 +381,7 @@ index 87f1a06205..59f3338c66 100644 // Mark strings for translation, but defer translation to userspace #define _(s) (s) -@@ -407,6 +408,11 @@ int rtapi_app_main(void) +@@ -452,6 +453,11 @@ int rtapi_app_main(void) return -1; } @@ -402,20 +393,19 @@ index 87f1a06205..59f3338c66 100644 rtapi_print_msg(RTAPI_MSG_INFO, "MOTION: rtapi_app_main() complete\n"); hal_ready(mot_comp_id); -@@ -429,6 +435,8 @@ void rtapi_app_exit(void) +@@ -474,6 +480,7 @@ void rtapi_app_exit(void) rtapi_print_msg(RTAPI_MSG_ERR, _("MOTION: hal_stop_threads() failed, returned %d\n"), retval); } + sp_scurve_jog_cleanup(); -+ sp_scurve_cleanup(); + /* free the S-curve planner + Ruckig pool (threads are stopped, safe) */ + sp_scurve_cleanup(); /* free shared memory */ - retval = rtapi_shmem_delete(emc_shmem_id, mot_comp_id); - if (retval < 0) { diff --git a/src/emc/motion/motion.h b/src/emc/motion/motion.h -index fd934976e2..4095c700db 100644 +index bed4351..51719c1 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h -@@ -187,6 +187,7 @@ extern "C" { +@@ -184,6 +184,7 @@ extern "C" { EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG, EMCMOT_SET_JOINT_AVAILABILITY, EMCMOT_SET_SPINDLE_AVAILABILITY, @@ -423,7 +413,7 @@ index fd934976e2..4095c700db 100644 } cmd_code_t; -@@ -240,6 +241,8 @@ extern "C" { +@@ -239,6 +240,8 @@ extern "C" { int joint; /* which joint index to use for below */ int axis; /* which axis index to use for below */ int spindle; /* which spindle to use */ @@ -434,16 +424,19 @@ index fd934976e2..4095c700db 100644 double home; /* joint home position */ diff --git a/src/emc/motion/power_jog.c b/src/emc/motion/power_jog.c new file mode 100644 -index 0000000000..2303950aac +index 0000000..1db5c50 --- /dev/null +++ b/src/emc/motion/power_jog.c -@@ -0,0 +1,128 @@ +@@ -0,0 +1,135 @@ +#include +#include +#include "power_jog.h" +#include "mot_priv.h" +#include "../tp/sp_scurve.h" + ++/* Distance in machine units a power jog stops short of a soft limit. */ ++#define POWER_JOG_LIMIT_MARGIN 1e-6 ++ +void power_jog_abort(power_jog_t *jog, int immediate) +{ + if (!power_jog_reserved(jog) || @@ -526,7 +519,11 @@ index 0000000000..2303950aac + velocity = fmin(velocity, axes[i].velocity / magnitude); + acceleration = fmin(acceleration, axes[i].acceleration / magnitude); + jerk = fmin(jerk, axes[i].jerk / magnitude); -+ double limit = d > 0 ? axes[i].maximum : axes[i].minimum; ++ /* Like an ordinary jog, which motion never lets rest on a soft ++ limit, end just inside it: an axis resting exactly on the limit ++ reports a teleop limit hit every cycle afterwards. */ ++ double limit = d > 0 ? axes[i].maximum - POWER_JOG_LIMIT_MARGIN ++ : axes[i].minimum + POWER_JOG_LIMIT_MARGIN; + target = fmin(target, (limit - jog->origin[i]) / d); + } + if (!(velocity > 0) || !(acceleration > 0) || target == DBL_MAX) { @@ -568,7 +565,7 @@ index 0000000000..2303950aac +} diff --git a/src/emc/motion/power_jog.h b/src/emc/motion/power_jog.h new file mode 100644 -index 0000000000..293e1d0c2e +index 0000000..293e1d0 --- /dev/null +++ b/src/emc/motion/power_jog.h @@ -0,0 +1,37 @@ @@ -610,10 +607,10 @@ index 0000000000..293e1d0c2e + +#endif diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index c40c9dbe5e..aac79f67e7 100644 +index 54d973c..133869b 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -67,6 +67,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) +@@ -65,6 +65,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) case EMC_JOG_CONT_TYPE: ((EMC_JOG_CONT *) buffer)->update(cms); break; @@ -623,7 +620,7 @@ index c40c9dbe5e..aac79f67e7 100644 case EMC_JOG_INCR_TYPE: ((EMC_JOG_INCR *) buffer)->update(cms); break; -@@ -385,6 +388,8 @@ const char *emc_symbol_lookup(uint32_t type) +@@ -386,6 +389,8 @@ const char *emc_symbol_lookup(uint32_t type) return "EMC_JOINT_SET_AVAILABILITY"; case EMC_JOG_CONT_TYPE: return "EMC_JOG_CONT"; @@ -632,7 +629,7 @@ index c40c9dbe5e..aac79f67e7 100644 case EMC_JOG_INCR_TYPE: return "EMC_JOG_INCR"; case EMC_JOG_ABS_TYPE: -@@ -967,6 +972,15 @@ void EMC_STAT::update(CMS * cms) +@@ -973,6 +978,15 @@ void EMC_STAT::update(CMS * cms) cms->update(debug); } @@ -649,7 +646,7 @@ index c40c9dbe5e..aac79f67e7 100644 * NML/CMS Update function for EMC_JOG_CONT */ diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index 32ca6fbaa0..06b99f229c 100644 +index 94d6a19..7d93f8a 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -75,6 +75,7 @@ struct PM_CARTESIAN; @@ -660,7 +657,7 @@ index 32ca6fbaa0..06b99f229c 100644 #define EMC_JOINT_STAT_TYPE ((NMLTYPE) 198) #define EMC_AXIS_STAT_TYPE ((NMLTYPE) 199) -@@ -337,6 +338,7 @@ extern int emcJointOverrideLimits(int joint); +@@ -357,6 +358,7 @@ extern int emcJointOverrideLimits(int joint); extern int emcJointLoadComp(int joint, const char *file, int type); extern int emcJogStop(int nr, int jjogmode); extern int emcJogCont(int nr, double vel, int jjogmode); @@ -669,10 +666,10 @@ index 32ca6fbaa0..06b99f229c 100644 extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index ac4d322a92..4141c12994 100644 +index feab3fb..a9fc353 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -362,6 +362,17 @@ class EMC_JOINT_SET_AVAILABILITY:public EMC_JOINT_CMD_MSG { +@@ -367,6 +367,17 @@ class EMC_JOINT_SET_AVAILABILITY:public EMC_JOINT_CMD_MSG { int available; }; @@ -691,10 +688,10 @@ index ac4d322a92..4141c12994 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 1314163557..8e88fcf1a3 100644 +index 900c430..db1e711 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1310,6 +1310,7 @@ static int emcTaskPlan(void) +@@ -1529,6 +1529,7 @@ static int emcTaskPlan(void) case EMC_JOINT_HOME_TYPE: case EMC_JOINT_UNHOME_TYPE: case EMC_JOG_CONT_TYPE: @@ -702,7 +699,7 @@ index 1314163557..8e88fcf1a3 100644 case EMC_JOG_INCR_TYPE: case EMC_JOG_ABS_TYPE: case EMC_JOG_STOP_TYPE: -@@ -2145,6 +2146,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2433,6 +2434,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; @@ -717,10 +714,10 @@ index 1314163557..8e88fcf1a3 100644 jog_incr_msg = reinterpret_cast(cmd); retval = emcJogIncr(jog_incr_msg->joint_or_axis, diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index ca5c4dc3a2..672de478c2 100644 +index 27418ce..98f2ca9 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -844,6 +844,18 @@ int emcJogCont(int nr, double vel, int jjogmode) +@@ -904,6 +904,18 @@ int emcJogCont(int nr, double vel, int jjogmode) return usrmotWriteEmcmotCommand(&emcmotCommand); } @@ -740,18 +737,18 @@ index ca5c4dc3a2..672de478c2 100644 { if (jjogmode) { diff --git a/src/emc/tp/sp_scurve.c b/src/emc/tp/sp_scurve.c -index d72caada77..f6fe23bc28 100644 +index d2a9102..200105a 100644 --- a/src/emc/tp/sp_scurve.c +++ b/src/emc/tp/sp_scurve.c -@@ -29,6 +29,7 @@ +@@ -39,6 +39,7 @@ static double scurve_peak_scale(void) { * destruction on every call. */ static RuckigPlanner cached_planner = NULL; +static RuckigPlanner jog_planner = NULL; static double cached_cycle_time = 0.0; /* cycle time used by the current planner */ - /** -@@ -96,6 +97,57 @@ static RuckigPlanner get_cached_planner(void) { + /* --------------------------------------------------------------------------- +@@ -206,6 +207,57 @@ static RuckigPlanner get_cached_planner(void) { return cached_planner; } @@ -810,7 +807,7 @@ index d72caada77..f6fe23bc28 100644 * Ruckig-based S-curve functions * ================================================================ */ diff --git a/src/emc/tp/sp_scurve.h b/src/emc/tp/sp_scurve.h -index 80b6dca4ce..236828307b 100644 +index 80b6dca..2368283 100644 --- a/src/emc/tp/sp_scurve.h +++ b/src/emc/tp/sp_scurve.h @@ -32,6 +32,13 @@ int sp_scurve_init(double cycle_time); @@ -828,10 +825,10 @@ index 80b6dca4ce..236828307b 100644 double nextAccel(double t, double targetV, double v, double a, double maxA, double maxJ); double sc_distance(double t, double v, double a, double j); diff --git a/src/emc/usr_intf/halui.cc b/src/emc/usr_intf/halui.cc -index bcb62bf9f9..509b9b1af3 100644 +index 65b890a..d59b478 100644 --- a/src/emc/usr_intf/halui.cc +++ b/src/emc/usr_intf/halui.cc -@@ -247,6 +247,10 @@ static int num_axes = 0; //number of axes, taken from the INI [TRAJ] section +@@ -241,6 +241,10 @@ static int num_axes = 0; //number of axes, taken from the INI [TRAJ] section static int num_joints = 3; //number of joints, taken from the INI [KINS] section static int num_spindles = 1; // number of spindles, [TRAJ]SPINDLES @@ -842,15 +839,15 @@ index bcb62bf9f9..509b9b1af3 100644 static double maxFeedOverride=1; static double maxMaxVelocity=1; static double minSpindleOverride=0.0; -@@ -913,6 +917,7 @@ int halui_hal_init(void) +@@ -754,6 +758,7 @@ int halui_hal_init(void) + CHK(halui_export_pin_IN_real(&(halui_data->jjog_deadband), "halui.joint.jog-deadband")); - retval = halui_export_pin_IN_float(&(halui_data->ajog_speed), "halui.axis.jog-speed"); - if (retval < 0) return retval; -+ if (lathe_mode && (retval = power_feed_jog.export_pins(comp_id)) < 0) return retval; - retval = halui_export_pin_IN_float(&(halui_data->ajog_deadband), "halui.axis.jog-deadband"); - if (retval < 0) return retval; + CHK(halui_export_pin_IN_real(&(halui_data->ajog_speed), "halui.axis.jog-speed")); ++ if (lathe_mode) CHK(power_feed_jog.export_pins(comp_id)); + CHK(halui_export_pin_IN_real(&(halui_data->ajog_deadband), "halui.axis.jog-deadband")); -@@ -1466,6 +1471,11 @@ static int iniLoad(const char *filename) + for (int n = 0; n < num_mdi_commands; n++) { +@@ -1305,6 +1310,11 @@ static int iniLoad(const char *filename) num_axes = EMCMOT_MAX_AXIS; axis_mask = (1 << EMCMOT_MAX_AXIS) - 1; } @@ -862,7 +859,7 @@ index bcb62bf9f9..509b9b1af3 100644 if (auto inival = inifile.findSInt("JOINTS", "KINS")) { if (*inival > 0) { -@@ -1624,6 +1634,10 @@ static void check_hal_changes() +@@ -1472,6 +1482,10 @@ static void check_hal_changes() local_halui_str new_halui_data_mutable; copy_hal_data(*halui_data, new_halui_data_mutable); const local_halui_str &new_halui_data = new_halui_data_mutable; @@ -871,65 +868,61 @@ index bcb62bf9f9..509b9b1af3 100644 + emcStatus->task.mode == EMC_TASK_MODE::MANUAL && + emcStatus->motion.traj.mode == EMC_TRAJ_MODE::TELEOP, emcCommandSend); - //check if machine_on pin has changed (the rest work exactly the same) + if (check_bit_changed(new_halui_data.machine_on, old_halui_data.machine_on) != 0) diff --git a/src/emc/usr_intf/halui_power_feed.hh b/src/emc/usr_intf/halui_power_feed.hh new file mode 100644 -index 0000000000..c29dd2bdb9 +index 0000000..c0024ad --- /dev/null +++ b/src/emc/usr_intf/halui_power_feed.hh -@@ -0,0 +1,69 @@ +@@ -0,0 +1,67 @@ +#pragma once + ++#include ++ +#include "hal.h" +#include "nml_intf/emc_nml.hh" + +/* HAL sampling and power-feed edges; motion owns the held feed and path. */ +class HaluiPowerFeed { + struct Pins { -+ hal_bit_t *xp, *xm, *zp, *zm; -+ hal_float_t *feed, *slope; -+ hal_u32_t *spindle; ++ hal_bool_t xp, xm, zp, zm; ++ hal_real_t feed, slope; ++ hal_uint_t spindle; + }; + Pins *pins = nullptr; + bool blocked = false; + int previous_x = 0, previous_z = 0; + double held_slope = 0; -+ unsigned held_spindle = 0; ++ rtapi_uint held_spindle = 0; + +public: + int export_pins(int id) { + pins = static_cast(hal_malloc(sizeof(Pins))); + if (!pins) return -1; + int result; -+ if ((result = hal_pin_bit_new("halui.power-feed.x.plus", HAL_IN, &pins->xp, id)) < 0 || -+ (result = hal_pin_bit_new("halui.power-feed.x.minus", HAL_IN, &pins->xm, id)) < 0 || -+ (result = hal_pin_bit_new("halui.power-feed.z.plus", HAL_IN, &pins->zp, id)) < 0 || -+ (result = hal_pin_bit_new("halui.power-feed.z.minus", HAL_IN, &pins->zm, id)) < 0 || -+ (result = hal_pin_float_new("halui.power-feed.per-rev", HAL_IN, &pins->feed, id)) < 0 || -+ (result = hal_pin_u32_new("halui.power-feed.spindle", HAL_IN, &pins->spindle, id)) < 0 || -+ (result = hal_pin_float_new("halui.power-feed.taper-slope", HAL_IN, &pins->slope, id)) < 0) ++ if ((result = hal_pin_new_bool(id, HAL_IN, &pins->xp, 0, "halui.power-feed.x.plus")) < 0 || ++ (result = hal_pin_new_bool(id, HAL_IN, &pins->xm, 0, "halui.power-feed.x.minus")) < 0 || ++ (result = hal_pin_new_bool(id, HAL_IN, &pins->zp, 0, "halui.power-feed.z.plus")) < 0 || ++ (result = hal_pin_new_bool(id, HAL_IN, &pins->zm, 0, "halui.power-feed.z.minus")) < 0 || ++ (result = hal_pin_new_real(id, HAL_IN, &pins->feed, 0.0, "halui.power-feed.per-rev")) < 0 || ++ (result = hal_pin_new_uint(id, HAL_IN, &pins->spindle, 0, "halui.power-feed.spindle")) < 0 || ++ (result = hal_pin_new_real(id, HAL_IN, &pins->slope, 0.0, "halui.power-feed.taper-slope")) < 0) + return result; -+ *pins->xp = 0; -+ *pins->xm = 0; -+ *pins->zp = 0; -+ *pins->zm = 0; -+ *pins->feed = 0; -+ *pins->slope = 0; -+ *pins->spindle = 0; + return 0; + } + + void update(bool permitted, int (*send)(RCS_CMD_MSG&)) { + if (!pins) return; -+ bool xp = *pins->xp, xm = *pins->xm; -+ bool zp = *pins->zp, zm = *pins->zm; ++ bool xp = hal_get_bool(pins->xp), xm = hal_get_bool(pins->xm); ++ bool zp = hal_get_bool(pins->zp), zm = hal_get_bool(pins->zm); + bool held = xp || xm || zp || zm; -+ double slope = *pins->slope; ++ double slope = hal_get_real(pins->slope); ++ rtapi_uint spindle = hal_get_uint(pins->spindle); + if (!held) blocked = false; + if (held && (!permitted || (xp && xm) || (zp && zm) || + ((previous_x || previous_z) && -+ (slope != held_slope || *pins->spindle != held_spindle)))) ++ (slope != held_slope || spindle != held_spindle)))) + blocked = true; + int x = permitted && !blocked ? int(xp) - int(xm) : 0; + int z = permitted && !blocked ? int(zp) - int(zm) : 0; @@ -937,350 +930,16 @@ index 0000000000..c29dd2bdb9 + EMC_JOG_POWER command; + command.x_direction = x; + command.z_direction = z; -+ command.feed_per_rev = *pins->feed; -+ command.spindle = *pins->spindle; ++ command.feed_per_rev = hal_get_real(pins->feed); ++ // The pin is 64 bits wide; an index that does not fit the ++ // command's int becomes -1, which motion refuses. ++ command.spindle = spindle <= INT_MAX ? int(spindle) : -1; + command.taper_slope = slope; + if (send(command) != 0 && (x || z)) blocked = true; + held_slope = slope; -+ held_spindle = *pins->spindle; ++ held_spindle = spindle; + } + previous_x = x; + previous_z = z; + } +}; -diff --git a/tests/power-jog/.gitignore b/tests/power-jog/.gitignore -new file mode 100644 -index 0000000000..d070f21698 ---- /dev/null -+++ b/tests/power-jog/.gitignore -@@ -0,0 +1,3 @@ -+nonlathe.ini -+scurve.ini -+sim.var* -diff --git a/tests/power-jog/checkresult b/tests/power-jog/checkresult -new file mode 100755 -index 0000000000..305bdc4180 ---- /dev/null -+++ b/tests/power-jog/checkresult -@@ -0,0 +1,4 @@ -+#!/bin/sh -+set -eu -+test "$(grep -c '^native power jog scenarios ok$' "$1")" = 2 -+grep -q '^nonlathe pins absent$' "$1" -diff --git a/tests/power-jog/core_sim.hal b/tests/power-jog/core_sim.hal -new file mode 100644 -index 0000000000..80225af5a7 ---- /dev/null -+++ b/tests/power-jog/core_sim.hal -@@ -0,0 +1,11 @@ -+loadrt trivkins coordinates=XZ -+loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=2000000 num_joints=2 num_spindles=2 -+addf motion-command-handler servo-thread -+addf motion-controller servo-thread -+net x-pos joint.0.motor-pos-cmd => joint.0.motor-pos-fb -+net z-pos joint.1.motor-pos-cmd => joint.1.motor-pos-fb -+net estop iocontrol.0.user-enable-out => iocontrol.0.emc-enable-in -+setp spindle.0.at-speed true -+setp spindle.1.at-speed true -+setp spindle.0.speed-in 10 -+setp spindle.1.speed-in -20 -diff --git a/tests/power-jog/test-ui.py b/tests/power-jog/test-ui.py -new file mode 100755 -index 0000000000..cc119402ba ---- /dev/null -+++ b/tests/power-jog/test-ui.py -@@ -0,0 +1,199 @@ -+#!/usr/bin/env python3 -+"""Exercise HALUI -> NML -> real motion, observing simulated axis positions.""" -+import math -+import os -+import sys -+import time -+import hal -+import linuxcnc -+ -+c, s, errors = linuxcnc.command(), linuxcnc.stat(), linuxcnc.error_channel() -+h = hal.component('power-jog-test') -+h.ready() -+ -+ -+def wait(predicate, label, timeout=8): -+ deadline = time.monotonic() + timeout -+ while time.monotonic() < deadline: -+ s.poll() -+ if predicate(): -+ return -+ time.sleep(.005) -+ raise AssertionError((label, s.position, s.task_state, errors.poll())) -+ -+ -+def done(): -+ assert c.wait_complete(8) == linuxcnc.RCS_DONE, errors.poll() -+ -+ -+def pin(name, value): -+ hal.set_p(name, str(value)) -+ -+ -+def velocity(axis): -+ return hal.get_value('axis.' + axis + '.teleop-vel-cmd') -+ -+ -+def position(): -+ s.poll() -+ return s.position[0], s.position[2] -+ -+ -+def release(): -+ for axis in ('x', 'z'): -+ for direction in ('plus', 'minus'): -+ pin('halui.power-feed.' + axis + '.' + direction, 0) -+ pin('halui.axis.' + axis + '.' + direction, 0) -+ wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'stop') -+ time.sleep(.1) # let HALUI consume the complete release -+ -+ -+def origin(): -+ release() -+ c.mode(linuxcnc.MODE_MDI); done() -+ c.mdi('G21 G90 G94 F120 G1 X0 Z0'); done() -+ c.mode(linuxcnc.MODE_MANUAL); done() -+ c.teleop_enable(1); done() -+ -+ -+wait(lambda: hal.component_exists('halui'), 'HALUI startup') -+wait(lambda: any(p['NAME'] == 'halui.axis.jog-speed' for p in hal.get_info_pins()), 'HALUI pins') -+if os.environ.get('POWER_JOG_NONLATHE'): -+ assert not any(p['NAME'].startswith('halui.power-feed.') for p in hal.get_info_pins()) -+ print('nonlathe pins absent', flush=True) -+ sys.exit(0) -+c.state(linuxcnc.STATE_ESTOP_RESET); done() -+c.state(linuxcnc.STATE_ON); done() -+c.mode(linuxcnc.MODE_MANUAL); done() -+c.home(-1); done() -+wait(lambda: all(s.homed[:2]), 'homing') -+c.teleop_enable(1); done() -+c.spindle(linuxcnc.SPINDLE_FORWARD, 600, 0); done() -+c.spindle(linuxcnc.SPINDLE_REVERSE, 1200, 1); done() -+pin('halui.power-feed.per-rev', .1) -+time.sleep(.1) -+ -+# Feed/rev is independent of the interpreter F and is captured until release. -+pin('halui.power-feed.z.plus', 1) -+wait(lambda: abs(velocity('z') - 1) < .01, 'initial feed') -+pin('halui.power-feed.per-rev', .2) -+time.sleep(.15) -+assert abs(velocity('z') - 1) < .01 -+c.feedrate(.5) -+wait(lambda: abs(velocity('z') - .5) < .01, 'live override') -+c.feedrate(0) -+wait(lambda: abs(velocity('z')) < 1e-8, 'zero override pauses') -+c.feedrate(.5) -+wait(lambda: abs(velocity('z') - .5) < .01, 'override resumes held feed') -+pin('halui.power-feed.x.plus', 1) -+wait(lambda: abs(velocity('x') - math.sqrt(.125)) < .01 and -+ abs(velocity('z') - math.sqrt(.125)) < .01, -+ 'direction change retains captured feed') -+release() -+c.feedrate(1); done() -+pin('halui.power-feed.z.plus', 1) -+wait(lambda: abs(velocity('z') - 2) < .01, 'next press captures feed') -+release() -+pin('halui.power-feed.spindle', 1) -+pin('halui.power-feed.z.minus', 1) -+wait(lambda: abs(velocity('z') + 4) < .01, 'selected reverse spindle magnitude') -+release() -+ -+# Unequal X/Z constraints must preserve geometry throughout acceleration/stop. -+pin('halui.power-feed.spindle', 0) -+pin('halui.power-feed.per-rev', 1) -+for axis, slope in [(a, k) for a in ('x', 'z') for k in (-1, -.5, 0, .5, 1)]: -+ origin() -+ pin('halui.power-feed.taper-slope', slope) -+ start_x, start_z = position() -+ pin('halui.power-feed.' + axis + '.plus', 1) -+ wait(lambda: velocity(axis) > .1, 'taper starts') -+ for _ in range(35): -+ x, z = position() -+ error = ((x-start_x) - slope*(z-start_z) if axis == 'z' -+ else (z-start_z) + slope*(x-start_x)) -+ assert abs(error) < .002, (axis, slope, x, z) -+ assert abs(velocity('x')) <= 3.001 -+ time.sleep(.005) -+ pin('halui.power-feed.' + axis + '.plus', 0) -+ wait(lambda: abs(velocity(axis)) < 1e-8, 'taper stops') -+ x, z = position() -+ error = ((x-start_x) - slope*(z-start_z) if axis == 'z' -+ else (z-start_z) + slope*(x-start_x)) -+ assert abs(error) < .002 -+ release() -+ -+origin() -+pin('halui.power-feed.taper-slope', 0) -+pin('halui.power-feed.per-rev', .1) -+pin('halui.power-feed.x.plus', 1) -+pin('halui.power-feed.z.plus', 1) -+wait(lambda: abs(velocity('x') - math.sqrt(.5)) < .01 and -+ abs(velocity('z') - math.sqrt(.5)) < .01, 'combined directions') -+c.jog(linuxcnc.JOG_STOP, 0, 0); done() -+wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'existing stop stops both') -+time.sleep(.1) -+assert abs(velocity('z')) < 1e-8 -+release() -+ -+origin() -+pin('halui.power-feed.taper-slope', .5) -+pin('halui.power-feed.per-rev', 1) -+pin('halui.power-feed.z.plus', 1) -+wait(lambda: s.position[2] > 9.99, 'coupled travel limit', 10) -+wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'limit stops both') -+x, z = position() -+assert z <= 10.000001 and abs(x - .5*z) < .002 -+release() -+ -+origin() -+pin('halui.power-feed.z.plus', 1) -+wait(lambda: velocity('z') > .1, 'jog before inhibit') -+pin('motion.jog-inhibit', 1) -+wait(lambda: abs(velocity('z')) < 1e-8, 'inhibit cancels') -+pin('motion.jog-inhibit', 0) -+time.sleep(.15) -+assert abs(velocity('z')) < 1e-8 -+pin('halui.power-feed.x.plus', 1) -+time.sleep(.15) -+assert abs(velocity('x')) + abs(velocity('z')) < 1e-8 -+release() -+ -+# A new vector must settle before starting in its new direction. -+origin() -+pin('halui.power-feed.taper-slope', 0) -+pin('halui.power-feed.per-rev', .1) -+pin('halui.power-feed.z.plus', 1) -+wait(lambda: abs(velocity('z') - 1) < .01, 'before vector change') -+pin('halui.power-feed.x.plus', 1) -+wait(lambda: abs(velocity('x') - math.sqrt(.5)) < .01 and -+ abs(velocity('z') - math.sqrt(.5)) < .01, 'new combined vector') -+pin('motion.jog-stop-immediate', 1) -+wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'immediate group stop') -+pin('motion.jog-stop-immediate', 0) -+time.sleep(.15) -+assert abs(velocity('x')) + abs(velocity('z')) < 1e-8 -+release() -+ -+# The two direction routes are independent. An ordinary jog cannot take over -+# a reserved power-feed path, and a power request cannot steal an ordinary jog. -+origin() -+pin('halui.axis.jog-speed', 30) -+pin('halui.power-feed.z.plus', 1) -+wait(lambda: abs(velocity('z') - 1) < .01, 'power feed before ordinary press') -+pin('halui.axis.z.minus', 1) -+time.sleep(.15) -+assert velocity('z') > 0 -+pin('halui.axis.z.minus', 0) -+release() -+ -+origin() -+pin('halui.axis.z.minus', 1) -+wait(lambda: abs(velocity('z') + .5) < .01, 'ordinary jog before power press') -+pin('halui.power-feed.z.plus', 1) -+time.sleep(.15) -+assert velocity('z') < 0 -+pin('halui.power-feed.z.plus', 0) -+release() -+ -+print('native power jog scenarios ok', flush=True) -diff --git a/tests/power-jog/test.ini b/tests/power-jog/test.ini -new file mode 100644 -index 0000000000..98afc6f1b2 ---- /dev/null -+++ b/tests/power-jog/test.ini -@@ -0,0 +1,69 @@ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0 -+[DISPLAY] -+DISPLAY = ./test-ui.py -+LATHE = 1 -+[RS274NGC] -+PARAMETER_FILE = sim.var -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4 -+SERVO_PERIOD = 1000000 -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 -+[HAL] -+HALFILE = core_sim.hal -+HALUI = halui -+[TRAJ] -+COORDINATES = XZ -+SPINDLES = 2 -+LINEAR_UNITS = mm -+ANGULAR_UNITS = degree -+DEFAULT_LINEAR_VELOCITY = 5 -+MAX_LINEAR_VELOCITY = 30 -+MAX_LINEAR_JERK = 10000 -+[EMCIO] -+TOOL_TABLE = tool.tbl -+[KINS] -+KINEMATICS = trivkins coordinates=XZ -+JOINTS = 2 -+[AXIS_X] -+MIN_LIMIT = -10 -+MAX_LIMIT = 10 -+MAX_VELOCITY = 3 -+MAX_ACCELERATION = 15 -+MAX_JERK = 5000 -+[AXIS_Z] -+MIN_LIMIT = -10 -+MAX_LIMIT = 10 -+MAX_VELOCITY = 10 -+MAX_ACCELERATION = 100 -+MAX_JERK = 10000 -+[JOINT_0] -+TYPE = LINEAR -+MIN_LIMIT = -10 -+MAX_LIMIT = 10 -+MAX_VELOCITY = 3 -+MAX_ACCELERATION = 15 -+MAX_JERK = 5000 -+FERROR = 1 -+MIN_FERROR = 0.25 -+HOME = 0 -+HOME_SEQUENCE = 0 -+HOME_SEARCH_VEL = 0 -+HOME_LATCH_VEL = 0 -+[JOINT_1] -+TYPE = LINEAR -+MIN_LIMIT = -10 -+MAX_LIMIT = 10 -+MAX_VELOCITY = 10 -+MAX_ACCELERATION = 100 -+MAX_JERK = 10000 -+FERROR = 1 -+MIN_FERROR = 0.25 -+HOME = 0 -+HOME_SEQUENCE = 0 -+HOME_SEARCH_VEL = 0 -+HOME_LATCH_VEL = 0 -diff --git a/tests/power-jog/test.sh b/tests/power-jog/test.sh -new file mode 100755 -index 0000000000..4397029735 ---- /dev/null -+++ b/tests/power-jog/test.sh -@@ -0,0 +1,7 @@ -+#!/bin/sh -+set -eu -+linuxcnc -r test.ini -+sed '/\[TRAJ\]/a PLANNER_TYPE = 1' test.ini > scurve.ini -+linuxcnc -r scurve.ini -+sed 's/LATHE = 1/LATHE = 0/' test.ini > nonlathe.ini -+POWER_JOG_NONLATHE=1 linuxcnc -r nonlathe.ini -diff --git a/tests/power-jog/tool.tbl b/tests/power-jog/tool.tbl -new file mode 100644 -index 0000000000..68840ea75c ---- /dev/null -+++ b/tests/power-jog/tool.tbl -@@ -0,0 +1 @@ -+T1 P1 Z0 D0 diff --git a/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch b/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch index 82765d4a..98e06109 100644 --- a/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch +++ b/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch @@ -4,21 +4,13 @@ Date: Tue, 22 Sep 2026 12:56:22 +0200 Subject: [PATCH] hal: support cross-compiling external components --- - docs/src/man/man1/halcompile.1.adoc | 34 ++++ - src/Makefile.modinc.in | 64 +++++-- - src/hal/utils/halcompile.g | 129 +++++++++++-- - tests/halcompile/cross-tools/.gitignore | 2 + - tests/halcompile/cross-tools/checkresult | 4 + - tests/halcompile/cross-tools/cross_tools.comp | 6 + - tests/halcompile/cross-tools/test.sh | 170 ++++++++++++++++++ - 7 files changed, 382 insertions(+), 27 deletions(-) - create mode 100644 tests/halcompile/cross-tools/.gitignore - create mode 100755 tests/halcompile/cross-tools/checkresult - create mode 100644 tests/halcompile/cross-tools/cross_tools.comp - create mode 100755 tests/halcompile/cross-tools/test.sh + docs/src/man/man1/halcompile.1.adoc | 34 ++++++++ + src/Makefile.modinc.in | 69 ++++++++++++--- + src/hal/utils/halcompile.g | 130 ++++++++++++++++++++++++---- + 3 files changed, 206 insertions(+), 27 deletions(-) diff --git a/docs/src/man/man1/halcompile.1.adoc b/docs/src/man/man1/halcompile.1.adoc -index c06cd1b868..f5f5bc1116 100644 +index 593be84..e688a75 100644 --- a/docs/src/man/man1/halcompile.1.adoc +++ b/docs/src/man/man1/halcompile.1.adoc @@ -74,6 +74,40 @@ Extra arguments passed to the C-compiler. @@ -63,10 +55,10 @@ index c06cd1b868..f5f5bc1116 100644 *halcompile* performs many different functions: diff --git a/src/Makefile.modinc.in b/src/Makefile.modinc.in -index ed9d75d98c..89904320d4 100644 +index 85bc79d..42db924 100644 --- a/src/Makefile.modinc.in +++ b/src/Makefile.modinc.in -@@ -65,46 +65,87 @@ BUILDSYS = @BUILD_SYS@ +@@ -65,46 +65,92 @@ BUILDSYS = @BUILD_SYS@ KERNELDIR := @KERNELDIR@ CC := @CC@ RTAI = @RTAI@ @@ -74,6 +66,11 @@ index ed9d75d98c..89904320d4 100644 +exec_prefix := @exec_prefix@ +EMC2_HOME=@EMC2_HOME@ +RUN_IN_PLACE=@RUN_IN_PLACE@ ++# Only halcompile --sysroot selects a cross build; a SYSROOT exported by a ++# cross SDK environment must not turn a native build into one. ++ifneq ($(origin SYSROOT),command line) ++SYSROOT := ++endif +ifneq ($(SYSROOT),) +ifeq ($(RUN_IN_PLACE),yes) +$(error Cross compilation from a run-in-place build requires an installed target Makefile.modinc; pass --modinc=...) @@ -163,7 +160,7 @@ index ed9d75d98c..89904320d4 100644 getobjs = $(if $(filter undefined, $(origin $(1)-objs)), $(1).o, $($(1)-objs)) getsrcs = $(patsubst %.o,%.c,$(call getobjs,$(1))) -@@ -119,8 +160,8 @@ $(foreach mod,$(patsubst %.o,%,$(obj-m)),\ +@@ -119,8 +165,8 @@ $(foreach mod,$(patsubst %.o,%,$(obj-m)),\ .PHONY: %.so %.so: $(ECHO) Linking $@ @@ -173,14 +170,14 @@ index ed9d75d98c..89904320d4 100644 + $(Q)$(OBJDUMP) -w -j .rtapi_export -t $*.tmp \ | awk 'BEGIN{print "{ global :"} /rtapi_exported_/{printf("%s;\n", substr($$6,16))} END{print "local : * ; };"}' \ > $*.ver - $(Q)$(CC) -shared -Bsymbolic $(LDFLAGS) -Wl,--version-script,$*.ver -o $@ $^ -lm $(EXTRA_LDFLAGS) -@@ -130,4 +171,3 @@ endif + $(Q)$(CC) -shared -Wl,-Bsymbolic $(LDFLAGS) -Wl,--version-script,$*.ver -o $@ $^ -lm $(EXTRA_LDFLAGS) +@@ -130,4 +176,3 @@ endif ifeq ($(BUILDSYS),normal) $(error Makefile.modinc is only suitable for 'kbuild' kernels and 'uspace' systems) endif - diff --git a/src/hal/utils/halcompile.g b/src/hal/utils/halcompile.g -index fcce8c6329..e8db9fcd42 100644 +index 6bd2afa..2daaf56 100644 --- a/src/hal/utils/halcompile.g +++ b/src/hal/utils/halcompile.g @@ -97,7 +97,7 @@ parser Hal: @@ -192,7 +189,7 @@ index fcce8c6329..e8db9fcd42 100644 import subprocess BASE = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), "..")) BINDIR = os.getenv('USER_MODULE_DIR', None) or os.path.join(BASE, "bin") -@@ -807,6 +807,9 @@ INSTALL, COMPILE, PREPROCESS, DOCUMENT, INSTALLDOC, VIEWDOC, MODINC = range(7) +@@ -982,6 +982,9 @@ INSTALL, COMPILE, PREPROCESS, DOCUMENT, INSTALLDOC, VIEWDOC, MODINC = range(7) modename = ("install", "compile", "preprocess", "document", "installdoc", "viewdoc", "print-modinc") modinc = None @@ -202,7 +199,7 @@ index fcce8c6329..e8db9fcd42 100644 def find_modinc(): global modinc if modinc: return modinc -@@ -818,44 +821,89 @@ def find_modinc(): +@@ -993,44 +996,89 @@ def find_modinc(): return e raise SystemExit("Unable to locate Makefile.modinc") @@ -305,7 +302,7 @@ index fcce8c6329..e8db9fcd42 100644 if mode == COMPILE: for extension in ".ko", ".so", ".o": kobjname = os.path.splitext(filename)[0] + extension -@@ -1187,6 +1235,18 @@ Options to add compile and link flags (only for userspace, only for .c files) +@@ -1362,6 +1410,18 @@ Options to add compile and link flags (only for userspace, only for .c files) --extra-compile-args="-I/usr/include/..." --extra-link-args="-l..." @@ -324,7 +321,7 @@ index fcce8c6329..e8db9fcd42 100644 Do not use [sudo] for RIP installation. """ % {'name': os.path.basename(sys.argv[0]),'dflt':MAX_PERSONALITIES}) -@@ -1205,14 +1265,24 @@ def main(): +@@ -1382,14 +1442,25 @@ def main(): outfile = None userspace = False global options @@ -339,18 +336,19 @@ index fcce8c6329..e8db9fcd42 100644 + objdump = None + sysroot = None try: - opts, args = getopt.getopt(sys.argv[1:], "UluijJcpdak:o:h?P:", + opts, args = getopt.getopt(sys.argv[1:], "UluijJcpdak:o:h?P:w", ['unix', 'install', 'compile', 'preprocess', 'outfile=', 'document', 'adoc', 'keep-adoc=', 'help', 'userspace', 'install-doc', 'view-doc', 'require-license', 'print-modinc', 'personalities=', "extra-compile-args=", -- 'extra-link-args=']) -+ 'extra-link-args=', 'cross-prefix=', 'sysroot=', -+ 'cc=', 'ld=', 'objdump=', 'make=', 'modinc=']) +- 'extra-link-args=', 'werror']) ++ 'extra-link-args=', 'werror', 'cross-prefix=', ++ 'sysroot=', 'cc=', 'ld=', 'objdump=', 'make=', ++ 'modinc=']) except getopt.GetoptError: usage(1) for k, v in opts: -@@ -1257,9 +1327,38 @@ def main(): +@@ -1434,11 +1505,40 @@ def main(): option("extra_compile_args", v) if k in ("--extra-link-args"): option("extra_link_args", v) @@ -370,6 +368,8 @@ index fcce8c6329..e8db9fcd42 100644 + modinc = os.path.abspath(v) if k in ("-?", "-h", "--help"): usage(0) + if k in ("-w", "--werror"): + warn_is_error = True + if modinc is not None and not os.path.isfile(modinc): + raise SystemExit("Makefile.modinc does not exist: %s" % modinc) @@ -389,209 +389,3 @@ index fcce8c6329..e8db9fcd42 100644 if outfile and mode != PREPROCESS and mode != DOCUMENT: raise SystemExit("Can only specify -o when preprocessing or documenting") -diff --git a/tests/halcompile/cross-tools/.gitignore b/tests/halcompile/cross-tools/.gitignore -new file mode 100644 -index 0000000000..b6e162464d ---- /dev/null -+++ b/tests/halcompile/cross-tools/.gitignore -@@ -0,0 +1,2 @@ -+cross_tools.so -+with space.*/ -diff --git a/tests/halcompile/cross-tools/checkresult b/tests/halcompile/cross-tools/checkresult -new file mode 100755 -index 0000000000..367210b0f7 ---- /dev/null -+++ b/tests/halcompile/cross-tools/checkresult -@@ -0,0 +1,4 @@ -+#!/bin/sh -+set -eu -+ -+test -f "$(dirname "$1")/cross_tools.so" -diff --git a/tests/halcompile/cross-tools/cross_tools.comp b/tests/halcompile/cross-tools/cross_tools.comp -new file mode 100644 -index 0000000000..1d48f620b8 ---- /dev/null -+++ b/tests/halcompile/cross-tools/cross_tools.comp -@@ -0,0 +1,6 @@ -+component cross_tools; -+pin out bit ready; -+function _; -+license "GPL"; -+;; -+ready = 1; -diff --git a/tests/halcompile/cross-tools/test.sh b/tests/halcompile/cross-tools/test.sh -new file mode 100755 -index 0000000000..13c1671450 ---- /dev/null -+++ b/tests/halcompile/cross-tools/test.sh -@@ -0,0 +1,170 @@ -+#!/bin/sh -+set -eu -+ -+space_root=$(mktemp -d "$PWD/with space.XXXXXX") -+trap 'rm -rf -- "$space_root"' EXIT -+cp cross_tools.comp "$space_root/cross_tools.comp" -+cat > "$space_root/cross_user.c" <<'EOF' -+#include "hal.h" -+int main(void) { return hal_init("cross_user") < 0; } -+EOF -+ -+# Target tools that record their arguments and run the host tools. The -+# compiler drops --sysroot so the host compiler keeps its own C library while -+# LinuxCNC headers and libraries still have to be found in the test sysroot. -+tools=$space_root/tools -+mkdir -p "$tools" -+for tool in gcc ld objdump; do -+ cat > "$tools/target-$tool" <> "\$0.log" -+printf '%s\t' "\$@" >> "\$0.log" -+printf '\n' >> "\$0.log" -+for argument; do -+ shift -+ case \$argument in -+ --sysroot=*) ;; -+ *) set -- "\$@" "\$argument" ;; -+ esac -+done -+exec $tool "\$@" -+EOF -+ chmod +x "$tools/target-$tool" -+done -+reset_tool_logs() { -+ rm -f "$tools"/*.log -+} -+# Succeeds when one logged call of tool $1 received every following argument. -+tool_called_with() { -+ calls=$(cat "$tools/target-$1.log") -+ shift -+ for argument; do -+ calls=$(printf '%s\n' "$calls" | grep -F -- "$(printf '\t%s\t' "$argument")") || return 1 -+ done -+} -+ -+# An installed target LinuxCNC, as seen through the sysroot. -+sysroot=$space_root/sysroot -+mkdir -p "$sysroot/usr/include" "$sysroot/usr/lib" -+ln -s "$EMC2_HOME/include" "$sysroot/usr/include/linuxcnc" -+ln -s "$EMC2_HOME/lib/liblinuxcnchal.so" "$sysroot/usr/lib/liblinuxcnchal.so" -+target_modinc=$space_root/target.modinc -+sed -e 's|^RUN_IN_PLACE=.*|RUN_IN_PLACE=no|' \ -+ -e 's|^prefix := .*|prefix := /usr|' \ -+ -e 's|^RTLIBDIR := .*|RTLIBDIR := /usr/lib/linuxcnc/modules|' \ -+ "$(halcompile --print-modinc)" > "$target_modinc" -+ -+target_halcompile() { -+ halcompile --modinc="$target_modinc" --cross-prefix="$tools/target-" \ -+ --sysroot="$sysroot" "$@" -+} -+ -+( -+ cd "$space_root" -+ reset_tool_logs -+ target_halcompile --compile cross_tools.comp -+ test -s cross_tools.so -+ tool_called_with gcc "--sysroot=$sysroot" -c cross_tools.c -+ tool_called_with gcc "--sysroot=$sysroot" -shared -+ tool_called_with ld -r -+ tool_called_with objdump .rtapi_export -+ -+ reset_tool_logs -+ target_halcompile --compile --userspace cross_user.c -+ test -x cross_user -+ tool_called_with gcc "--sysroot=$sysroot" "-L$sysroot/usr/lib" \ -+ -Wl,-rpath,/usr/lib -+) -+ -+# Installation goes to the sysroot unless the caller stages into DESTDIR. -+mkdir -p "$sysroot/usr/lib/linuxcnc/modules" -+( -+ cd "$space_root" -+ target_halcompile --install cross_tools.comp -+ target_halcompile --install --userspace cross_user.c -+) -+test -s "$sysroot/usr/lib/linuxcnc/modules/cross_tools.so" -+test -x "$sysroot/usr/bin/cross_user" -+rm "$sysroot/usr/lib/linuxcnc/modules/cross_tools.so" "$sysroot/usr/bin/cross_user" -+ -+stage=$space_root/stage -+mkdir -p "$stage/usr/lib/linuxcnc/modules" -+( -+ cd "$space_root" -+ DESTDIR=$stage target_halcompile --install cross_tools.comp -+ DESTDIR=$stage target_halcompile --install --userspace cross_user.c -+) -+test -s "$stage/usr/lib/linuxcnc/modules/cross_tools.so" -+test -x "$stage/usr/bin/cross_user" -+test ! -e "$sysroot/usr/lib/linuxcnc/modules/cross_tools.so" -+test ! -e "$sysroot/usr/bin/cross_user" -+ -+if halcompile --install --cross-prefix="$tools/target-" cross_tools.comp \ -+ >"$space_root/host-install-output" 2>&1; then -+ echo "cross installation without a sysroot was accepted" >&2 -+ exit 1 -+fi -+grep -F -- '--cross-prefix requires --sysroot' "$space_root/host-install-output" -+ -+if halcompile --compile --sysroot="$sysroot" cross_tools.comp \ -+ >"$space_root/rip-cross-output" 2>&1; then -+ echo "cross compilation unexpectedly accepted a run-in-place Makefile.modinc" >&2 -+ exit 1 -+fi -+grep -F 'requires an installed target Makefile.modinc' "$space_root/rip-cross-output" -+ -+# A native build ignores target tools exported by a cross SDK environment. -+rm -f cross_tools.so -+LD=false OBJDUMP=false halcompile --compile cross_tools.comp -+test -s cross_tools.so -+ -+# Compiler and make overrides may be commands with arguments. -+( -+ cd "$space_root" -+ rm -f cross_tools.so -+ halcompile --compile --cc="env gcc" --make="env make" cross_tools.comp -+ test -s cross_tools.so -+) -+ -+# Kbuild passes paths with spaces to the kernel build intact. -+mkdir -p "$space_root/kernel dir" "$space_root/module dir" -+cp "$(halcompile --print-modinc)" "$space_root/Makefile.modinc" -+cat > "$space_root/kernel dir/Makefile" <<'EOF' -+modules: -+ @$(CC) --version > "$(CHECK_OUTPUT)" -+ @printf '%s\n' '$(KBUILD_EXTRA_SYMBOLS)' '$(SUBDIRS)' >> "$(CHECK_OUTPUT)" -+EOF -+( -+ cd "$space_root/module dir" -+ make -s -f "$space_root/Makefile.modinc" modules \ -+ BUILDSYS=kbuild KERNELDIR="$space_root/kernel dir" \ -+ RTLIBDIR="$space_root/rt lib" CC="'$tools/target-gcc'" \ -+ CHECK_OUTPUT="$space_root/kbuild-output" -+) -+test -s "$space_root/kbuild-output" -+grep -Fx -- "$space_root/rt lib/Module.symvers" "$space_root/kbuild-output" -+grep -Fx -- "$space_root/module dir" "$space_root/kbuild-output" -+ -+# Kbuild rereads the component Makefile from inside the kernel tree, as -+# scripts/Makefile.build does, so its Makefile.modinc include must resolve -+# from there. -+kbuild_root=$space_root/kbuild -+mkdir -p "$kbuild_root/kernel" -+sed -e 's|^BUILDSYS = .*|BUILDSYS = kbuild|' \ -+ -e "s|^KERNELDIR := .*|KERNELDIR := $kbuild_root/kernel|" \ -+ "$(halcompile --print-modinc)" > "$kbuild_root/Makefile.modinc" -+cat > "$kbuild_root/kernel/Makefile" <<'EOF' -+modules: -+ @$(MAKE) -f "$(SUBDIRS)/Makefile" -f kbuild.mk component -+EOF -+cat > "$kbuild_root/kernel/kbuild.mk" <<'EOF' -+component: -+ @test "$(obj-m)" = cross_tools.o -+ @touch "$(SUBDIRS)/cross_tools.ko" -+EOF -+( -+ cd "$kbuild_root" -+ cp ../cross_tools.comp . -+ halcompile --compile --modinc="$kbuild_root/Makefile.modinc" cross_tools.comp -+ test -f cross_tools.ko -+) diff --git a/linuxcnc-patches/0022-hal-raise-HAL_NAME_LEN-to-55.patch b/linuxcnc-patches/0022-hal-raise-HAL_NAME_LEN-to-55.patch deleted file mode 100644 index 097bbf6b..00000000 --- a/linuxcnc-patches/0022-hal-raise-HAL_NAME_LEN-to-55.patch +++ /dev/null @@ -1,54 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Dariusz Majnert -Date: Wed, 11 Nov 2026 00:11:23 +0100 -Subject: [PATCH] hal: raise HAL_NAME_LEN to 55 - -Match the name length LinuxCNC 2.10 uses, so longer HAL names, including -thread names with descriptive statistic suffixes, fit. The name length is -part of the HAL shared-memory layout, so bump HAL_VER to refuse mixed -builds. ---- - docs/src/hal/general-ref.adoc | 2 +- - src/hal/hal.h | 2 +- - src/hal/hal_priv.h | 2 +- - 3 files changed, 3 insertions(+), 3 deletions(-) - -diff --git a/docs/src/hal/general-ref.adoc b/docs/src/hal/general-ref.adoc -index 5640eb29e8..2bf567ba64 100644 ---- a/docs/src/hal/general-ref.adoc -+++ b/docs/src/hal/general-ref.adoc -@@ -11,7 +11,7 @@ - - (((HAL Entity Names))) - All HAL entities are accessible and manipulable by their names, so documenting the names of pins, signals, parameters, etc., is very important. --Names in HAL have a maximum length of 41 characters (as defined by HAL_NAME_LEN in hal.h). -+Names in HAL have a maximum length of 55 characters (as defined by HAL_NAME_LEN in hal.h). - Many names will be presented in the general form, with formatted text __ representing fields of various values. - - When pins, signals, or parameters are described for the first time, their name will be preceded by their type in parentheses (_float_) and followed by a brief description. -diff --git a/src/hal/hal.h b/src/hal/hal.h -index fb67a33d3c..88bfc9556a 100644 ---- a/src/hal/hal.h -+++ b/src/hal/hal.h -@@ -136,7 +136,7 @@ RTAPI_BEGIN_DECLS - - #include "rtapi_errno.h" - --#define HAL_NAME_LEN 47 /* length for pin, signal, etc, names */ -+#define HAL_NAME_LEN 55 /* length for pin, signal, etc, names */ - - /** These locking codes define the state of HAL locking, are used by most functions */ - /** The functions locked will return a -EPERM error message **/ -diff --git a/src/hal/hal_priv.h b/src/hal/hal_priv.h -index 1bb7d08044..708eb9511d 100644 ---- a/src/hal/hal_priv.h -+++ b/src/hal/hal_priv.h -@@ -118,7 +118,7 @@ - */ - - #define HAL_KEY 0x48414C32 /* key used to open HAL shared memory */ --#define HAL_VER 0x00000010 /* version code */ -+#define HAL_VER 0x00000011 /* version code */ - #define HAL_SIZE (256*4096) - #define HAL_PSEUDO_COMP_PREFIX "__" /* prefix to identify a pseudo component */ - diff --git a/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch b/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch index accd4795..ad546fc6 100644 --- a/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch +++ b/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch @@ -3,29 +3,23 @@ From: Dariusz Majnert Date: Tue, 22 Sep 2026 21:15:00 +0200 Subject: [PATCH] hal: expose native thread period statistics +Ported to the getter/setter HAL API of v2.10.0-pre2. The statistics are +now sint parameters (64-bit, printed in decimal by halcmd) instead of u32 +and s64 ones, and stats-reset is a bool parameter. The measurement keeps +its values in the thread structure and publishes them to the parameters +once per cycle. --- - docs/src/hal/basic-hal.adoc | 23 +++++ - src/hal/hal_lib.c | 73 +++++++++++++++ - src/hal/hal_period_stats.h | 89 +++++++++++++++++++ - src/hal/hal_priv.h | 22 ++++- - tests/save.0/expected | 1 + - .../arithmetic.c | 81 +++++++++++++++++ - tests/thread-period-stats-arithmetic/expected | 0 - tests/thread-period-stats-arithmetic/test.sh | 9 ++ - tests/thread-period-stats/README | 4 + - tests/thread-period-stats/checkresult | 29 ++++++ - tests/thread-period-stats/test.hal | 11 +++ - 11 files changed, 341 insertions(+), 1 deletion(-) + docs/src/hal/basic-hal.adoc | 23 ++++++ + src/hal/hal_lib.c | 98 +++++++++++++++++++++++++ + src/hal/hal_period_stats.h | 118 ++++++++++++++++++++++++++++++ + src/hal/hal_priv.h | 7 +- + tests/halmodule/halquery/expected | 16 ++++ + tests/save.0/expected | 1 + + 6 files changed, 262 insertions(+), 1 deletion(-) create mode 100644 src/hal/hal_period_stats.h - create mode 100644 tests/thread-period-stats-arithmetic/arithmetic.c - create mode 100644 tests/thread-period-stats-arithmetic/expected - create mode 100644 tests/thread-period-stats-arithmetic/test.sh - create mode 100644 tests/thread-period-stats/README - create mode 100755 tests/thread-period-stats/checkresult - create mode 100644 tests/thread-period-stats/test.hal diff --git a/docs/src/hal/basic-hal.adoc b/docs/src/hal/basic-hal.adoc -index b23a0f465a..0112a56838 100644 +index 5cf2078..667f4be 100644 --- a/docs/src/hal/basic-hal.adoc +++ b/docs/src/hal/basic-hal.adoc @@ -383,6 +383,29 @@ These allow you to scope the execution time of a component. @@ -42,15 +36,15 @@ index b23a0f465a..0112a56838 100644 +All times are in nanoseconds. + +[horizontal] -+`.period-target` (u32, RO):: Configured period. -+`.period-last`, `.period-min`, `.period-max`, `.period-avg` (u32, RO):: Latest, shortest, longest and average measured interval. -+`.jitter`, `.jitter-avg`, `.jitter-max` (u32, RO):: Latest, average and largest absolute difference between the measured interval and the configured period. -+`.exec-avg`, `.exec-max` (u32, RO):: Average and longest time to run the thread's functions. -+`.outlier-q`, `.outlier-h` (s64, RO):: Number of intervals whose jitter was at least a quarter or a half of the period. -+`.outlier-at` (s64, RO):: Value of `samples` at the latest quarter-period outlier. -+`.missed` (s64, RO):: Number of intervals longer than two periods. -+`.samples` (s64, RO):: Number of measured intervals. -+`.stats-reset` (bit, RW):: Set to true to clear the statistics. The thread clears them, and this parameter, at the start of its next cycle. ++`.period-target` (sint, RO):: Configured period. ++`.period-last`, `.period-min`, `.period-max`, `.period-avg` (sint, RO):: Latest, shortest, longest and average measured interval. ++`.jitter`, `.jitter-avg`, `.jitter-max` (sint, RO):: Latest, average and largest absolute difference between the measured interval and the configured period. ++`.exec-avg`, `.exec-max` (sint, RO):: Average and longest time to run the thread's functions. ++`.outlier-q`, `.outlier-h` (sint, RO):: Number of intervals whose jitter was at least a quarter or a half of the period. ++`.outlier-at` (sint, RO):: Value of `samples` at the latest quarter-period outlier. ++`.missed` (sint, RO):: Number of intervals longer than two periods. ++`.samples` (sint, RO):: Number of measured intervals. ++`.stats-reset` (bool, RW):: Set to true to clear the statistics. The thread clears them, and this parameter, at the start of its next cycle. + +The first cycle and intervals during which threads were stopped are not measured. +Thread names longer than 41 characters leave no room for the parameter suffixes, so such threads are created without statistics and a warning is logged. @@ -59,97 +53,96 @@ index b23a0f465a..0112a56838 100644 == Basic Logic Components diff --git a/src/hal/hal_lib.c b/src/hal/hal_lib.c -index 653fa53f0c..c10dd268ea 100644 +index 0839355..2820c07 100644 --- a/src/hal/hal_lib.c +++ b/src/hal/hal_lib.c -@@ -56,9 +56,11 @@ - #include /* RTAPI realtime OS API */ - #include "hal.h" /* HAL public API decls */ - #include "hal_priv.h" /* HAL private decls */ -+#include "hal_period_stats.h" - - #include - #include -+#include +@@ -2093,6 +2093,72 @@ int hal_export_funct(const char *name, void (*funct) (void *, long), + return 0; + } - #ifdef RTAPI - #include -@@ -2074,6 +2076,15 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) - hal_thread_t *new, *tptr; - long prev_period, curr_period; - char buf[HAL_NAME_LEN + 1]; -+ unsigned int stat_index; -+ struct period_stat_param { -+ const char *name; -+ hal_u32_t *value; -+ } period_stats[10]; -+ struct period_count_param { -+ const char *name; -+ hal_s64_t *value; -+ } period_counts[5]; - - rtapi_print_msg(RTAPI_MSG_DBG, - "HAL: creating thread %s, %ld nsec\n", name, period_nsec); -@@ -2234,6 +2245,58 @@ int hal_create_thread(const char *name, unsigned long period_nsec, int uses_fp) - return -EINVAL; - } - *(new->runtime) = 0; -+ /* The longest statistic suffix, ".period-target", needs 14 characters. -+ Longer thread names keep working, without period statistics. */ -+ if (strlen(new->name) + 14 > HAL_NAME_LEN) { ++/* Parameter name suffixes of the period statistics, indexed by ++ enum hal_period_stat. */ ++static const char *const period_stat_names[HAL_PERIOD_STAT_COUNT] = { ++ [HAL_PERIOD_STAT_PERIOD_TARGET] = "period-target", ++ [HAL_PERIOD_STAT_PERIOD_LAST] = "period-last", ++ [HAL_PERIOD_STAT_PERIOD_MIN] = "period-min", ++ [HAL_PERIOD_STAT_PERIOD_MAX] = "period-max", ++ [HAL_PERIOD_STAT_JITTER] = "jitter", ++ [HAL_PERIOD_STAT_PERIOD_AVG] = "period-avg", ++ [HAL_PERIOD_STAT_JITTER_AVG] = "jitter-avg", ++ [HAL_PERIOD_STAT_JITTER_MAX] = "jitter-max", ++ [HAL_PERIOD_STAT_EXEC_AVG] = "exec-avg", ++ [HAL_PERIOD_STAT_EXEC_MAX] = "exec-max", ++ [HAL_PERIOD_STAT_OUTLIER_Q] = "outlier-q", ++ [HAL_PERIOD_STAT_OUTLIER_H] = "outlier-h", ++ [HAL_PERIOD_STAT_OUTLIER_AT] = "outlier-at", ++ [HAL_PERIOD_STAT_MISSED] = "missed", ++ [HAL_PERIOD_STAT_SAMPLES] = "samples", ++}; ++#define PERIOD_STATS_RESET_NAME "stats-reset" ++ ++/* Create the period statistic parameters of a thread. Returns 0 when they ++ were created, 1 when the thread name leaves no room for their suffixes, ++ or a negative error code. */ ++static int create_period_stat_params(hal_thread_t *thread) ++{ ++ size_t longest_suffix = strlen(PERIOD_STATS_RESET_NAME); ++ int i, retval; ++ ++ for (i = 0; i < HAL_PERIOD_STAT_COUNT; i++) { ++ if (strlen(period_stat_names[i]) > longest_suffix) ++ longest_suffix = strlen(period_stat_names[i]); ++ } ++ /* "."; ".period-target" is the longest at 14 ++ characters, so thread names of up to HAL_NAME_LEN - 14 = 41 ++ characters receive statistics. */ ++ if (strlen(thread->name) + 1 + longest_suffix > HAL_NAME_LEN) { + rtapi_print_msg(RTAPI_MSG_WARN, + "HAL: thread '%s' name is too long for period statistics\n", -+ new->name); -+ hal_ready(new->comp_id); -+ return new->comp_id; ++ thread->name); ++ return 1; + } -+ new->target_period_ns = new->period > UINT_MAX ? UINT_MAX : new->period; -+ period_stats[0] = (struct period_stat_param){"period-target", &new->target_period_ns}; -+ period_stats[1] = (struct period_stat_param){"period-last", &new->last_period_ns}; -+ period_stats[2] = (struct period_stat_param){"period-min", &new->minimum_period_ns}; -+ period_stats[3] = (struct period_stat_param){"period-max", &new->maximum_period_ns}; -+ period_stats[4] = (struct period_stat_param){"jitter", &new->current_jitter_ns}; -+ period_stats[5] = (struct period_stat_param){"period-avg", &new->average_period_ns}; -+ period_stats[6] = (struct period_stat_param){"jitter-avg", &new->average_jitter_ns}; -+ period_stats[7] = (struct period_stat_param){"jitter-max", &new->maximum_jitter_ns}; -+ period_stats[8] = (struct period_stat_param){"exec-avg", &new->average_execution_ns}; -+ period_stats[9] = (struct period_stat_param){"exec-max", &new->maximum_execution_ns}; -+ period_counts[0] = (struct period_count_param){"outlier-q", &new->jitter_over_quarter_period_count}; -+ period_counts[1] = (struct period_count_param){"outlier-h", &new->jitter_over_half_period_count}; -+ period_counts[2] = (struct period_count_param){"outlier-at", &new->last_jitter_over_quarter_period_sample}; -+ period_counts[3] = (struct period_count_param){"missed", &new->deadline_misses}; -+ period_counts[4] = (struct period_count_param){"samples", &new->sample_count}; -+ for (stat_index = 0; stat_index < 10; stat_index++) { -+ const char *stat_name = period_stats[stat_index].name; -+ if (hal_param_u32_newf(HAL_RO, period_stats[stat_index].value, -+ new->comp_id, "%s.%s", new->name, stat_name)) { -+ rtapi_print_msg(RTAPI_MSG_ERR, -+ "HAL: ERROR: fail to create period stat '%s.%s'\n", -+ new->name, stat_name); -+ return -EINVAL; -+ } -+ } -+ for (stat_index = 0; stat_index < 5; stat_index++) { -+ const char *stat_name = period_counts[stat_index].name; -+ if (hal_param_s64_newf(HAL_RO, period_counts[stat_index].value, -+ new->comp_id, "%s.%s", new->name, stat_name)) { ++ ++ thread->period_stats.value[HAL_PERIOD_STAT_PERIOD_TARGET] = thread->period; ++ for (i = 0; i < HAL_PERIOD_STAT_COUNT; i++) { ++ if ((retval = hal_param_new_sint(thread->comp_id, HAL_RO, ++ &(thread->period_stat_params[i]), ++ thread->period_stats.value[i], ++ "%s.%s", thread->name, period_stat_names[i])) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, -+ "HAL: ERROR: fail to create period count '%s.%s'\n", -+ new->name, stat_name); -+ return -EINVAL; ++ "HAL: ERROR: fail to create param '%s.%s'\n", ++ thread->name, period_stat_names[i]); ++ return retval; + } + } -+ if (hal_param_bit_newf(HAL_RW, &new->period_stats_reset, -+ new->comp_id, "%s.stats-reset", new->name)) { ++ if ((retval = hal_param_new_bool(thread->comp_id, HAL_RW, ++ &(thread->period_stats_reset), 0, ++ "%s." PERIOD_STATS_RESET_NAME, thread->name)) < 0) { + rtapi_print_msg(RTAPI_MSG_ERR, -+ "HAL: ERROR: fail to create period reset for thread '%s'\n", -+ new->name); -+ return -EINVAL; ++ "HAL: ERROR: fail to create param '%s." PERIOD_STATS_RESET_NAME "'\n", ++ thread->name); ++ return retval; ++ } ++ return 0; ++} ++ + int hal_create_thread(const char *name, unsigned long period_nsec) + { + int next, cmp, prev_priority; +@@ -2269,6 +2335,12 @@ int hal_create_thread(const char *name, unsigned long period_nsec) + return retval; + } + ++ // A name too long for the statistics still creates the thread. ++ if ((retval = create_period_stat_params(new)) < 0) { ++ return retval; + } ++ new->period_stats_published = (retval == 0); ++ hal_ready(new->comp_id); rtapi_print_msg(RTAPI_MSG_DBG, "HAL: thread created\n"); -@@ -3150,6 +3213,7 @@ static void thread_task(void *arg) +@@ -3187,6 +3259,7 @@ static void thread_task(void *arg) hal_funct_entry_t *funct_root, *funct_entry; long long int start_time, end_time; long long int thread_start_time; @@ -157,354 +150,251 @@ index 653fa53f0c..c10dd268ea 100644 thread = arg; while (1) { -@@ -3173,6 +3237,7 @@ static void thread_task(void *arg) +@@ -3210,6 +3283,8 @@ static void thread_task(void *arg) funct_entry = SHMPTR(funct_entry->links.next); } rtapi_task_self_resync(); -+ thread->previous_period_start_ns = 0; ++ /* the init cycle and the resync are not a measured interval */ ++ thread->period_stats.previous_start_ns = 0; thread->init_done = 1; /* drain the list now that the init pass is complete */ funct_entry = SHMPTR(funct_root->links.next); -@@ -3190,6 +3255,7 @@ static void thread_task(void *arg) +@@ -3227,6 +3302,14 @@ static void thread_task(void *arg) start_time = rtapi_get_time(); end_time = start_time; thread_start_time = start_time; -+ recorded_sample = hal_period_stats_record_start(thread, thread_start_time); ++ recorded_sample = 0; ++ if (thread->period_stats_published) { ++ if (hal_get_bool(thread->period_stats_reset)) { ++ hal_period_stats_clear(&thread->period_stats); ++ hal_set_bool(thread->period_stats_reset, 0); ++ } ++ recorded_sample = hal_period_stats_record_start(&thread->period_stats, thread_start_time); ++ } /* run thru function list */ while (funct_entry != funct_root) { /* call the function */ -@@ -3216,6 +3282,12 @@ static void thread_task(void *arg) - if ( *(thread->runtime) > thread->maxtime) { - thread->maxtime = *(thread->runtime); +@@ -3254,6 +3337,20 @@ static void thread_task(void *arg) + hal_set_si32(thread->maxtime, runtime); } -+ if (recorded_sample) { -+ unsigned long long execution_ns = end_time - thread_start_time; -+ hal_period_stats_record_execution(thread, execution_ns); + hal_set_sint(thread->threadbeat, ++thread->beatcnt); ++ if (thread->period_stats_published) { ++ int i; ++ if (recorded_sample) { ++ hal_period_stats_record_execution(&thread->period_stats, ++ end_time - thread_start_time); ++ } ++ for (i = 0; i < HAL_PERIOD_STAT_COUNT; i++) { ++ hal_set_sint(thread->period_stat_params[i], ++ thread->period_stats.value[i]); ++ } + } + } else { -+ thread->previous_period_start_ns = 0; ++ /* intervals while threads are stopped are not measured */ ++ thread->period_stats.previous_start_ns = 0; } /* wait until next period */ rtapi_wait(); -@@ -3570,6 +3642,7 @@ static hal_thread_t *alloc_thread_struct(void) +@@ -3613,6 +3710,7 @@ static hal_thread_t *alloc_thread_struct(void) } if (p) { /* make sure it's empty */ + memset(p, 0, sizeof(*p)); p->next_ptr = 0; - p->uses_fp = 0; p->period = 0; + p->priority = 0; diff --git a/src/hal/hal_period_stats.h b/src/hal/hal_period_stats.h new file mode 100644 -index 0000000000..51daf69621 +index 0000000..f38db05 --- /dev/null +++ b/src/hal/hal_period_stats.h -@@ -0,0 +1,89 @@ +@@ -0,0 +1,118 @@ +#ifndef HAL_PERIOD_STATS_H +#define HAL_PERIOD_STATS_H + -+#include -+#include "hal.h" -+#include "hal_priv.h" ++/* Thread period statistics, measured by the HAL thread task and published ++ as . parameters by hal_lib.c. This header only does the ++ arithmetic on plain values, so it can be used from a kernel module and ++ tested without HAL. Times are in nanoseconds. */ ++ ++#include ++ ++enum hal_period_stat { ++ HAL_PERIOD_STAT_PERIOD_TARGET, ++ HAL_PERIOD_STAT_PERIOD_LAST, ++ HAL_PERIOD_STAT_PERIOD_MIN, ++ HAL_PERIOD_STAT_PERIOD_MAX, ++ HAL_PERIOD_STAT_JITTER, ++ HAL_PERIOD_STAT_PERIOD_AVG, ++ HAL_PERIOD_STAT_JITTER_AVG, ++ HAL_PERIOD_STAT_JITTER_MAX, ++ HAL_PERIOD_STAT_EXEC_AVG, ++ HAL_PERIOD_STAT_EXEC_MAX, ++ HAL_PERIOD_STAT_OUTLIER_Q, ++ HAL_PERIOD_STAT_OUTLIER_H, ++ HAL_PERIOD_STAT_OUTLIER_AT, ++ HAL_PERIOD_STAT_MISSED, ++ HAL_PERIOD_STAT_SAMPLES, ++ HAL_PERIOD_STAT_COUNT ++}; ++ ++typedef struct { ++ rtapi_sint value[HAL_PERIOD_STAT_COUNT]; ++ rtapi_s64 previous_start_ns; /* 0: no interval start to measure from */ ++ rtapi_u64 period_sum_ns; ++ rtapi_u64 jitter_sum_ns; ++ rtapi_u64 execution_sum_ns; ++} hal_period_stats_t; + -+static inline void hal_period_stats_clear(hal_thread_t *thread) ++/* Clear everything except the configured period. The next interval is ++ measured from the next start, not from the one before the clear. */ ++static inline void hal_period_stats_clear(hal_period_stats_t *stats) +{ -+ thread->last_period_ns = 0; -+ thread->minimum_period_ns = 0; -+ thread->maximum_period_ns = 0; -+ thread->current_jitter_ns = 0; -+ thread->average_period_ns = 0; -+ thread->average_jitter_ns = 0; -+ thread->maximum_jitter_ns = 0; -+ thread->average_execution_ns = 0; -+ thread->maximum_execution_ns = 0; -+ thread->jitter_over_quarter_period_count = 0; -+ thread->jitter_over_half_period_count = 0; -+ thread->last_jitter_over_quarter_period_sample = 0; -+ thread->deadline_misses = 0; -+ thread->sample_count = 0; -+ thread->period_sum_ns = 0; -+ thread->jitter_sum_ns = 0; -+ thread->execution_sum_ns = 0; -+ thread->previous_period_start_ns = 0; -+ thread->period_stats_reset = 0; ++ int i; ++ ++ for (i = 0; i < HAL_PERIOD_STAT_COUNT; i++) { ++ if (i != HAL_PERIOD_STAT_PERIOD_TARGET) ++ stats->value[i] = 0; ++ } ++ stats->previous_start_ns = 0; ++ stats->period_sum_ns = 0; ++ stats->jitter_sum_ns = 0; ++ stats->execution_sum_ns = 0; +} + -+static inline int hal_period_stats_record_start(hal_thread_t *thread, -+ long long start_ns) ++static inline void hal_period_stats_saturating_increment(rtapi_sint *value) +{ -+ unsigned long long actual_period, jitter, average; ++ if (*value < RTAPI_SINT_MAX) ++ (*value)++; ++} ++ ++/* Record the start of a cycle. Returns nonzero when the interval since the ++ previous start was measured, so the cycle's execution time is recorded ++ too. */ ++static inline int hal_period_stats_record_start(hal_period_stats_t *stats, ++ rtapi_s64 start_ns) ++{ ++ rtapi_sint *value = stats->value; ++ rtapi_u64 period = value[HAL_PERIOD_STAT_PERIOD_TARGET]; ++ rtapi_u64 actual_period, jitter; + int recorded = 0; + -+ if (thread->period_stats_reset) hal_period_stats_clear(thread); -+ if (thread->previous_period_start_ns > 0 && -+ start_ns >= thread->previous_period_start_ns) { -+ actual_period = start_ns - thread->previous_period_start_ns; -+ jitter = actual_period > (unsigned long long)thread->period -+ ? actual_period - thread->period : thread->period - actual_period; -+ thread->last_period_ns = actual_period > UINT_MAX ? UINT_MAX : actual_period; -+ thread->current_jitter_ns = jitter > UINT_MAX ? UINT_MAX : jitter; -+ if (thread->minimum_period_ns == 0 || -+ actual_period < thread->minimum_period_ns) -+ thread->minimum_period_ns = thread->last_period_ns; -+ if (actual_period > thread->maximum_period_ns) -+ thread->maximum_period_ns = thread->last_period_ns; -+ if (jitter > thread->maximum_jitter_ns) -+ thread->maximum_jitter_ns = thread->current_jitter_ns; -+ if (thread->sample_count < LLONG_MAX) -+ thread->sample_count++; ++ if (stats->previous_start_ns > 0 && start_ns >= stats->previous_start_ns) { ++ actual_period = start_ns - stats->previous_start_ns; ++ jitter = actual_period > period ++ ? actual_period - period : period - actual_period; ++ value[HAL_PERIOD_STAT_PERIOD_LAST] = actual_period; ++ value[HAL_PERIOD_STAT_JITTER] = jitter; ++ if (value[HAL_PERIOD_STAT_SAMPLES] == 0 || ++ actual_period < (rtapi_u64)value[HAL_PERIOD_STAT_PERIOD_MIN]) ++ value[HAL_PERIOD_STAT_PERIOD_MIN] = actual_period; ++ if (actual_period > (rtapi_u64)value[HAL_PERIOD_STAT_PERIOD_MAX]) ++ value[HAL_PERIOD_STAT_PERIOD_MAX] = actual_period; ++ if (jitter > (rtapi_u64)value[HAL_PERIOD_STAT_JITTER_MAX]) ++ value[HAL_PERIOD_STAT_JITTER_MAX] = jitter; ++ hal_period_stats_saturating_increment(&value[HAL_PERIOD_STAT_SAMPLES]); + recorded = 1; -+ thread->period_sum_ns += actual_period; -+ thread->jitter_sum_ns += jitter; -+ average = thread->period_sum_ns / thread->sample_count; -+ thread->average_period_ns = average > UINT_MAX ? UINT_MAX : average; -+ average = thread->jitter_sum_ns / thread->sample_count; -+ thread->average_jitter_ns = average > UINT_MAX ? UINT_MAX : average; -+ if (jitter >= ((unsigned long long)thread->period + 3) / 4) { -+ if (thread->jitter_over_quarter_period_count < LLONG_MAX) -+ thread->jitter_over_quarter_period_count++; -+ thread->last_jitter_over_quarter_period_sample = thread->sample_count; ++ stats->period_sum_ns += actual_period; ++ stats->jitter_sum_ns += jitter; ++ value[HAL_PERIOD_STAT_PERIOD_AVG] = ++ stats->period_sum_ns / (rtapi_u64)value[HAL_PERIOD_STAT_SAMPLES]; ++ value[HAL_PERIOD_STAT_JITTER_AVG] = ++ stats->jitter_sum_ns / (rtapi_u64)value[HAL_PERIOD_STAT_SAMPLES]; ++ if (jitter >= (period + 3) / 4) { ++ hal_period_stats_saturating_increment(&value[HAL_PERIOD_STAT_OUTLIER_Q]); ++ value[HAL_PERIOD_STAT_OUTLIER_AT] = value[HAL_PERIOD_STAT_SAMPLES]; + } -+ if (jitter >= ((unsigned long long)thread->period + 1) / 2 && -+ thread->jitter_over_half_period_count < LLONG_MAX) -+ thread->jitter_over_half_period_count++; -+ if (actual_period > (unsigned long long)thread->period * 2 && -+ thread->deadline_misses < LLONG_MAX) -+ thread->deadline_misses++; ++ if (jitter >= (period + 1) / 2) ++ hal_period_stats_saturating_increment(&value[HAL_PERIOD_STAT_OUTLIER_H]); ++ if (actual_period > period * 2) ++ hal_period_stats_saturating_increment(&value[HAL_PERIOD_STAT_MISSED]); + } -+ thread->previous_period_start_ns = start_ns; ++ stats->previous_start_ns = start_ns; + return recorded; +} + -+static inline void hal_period_stats_record_execution(hal_thread_t *thread, -+ unsigned long long execution_ns) ++/* Record the execution time of a cycle whose start was recorded. */ ++static inline void hal_period_stats_record_execution(hal_period_stats_t *stats, ++ rtapi_u64 execution_ns) +{ -+ unsigned long long average; ++ rtapi_sint *value = stats->value; + -+ if (execution_ns > thread->maximum_execution_ns) -+ thread->maximum_execution_ns = execution_ns > UINT_MAX ? UINT_MAX : execution_ns; -+ thread->execution_sum_ns += execution_ns; -+ average = thread->execution_sum_ns / thread->sample_count; -+ thread->average_execution_ns = average > UINT_MAX ? UINT_MAX : average; ++ if (execution_ns > (rtapi_u64)value[HAL_PERIOD_STAT_EXEC_MAX]) ++ value[HAL_PERIOD_STAT_EXEC_MAX] = execution_ns; ++ stats->execution_sum_ns += execution_ns; ++ value[HAL_PERIOD_STAT_EXEC_AVG] = ++ stats->execution_sum_ns / (rtapi_u64)value[HAL_PERIOD_STAT_SAMPLES]; +} + +#endif diff --git a/src/hal/hal_priv.h b/src/hal/hal_priv.h -index 708eb9511d..9edf398358 100644 +index c465dcc..5196348 100644 --- a/src/hal/hal_priv.h +++ b/src/hal/hal_priv.h -@@ -118,7 +118,7 @@ +@@ -100,6 +100,7 @@ + + #include + #include ++#include "hal_period_stats.h" + + /* IMPORTANT: If any of the structures in this file are changed, the + version code (HAL_VER) must be incremented, to ensure that +@@ -124,7 +125,7 @@ */ #define HAL_KEY 0x48414C32 /* key used to open HAL shared memory */ --#define HAL_VER 0x00000011 /* version code */ -+#define HAL_VER 0x00000012 /* version code */ - #define HAL_SIZE (256*4096) - #define HAL_PSEUDO_COMP_PREFIX "__" /* prefix to identify a pseudo component */ +-#define HAL_VER 0x00000015 /* version code */ ++#define HAL_VER 0x00000016 /* version code */ + #define HAL_SIZE (2*256*4096) -@@ -394,6 +394,26 @@ struct hal_thread_t { - int task_id; /* ID of the task that runs this thread */ - hal_s32_t* runtime; /* (pin) duration of last run, in ns */ - hal_s32_t maxtime; /* (param) duration of longest run, in ns */ -+ hal_u32_t target_period_ns; -+ hal_u32_t last_period_ns; -+ hal_u32_t minimum_period_ns; -+ hal_u32_t maximum_period_ns; -+ hal_u32_t current_jitter_ns; -+ hal_u32_t average_period_ns; -+ hal_u32_t average_jitter_ns; -+ hal_u32_t maximum_jitter_ns; -+ hal_u32_t average_execution_ns; -+ hal_u32_t maximum_execution_ns; -+ hal_s64_t jitter_over_quarter_period_count; -+ hal_s64_t jitter_over_half_period_count; -+ hal_s64_t last_jitter_over_quarter_period_sample; -+ hal_s64_t deadline_misses; -+ hal_s64_t sample_count; -+ hal_bit_t period_stats_reset; -+ long long previous_period_start_ns; -+ unsigned long long period_sum_ns; -+ unsigned long long jitter_sum_ns; -+ unsigned long long execution_sum_ns; - hal_list_t funct_list; /* list of functions to run */ - hal_list_t init_funct_list; /* list of init functions, run once before first cyclic cycle */ - int init_done; /* 0 = init pending, 1 = init cycle has executed */ + /* These pointers are set by hal_init() to point to the shmem block +@@ -427,6 +428,10 @@ struct hal_thread_t { + hal_sint_t maxtime; // (param) duration of longest run, in ns + hal_sint_t threadbeat; // (pin) visible monotonic loop beat counter + rtapi_sint beatcnt; // Thread monotonic increasing loop beat counter (so we don't need to read/write volatile) ++ hal_period_stats_t period_stats; // period statistics, measured by the thread ++ hal_sint_t period_stat_params[HAL_PERIOD_STAT_COUNT]; // (params) published period_stats values ++ hal_bool_t period_stats_reset; // (param) clear period_stats on the next cycle ++ int period_stats_published; // nonzero once the period statistic params exist + hal_list_t funct_list; // list of functions to run + hal_list_t init_funct_list; // list of init functions, run once before first cyclic cycle + int init_done; // 0 = init pending, 1 = init cycle has executed +diff --git a/tests/halmodule/halquery/expected b/tests/halmodule/halquery/expected +index 84bb9e1..892ac12 100644 +--- a/tests/halmodule/halquery/expected ++++ b/tests/halmodule/halquery/expected +@@ -18,6 +18,22 @@ and2.0.tmax {'haltype': 'parameter', 'name': 'and2.0.tmax', 'type': , + and2.0.tmax-increased {'haltype': 'parameter', 'name': 'and2.0.tmax-increased', 'type': , 'dir': , 'value': False, 'alias': None, 'comp': 'and2', 'comp_id': 'ID'} + or2.0.tmax {'haltype': 'parameter', 'name': 'or2.0.tmax', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': 'or2', 'comp_id': 'ID'} + or2.0.tmax-increased {'haltype': 'parameter', 'name': 'or2.0.tmax-increased', 'type': , 'dir': , 'value': False, 'alias': None, 'comp': 'or2', 'comp_id': 'ID'} ++testthread.exec-avg {'haltype': 'parameter', 'name': 'testthread.exec-avg', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.exec-max {'haltype': 'parameter', 'name': 'testthread.exec-max', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.jitter {'haltype': 'parameter', 'name': 'testthread.jitter', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.jitter-avg {'haltype': 'parameter', 'name': 'testthread.jitter-avg', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.jitter-max {'haltype': 'parameter', 'name': 'testthread.jitter-max', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.missed {'haltype': 'parameter', 'name': 'testthread.missed', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.outlier-at {'haltype': 'parameter', 'name': 'testthread.outlier-at', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.outlier-h {'haltype': 'parameter', 'name': 'testthread.outlier-h', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.outlier-q {'haltype': 'parameter', 'name': 'testthread.outlier-q', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.period-avg {'haltype': 'parameter', 'name': 'testthread.period-avg', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.period-last {'haltype': 'parameter', 'name': 'testthread.period-last', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.period-max {'haltype': 'parameter', 'name': 'testthread.period-max', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.period-min {'haltype': 'parameter', 'name': 'testthread.period-min', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.period-target {'haltype': 'parameter', 'name': 'testthread.period-target', 'type': , 'dir': , 'value': 1000000, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.samples {'haltype': 'parameter', 'name': 'testthread.samples', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} ++testthread.stats-reset {'haltype': 'parameter', 'name': 'testthread.stats-reset', 'type': , 'dir': , 'value': False, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} + testthread.tmax {'haltype': 'parameter', 'name': 'testthread.tmax', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': '__testthread', 'comp_id': 'ID'} + xor2.0.tmax {'haltype': 'parameter', 'name': 'xor2.0.tmax', 'type': , 'dir': , 'value': 0, 'alias': None, 'comp': 'xor2', 'comp_id': 'ID'} + xor2.0.tmax-increased {'haltype': 'parameter', 'name': 'xor2.0.tmax-increased', 'type': , 'dir': , 'value': False, 'alias': None, 'comp': 'xor2', 'comp_id': 'ID'} diff --git a/tests/save.0/expected b/tests/save.0/expected -index 1ad2895953..d0e14360e9 100644 +index 6b849eb..cfbf203 100644 --- a/tests/save.0/expected +++ b/tests/save.0/expected -@@ -11,6 +11,7 @@ newsig unlinked bit +@@ -11,6 +11,7 @@ newsig unlinked bool net dir stepgen.0.dir => sampler.0.pin.0 net step stepgen.0.step => sampler.0.pin.1 # parameter values +setp fast.stats-reset FALSE setp fast.tmax 0 setp sampler.0.tmax 0 - setp stepgen.0.dirhold 0x00000001 -diff --git a/tests/thread-period-stats-arithmetic/arithmetic.c b/tests/thread-period-stats-arithmetic/arithmetic.c -new file mode 100644 -index 0000000000..b424f911f7 ---- /dev/null -+++ b/tests/thread-period-stats-arithmetic/arithmetic.c -@@ -0,0 +1,81 @@ -+#include -+#include -+#include -+ -+#include "hal_period_stats.h" -+ -+int main(void) -+{ -+ hal_thread_t thread; -+ -+ memset(&thread, 0, sizeof(thread)); -+ thread.period = 1000000; -+ thread.target_period_ns = 1000000; -+ -+ assert(!hal_period_stats_record_start(&thread, 1000000)); -+ assert(thread.sample_count == 0); -+ -+ assert(hal_period_stats_record_start(&thread, 2100000)); -+ hal_period_stats_record_execution(&thread, 80000); -+ assert(thread.last_period_ns == 1100000); -+ assert(thread.current_jitter_ns == 100000); -+ assert(thread.minimum_period_ns == 1100000); -+ assert(thread.maximum_period_ns == 1100000); -+ assert(thread.jitter_over_quarter_period_count == 0); -+ assert(thread.deadline_misses == 0); -+ -+ assert(hal_period_stats_record_start(&thread, 3700000)); -+ hal_period_stats_record_execution(&thread, 120000); -+ assert(thread.sample_count == 2); -+ assert(thread.average_period_ns == 1350000); -+ assert(thread.average_jitter_ns == 350000); -+ assert(thread.maximum_jitter_ns == 600000); -+ assert(thread.jitter_over_quarter_period_count == 1); -+ assert(thread.jitter_over_half_period_count == 1); -+ assert(thread.last_jitter_over_quarter_period_sample == 2); -+ assert(thread.average_execution_ns == 100000); -+ assert(thread.maximum_execution_ns == 120000); -+ -+ assert(hal_period_stats_record_start(&thread, 6800000)); -+ hal_period_stats_record_execution(&thread, 40000); -+ assert(thread.sample_count == 3); -+ assert(thread.last_period_ns == 3100000); -+ assert(thread.minimum_period_ns == 1100000); -+ assert(thread.maximum_period_ns == 3100000); -+ assert(thread.current_jitter_ns == 2100000); -+ assert(thread.average_period_ns == 1933333); -+ assert(thread.average_jitter_ns == 933333); -+ assert(thread.maximum_jitter_ns == 2100000); -+ assert(thread.jitter_over_quarter_period_count == 2); -+ assert(thread.jitter_over_half_period_count == 2); -+ assert(thread.last_jitter_over_quarter_period_sample == 3); -+ assert(thread.deadline_misses == 1); -+ assert(thread.average_execution_ns == 80000); -+ assert(thread.maximum_execution_ns == 120000); -+ -+ thread.period_stats_reset = 1; -+ assert(!hal_period_stats_record_start(&thread, 7800000)); -+ assert(!thread.period_stats_reset); -+ assert(thread.sample_count == 0); -+ assert(thread.maximum_period_ns == 0); -+ assert(thread.maximum_jitter_ns == 0); -+ assert(thread.maximum_execution_ns == 0); -+ assert(thread.jitter_over_quarter_period_count == 0); -+ assert(thread.deadline_misses == 0); -+ assert(thread.target_period_ns == 1000000); -+ -+ assert(hal_period_stats_record_start(&thread, 8800000)); -+ hal_period_stats_record_execution(&thread, 60000); -+ assert(thread.sample_count == 1); -+ assert(thread.average_period_ns == 1000000); -+ assert(thread.average_jitter_ns == 0); -+ assert(thread.average_execution_ns == 60000); -+ -+ thread.sample_count = UINT_MAX; -+ assert(hal_period_stats_record_start(&thread, 9800000)); -+ hal_period_stats_record_execution(&thread, 200000); -+ assert(thread.sample_count == (long long)UINT_MAX + 1); -+ assert(thread.maximum_execution_ns == 200000); -+ -+ return 0; -+} -diff --git a/tests/thread-period-stats-arithmetic/expected b/tests/thread-period-stats-arithmetic/expected -new file mode 100644 -index 0000000000..e69de29bb2 -diff --git a/tests/thread-period-stats-arithmetic/test.sh b/tests/thread-period-stats-arithmetic/test.sh -new file mode 100644 -index 0000000000..fa95744a0b ---- /dev/null -+++ b/tests/thread-period-stats-arithmetic/test.sh -@@ -0,0 +1,9 @@ -+#!/bin/sh -+set -eu -+ -+test_dir=$(mktemp -d) -+trap 'rm -rf -- "$test_dir"' EXIT -+cc -std=gnu11 -DULAPI -I"$EMC2_HOME/src/hal" -I"$EMC2_HOME/src/rtapi" \ -+ -I"$EMC2_HOME/src" -I"$EMC2_HOME/src/include" \ -+ -o "$test_dir/arithmetic" arithmetic.c -+"$test_dir/arithmetic" -diff --git a/tests/thread-period-stats/README b/tests/thread-period-stats/README -new file mode 100644 -index 0000000000..dd01becf7f ---- /dev/null -+++ b/tests/thread-period-stats/README -@@ -0,0 +1,4 @@ -+Period statistics use fixed short suffixes. A 41-character thread name is the -+longest that holds them within HAL_NAME_LEN; a longer valid name still creates -+its thread, without statistics. The sample counter is a 64-bit decimal HAL -+parameter and advances after the thread starts. -diff --git a/tests/thread-period-stats/checkresult b/tests/thread-period-stats/checkresult -new file mode 100755 -index 0000000000..26d2ded04d ---- /dev/null -+++ b/tests/thread-period-stats/checkresult -@@ -0,0 +1,29 @@ -+#!/usr/bin/env python3 -+import sys -+ -+samples = {"servo-thread.samples": [], "period-statistics-boundary-thread-name-41.samples": []} -+resets = {"servo-thread.stats-reset": False, "period-statistics-boundary-thread-name-41.stats-reset": False} -+unpublished = [] -+with open(sys.argv[1], encoding="utf-8") as output: -+ for line in output: -+ fields = line.split() -+ if len(fields) < 5: -+ continue -+ if fields[-1] in samples: -+ if fields[1] != "s64" or fields[2] != "RO": -+ raise SystemExit("sample counter has an unexpected type") -+ samples[fields[-1]].append(int(fields[-2], 0)) -+ if fields[-1] in resets: -+ resets[fields[-1]] = fields[1] == "bit" and fields[2] == "RW" -+ if fields[-1].startswith("period-statistics-boundary-thread-name-41x."): -+ unpublished.append(fields[-1]) -+ -+if not all(resets.values()): -+ raise SystemExit("thread reset parameter was not published") -+for name, observed in samples.items(): -+ if len(observed) != 2 or observed[0] != 0 or observed[1] <= 0: -+ raise SystemExit("sample counter did not advance after thread start: " + name) -+if any(name not in ("period-statistics-boundary-thread-name-41x.time", "period-statistics-boundary-thread-name-41x.tmax") for name in unpublished): -+ raise SystemExit("statistics published for a name that cannot hold them: " + str(unpublished)) -+if "period-statistics-boundary-thread-name-41x.tmax" not in unpublished: -+ raise SystemExit("thread with a long name was not created") -diff --git a/tests/thread-period-stats/test.hal b/tests/thread-period-stats/test.hal -new file mode 100644 -index 0000000000..452dd58828 ---- /dev/null -+++ b/tests/thread-period-stats/test.hal -@@ -0,0 +1,11 @@ -+setexact_for_test_suite_only -+loadrt threads name1=servo-thread period1=1000000 name2=period-statistics-boundary-thread-name-41 period2=2000000 name3=period-statistics-boundary-thread-name-41x period3=2000000 -+show param servo-thread.samples -+show param servo-thread.stats-reset -+show param period-statistics-boundary-thread-name-41.samples -+show param period-statistics-boundary-thread-name-41.stats-reset -+show param period-statistics-boundary-thread-name-41x. -+start -+loadusr -w sleep 0.05 -+show param servo-thread.samples -+show param period-statistics-boundary-thread-name-41.samples + setp stepgen.0.dirhold 0x0000000000000001 diff --git a/linuxcnc-patches/0024-task-drop-interrupted-MDI-call-state-whenever-the-interpreter-is-reset.patch b/linuxcnc-patches/0024-task-drop-interrupted-MDI-call-state-whenever-the-interpreter-is-reset.patch new file mode 100644 index 00000000..c0080197 --- /dev/null +++ b/linuxcnc-patches/0024-task-drop-interrupted-MDI-call-state-whenever-the-interpreter-is-reset.patch @@ -0,0 +1,78 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Dariusz Majnert +Date: Thu, 12 Nov 2026 14:09:33 +0100 +Subject: [PATCH] task: drop interrupted MDI call state whenever the + interpreter is reset + +An MDI command that runs a remap (or an O-word call) and has to wait for +its queue to drain leaves task with continuation state: mdi_execute_level, +mdi_execute_wait and mdi_execute_next, which make task call +interp.execute(NULL) to resume the call once the queue is empty. +mdi_execute_abort() clears that state, but only some abort paths call it. + +emcTaskAbort() closes and resets the interpreter, which unwinds the call +stack, yet the callers in emctask.cc cannot reach the static +mdi_execute_abort(): emcTaskSetState() for E-stop, machine off and E-stop +reset, emcTaskSetMode() for MDI and AUTO, the ON to not-ON edge in +emcTaskUpdate() and the error path of emcTaskPlanSynch(). In all of these +the stale state survives, and when the machine is back on in MDI mode task +resumes a call that no longer exists. For a Python remap that segfaults +milltask in Interp::execute_call() (no executing remap); for an NGC remap +the MDI command never finishes. Commands queued behind the interrupted one +also survived and ran after the machine was re-enabled. + +Make mdi_execute_abort() visible to emctask.cc and call it at the end of +emcTaskAbort(), right after the interpreter reset. The existing explicit +calls next to emcTaskAbort() are left as they are; a second call is a +no-op. + +tests/remap/mdi-remap-abort interrupts a waiting NGC and a waiting Python +remap with each of E-stop, machine off, a mode change and an abort followed +by an interpreter re-init once idle, and checks that milltask survives and +MDI works afterwards. +--- + src/emc/task/emctask.cc | 4 ++++ + src/emc/task/emctaskmain.cc | 2 +- + src/emc/task/task.hh | 1 + + 3 files changed, 6 insertions(+), 1 deletion(-) + +diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc +index f889dd3..b6793d2 100644 +--- a/src/emc/task/emctask.cc ++++ b/src/emc/task/emctask.cc +@@ -282,6 +282,10 @@ int emcTaskAbort() + } + } + ++ // the reset above unwound any call an interrupted MDI command was ++ // inside of, so its continuation and queued MDI commands go too ++ mdi_execute_abort(); ++ + return 0; + } + +diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc +index db1e711..f318c1e 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -817,7 +817,7 @@ interpret_again: + } // if interp len is less than max + } + +-static void mdi_execute_abort(void) ++void mdi_execute_abort(void) + { + int queued_mdi_commands; + +diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh +index 4a7089e..4220b67 100644 +--- a/src/emc/task/task.hh ++++ b/src/emc/task/task.hh +@@ -34,6 +34,7 @@ int emcTaskInit(); + int emcTaskHalt(); + int emcTaskStateRestore(); + int emcTaskAbort(); ++void mdi_execute_abort(void); + void emcTaskCancelAvailability(); + int emcTaskSetMode(EMC_TASK_MODE mode); + int emcTaskSetState(EMC_TASK_STATE state); diff --git a/linuxcnc-patches/0025-task-refuse-an-interpreter-reset-unless-the-machine-is-idle.patch b/linuxcnc-patches/0025-task-refuse-an-interpreter-reset-unless-the-machine-is-idle.patch new file mode 100644 index 00000000..1cc55f2a --- /dev/null +++ b/linuxcnc-patches/0025-task-refuse-an-interpreter-reset-unless-the-machine-is-idle.patch @@ -0,0 +1,110 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Dariusz Majnert +Date: Thu, 19 Nov 2026 08:33:55 +0100 +Subject: [PATCH] task: refuse an interpreter reset unless the machine is idle + +EMC_TASK_PLAN_INIT re-initialises the interpreter at once: it reloads the +INI settings and runs RS274NGC_STARTUP_CODE, whatever task is doing. On a +machine that is still running an MDI command, a dwell, queued motion or a +jog, that silently swaps the modes underneath work in progress. + +Check in emcTaskPlan(), where task handles the command, that the +interpreter, task, the MDI queue and motion are all at rest, and refuse the +reset with an operator error otherwise. Because task is single threaded and +owns this state, no other client can start work between the check and the +reset. + +The new test tests/task/interp-reset-requires-idle checks that resets are +refused during an MDI move, a dwell and a jog without touching the modes, +and accepted again once the machine is idle. +--- + src/emc/task/emctaskmain.cc | 62 +++++++++++++++++++++++++++++++++++++ + 1 file changed, 62 insertions(+) + +diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc +index f318c1e..758ed70 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -1277,6 +1277,45 @@ static void emcTaskStopProgress() + } + } + ++// Why an interpreter reset must wait, or NULL when task, the interpreter ++// and motion are all at rest. ++static const char *interpreterResetBlocker() ++{ ++ if (availability_pending.active) { ++ return "an availability change is in progress"; ++ } ++ if (emcStatus->task.interpState != EMC_TASK_INTERP::IDLE || ++ emcStatus->task.callLevel != 0 || emcTaskPlanIsWait()) { ++ return "the interpreter is running"; ++ } ++ if (emcTaskCommand || interp_list.len() || ++ emcStatus->task.execState != EMC_TASK_EXEC::DONE) { ++ return "task is executing a command"; ++ } ++ if (mdi_execute_queue.len() || mdi_execute_wait || mdi_execute_next || ++ mdi_execute_level >= 0) { ++ return "MDI commands are queued"; ++ } ++ if (emcStatus->task.task_paused || emcStatus->motion.traj.paused || ++ emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE) { ++ return "the machine is paused or stopped mid-program"; ++ } ++ if (emcStatus->motion.status != RCS_STATUS::DONE || ++ emcStatus->io.status != RCS_STATUS::DONE || ++ emcStatus->motion.traj.queue != 0 || ++ emcStatus->motion.traj.activeQueue != 0 || ++ !emcStatus->motion.traj.inpos || ++ emcStatus->motion.traj.current_vel != 0.0) { ++ return "motion is in progress"; ++ } ++ for (int j = 0; j < emcStatus->motion.traj.joints; j++) { ++ if (emcStatus->motion.joint[j].homing) { ++ return "a joint is homing"; ++ } ++ } ++ return NULL; ++} ++ + /* + emcTaskPlan() + +@@ -1296,6 +1335,18 @@ static int emcTaskPlan(void) + type = 0; + } + ++ // Tool table edits and other commands outside a program set the plan ++ // wait so the interpreter does not read past them, but only a reading ++ // interpreter or an MDI call clears it. Once task is idle nothing is ++ // waiting any more; a wait left set would make an idle machine look ++ // busy and refuse interpreter resets. ++ if (emcTaskPlanIsWait() && !mdi_execute_wait && ++ emcStatus->task.interpState == EMC_TASK_INTERP::IDLE && ++ interp_list.len() == 0 && emcTaskCommand == NULL && ++ emcStatus->task.execState == EMC_TASK_EXEC::DONE) { ++ emcTaskPlanClearWait(); ++ } ++ + // Always display messages + switch (type) { + case EMC_OPERATOR_ERROR_TYPE: +@@ -1334,6 +1385,17 @@ static int emcTaskPlan(void) + return retval; + } + ++ if (type == EMC_TASK_PLAN_INIT_TYPE) { ++ // Re-initialising the interpreter restores the startup modes and ++ // drops its state, so it is only allowed on a machine at rest. ++ // Checking here, where task handles the command, leaves no window ++ // in which another client could start work after the check. ++ if (const char *busy = interpreterResetBlocker()) { ++ emcOperatorError(_("interpreter reset refused: %s; abort and wait for the machine to stop first"), busy); ++ return -1; ++ } ++ } ++ + if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && + (type == EMC_TASK_PLAN_RUN_TYPE || + type == EMC_TASK_PLAN_RESUME_TYPE || diff --git a/linuxcnc-patches/0024-task-identify-the-command-an-operator-error-rejects.patch b/linuxcnc-patches/0026-task-identify-the-command-an-operator-error-rejects.patch similarity index 86% rename from linuxcnc-patches/0024-task-identify-the-command-an-operator-error-rejects.patch rename to linuxcnc-patches/0026-task-identify-the-command-an-operator-error-rejects.patch index 76178022..9cf5a0fc 100644 --- a/linuxcnc-patches/0024-task-identify-the-command-an-operator-error-rejects.patch +++ b/linuxcnc-patches/0026-task-identify-the-command-an-operator-error-rejects.patch @@ -28,10 +28,10 @@ the triggering command was refused. 5 files changed, 46 insertions(+), 1 deletion(-) diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index aac79f67e7..cb79aec95f 100644 +index 133869b..a6ac0c1 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc -@@ -1724,6 +1724,7 @@ void EMC_TRAJ_CMD_MSG::update(CMS * /*cms*/) +@@ -1761,6 +1761,7 @@ void EMC_TRAJ_CMD_MSG::update(CMS * /*cms*/) void EMC_OPERATOR_ERROR::update(CMS * cms) { cms->update(error, LINELEN); @@ -40,10 +40,10 @@ index aac79f67e7..cb79aec95f 100644 /* diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index 4141c12994..85118e26e8 100644 +index a9fc353..b105d58 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -40,12 +40,17 @@ class EMC_OPERATOR_ERROR:public RCS_CMD_MSG { +@@ -41,12 +41,17 @@ class EMC_OPERATOR_ERROR:public RCS_CMD_MSG { public: EMC_OPERATOR_ERROR() : RCS_CMD_MSG(EMC_OPERATOR_ERROR_TYPE, sizeof(EMC_OPERATOR_ERROR)), @@ -63,10 +63,10 @@ index 4141c12994..85118e26e8 100644 /** diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index ac4a55781b..865db714c1 100644 +index b6793d2..f378a53 100644 --- a/src/emc/task/emctask.cc +++ b/src/emc/task/emctask.cc -@@ -786,6 +786,10 @@ int emcTaskUpdate(EMC_TASK_STAT * stat) +@@ -865,6 +865,10 @@ int emcTaskUpdate(EMC_TASK_STAT * stat) int emcAbortCleanup(EMC_ABORT reason, const char *message) { @@ -78,10 +78,10 @@ index ac4a55781b..865db714c1 100644 if (status > INTERP_MIN_ERROR) print_interp_error(status); diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 8e88fcf1a3..987314fb83 100644 +index 758ed70..d84d396 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -164,6 +164,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd); +@@ -166,6 +166,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd); // pending command to be sent out by emcTaskExecute() std::unique_ptr emcTaskCommand; @@ -90,7 +90,7 @@ index 8e88fcf1a3..987314fb83 100644 // signal handling code to stop main loop volatile int done; static int emctask_shutdown(void); -@@ -315,6 +317,7 @@ int emcOperatorError(const char *fmt, ...) +@@ -318,6 +320,7 @@ int emcOperatorError(const char *fmt, ...) // force a NULL at the end for safety error_msg.error[LINELEN - 1] = 0; @@ -98,17 +98,17 @@ index 8e88fcf1a3..987314fb83 100644 // write it rcs_print("%s\n", error_msg.error); -@@ -595,6 +598,9 @@ extern int emcTaskMopup(); +@@ -656,6 +659,9 @@ extern int emcTaskMopup(); void readahead_reading(void) { + // Program and queued MDI execution are not part of the command being + // handled in this cycle. + CommandErrorSerialScope background(0); - if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE) { - return; - } -@@ -755,6 +761,9 @@ static void mdi_execute_abort(void) + // While a Stop or Pause holds, only an executor remap polling a request + // it has started runs, until the request ends; nothing past it is read. + const bool held = +@@ -840,6 +846,9 @@ void mdi_execute_abort(void) static void mdi_execute_hook(void) { @@ -118,7 +118,7 @@ index 8e88fcf1a3..987314fb83 100644 if (mdi_execute_wait && emcTaskPlanIsWait()) { // delay reading of next line until all is done if (interp_list.len() == 0 && -@@ -812,6 +821,9 @@ static void mdi_execute_hook(void) +@@ -900,6 +909,9 @@ static void mdi_execute_hook(void) void readahead_waiting(void) { @@ -128,7 +128,7 @@ index 8e88fcf1a3..987314fb83 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE) { return; } -@@ -1091,6 +1103,11 @@ static int emcTaskPlan(void) +@@ -1356,6 +1368,11 @@ static int emcTaskPlan(void) return retval; } @@ -141,10 +141,10 @@ index 8e88fcf1a3..987314fb83 100644 return emcTaskIssueCommand(emcCommand); } diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh -index 223886ebb2..8077e96530 100644 +index 4220b67..010dc97 100644 --- a/src/emc/task/task.hh +++ b/src/emc/task/task.hh -@@ -60,4 +60,22 @@ int emcTaskPlanCommand(char *cmd); +@@ -65,4 +65,22 @@ int emcTaskPlanCommand(char *cmd); int emcTaskUpdate(EMC_TASK_STAT * stat); diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index f1eccf76..cb861c73 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -9,7 +9,7 @@ The series is based on the LinuxCNC checkout currently used by this workspace: - Repository: - Revision: the commit recorded in [`base-revision`](./base-revision) -- Version line: LinuxCNC 2.10 development +- Version line: LinuxCNC 2.10, tag `v2.10.0-pre2` `base-revision` is the single source of truth used by the stack tooling and CI. Patch files remain the reviewable source of truth in this repository, but @@ -19,12 +19,36 @@ complete series. ## Continuous integration -Changes under `linuxcnc-patches/` trigger the +Changes under `linuxcnc-patches/` or `linuxcnc-tests/` trigger the [`LinuxCNC patch tests`](../.github/workflows/linuxcnc-patches.yml) workflow on pushes and pull requests. The workflow materializes the complete series on the -pinned revision, builds LinuxCNC in run-in-place mode with its upstream CI -tooling, and runs the full LinuxCNC regression suite with failure output -enabled. +pinned revision, builds a headless LinuxCNC in run-in-place mode, and runs the +regression suite with [`linuxcnc-tests/run.sh`](../linuxcnc-tests/run.sh), +which leaves out tests for features that are out of scope for this repository: GUIs +and GUI tools (`tests/build/ui`, `tests/glcanon`, `tests/pyvcp`, +`tests/tooledit`, `tests/ui-smoke`), older remote interfaces (`tests/halrmt`, +`tests/linuxcncrsh`, `tests/linuxcncrsh-tcp`) and tool database programs +(`tests/tooldb`). + +## Tests + +The regression tests for the patches live in +[`linuxcnc-tests/`](../linuxcnc-tests), not in the patches. Its layout mirrors +LinuxCNC's `tests/` directory. The patches only change upstream tests whose +expected output or setup they affect, and add `skip` files to upstream tests +for features this build refuses. Run both sets, without the out-of-scope +tests, against a run-in-place build of the patched LinuxCNC: + +```sh +./linuxcnc-tests/run.sh /path/to/linuxcnc +``` + +Extra arguments go to LinuxCNC's `runtests`, for example `-p` to print the +output of failing tests. A single test still runs directly with +`scripts/runtests ` from the LinuxCNC checkout. + +Tests that need files from the LinuxCNC tree find it through `$EMC2_HOME`, +which a run-in-place build sets to the LinuxCNC checkout. ## Applying the series @@ -74,15 +98,23 @@ commit on the managed branch and export commits with the repository tooling: ``` `refresh.sh` requires a linear history rooted at `base-revision`, preserves -existing filenames by ordinal, names newly appended patches from their commit +existing filenames by position, names newly appended patches from their commit subjects, and replays the generated series before replacing any patch file. It then normalizes the checked-out branch to those deterministic replayed commit IDs, retaining its prior tip under `linuxcnc-ctrl/backups/` when the IDs change. It refuses to remove patches implicitly. -Patch filenames begin with a sequence number. New patches must use the next -number so their application order remains explicit. The filename order and -commit order must match. +Patch filenames begin with a four-digit sequence number. The filename order +and commit order must match. Numbers are permanent: + +- A patch keeps its number for its whole life. The series is never renumbered. +- Removing a patch leaves a gap. Delete the patch file, and keep its entry in + the patch inventory below with the heading struck through and a note saying + when and why it was removed, so the inventory still records what was there. +- A removed patch's number is never reused. New patches take the number after + the highest number the series has ever used, including removed patches. + `refresh.sh` numbers an appended patch after the highest existing file, so + check the inventory when the removed patch was the last one. ## Patch inventory @@ -149,6 +181,11 @@ This patch: `settings->spindle_mode[s] = SPINDLE_MODE::CONSTANT_RPM` after calling `SET_SPINDLE_MODE(s, 0)`, keeping the interpreter model consistent with canon when a program ends. +- Treats the interpreter's `css_maximum[s]` (the G96 `D` limit, which the + G33/G76 pitch check reads) the same way: initialized in `Interp::init()`, + preserved across `Interp::synch()`, and cleared by M2/M30. Canon keeps its + own CSS limit across a mode switch, so resetting only the interpreter's copy + would leave the two models disagreeing about the limit. No new `EMC_STAT` fields or public transport fields are added. @@ -158,35 +195,121 @@ Adds a dedicated `EMC_TASK_PLAN_STOP` command. Stop decelerates an active AUTO program without clearing interpreter or motion queues, safely finishes position-synchronized threading and rigid tapping, stops saved spindle and coolant outputs, and restores them before Run, Resume, or Single Step continues -the program. The command is rejected when no AUTO program is active; callers -must issue `EMC_TASK_ABORT` explicitly when execution should be terminated. +the program. The command is rejected when no AUTO program is active (the +interpreter is idle, also while task finishes an availability change or a tool +table edit); callers must issue `EMC_TASK_ABORT` explicitly when execution should be terminated. Abort, E-stop, faults, mode changes, M0/M1, and Pause retain their existing behavior. +Motion that cannot be interrupted part way runs to completion before Stop +reaches `STOPPED`: + +- A position-synchronized move (`G33`, `G33.1`), together with the + position-synchronized moves that follow it and continue the same spindle + synchronization. Halting at the start of the next `G33` would leave the axis + behind the turning spindle. +- A homing cycle queued from G-code with `G28.2`. Stop is accepted during it + and stays in `STOPPING` until homing finishes. + +An operation task has already handed to another subsystem also runs to its +end, as an M function runs to its completion signal on other controls, and +only then does Stop switch spindle and coolant off: a tool change or other +I/O controller command, and a user `M100`-`M199` program (patches 0013 and +0017 add executor requests and availability handshakes). These waits have no +timeout of their own; Abort, E-stop and Machine Off end them. While Stop is +`STOPPING`, and while a program is paused, `EMC_TASK_STAT.holdWait` (Python +`hold_wait`, protobuf `hold_wait`) names the operation the hold waits for. + +`STOPPED` is reported only once the axes are at rest. While stopping, the +planner does not start a held move from rest, so a pending spindle at-speed +wait or a `G33` index search is not consumed while Stop has the spindle off. + +Known limitation: position-synchronized threading (`G33`, `G33.1`, `G76`) +and rigid tapping always run on the trapezoidal planner, also when +`PLANNER_TYPE` selects the jerk-limited one, so they start and reverse +without jerk limiting. Their speed limit follows spindle feedback and drops +to zero while the spindle restarts after Stop or while a thread waits for its +index, and the jerk-limited (Ruckig) planner rejects a zero maximum speed. +Velocity-synchronized motion stays on the jerk-limited planner and uses +velocity control while its limit is zero. To be revisited with the Stop +rework. + The command is exposed as Python `command.program_stop()`, protobuf `stop_program`, and `halui.program.stop`. Stop progress is reported as `EMC_TASK_STOP_STATE` (`IDLE`, `STOPPING`, `STOPPED`, `STARTING`) -through Python `stop_state` and the task-status protobuf. The patch adds a -`tests/resumable-stop` LinuxCNC regression that verifies active AUTO -Stop/Resume and Stop/Single-Step preserve the queued program, disable -spindle/coolant while stopped, restore them without adding a task-level spindle-at-speed -wait, preserves the normal next-feed at-speed wait after rapid motion, -completes the same program, and waits for active `G33` threading and `G33.1` -rigid-tap synchronized motion to finish before entering `STOPPED`. - -### 0005 — Headless and documentation-free build options - -Adds the Autoconf-standard `--enable-headless` option for backend-only builds -and the independent `--disable-build-manpages` option. Headless builds retain -the controller, realtime/HAL stack, interpreters, remote interfaces, and core -Python and Tcl APIs while omitting LinuxCNC-supplied GUIs, graphical probes, -assets, samples, and desktop integration. The launcher requires an explicit -INI path but continues to execute an external `[DISPLAY] DISPLAY` command. - -The Debian build profiles `pkg.linuxcnc.headless` and `nodoc` select the -corresponding configure options and packaging manifests. With no new options -or profiles, the existing GUI, documentation, manpage, and packaging behavior -is unchanged. +through Python `stop_state` and the task-status protobuf. + +Resume, Run and Single Step from `STOPPED` restore spindle and coolant and +then wait, in `STARTING`, until every spindle that Stop switched off reports +at-speed before motion continues, so an interrupted feed or rapid never +restarts on a spindle that is still spinning up. An at-speed signal left over +from before the restore does not count: once the spindle has been seen not at +speed with its output on, task requires `spindle.N.at-speed` to drop and rise +again after the restore. A spindle whose at-speed has never read false (not +connected, or tied true) does not hold Resume. A second Stop, Abort, E-stop or +Machine Off end the wait. A next-feed at-speed wait that was pending before +Stop still holds after Resume, and a later `S` word change still arms one. +Resume or Run during a Stop leaves single-step mode entered by an earlier Step. +Setting the AUTO or MDI mode aborts the program, also when the mode does not +change, and so ends a Stop as Abort does. +Single Step from `STOPPED` continues the program; it never marks a program +that is still running as finished. With no motion queued (Stop during a dwell +or an M-code) motion is resumed instead and the interpreter steps the next +line. +Resume, Run and Single Step during `STOPPING` are refused with an operator +error, not remembered: the operator resumes once the machine has stopped. +A second Stop or a Pause during `STARTING` cancels the Resume: the program +returns to `STOPPED` with the restored outputs off. A spindle restored at commanded speed 0 does not +hold Resume; spindle override 0 still waits for at-speed. + +While Stop waits for motion to come to rest, task issues only commands that +add to the motion queue. Spindle, coolant, I/O, dwell, tool-change and other +commands read behind the stopping motion run once, in program order, after +Resume, so an `M5` or `S` word after a thread is not undone by Resume's restore. + +`STOPPED` also clears the planner's record of the current spindle +synchronization, so a `G33` that follows velocity-synchronized motion waits +for a fresh index after Resume instead of catching up the revolutions turned +during the Stop. Stop's spindle-off and spindle-on leave the at-speed and +spindle-state bookkeeping of later spindle commands untouched. + +The `linuxcnc-tests/resumable-stop` LinuxCNC regressions run as four tests +(`general`, `threading`, `g76-stop`, `g76-step`) that share one driver, so they +run in parallel. With patches 0009 and 0011 they hold 42 scenarios with the +jerk-limited planner and five with the trapezoidal planner. They cover +Stop/Resume and Stop/Single-Step preserving the queued program, spindle and +coolant handling, the at-speed wait on Resume including a stale at-speed +signal, Pause while Resume is pending, Resume and Step refused while +stopping, Stop waiting for a running user M-code, Pause during an in-flight Step, Abort with an in-flight Step armed, Resume of a spindle restored at S0, commands queued behind a thread, `G33` threading including a chain of +`G33` moves and `G33`/`G95`/`G33`, `G33.1` rigid tapping, Stop during and after +an interrupted `G28.2`, and that `STOPPED` is never reported while moving. + +### 0005 — Headless backend-only builds on top of `--disable-gui` + +Upstream LinuxCNC provides the headless build itself through +`--disable-gui` and `--disable-manpages`. This patch adds what a backend-only +installation still needs on top of them. It no longer defines +`--enable-headless` or `--disable-build-manpages`. + +- Without a GUI, Tcl is optional instead of skipped. When `tclConfig.sh` is + found, the Tcl HAL and LinuxCNC bindings are built without Tk or Xinerama, + and the Tcl runtime used by `haltcl`, `.tcl` HAL files, and `[HAL]TWOPASS` is + installed. Tk, X11, and GL are never needed. +- Desktop menu entries are not installed. +- The launcher requires an explicit INI path, keeps its output on stdout and + stderr when not attached to a terminal, and never runs `wish`. It still + executes an external `[DISPLAY] DISPLAY` command. +- The Debian build profile `pkg.linuxcnc.headless` configures with + `--disable-gui`, uses a backend-only package manifest, and drops the GUI + build and runtime dependencies. The `nodoc` profile configures with + `--disable-build-documentation --disable-manpages` and no longer needs + `asciidoctor`. + +A headless `make install` follows upstream's install rules, so it also +contains the sample configurations, `nc_files`, and some GUI-only helper +scripts; the Debian headless package leaves those out. With no options or +profiles, the existing GUI, documentation, manpage, and packaging behavior is +unchanged. ### 0006 — Ordered realtime component search path @@ -209,12 +332,38 @@ Adds a separate nine-axis `wear_offset` to every tool record and extends tool tables with `WX/WY/WZ/WA/WB/WC/WU/WV/WW`. `G10 L3` edits stored wear with partial-axis semantics, while `G43` applies geometry plus wear. Built-in M6 and M61 activate the resulting combined offset automatically; G49 still -cancels compensation and same-block explicit G-codes take precedence. +cancels compensation and same-block explicit G-codes take precedence. M6 +decides whether a tool was loaded from the pocket it loaded, which the +interpreter resynchronises after an abort (as upstream `RETAIN_G43` does), +not from the last `T` word read. Stored wear is available in interpreter parameters `#5430–#5438`, Python tool -status, and the interpreter Python tool object. The tool database protocol is -v2.2 and the tool-entry line limit is 512 bytes. The protobuf contract exposes -`ToolEntry.wearOffset`, including status deltas and partial `setTool` updates. +status, and the interpreter Python tool object. On v2.10.0-pre2, +`#5401–#5409` hold the loaded tool's stored geometry and `#5081–#5089` the +applied offset (geometry plus wear), following upstream's split of those +parameters. The protobuf contract exposes `ToolEntry.wearOffset`, including +status deltas and partial `setTool` updates. + +The automatic offset takes effect together with the tool: it travels with the +`EMC_TOOL_LOAD` or `EMC_TOOL_SET_NUMBER` message and task applies it when the +change completes, so an abort or E-stop during a change never leaves one +tool's offset applied with another tool loaded. M61 is refused under cutter +radius compensation, as M6 is. + +The tool database protocol is v2.2. A tool-table line holds at most 510 +characters before its newline. Loading, database replies, formatting, saving +and database notification refuse a longer line with an error instead of +cutting it; a table loaded with a refused line is not saved over until it is +reloaded without it, and an edit whose save or notification fails is rolled +back in memory. A `G10` whose save fails reports "tool N: offsets not stored, +tool table unchanged" and fails the command, so the program or MDI command +aborts. On a random toolchanger the table is saved after every M6 and +M61; if that save fails, the change is reported as an error ("tool table ... +not saved after the tool change") and the program aborts. The tools stay +swapped in memory, as they are on the machine, and the new tool's offset is +applied, but the file is unchanged and must be corrected before it is reloaded. +`linuxcnc-tests/tool-line-length-save` covers this. The G-code preview applies the same geometry-plus-wear offset +as the machine. ### 0008 — Tapered G76 drive lines and alternating infeed @@ -231,12 +380,21 @@ line, including their independently corrected synchronized leads. Interpreter regressions cover external and internal threads, both taper directions, absolute and incremental endpoints, radius and diameter modes, entry/exit tapers in both Z directions, compound infeed, spring passes, and rejection of -Y endpoints. G76 also accepts `D0` for the existing fixed compound-infeed -direction (the default) and `D1` to alternate roughing passes across the final -thread line; full-depth and spring passes remain centered, and `Q0` keeps every -pass on the centered line. Both cylindrical and tapered alternating paths are +Y endpoints. `G76.1` takes the same words as G76 and alternates roughing passes +across the final thread line; full-depth and spring passes remain centered, and +`Q0` keeps every pass on the centered line. A mirrored pass keeps its offset at +the start, which puts it on the other flank, but ends where the final pass ends, +so no pass cuts past the programmed Z. Status reports it as `G76`. `D` is +not accepted on either code, because upstream `master` uses it on G76 for a +spindle start angle. Both cylindrical and tapered alternating paths are covered. No NML or public transport changes are required. +On v2.10.0-pre2 a tapered cycle passes upstream's synchronized-feed check: +every synchronized move of every pass (drive line, the feed in and angled move +of an entry taper, the angled move of an exit taper) is checked at its own lead +against the axis velocity limits, and in G96 at its own smallest radius. +Upstream's spindle-override hold covers all passes. + ### 0009 — Safe G76 Stop clearance and two-stage Single Step G76 marks each approach, synchronized cut, and particular clearance retract @@ -245,8 +403,10 @@ the trajectory planner latches that pass and completes exactly its marked retract before entering `STOPPED`, binding the target when it reaches motion if necessary. This leaves the tool clear instead of cutting a groove at thread depth, while ordinary G33, rigid tapping, and unrelated following rapids -retain their prior Stop boundaries. The clearance is an exact, non-blendable -endpoint, so arc blending cannot trim it. Synthetic blend arcs within a +retain their prior Stop boundaries. The clearance and the approach endpoint +are exact, non-blendable endpoints, so arc blending cannot trim them; with +later passes prequeued, the rapid back to the pass start therefore stops at +the approach point instead of rounding into the infeed. Synthetic blend arcs within a synchronized cut inherit the pass owner, keeping Stop bound to that pass's marked clearance. @@ -265,28 +425,50 @@ arc-blend clearance endpoints, an unmarked post-G33 rapid, and repeated Stops with deterministic cut-side timing near the cut/retract handoff. The internal NML and motion fields add no public status or transport field. -### 0010 — Recording canon backend for native G-code preview +On v2.10.0-pre2 the spindle-override lock that upstream issues before the first +G76 pass belongs to that pass's approach unit, so the first Single Step does +not stop after the lock alone. A Stop during plain `G33` threading still +finishes the synchronized run as patch 0004 describes; only G76 passes use the +marked clearance target. + +### 0010 — Support for the native G-code preview -Adds `recordingcanon.cc` and `recordingcanon.hh`, a separate link-selected -implementation of LinuxCNC's global CANON API for native offline interpreters. -It follows the same backend boundary already used by task (`emccanon.cc`), Axis -(`gcodemodule.cc`), and the standalone interpreter (`saicanon.cc`), leaving -those existing implementations untouched. +The native server records previews with its own implementation of LinuxCNC's +CANON API (`native/server/src/gcode/recording_canon.cc`). This patch adds what +that implementation needs inside LinuxCNC: the interpreter reports cutter +compensation being switched on and off through the existing canon calls, and +`tool_mmap_user()` is safe to call from several threads. ### 0011 — In-flight Single Step arming `AUTO_STEP` is forwarded to motion while an AUTO program is already running. The trajectory planner latches the active source block, or the active G76 approach or thread-plus-clearance unit supplied by patch 0009, and finishes it -before stopping at an exact boundary. Later motion remains queued and does not +before stopping at an exact boundary. As on most controls, when the end of the +active block is closer than the distance needed to stop from the current speed +(within the acceleration and, for the S-curve planner, jerk limits), Step stops +at the first later block end it can reach instead, and the planner lowers the +end speeds of the segments before that point so the machine never brakes +harder than its limits. During position-synchronized motion (`G33`) Step, +like Stop, ends at the end of the synchronized run, never between its moves, +which would leave the axis behind the spindle; when the run's next move is +queued after Step was armed, the stop moves to it. A blend already under way +when Step is armed is finished, so the earliest stop is the end of the segment +it blends into. A Step that is canceled +restores every segment it changed, including a stricter end condition (no +blend into a following `G33` or rapid) that motion queued later required. +Later motion remains queued and does not begin, including when several following blocks or threading passes were prequeued by readahead. -The temporary exact boundary is restored if Step is canceled by Resume or Stop. -Existing paused source-line stepping and two-stage G76 stepping remain intact. -Two additional runtime scenarios arm Step during an ordinary block with three -later blocks queued and during an active G76 cut with later passes queued, -bringing the resumable-stop suite to twenty-seven scenarios. During an +The temporary exact boundary is restored if Step is canceled by Resume, Stop or +Pause; Pause during an in-flight Step is an ordinary Pause. Motion's abort +also drops an armed Step, so the planner is not paused again afterwards. Existing paused source-line stepping and two-stage G76 stepping remain intact. +Runtime scenarios arm Step during an ordinary block with three later blocks +queued, at full speed among blocks shorter than the stopping distance (checking +the peak deceleration through HAL), and during an active G76 cut with later +passes queued, stepping on through the prequeued passes; +they are part of the resumable-stop tests described under patch 0004. During an in-flight step, `single_stepping` reports the armed/active state while task and motion remain unpaused; both paused flags become true only after motion reaches the boundary. @@ -304,7 +486,34 @@ Remote CRUD supports LinuxCNC's native random and nonrandom table models for file-backed configurations. Random support covers ATC-addressable pockets and the spindle; it does not model off-machine tool inventory. This patched build rejects `[EMCIO]DB_PROGRAM` during IO initialization and requires file-backed -`[EMCIO]TOOL_TABLE` configuration for managed tool data. +`[EMCIO]TOOL_TABLE` configuration for managed tool data. The LinuxCNC tests +that need a database program (`tests/tooldb/*`, added upstream after the old +base) are therefore skipped. Saving keeps patch 0007's 510-character line limit +and its refusal to overwrite a table loaded with refused lines. + +A tool-table file with an unrecognised line does not load at all, so no +partial table is ever published. At startup task reports "can't load tool +table ..." and runs with no tools; a failed reload keeps the previous table. In +both cases nothing saves over the file (G10, a random-changer M6, tool CRUD) +until a table loads successfully; a missing table file can still be created by +a save. A reload that is refused reports why and keeps the table in use. If the +refused file still matches that table, saves continue. Pocket numbers above the +changer limit are refused only on a random changer, where they address slots. On +a random changer a reload is also refused unless pocket 0 holds the tool in the +spindle, so a file left stale by a failed save cannot replace the real layout. CRLF line endings, whitespace-only lines and comment-only lines count as +blank. `linuxcnc-tests/tool-table-load` covers this. + +A save replaces the table atomically and follows symbolic links, so a linked +table stays linked. LinuxCNC remembers the bytes it last loaded from or saved to +the configured file and refuses a save if the file now holds anything else, +including a file created after startup found none; reloading accepts the change. +A deleted file is created again. Only loading the configured file lifts a save +block. On a random changer, the first table to load after a failed startup sets +the spindle tool and `iocontrol.0.tool-number` from pocket 0. + +A refused tool update, delete or table load tells the operator why and fails +only that command: spindle, coolant and an open program are unaffected. +`linuxcnc-tests/tool-crud-refusal` covers this. Tool-table reload now preserves the live table when opening, parsing, or validation fails. Read-only mmap clients detect inode replacement after a @@ -319,7 +528,19 @@ ordinary, explicitly named remaps and pass an endpoint object into either helper. `transact` owns cooperative waiting, timeout, release, and abort cancellation while returning the terminal response for machine-specific policy. `execute` adds the common policy that only a successful response -continues program execution. The default timeout is 10 seconds. +continues program execution. The default timeout is 10 seconds. A request +starts only after everything queued before it has finished, so in AUTO it +does not run ahead of earlier moves while the interpreter reads ahead. With +cutter radius compensation on the move before it is still held back, so both +helpers refuse a request then, as M54/M55 and tool changes are refused. + +A request already started runs to its end when a resumable Stop (patch 0004) +or a Pause arrives, like any other M function: task keeps running the remap +that polls it while the program holds, reads nothing past it, and reports +`hold_wait` `EXECUTOR` meanwhile; in MDI an operation that finishes while paused +is reported done after Resume. Its timeout keeps counting, and a failure +or timeout while held ends the program as an execution error, which also +clears the Stop. A request that has not started yet starts after Resume. The supplied `HalExecutor` endpoint adds namespaced request and response pins to a HAL component provided and owned by the machine configuration. It neither @@ -328,10 +549,17 @@ machine-specific pins to share one component. HAL remains optional: an integration regression exercises the same helpers with both the standard HAL endpoint and an in-memory endpoint. +A Python remap generator that returns before its first `yield` ends normally, +as one that returns later does, so the helpers also work in the G-code +preview, where no request is made. + Python remap generators are closed during interpreter unwind so their `finally` cleanup runs on task or operator abort. The regression also covers success, raw failure handling, standard failure policy, timeout, stale -responses, monotonic request IDs, request release, and cancellation. Headless +responses, monotonic request IDs, request release, cancellation, a request +read ahead of a running AUTO move, Stop and Pause during a request, a +timeout while stopping, and a request refused under cutter radius +compensation. Headless installs now include the curated `stdglue`. ### 0014 — Publish modal CSS maximum in spindle status @@ -343,7 +571,7 @@ G97 clears it. Spindle `enabled` is now derived from the motion controller's explicit on/off state instead of commanded speed, so a stopped spindle with a nonzero CSS limit remains disabled and is not restarted by resumable Stop. -The `tests/css-status` regression covers G96 while stopped, persistence across +The `linuxcnc-tests/css-status` regression covers G96 while stopped, persistence across M5, clearing on G97, and stopped-spindle enabled state. The patch exposes `css_maximum` through Python spindle status; the canonical protobuf schema already carries it, so no transport-contract change is required. @@ -358,7 +586,7 @@ retains responsibility for validating the spindle values it supports. When `^` requires a positive spindle speed, `$` selects which spindle is checked and supplied as `s`; omitting `$` preserves the spindle 0 default. -The `tests/remap/dollar-argspec` regression covers omitted, numbered, and +The `linuxcnc-tests/remap/dollar-argspec` regression covers omitted, numbered, and all-spindle selectors through Python, named NGC, and positional NGC remaps, plus selected-spindle behavior for `^`. @@ -375,7 +603,7 @@ than planner, interpolator, compensation, jog, homing, and probing internals. This patch exposes no availability controls and builds independently of the runtime feature. -`tests/motion-target-preparation` compiles the production target-preparation +`linuxcnc-tests/motion-target-preparation` compiles the production target-preparation function with deterministic kinematics and the real cubic implementation. It covers late invalid targets, interpolation failure, and no partial commitment. @@ -411,7 +639,24 @@ Availability-controlled joints cannot define `HOME_SEQUENCE`; Home All skips unavailable controlled joints and continues with its ordinary sequence. Controlled joints are homed individually only by acquisition and reject user HOME and UNHOME commands, so AVAILABLE implies a valid homed state. +Acquisition homing uses the home cycle LinuxCNC provides for `G28.2`: task +queues the joint home, waits in its homing state with the usual start timeout +(motion publishes the command number of the last home it started, so a home +that begins and ends between two task status reads counts as run; this also +applies to `G28.2` and is covered by `linuxcnc-tests/interp/g28.2/instant-home`), +and restores the task mode afterwards. Abort, E-stop and Machine Off cancel it +as they cancel a `G28.2`, and a resumable Stop (patch 0004) during it is +accepted and stays `STOPPING` until homing ends. A handshake waiting for its +hardware acknowledgment also runs to its end: Stop stays `STOPPING`, with +`hold_wait` `AVAILABILITY`, until the acknowledgment arrives (Abort ends the +wait). For an unhomed joint the acquisition home then starts only after +Resume. Once acknowledged, the home must start within +`AVAILABILITY_TIMEOUT`, not counting time paused or stopped; if it does not, +the trajectory mode is restored once Abort has cancelled the acquisition. A failed acquisition homing +reports the `G28.2` homing messages; the motion fault code is set as before. Other resources can continue operating while a joint or spindle is released. +A released spindle counts as at speed, so its at-speed input, driven by its +external owner, does not hold the at-speed waits of the other spindles. Coordinated and teleop motion are permitted only when inverse kinematics leaves every unavailable joint at its held command position. Commands requiring an unavailable spindle are rejected. Deliberately released joints do not block Run @@ -436,7 +681,9 @@ identifies a spindle. Selectors are zero-based integer indices, and the selected resource must have availability control enabled. For example, `M54 P2` acquires joint 2, while `M55 $0` releases spindle 0. Each command occupies its own block; line numbers and comments are allowed, but other commands and parameter -assignments cannot share the block. Standalone validation uses the parser's +assignments cannot share the block. Both are refused while cutter radius +compensation is on, because the compensation queue still holds the preceding +move, like other LinuxCNC codes that must wait for motion. Standalone validation uses the parser's generic non-comment item count. The interpreter checks selector representation; task and motion authoritatively validate configured resource topology and availability ownership. @@ -467,10 +714,23 @@ HOME ALL ordering and negative synchronized `HOME_SEQUENCE` groups retain the global sequence controller. HOME ALL or a synchronized group cannot start while independent homing is active, and independent requests cannot be mixed into an active global sequence. Duplicate requests for an active joint are -rejected. An abort or homing error affects only that joint during independent +rejected. An individual request is also refused while any other joint is +homing if either joint sets `HOME_IS_SHARED` or `HOME_IGNORE_LIMITS`: its home +input may be a shared switch or a limit chain that the other joint's motion +trips, latching a wrong home position. Such joints home one at a time when +homed individually; HOME ALL and synchronized `HOME_SEQUENCE` groups keep +upstream behavior. Homing modules export `get_home_is_exclusive()` for this +check (`homing.c` and both `homecomp.comp` variants). An abort or homing error affects only that joint during independent homing, while sequence-controlled operations preserve their group-wide abort behavior. No NML or protobuf interface changes are required. +On v2.10.0-pre2 an independently homed joint finishes upstream's bounded +homing return on its own, without waiting for other joints. A `G28.2` for one +joint completes when the aggregate homing status clears, so it also waits for +any other joint homing at the same time. Acquisition homing (patch 0017) and +independent user homing never overlap: each refuses to start while the other +is active. + ### 0020 — Native lathe power jogging Adds lathe-only HALUI power-feed and taper controls backed by native coupled @@ -478,6 +738,10 @@ X/Z motion. Feed/rev is captured per held request, with live spindle feedback and feed override. Both axes share acceleration and travel constraints. Dedicated power-feed X/Z direction pins keep ordinary axis jogging separate. Cancelled motion requires all direction buttons to release before rearming. +A `halui.power-feed.spindle` value too large for the command's spindle index +is sent as an invalid index, so motion refuses the jog. Like an ordinary +jog, a power jog stops just inside a soft limit (by 1e-6 machine units), so +motion does not report a teleop limit hit once the jog has ended. Includes simulator coverage and HALUI pin documentation. ### 0021 — Cross-compile external HAL components @@ -508,14 +772,17 @@ userspace components alike. The kbuild recipe preserves paths containing spaces when passing the compiler, kernel directory, module directory, and symbol file to make. `--cc` and `--make` accept a command with arguments. With no new options, native compilation retains the existing configured -compiler and standard `ld` and `objdump`, ignoring `LD` and `OBJDUMP` exported -by a cross SDK environment. The accompanying regression test builds and +compiler and standard `ld` and `objdump`, ignoring `LD`, `OBJDUMP` and +`SYSROOT` exported by a cross SDK environment. The accompanying regression test builds and installs realtime and userspace components through argument-logging target tool wrappers and checks that the target sysroot reaches compilation and linking, and that installation honours `DESTDIR`. It also covers paths with spaces and a kbuild build that rereads the component Makefile. -### 0022 — Raise HAL_NAME_LEN to 55 +### ~~0022 — Raise HAL_NAME_LEN to 55~~ + +> **Removed** with the move to LinuxCNC v2.10.0-pre2. Upstream defines `HAL_NAME_LEN` as 55 there. +> The description below records what the patch did. Raises the HAL name length from 47 to 55, the value LinuxCNC 2.10 uses, so thread names with statistic suffixes and other long names fit. The name length @@ -543,7 +810,53 @@ are not supported. Known limitation, shared with the existing thread `tmax` and `time` handling: a failure while creating the parameters leaves a partially created thread. -### 0024 — Identify the command an operator error rejects +### 0024 — Drop interrupted MDI call state on every interpreter reset + +An MDI command whose remap or O-word call has to wait for its queue to drain +leaves task with continuation state that resumes the call once the queue is +empty. Only some abort paths cleared it: E-stop, machine off, a mode change +to MDI or AUTO and a drop out of the ON state reset the interpreter, which +unwinds the call, but kept the state. When the machine was back in MDI, task +resumed a call that no longer existed, which crashed milltask in +`Interp::execute_call()` for a Python remap and left an NGC remap's MDI command +hanging. Commands queued behind it also survived and ran after the machine was +re-enabled; they are now dropped. + +`emcTaskAbort()` now runs `mdi_execute_abort()` after its interpreter reset. +`linuxcnc-tests/remap/mdi-remap-abort` interrupts a waiting NGC and Python remap with +each of these and with an abort followed by an `EMC_TASK_PLAN_INIT` once idle, +and checks that an MDI command queued behind it never runs and that MDI still +works. + +This patch does not handle an `EMC_TASK_PLAN_INIT` that arrives during +active work; 0025 refuses that. The bug is present in plain v2.10.0-pre2; the +fix touches only upstream code paths. + +### 0025 — Interpreter reset only on an idle machine + +Upstream `EMC_TASK_PLAN_INIT` (`reset_interpreter()` in Python) re-initializes +the interpreter at once, whatever task is doing: it reloads the INI settings +and runs `RS274NGC_STARTUP_CODE`, so an MDI command, dwell, queued motion or +jog that is still running suddenly sees the startup modes. + +Task now refuses the reset with an operator error unless the interpreter, task, +the MDI queue and motion are all at rest and no joint is homing or availability +change is in progress. The check runs in `emcTaskPlan()`, where task handles +the command, so no client can start work between the check and the reset. +Abort first, wait for the machine to stop, then reset. Right after startup task +is busy for a few cycles, and a reset sent then is refused too. A tool table +edit holds the interpreter until it is done, and only a reading interpreter or +an MDI call used to release that hold; task now releases it once it is idle, +so an edit does not leave an idle machine looking busy. + +`linuxcnc-tests/task/interp-reset-requires-idle` checks that resets are refused during +an MDI move, a dwell and a jog without changing the modes, and accepted again +once the machine is idle, including after tool edits made while idle and +during an MDI move. The native server additionally refuses a reset while +a command it wrote earlier is still in progress, because task may not have +seen that command yet. + +### 0026 — Identify the command an operator error rejects `EMC_OPERATOR_ERROR` gains `command_serial`. While task plans or issues a new command read from the command channel, operator errors it raises carry that diff --git a/linuxcnc-patches/apply.sh b/linuxcnc-patches/apply.sh index be271f09..5a169669 100755 --- a/linuxcnc-patches/apply.sh +++ b/linuxcnc-patches/apply.sh @@ -92,11 +92,15 @@ git check-ref-format --branch "${branch_name}" >/dev/null 2>&1 || \ shopt -s nullglob patches=("${PATCH_DIR}"/*.patch) [[ ${#patches[@]} -gt 0 ]] || fail "No LinuxCNC patches found in ${PATCH_DIR}" -for index in "${!patches[@]}"; do - number="$(printf '%04d' "$((index + 1))")" - filename="$(basename -- "${patches[index]}")" - [[ "${filename}" == "${number}-"*.patch ]] || \ - fail "Patch filename ${filename} does not match its ordinal ${number}" +previous_number=0 +for patch in "${patches[@]}"; do + filename="$(basename -- "${patch}")" + [[ "${filename}" =~ ^([0-9]{4})-.+\.patch$ ]] || \ + fail "Patch filename ${filename} does not start with a four-digit sequence number" + number=$((10#${BASH_REMATCH[1]})) + ((number > previous_number)) || \ + fail "Patch filename ${filename} does not continue the ascending sequence" + previous_number=${number} done readonly TEMP_DIR="$(mktemp -d)" diff --git a/linuxcnc-patches/base-revision b/linuxcnc-patches/base-revision index 88ef55d4..3700bac1 100644 --- a/linuxcnc-patches/base-revision +++ b/linuxcnc-patches/base-revision @@ -1 +1 @@ -888cb941fbf23ee32fc8e15ca180997d99a39117 +49119ab84f260c208d598c8e0d7e3bcc9f37834c diff --git a/linuxcnc-patches/refresh.sh b/linuxcnc-patches/refresh.sh index 9539b499..4f1f48a4 100755 --- a/linuxcnc-patches/refresh.sh +++ b/linuxcnc-patches/refresh.sh @@ -59,16 +59,21 @@ cleanup() { trap cleanup EXIT generated=() +next_number=1 for index in "${!commits[@]}"; do - number="$(printf '%04d' "$((index + 1))")" if [[ ${index} -lt ${#existing_patches[@]} ]]; then filename="$(basename -- "${existing_patches[index]}")" - [[ "${filename}" == "${number}-"*.patch ]] || \ - fail "Patch filename ${filename} does not match its ordinal ${number}" + [[ "${filename}" =~ ^([0-9]{4})-.+\.patch$ ]] || \ + fail "Patch filename ${filename} does not start with a four-digit sequence number" + number=$((10#${BASH_REMATCH[1]})) + ((number >= next_number)) || \ + fail "Patch filename ${filename} does not continue the ascending sequence" else + number=${next_number} slug="$(git -C "${LINUXCNC_DIR}" show -s --format=%f "${commits[index]}")" - filename="${number}-${slug}.patch" + filename="$(printf '%04d' "${number}")-${slug}.patch" fi + next_number=$((number + 1)) git -C "${LINUXCNC_DIR}" format-patch --zero-commit --no-signature \ --stdout -1 "${commits[index]}" >"${OUTPUT_DIR}/${filename}" diff --git a/linuxcnc-patches/test-stack.sh b/linuxcnc-patches/test-stack.sh index 152d4652..b3f70542 100755 --- a/linuxcnc-patches/test-stack.sh +++ b/linuxcnc-patches/test-stack.sh @@ -162,4 +162,41 @@ if "${STACK}/refresh.sh" "${MERGED}" >/dev/null 2>&1; then fail "refresh accepted a merge commit" fi +readonly GAP_STACK="${TEMP_DIR}/gap-stack" +readonly GAP="${TEMP_DIR}/gap" +readonly GAP_DUPLICATE="${TEMP_DIR}/gap-duplicate" +mkdir -p "${GAP_STACK}" +cp "${SOURCE_DIR}/apply.sh" "${SOURCE_DIR}/refresh.sh" \ + "${STACK}/base-revision" "${GAP_STACK}/" +cp "${STACK}/0001-first.patch" "${GAP_STACK}/0001-first.patch" +cp "${STACK}/0002-second.patch" "${GAP_STACK}/0004-second.patch" + +git clone --quiet "${UPSTREAM}" "${GAP}" +git -C "${GAP}" checkout --quiet --detach "${base_revision}" +"${GAP_STACK}/apply.sh" "${GAP}" >/dev/null || \ + fail "a gap left by a removed patch was rejected" +[[ "$(git -C "${GAP}" rev-list --count "${base_revision}..HEAD")" == 2 ]] || \ + fail "gapped series did not create one commit per patch" + +git -C "${GAP}" config user.name "Patch Stack Test" +git -C "${GAP}" config user.email "patch-stack-test@example.invalid" +printf 'appended\n' >"${GAP}/appended.txt" +git -C "${GAP}" add appended.txt +git -C "${GAP}" commit --quiet -m "fixture: appended patch" +"${GAP_STACK}/refresh.sh" "${GAP}" >/dev/null +[[ -f "${GAP_STACK}/0001-first.patch" && \ + -f "${GAP_STACK}/0004-second.patch" ]] || \ + fail "refresh renumbered a gapped series" +[[ -f "${GAP_STACK}/0005-fixture-appended-patch.patch" ]] || \ + fail "refresh did not number the appended patch after the highest number" +[[ "$(find "${GAP_STACK}" -maxdepth 1 -name '*.patch' | wc -l)" == 3 ]] || \ + fail "refresh of a gapped series produced unexpected patch files" + +cp "${GAP_STACK}/0001-first.patch" "${GAP_STACK}/0004-duplicate.patch" +git clone --quiet "${UPSTREAM}" "${GAP_DUPLICATE}" +git -C "${GAP_DUPLICATE}" checkout --quiet --detach "${base_revision}" +if "${GAP_STACK}/apply.sh" --detach "${GAP_DUPLICATE}" >/dev/null 2>&1; then + fail "a duplicated sequence number was accepted" +fi + echo "patch-stack tests passed" diff --git a/linuxcnc-tests/.gitignore b/linuxcnc-tests/.gitignore new file mode 100644 index 00000000..cfdfe076 --- /dev/null +++ b/linuxcnc-tests/.gitignore @@ -0,0 +1,7 @@ +result +stderr +*.var +*.var.bak +*.ini.expanded +__pycache__/ +*.log diff --git a/linuxcnc-tests/availability-mcodes-regressions/.gitignore b/linuxcnc-tests/availability-mcodes-regressions/.gitignore new file mode 100644 index 00000000..425d52b6 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes-regressions/.gitignore @@ -0,0 +1,2 @@ +/*.ini +!/base.ini diff --git a/linuxcnc-tests/availability-mcodes-regressions/README b/linuxcnc-tests/availability-mcodes-regressions/README new file mode 100644 index 00000000..3be13a3d --- /dev/null +++ b/linuxcnc-tests/availability-mcodes-regressions/README @@ -0,0 +1,9 @@ +M54/M55 production-path regressions using the runtime API regression fixture. +The retained G95 case rejects a feed after M55 releases its spindle, then clears +synchronization with G94. The paused-AUTO case advances an acquired M54 barrier +using only Single Step. Select with AVAILABILITY_MCODE_REGRESSION_CASES. + +INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local +*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before +launching an individual case directly. @unset explicitly removes an inherited +key. Generated INIs are ignored; edit the base or the case override instead. diff --git a/linuxcnc-tests/availability-mcodes-regressions/checkresult b/linuxcnc-tests/availability-mcodes-regressions/checkresult new file mode 100755 index 00000000..14417ee8 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes-regressions/checkresult @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +for scenario in ${AVAILABILITY_MCODE_REGRESSION_CASES:-sync step}; do + grep -q "^availability M-code regression $scenario ok$" "$1" +done diff --git a/linuxcnc-tests/availability-mcodes-regressions/step.ngc b/linuxcnc-tests/availability-mcodes-regressions/step.ngc new file mode 100644 index 00000000..a9bcd9e2 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes-regressions/step.ngc @@ -0,0 +1,6 @@ +M54 P1 +G91 G0 Y1 +M64 P0 +G0 Y1 +M64 P1 +M2 diff --git a/linuxcnc-tests/availability-mcodes-regressions/test-ui.py b/linuxcnc-tests/availability-mcodes-regressions/test-ui.py new file mode 100755 index 00000000..1cf2f53b --- /dev/null +++ b/linuxcnc-tests/availability-mcodes-regressions/test-ui.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'runtime-availability-regressions')) +from fixture import * + +if case == 'sync': + acquire('spindle.0') + c.mode(linuxcnc.MODE_MDI); done() + c.mdi('S1000 G95 F1'); done() + c.mdi('M55 $0') + wait(lambda: not hal.get_value('spindle.0.availability-request'), 'M55 release') + pin('spindle.0.availability-ack', 0); done() + c.mdi('G1 X1') + result = c.wait_complete(2) + assert result == linuxcnc.RCS_ERROR, 'feed inherited unavailable spindle sync' + assert abs(hal.get_value('joint.0.pos-cmd')) < 1e-9 + c.abort(); done() + c.mdi('G94'); done() + c.mdi('G0 X1'); done() + wait(lambda: abs(s.joint_position[0] - 1) < 1e-6, + 'G94 did not allow unrelated motion') + +elif case == 'step': + release('joint.1') + run('step.ngc') + wait(lambda: hal.get_value('joint.1.availability-request'), 'M54 ACK wait') + c.auto(linuxcnc.AUTO_PAUSE) + wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED, 'AUTO pause') + def held_at(position, output=False): + assert s.enabled and s.task_mode == linuxcnc.MODE_AUTO + assert abs(s.joint_position[1] - position) < 1e-6 + assert bool(hal.get_value('motion.digital-out-00')) == output + assert not hal.get_value('motion.digital-out-01'), 'later output escaped Single Step' + + # Pausing at the ACK barrier must block the move and both later outputs. + settle(.2) + held_at(0) + assert s.interp_state == linuxcnc.INTERP_PAUSED + assert not s.joint[1]['available'] + pin('joint.1.availability-ack', 1) + wait(lambda: s.joint[1]['available'], 'acquisition completion') + settle(.2) + held_at(0) + assert s.interp_state == linuxcnc.INTERP_PAUSED + + def step(): + c.auto(linuxcnc.AUTO_STEP) + serial = c.serial + wait(lambda: s.echo_serial_number >= serial, 'Single Step acknowledgement') + settle(.2) + + # The first step clears the completion/synchronization boundary only. + # The next canonical motion line is waiting; neither motion nor output + # may escape without another explicit step. + step() + held_at(0) + assert s.current_line == 2, 'Single Step did not reach the first motion boundary' + settle(.3) + held_at(0) + + # Immediate M64 output carries the preceding motion's canonical line id. + # Step that group, then prove the next move/output group is still blocked. + step() + wait(lambda: abs(s.joint_position[1] - 1) < 1e-6 + and hal.get_value('motion.digital-out-00'), 'stepped motion/output group') + held_at(1, True) + assert s.current_line == 4, 'Single Step did not stop at the next motion boundary' + settle(.3) + held_at(1, True) + +else: + raise AssertionError(case) +print(f'availability M-code regression {case} ok') diff --git a/linuxcnc-tests/availability-mcodes-regressions/test.ini.in b/linuxcnc-tests/availability-mcodes-regressions/test.ini.in new file mode 100644 index 00000000..bcbcb6c0 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes-regressions/test.ini.in @@ -0,0 +1,9 @@ +# Case-specific overrides; unspecified values come from FIXTURE.BASE. +[FIXTURE] +BASE = ../runtime-availability-regressions/base.ini + +[HAL] +HALFILE = ../runtime-availability-regressions/core.hal + +[EMCIO] +TOOL_TABLE = ../runtime-availability-regressions/tool.tbl diff --git a/linuxcnc-tests/availability-mcodes-regressions/test.sh b/linuxcnc-tests/availability-mcodes-regressions/test.sh new file mode 100755 index 00000000..5ed42c86 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes-regressions/test.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +python3 ../runtime-availability/make-fixtures.py +for scenario in ${AVAILABILITY_MCODE_REGRESSION_CASES:-sync step}; do + AVAILABILITY_REGRESSION_CASE=$scenario linuxcnc -r test.ini +done diff --git a/linuxcnc-tests/availability-mcodes/.gitignore b/linuxcnc-tests/availability-mcodes/.gitignore new file mode 100644 index 00000000..425d52b6 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/.gitignore @@ -0,0 +1,2 @@ +/*.ini +!/base.ini diff --git a/linuxcnc-tests/availability-mcodes/README b/linuxcnc-tests/availability-mcodes/README new file mode 100644 index 00000000..bbb8ad63 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/README @@ -0,0 +1,12 @@ +AUTO M54/M55 barriers: prior motion drains, ACK wait, held-position validation, +required homing wait, release wait, and failure prevents continuation. +Runs with interpolation rate 4 and releases the joint just moved, checking a fixed command and successful unrelated motion. Home All skips unavailable availability-controlled joints; any unhomed controlled joint is homed individually inside M54 before the program may continue. Invalid but syntactically representable selectors are passed through the interpreter and rejected against authoritative task topology. A second run confirms acquisition homing with forced homing disabled, then covers direct nonvolatile reacquisition. +Abort in AUTO during ACK wait and moving acquisition homing terminates the program. Late ACK never enables the joint or executes the following block; a new program can reacquire and home. +Machine Off during acquisition homing cancels it like Abort. Stop during M54 acquisition homing behaves like Stop during G28.2: it stays STOPPING until homing ends, then holds the next block until Resume. +Stop or Pause before the ACK of an unhomed joint holds the acquisition home, +for longer than AVAILABILITY_TIMEOUT, until Resume. + +INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local +*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before +launching an individual case directly. @unset explicitly removes an inherited +key. Generated INIs are ignored; edit the base or the case override instead. diff --git a/linuxcnc-tests/availability-mcodes/checkresult b/linuxcnc-tests/availability-mcodes/checkresult new file mode 100755 index 00000000..1e0aa792 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/checkresult @@ -0,0 +1,4 @@ +#!/bin/sh +set -e +grep -q "^availability M-code scenarios ok$" "$1" +grep -q "^availability without forced homing ok$" "$1" diff --git a/linuxcnc-tests/availability-mcodes/core_sim.hal b/linuxcnc-tests/availability-mcodes/core_sim.hal new file mode 120000 index 00000000..563a89b0 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/core_sim.hal @@ -0,0 +1 @@ +../runtime-availability/core_sim.hal \ No newline at end of file diff --git a/linuxcnc-tests/availability-mcodes/homing.ngc b/linuxcnc-tests/availability-mcodes/homing.ngc new file mode 100644 index 00000000..ca47f56f --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/homing.ngc @@ -0,0 +1,4 @@ +G90 G0 X4 +M54 P2 +G0 X5 +M2 diff --git a/linuxcnc-tests/availability-mcodes/no-force.ini.in b/linuxcnc-tests/availability-mcodes/no-force.ini.in new file mode 100644 index 00000000..12b5b7a8 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/no-force.ini.in @@ -0,0 +1,6 @@ +# Case-specific overrides; unspecified values come from FIXTURE.BASE. +[FIXTURE] +BASE = ../runtime-availability/base.ini + +[TRAJ] +NO_FORCE_HOMING = 1 diff --git a/linuxcnc-tests/availability-mcodes/ordered.ngc b/linuxcnc-tests/availability-mcodes/ordered.ngc new file mode 100644 index 00000000..a1800559 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/ordered.ngc @@ -0,0 +1,6 @@ +G90 G0 X1 +M54 P1 +G91 G0 X1 Y1 +M55 P1 +G90 G0 X3 +M2 diff --git a/linuxcnc-tests/availability-mcodes/test-ui.py b/linuxcnc-tests/availability-mcodes/test-ui.py new file mode 100755 index 00000000..36ce8732 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/test-ui.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +import os +import time +import linuxcnc +import hal +h = hal.component('availability-mcode-test'); h.ready() +c = linuxcnc.command(); s = linuxcnc.stat() +def pin(n,v): hal.set_p(n,str(v)) +def wait(fn, message): + end = time.monotonic()+10 + while time.monotonic() .1, 'AUTO homing motion') + cancel() + wait(lambda: not hal.get_value('joint.2.availability-request'), 'AUTO abort output') + pin('joint.2.availability-ack', 0) + done(); idle() + assert abs(s.joint_position[0]-4)<.001, 'Abort continued after M54' + pin('joint.2.availability-ack', 1) + time.sleep(.05); s.poll() + assert not s.joint[2]['available'] + assert not hal.get_value('joint.2.amp-enable-out') + assert abs(s.joint_position[0]-4)<.001, 'late ACK resumed aborted program' + pin('joint.2.availability-ack', 0) + c.state(linuxcnc.STATE_OFF); c.wait_complete(3) + wait(lambda: s.exec_state == linuxcnc.EXEC_DONE, 'fault cleanup') + for n in (1, 2): + c.set_joint_availability(n, False); done() + c.state(linuxcnc.STATE_ON); done() + c.mode(linuxcnc.MODE_MANUAL); done() + c.home(0); done() + wait(lambda: s.homed[0], 'rehome X after abort cleanup') + c.mode(linuxcnc.MODE_AUTO); done() +# The next fresh program can acquire and home successfully. +run('homing.ngc') +wait(lambda: hal.get_value('joint.2.availability-request'), 'M54 home request') +pin('joint.2.availability-ack',1) +for state, switch in [(7,1),(10,0),(12,1)]: + wait(lambda: hal.get_value('joint.2.home-state') == state, 'home phase') + assert abs(s.joint_position[0]-4)<.001, 'continued before homing finished' + assert not hal.get_value('joint.2.available') + pin('joint.2.home-sw-in',switch) +done(); idle() +assert s.joint[2]['available'] and abs(s.joint_position[0]-5)<.001 +# Stop during M54 acquisition homing behaves like Stop during G28.2: it is +# accepted, stays STOPPING until homing ends, and holds the next block. +c.mode(linuxcnc.MODE_MDI); done() +c.mdi('M55 P2') +wait(lambda: not hal.get_value('joint.2.availability-request'), 'release Z') +pin('joint.2.availability-ack', 0); done() +assert not s.joint[2]['homed'] +pin('joint.2.home-sw-in', 0) +c.mode(linuxcnc.MODE_AUTO); done() +run('homing.ngc') +wait(lambda: hal.get_value('joint.2.availability-request'), 'Stop M54 request') +pin('joint.2.availability-ack', 1) +wait(lambda: s.exec_state == getattr(linuxcnc, 'EXEC_WAITING_FOR_HOMING', 12) and + s.joint[2]['homing'], 'M54 queued homing cycle') +c.program_stop() +wait(lambda: s.stop_state == linuxcnc.STOP_STOPPING, 'Stop during M54 homing') +for state, switch in [(7,1),(10,0),(12,1)]: + wait(lambda: hal.get_value('joint.2.home-state') == state, 'stopping home phase') + assert s.stop_state == linuxcnc.STOP_STOPPING, 'Stop ended before homing' + pin('joint.2.home-sw-in',switch) +wait(lambda: s.stop_state == linuxcnc.STOP_STOPPED, 'Stop after M54 homing') +assert s.joint[2]['available'] and s.task_mode == linuxcnc.MODE_AUTO +time.sleep(.1); s.poll() +assert abs(s.joint_position[0]-4)<.001, 'continued after M54 while stopped' +c.auto(linuxcnc.AUTO_RESUME) +idle() +assert abs(s.joint_position[0]-5)<.001 +# Stop or Pause before the ACK of an unhomed joint: the handshake already +# under way runs to its ACK first (Stop stays STOPPING until then), but like +# a queued G28.2 the acquisition home starts only after Resume. Time held +# exceeds AVAILABILITY_TIMEOUT, which does not run then. +for hold in (c.program_stop, lambda: c.auto(linuxcnc.AUTO_PAUSE)): + c.mode(linuxcnc.MODE_MDI); done() + c.mdi('M55 P2') + wait(lambda: not hal.get_value('joint.2.availability-request'), 'release Z before hold') + pin('joint.2.availability-ack', 0); done() + pin('joint.2.home-sw-in', 0) + c.mode(linuxcnc.MODE_AUTO); done() + run('homing.ngc') + wait(lambda: hal.get_value('joint.2.availability-request'), 'held M54 request') + hold() + if hold == c.program_stop: + wait(lambda: s.stop_state == linuxcnc.STOP_STOPPING + and s.hold_wait == linuxcnc.HOLD_WAIT_AVAILABILITY, 'Stop before ACK') + time.sleep(.3); s.poll() + assert s.stop_state == linuxcnc.STOP_STOPPING, 'Stop did not wait for the ACK' + else: + wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED + and s.hold_wait == linuxcnc.HOLD_WAIT_AVAILABILITY, 'Pause before ACK') + pin('joint.2.availability-ack', 1) + if hold == c.program_stop: + wait(lambda: s.stop_state == linuxcnc.STOP_STOPPED, 'Stop after ACK') + wait(lambda: s.hold_wait == linuxcnc.HOLD_WAIT_NONE, 'hold wait after ACK') + time.sleep(2.5); s.poll() + assert not s.joint[2]['homing'] and hal.get_value('joint.2.home-state') == 0, \ + 'acquisition homing started while held' + assert abs(hal.get_value('joint.2.vel-cmd')) < 1e-9, 'Z moved while held' + assert s.joint[2]['availability_fault'] == 0, 'acquisition timed out while held' + assert hal.get_value('joint.2.availability-request') + assert not s.joint[2]['available'] + assert abs(s.joint_position[0]-4)<.001, 'continued after M54 while held' + c.auto(linuxcnc.AUTO_RESUME) + for state, switch in [(7,1),(10,0),(12,1)]: + wait(lambda: hal.get_value('joint.2.home-state') == state, 'home phase after Resume') + assert abs(s.joint_position[0]-4)<.001, 'continued before homing finished' + pin('joint.2.home-sw-in',switch) + idle() + assert s.joint[2]['available'] and abs(s.joint_position[0]-5)<.001 + assert s.stop_state == linuxcnc.STOP_IDLE and not s.task_paused +run('timeout.ngc') +wait(lambda: s.spindle[0]['availability_fault'] != 0, 'timeout propagation') +assert abs(s.joint_position[0]-6)<.001, 'continued after failed acquisition' +print('availability M-code scenarios ok') diff --git a/linuxcnc-tests/availability-mcodes/test.ini.in b/linuxcnc-tests/availability-mcodes/test.ini.in new file mode 100644 index 00000000..fe357c0f --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/test.ini.in @@ -0,0 +1,3 @@ +# Uses the shared base unchanged. +[FIXTURE] +BASE = ../runtime-availability/base.ini diff --git a/linuxcnc-tests/availability-mcodes/test.sh b/linuxcnc-tests/availability-mcodes/test.sh new file mode 100755 index 00000000..882b1518 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/test.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -e +python3 ../runtime-availability/make-fixtures.py +linuxcnc -r test.ini +AVAILABILITY_NO_FORCE=1 linuxcnc -r no-force.ini diff --git a/linuxcnc-tests/availability-mcodes/timeout.ngc b/linuxcnc-tests/availability-mcodes/timeout.ngc new file mode 100644 index 00000000..8a28c6f4 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/timeout.ngc @@ -0,0 +1,4 @@ +G90 G0 X6 +M54 $0 +G0 X7 +M2 diff --git a/linuxcnc-tests/availability-mcodes/tool.tbl b/linuxcnc-tests/availability-mcodes/tool.tbl new file mode 120000 index 00000000..37d25715 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/tool.tbl @@ -0,0 +1 @@ +../runtime-availability/tool.tbl \ No newline at end of file diff --git a/linuxcnc-tests/availability-mcodes/unhomed.ngc b/linuxcnc-tests/availability-mcodes/unhomed.ngc new file mode 100644 index 00000000..e5728900 --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/unhomed.ngc @@ -0,0 +1,4 @@ +G90 G0 X1 +M54 P1 +G0 Y10 +M2 diff --git a/linuxcnc-tests/css-status/README b/linuxcnc-tests/css-status/README new file mode 100644 index 00000000..66ad330d --- /dev/null +++ b/linuxcnc-tests/css-status/README @@ -0,0 +1,6 @@ +Verify CSS maximum spindle speed status follows the active G96/G97 mode. + +The regression enters G96 while the spindle is stopped, checks that the D +word is published through spindle status, verifies M5 does not discard that +modal limit, and checks that G97 clears it. It also verifies that spindle +`enabled` follows the explicit on/off state rather than a nonzero CSS limit. diff --git a/linuxcnc-tests/css-status/checkresult b/linuxcnc-tests/css-status/checkresult new file mode 100755 index 00000000..56f319c1 --- /dev/null +++ b/linuxcnc-tests/css-status/checkresult @@ -0,0 +1,4 @@ +#!/bin/sh +set -e + +grep -q '^CSS status scenario ok$' "$1" diff --git a/linuxcnc-tests/css-status/core_sim.hal b/linuxcnc-tests/css-status/core_sim.hal new file mode 100644 index 00000000..e244f001 --- /dev/null +++ b/linuxcnc-tests/css-status/core_sim.hal @@ -0,0 +1,10 @@ +loadrt trivkins +loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 num_joints=1 num_spindles=1 + +addf motion-command-handler servo-thread +addf motion-controller servo-thread + +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in + +setp spindle.0.at-speed true diff --git a/linuxcnc-tests/css-status/test-ui.py b/linuxcnc-tests/css-status/test-ui.py new file mode 100755 index 00000000..2372f6c8 --- /dev/null +++ b/linuxcnc-tests/css-status/test-ui.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 + +import math +import sys +import time + +import linuxcnc + + +def fail(message): + print(message) + sys.exit(1) + + +def wait_complete(message, timeout=10.0): + if command.wait_complete(timeout) != linuxcnc.RCS_DONE: + fail(message) + status.poll() + + +def assert_css_maximum(expected, message): + status.poll() + actual = status.spindle[0]["css_maximum"] + if not math.isclose(actual, expected, abs_tol=0.001): + fail("%s: expected %.3f, got %.3f" % (message, expected, actual)) + + +command = linuxcnc.command() +status = linuxcnc.stat() + +deadline = time.time() + 10.0 +while time.time() < deadline: + status.poll() + if status.task_state == linuxcnc.STATE_ESTOP: + break + time.sleep(0.02) +else: + fail("LinuxCNC did not initialize") + +command.state(linuxcnc.STATE_ESTOP_RESET) +command.state(linuxcnc.STATE_ON) +wait_complete("machine did not turn on") + +command.mode(linuxcnc.MODE_MDI) +wait_complete("machine did not enter MDI") + +command.mdi("G96 S100 D2111") +wait_complete("G96 command did not complete") +assert_css_maximum(2111.0, "G96 did not publish its D word") +if status.spindle[0]["enabled"]: + fail("G96 reported a stopped spindle as running") + +command.mdi("M5") +wait_complete("M5 command did not complete") +assert_css_maximum(2111.0, "M5 discarded the modal CSS maximum") + +command.mdi("G97") +wait_complete("G97 command did not complete") +assert_css_maximum(0.0, "G97 did not clear the CSS maximum") + +print("CSS status scenario ok") diff --git a/linuxcnc-tests/css-status/test.ini b/linuxcnc-tests/css-status/test.ini new file mode 100644 index 00000000..61ccf6bc --- /dev/null +++ b/linuxcnc-tests/css-status/test.ini @@ -0,0 +1,55 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0x0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +AXES = 1 +COORDINATES = X +SPINDLES = 1 +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 10 +MAX_LINEAR_VELOCITY = 50 + +[EMCIO] +TOOL_TABLE = tool.tbl + +[KINS] +KINEMATICS = trivkins coordinates=X +JOINTS = 1 + +[AXIS_X] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[JOINT_0] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 diff --git a/linuxcnc-tests/css-status/test.sh b/linuxcnc-tests/css-status/test.sh new file mode 100755 index 00000000..13436c16 --- /dev/null +++ b/linuxcnc-tests/css-status/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -e + +linuxcnc -r test.ini diff --git a/linuxcnc-tests/css-status/tool.tbl b/linuxcnc-tests/css-status/tool.tbl new file mode 100644 index 00000000..e69de29b diff --git a/linuxcnc-tests/g76-tapered-pitch/README b/linuxcnc-tests/g76-tapered-pitch/README new file mode 100644 index 00000000..ff9a863d --- /dev/null +++ b/linuxcnc-tests/g76-tapered-pitch/README @@ -0,0 +1,34 @@ +Check that a tapered G76 (an X endpoint) is rejected before it cuts when any +synchronized move of any pass needs an axis to run faster than its maximum +velocity, and that a thread just inside the limit is accepted. The pitch check +needs real axis limits, which the standalone interpreter does not have, so the +test runs milltask with a simulated XZ lathe and drives it over MDI. + +The X axis allows 0.5 mm/s (30 mm/min) and Z 10 mm/s (600 mm/min). A +synchronized move with lead L along a direction (dx, dz) at N RPM needs +L * N * |dx| / hypot(dx, dz) per minute of X. Every tapered move is built so +its Z advance per revolution is the programmed pitch P, so that X rate is +P * N * |dx / dz|. + +- Drive line X10 Z0 to X8 Z-20 (G8): |dx/dz| = 0.1, so X needs 0.15 mm/min per + RPM and the limit is 200 RPM (Z alone would allow 400). S199 is accepted, + S201 rejected. The internal thread (X5 to X7) and the same thread in G7 + (X20 to X16, I-2 J1 K2) have the same slope and limit. A cylindrical G76 at + S201 is accepted: its synchronized moves are along Z only. +- G96 without D: the smallest radius of any synchronized move is 6 mm, at the + end of the full-depth pass (8 - |I| - K). 200 RPM there is + S = 200 * 2 * pi * 6 / 1000 = 7.5398 m/min, so S7.5 is accepted and S7.6 + (201.596 RPM) rejected. +- G96 S100 with D: radius 6 would give 2653 RPM, so D bounds the speed. D199 + is accepted, D201 rejected, also for a later block using G76.1 (the G96 + limit is modal). +- E2 L1: a tapered entry first feeds in along X alone, from the clearance to + the thread crest, at the entry lead 1.5 * hypot(1.199, 1.990) / 1.990 = + 1.75121, where 1.199 = K + 0.0995 * E is the X travel and 1.990 = 0.995 * E + the Z travel of the angled entry. X limits that to 30 / 1.75121 = 17.13 RPM: + S17 is accepted, S18 rejected. +- E2 L2: the exit leaves the decreasing drive line outwards, so its X travel is + K - 0.0995 * E = 0.801 over Z 1.990; the limit is 30 / (1.5 * 0.4025) = + 49.69 RPM: S49 is accepted, S50 rejected. + +An accepted G76 is aborted as soon as its moves are queued. diff --git a/linuxcnc-tests/g76-tapered-pitch/checkresult b/linuxcnc-tests/g76-tapered-pitch/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/g76-tapered-pitch/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/g76-tapered-pitch/core_sim.hal b/linuxcnc-tests/g76-tapered-pitch/core_sim.hal new file mode 100644 index 00000000..47884cf6 --- /dev/null +++ b/linuxcnc-tests/g76-tapered-pitch/core_sim.hal @@ -0,0 +1,18 @@ +loadrt [KINS]KINEMATICS +loadrt [EMCMOT]EMCMOT base_period_nsec=[EMCMOT]BASE_PERIOD servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS + +addf motion-command-handler servo-thread +addf motion-controller servo-thread + +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Zpos joint.1.motor-pos-cmd => joint.1.motor-pos-fb + +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in + +net tool-prepare <= iocontrol.0.tool-prepare +net tool-prepared => iocontrol.0.tool-prepared + +net tool-change <= iocontrol.0.tool-change +net tool-changed => iocontrol.0.tool-changed + +setp spindle.0.at-speed true diff --git a/linuxcnc-tests/g76-tapered-pitch/test-ui.py b/linuxcnc-tests/g76-tapered-pitch/test-ui.py new file mode 100755 index 00000000..38ac4f5c --- /dev/null +++ b/linuxcnc-tests/g76-tapered-pitch/test-ui.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Check the tapered G76 pitch check against the configured axis limits. + +See README for how each spindle speed limit below is derived. +""" + +import sys +import time + +import linuxcnc + + +def fail(message): + print("FAIL: " + message) + sys.exit(1) + + +c = linuxcnc.command() +s = linuxcnc.stat() +e = linuxcnc.error_channel() + + +def wait_for(predicate, message, timeout=10.0): + start = time.time() + while time.time() - start < timeout: + s.poll() + if predicate(): + return + time.sleep(0.01) + fail(message) + + +def drain_errors(): + messages = [] + while True: + error = e.poll() + if not error: + return messages + messages.append(error[1]) + + +def mdi(command): + if c.wait_complete(10.0) == -1: + fail("previous command did not complete before %r" % command) + c.mdi(command) + if c.wait_complete(30.0) != linuxcnc.RCS_DONE: + fail("%r failed: %s" % (command, drain_errors())) + + +wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP, "LinuxCNC did not initialize") +c.state(linuxcnc.STATE_ESTOP_RESET) +c.state(linuxcnc.STATE_ON) +c.wait_complete() +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() + +# The X axis allows 30 mm/min and the Z axis 600 mm/min. In G8 the thread +# runs from X10 Z0 to X8 Z-20: the drive line moves 0.1 mm of X per mm of Z, so +# at pitch 1.5 X needs 0.15 mm/min per RPM and the limit is 200 RPM. +EXTERNAL = "g76 p1.5 x8 z-20 i-1 j.5 k1 h1 q29.5" +INTERNAL = "g76 p1.5 x7 z-20 i1 j.5 k1 h1 q29.5" +CYLINDRICAL = "g76 p1.5 z-20 i-1 j.5 k1 h1 q29.5" +DIAMETER = "g76 p1.5 x16 z-20 i-2 j1 k2 h1 q29.5" + +TAPERED_X = "on the X axis, which exceeds its maximum velocity of 30" + +cases = [ + # (description, setup, G76 block, None if accepted else expected text) + ("external tapered thread just under the limit", + ["g8 g97 s199 m3", "g0 x10 z0"], EXTERNAL, None), + ("external tapered thread just over the limit", + ["g8 g97 s201 m3", "g0 x10 z0"], EXTERNAL, + ["G76 tapered thread pitch 1.50748 at spindle speed 201 needs 30.15 per " + "minute", TAPERED_X]), + ("cylindrical thread at the same speed does not move X while synchronized", + ["g8 g97 s201 m3", "g0 x10 z0"], CYLINDRICAL, None), + ("internal tapered thread just under the limit", + ["g8 g97 s199 m3", "g0 x5 z0"], INTERNAL, None), + ("internal tapered thread just over the limit", + ["g8 g97 s201 m3", "g0 x5 z0"], INTERNAL, + ["G76 tapered thread pitch 1.50748 at spindle speed 201", TAPERED_X]), + ("diameter mode tapered thread just under the limit", + ["g7 g97 s199 m3", "g0 x20 z0"], DIAMETER, None), + ("diameter mode tapered thread just over the limit", + ["g7 g97 s201 m3", "g0 x20 z0"], DIAMETER, + ["G76 tapered thread pitch 1.50748 at spindle speed 201", TAPERED_X]), + # G96 without D: the smallest radius of any synchronized move is 6, at the + # end of the full-depth pass, so 200 RPM is reached at S7.53982. + ("G96 tapered thread just under the limit", + ["g8 g0 x10 z0", "g96 s7.5 m3"], EXTERNAL, None), + ("G96 tapered thread just over the limit", + ["g8 g0 x10 z0", "g96 s7.6 m3"], EXTERNAL, + ["G76 tapered thread pitch 1.50748 reaches spindle speed 201.596 in " + "constant surface speed mode", TAPERED_X]), + # G96 with D: radius 6 at S100 would be 2653 RPM, so D is the bound. + ("G96 tapered thread with D just under the limit", + ["g8 g0 x10 z0", "g96 s100 d199 m3"], EXTERNAL, None), + ("G96 tapered thread with D just over the limit", + ["g8 g0 x10 z0", "g96 s100 d201 m3"], EXTERNAL, + ["G76 tapered thread pitch 1.50748 reaches spindle speed 201 in " + "constant surface speed mode", TAPERED_X]), + ("G96 D limit stays modal for a later G76.1", + ["g8 g0 x10 z0", "g96 s100 d201 m3"], EXTERNAL.replace("g76", "g76.1"), + ["reaches spindle speed 201", TAPERED_X]), + # A tapered entry first feeds in along X alone at the entry lead of + # 1.75121, so X limits it to 17.131 RPM. + ("tapered entry just under the limit", + ["g8 g97 s17 m3", "g0 x10 z0"], EXTERNAL + " e2 l1", None), + ("tapered entry just over the limit", + ["g8 g97 s18 m3", "g0 x10 z0"], EXTERNAL + " e2 l1", + ["G76 entry taper pitch 1.75121 at spindle speed 18 needs 31.5218 per " + "minute", TAPERED_X]), + # The exit leaves the decreasing drive line outwards, so its X component is + # the thread height less the drive line's: 49.6902 RPM. + ("tapered exit just under the limit", + ["g8 g97 s49 m3", "g0 x10 z0"], EXTERNAL + " e2 l2", None), + ("tapered exit just over the limit", + ["g8 g97 s50 m3", "g0 x10 z0"], EXTERNAL + " e2 l2", + ["G76 exit taper pitch 1.61694 at spindle speed 50 needs 30.187 per " + "minute", TAPERED_X]), +] + +for description, setup, block, expected in cases: + print("case: %s: %s" % (description, block)) + for command in setup: + mdi(command) + s.poll() + if s.queue != 0: + fail("motion queue not empty before %r" % block) + stale = drain_errors() + if stale: + fail("unexpected errors before %r: %s" % (block, stale)) + + c.mdi(block) + messages = [] + accepted = False + deadline = time.time() + 10.0 + while time.time() < deadline: + messages = drain_errors() + if messages: + break + s.poll() + if s.queue > 0: + accepted = True + break + time.sleep(0.01) + + if expected is None: + if not accepted: + fail("%s: rejected or not started: %s" % (description, messages)) + # The check passed and the passes are queued; nothing more to see. + c.abort() + c.wait_complete() + wait_for(lambda: s.queue == 0 and s.current_vel == 0.0, + "%s: did not stop after abort" % description) + c.mode(linuxcnc.MODE_MDI) + c.wait_complete() + late = drain_errors() + if late: + fail("%s: errors after accepting: %s" % (description, late)) + print(" accepted") + else: + if accepted or not messages: + fail("%s: not rejected" % description) + text = " ".join(messages) + for part in expected: + if part not in text: + fail("%s: expected %r in %r" % (description, part, text)) + c.wait_complete() + print(" rejected: %s" % text) + +print("g76 tapered pitch checks complete") +sys.exit(0) diff --git a/linuxcnc-tests/g76-tapered-pitch/test.ini b/linuxcnc-tests/g76-tapered-pitch/test.ini new file mode 100644 index 00000000..8c04f366 --- /dev/null +++ b/linuxcnc-tests/g76-tapered-pitch/test.ini @@ -0,0 +1,67 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0x0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +COORDINATES = X Z +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 10 +MAX_LINEAR_VELOCITY = 50 + +[KINS] +KINEMATICS = trivkins coordinates=XZ +JOINTS = 2 + +# X is deliberately slow: 0.5 mm/s is 30 mm/min. Z allows 600 mm/min. +[AXIS_X] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 0.5 +MAX_ACCELERATION = 50 + +[JOINT_0] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 0.5 +MAX_ACCELERATION = 50 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[AXIS_Z] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 10 +MAX_ACCELERATION = 500 + +[JOINT_1] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 10 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 diff --git a/linuxcnc-tests/g76-tapered-pitch/test.sh b/linuxcnc-tests/g76-tapered-pitch/test.sh new file mode 100755 index 00000000..411ae8c1 --- /dev/null +++ b/linuxcnc-tests/g76-tapered-pitch/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash -e + +linuxcnc -r test.ini diff --git a/linuxcnc-tests/halcompile/cross-tools/.gitignore b/linuxcnc-tests/halcompile/cross-tools/.gitignore new file mode 100644 index 00000000..b6e16246 --- /dev/null +++ b/linuxcnc-tests/halcompile/cross-tools/.gitignore @@ -0,0 +1,2 @@ +cross_tools.so +with space.*/ diff --git a/linuxcnc-tests/halcompile/cross-tools/checkresult b/linuxcnc-tests/halcompile/cross-tools/checkresult new file mode 100755 index 00000000..367210b0 --- /dev/null +++ b/linuxcnc-tests/halcompile/cross-tools/checkresult @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu + +test -f "$(dirname "$1")/cross_tools.so" diff --git a/linuxcnc-tests/halcompile/cross-tools/cross_tools.comp b/linuxcnc-tests/halcompile/cross-tools/cross_tools.comp new file mode 100644 index 00000000..8265a4fa --- /dev/null +++ b/linuxcnc-tests/halcompile/cross-tools/cross_tools.comp @@ -0,0 +1,6 @@ +component cross_tools; +pin out bool ready; +function _; +license "GPL"; +;; +ready_set(1); diff --git a/linuxcnc-tests/halcompile/cross-tools/test.sh b/linuxcnc-tests/halcompile/cross-tools/test.sh new file mode 100755 index 00000000..a2677b78 --- /dev/null +++ b/linuxcnc-tests/halcompile/cross-tools/test.sh @@ -0,0 +1,171 @@ +#!/bin/sh +set -eu + +space_root=$(mktemp -d "$PWD/with space.XXXXXX") +trap 'rm -rf -- "$space_root"' EXIT +cp cross_tools.comp "$space_root/cross_tools.comp" +cat > "$space_root/cross_user.c" <<'EOF' +#include "hal.h" +int main(void) { return hal_init("cross_user") < 0; } +EOF + +# Target tools that record their arguments and run the host tools. The +# compiler drops --sysroot so the host compiler keeps its own C library while +# LinuxCNC headers and libraries still have to be found in the test sysroot. +tools=$space_root/tools +mkdir -p "$tools" +for tool in gcc ld objdump; do + cat > "$tools/target-$tool" <> "\$0.log" +printf '%s\t' "\$@" >> "\$0.log" +printf '\n' >> "\$0.log" +for argument; do + shift + case \$argument in + --sysroot=*) ;; + *) set -- "\$@" "\$argument" ;; + esac +done +exec $tool "\$@" +EOF + chmod +x "$tools/target-$tool" +done +reset_tool_logs() { + rm -f "$tools"/*.log +} +# Succeeds when one logged call of tool $1 received every following argument. +tool_called_with() { + calls=$(cat "$tools/target-$1.log") + shift + for argument; do + calls=$(printf '%s\n' "$calls" | grep -F -- "$(printf '\t%s\t' "$argument")") || return 1 + done +} + +# An installed target LinuxCNC, as seen through the sysroot. +sysroot=$space_root/sysroot +mkdir -p "$sysroot/usr/include" "$sysroot/usr/lib" +ln -s "$EMC2_HOME/include" "$sysroot/usr/include/linuxcnc" +ln -s "$EMC2_HOME/lib/liblinuxcnchal.so" "$sysroot/usr/lib/liblinuxcnchal.so" +target_modinc=$space_root/target.modinc +sed -e 's|^RUN_IN_PLACE=.*|RUN_IN_PLACE=no|' \ + -e 's|^prefix := .*|prefix := /usr|' \ + -e 's|^RTLIBDIR := .*|RTLIBDIR := /usr/lib/linuxcnc/modules|' \ + "$(halcompile --print-modinc)" > "$target_modinc" + +target_halcompile() { + halcompile --modinc="$target_modinc" --cross-prefix="$tools/target-" \ + --sysroot="$sysroot" "$@" +} + +( + cd "$space_root" + reset_tool_logs + target_halcompile --compile cross_tools.comp + test -s cross_tools.so + tool_called_with gcc "--sysroot=$sysroot" -c cross_tools.c + tool_called_with gcc "--sysroot=$sysroot" -shared + tool_called_with ld -r + tool_called_with objdump .rtapi_export + + reset_tool_logs + target_halcompile --compile --userspace cross_user.c + test -x cross_user + tool_called_with gcc "--sysroot=$sysroot" "-L$sysroot/usr/lib" \ + -Wl,-rpath,/usr/lib +) + +# Installation goes to the sysroot unless the caller stages into DESTDIR. +mkdir -p "$sysroot/usr/lib/linuxcnc/modules" +( + cd "$space_root" + target_halcompile --install cross_tools.comp + target_halcompile --install --userspace cross_user.c +) +test -s "$sysroot/usr/lib/linuxcnc/modules/cross_tools.so" +test -x "$sysroot/usr/bin/cross_user" +rm "$sysroot/usr/lib/linuxcnc/modules/cross_tools.so" "$sysroot/usr/bin/cross_user" + +stage=$space_root/stage +mkdir -p "$stage/usr/lib/linuxcnc/modules" +( + cd "$space_root" + DESTDIR=$stage target_halcompile --install cross_tools.comp + DESTDIR=$stage target_halcompile --install --userspace cross_user.c +) +test -s "$stage/usr/lib/linuxcnc/modules/cross_tools.so" +test -x "$stage/usr/bin/cross_user" +test ! -e "$sysroot/usr/lib/linuxcnc/modules/cross_tools.so" +test ! -e "$sysroot/usr/bin/cross_user" + +if halcompile --install --cross-prefix="$tools/target-" cross_tools.comp \ + >"$space_root/host-install-output" 2>&1; then + echo "cross installation without a sysroot was accepted" >&2 + exit 1 +fi +grep -F -- '--cross-prefix requires --sysroot' "$space_root/host-install-output" + +if halcompile --compile --sysroot="$sysroot" cross_tools.comp \ + >"$space_root/rip-cross-output" 2>&1; then + echo "cross compilation unexpectedly accepted a run-in-place Makefile.modinc" >&2 + exit 1 +fi +grep -F 'requires an installed target Makefile.modinc' "$space_root/rip-cross-output" + +# A native build ignores target tools and a sysroot exported by a cross SDK +# environment. +rm -f cross_tools.so +LD=false OBJDUMP=false SYSROOT="$sysroot" halcompile --compile cross_tools.comp +test -s cross_tools.so + +# Compiler and make overrides may be commands with arguments. +( + cd "$space_root" + rm -f cross_tools.so + halcompile --compile --cc="env gcc" --make="env make" cross_tools.comp + test -s cross_tools.so +) + +# Kbuild passes paths with spaces to the kernel build intact. +mkdir -p "$space_root/kernel dir" "$space_root/module dir" +cp "$(halcompile --print-modinc)" "$space_root/Makefile.modinc" +cat > "$space_root/kernel dir/Makefile" <<'EOF' +modules: + @$(CC) --version > "$(CHECK_OUTPUT)" + @printf '%s\n' '$(KBUILD_EXTRA_SYMBOLS)' '$(SUBDIRS)' >> "$(CHECK_OUTPUT)" +EOF +( + cd "$space_root/module dir" + make -s -f "$space_root/Makefile.modinc" modules \ + BUILDSYS=kbuild KERNELDIR="$space_root/kernel dir" \ + RTLIBDIR="$space_root/rt lib" CC="'$tools/target-gcc'" \ + CHECK_OUTPUT="$space_root/kbuild-output" +) +test -s "$space_root/kbuild-output" +grep -Fx -- "$space_root/rt lib/Module.symvers" "$space_root/kbuild-output" +grep -Fx -- "$space_root/module dir" "$space_root/kbuild-output" + +# Kbuild rereads the component Makefile from inside the kernel tree, as +# scripts/Makefile.build does, so its Makefile.modinc include must resolve +# from there. +kbuild_root=$space_root/kbuild +mkdir -p "$kbuild_root/kernel" +sed -e 's|^BUILDSYS = .*|BUILDSYS = kbuild|' \ + -e "s|^KERNELDIR := .*|KERNELDIR := $kbuild_root/kernel|" \ + "$(halcompile --print-modinc)" > "$kbuild_root/Makefile.modinc" +cat > "$kbuild_root/kernel/Makefile" <<'EOF' +modules: + @$(MAKE) -f "$(SUBDIRS)/Makefile" -f kbuild.mk component +EOF +cat > "$kbuild_root/kernel/kbuild.mk" <<'EOF' +component: + @test "$(obj-m)" = cross_tools.o + @touch "$(SUBDIRS)/cross_tools.ko" +EOF +( + cd "$kbuild_root" + cp ../cross_tools.comp . + halcompile --compile --modinc="$kbuild_root/Makefile.modinc" cross_tools.comp + test -f cross_tools.ko +) diff --git a/linuxcnc-tests/homing-concurrent/checkresult b/linuxcnc-tests/homing-concurrent/checkresult new file mode 100755 index 00000000..9c14eb33 --- /dev/null +++ b/linuxcnc-tests/homing-concurrent/checkresult @@ -0,0 +1,3 @@ +#!/bin/sh +set -e +grep -q "^concurrent homing regression passed$" "$1" diff --git a/linuxcnc-tests/homing-concurrent/homing.hal b/linuxcnc-tests/homing-concurrent/homing.hal new file mode 100644 index 00000000..5d4eaa30 --- /dev/null +++ b/linuxcnc-tests/homing-concurrent/homing.hal @@ -0,0 +1,16 @@ +loadrt [KINS]KINEMATICS +loadrt [EMCMOT]EMCMOT servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS unlock_joints_mask=127 + +addf motion-command-handler servo-thread +addf motion-controller servo-thread + +net joint-0-position joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net joint-1-position joint.1.motor-pos-cmd => joint.1.motor-pos-fb +net joint-2-position joint.2.motor-pos-cmd => joint.2.motor-pos-fb +net joint-3-position joint.3.motor-pos-cmd => joint.3.motor-pos-fb +net joint-4-position joint.4.motor-pos-cmd => joint.4.motor-pos-fb +net joint-5-position joint.5.motor-pos-cmd => joint.5.motor-pos-fb +net joint-6-position joint.6.motor-pos-cmd => joint.6.motor-pos-fb + +net estop-loop <= iocontrol.0.user-enable-out +net estop-loop => iocontrol.0.emc-enable-in diff --git a/linuxcnc-tests/homing-concurrent/test-ui.py b/linuxcnc-tests/homing-concurrent/test-ui.py new file mode 100755 index 00000000..3a0aac08 --- /dev/null +++ b/linuxcnc-tests/homing-concurrent/test-ui.py @@ -0,0 +1,235 @@ +#!/usr/bin/env python3 + +import time + +import hal +import linuxcnc + + +HOME_IDLE = 0 +HOME_UNLOCK_WAIT = 3 +HOME_FINAL_MOVE_START = 20 +HOME_LOCK_WAIT = 23 +TIMEOUT = 5.0 + + +command = linuxcnc.command() +status = linuxcnc.stat() +errors = linuxcnc.error_channel() +component = hal.component("homing-concurrent-test") +for joint in range(7): + component.newpin("is-unlocked-%d" % joint, hal.HAL_BOOL, hal.HAL_OUT) +component.newpin("joint-5-home-switch", hal.HAL_BOOL, hal.HAL_OUT) +component.ready() +for joint in range(7): + signal = "homing-concurrent-test-unlocked-%d" % joint + hal.new_sig(signal, hal.HAL_BOOL) + hal.connect( + "homing-concurrent-test.is-unlocked-%d" % joint, + signal, + ) + hal.connect("joint.%d.is-unlocked" % joint, signal) +hal.new_sig("homing-concurrent-test-joint-5-home-switch", hal.HAL_BOOL) +hal.connect( + "homing-concurrent-test.joint-5-home-switch", + "homing-concurrent-test-joint-5-home-switch", +) +hal.connect("joint.5.home-sw-in", "homing-concurrent-test-joint-5-home-switch") + + +def wait(predicate, description, timeout=TIMEOUT, poll_interval=0.01): + deadline = time.time() + timeout + while time.time() < deadline: + status.poll() + if predicate(): + return + time.sleep(poll_interval) + raise AssertionError("timeout waiting for %s" % description) + + +def state(joint): + return hal.get_value("joint.%d.home-state" % joint) + + +def homing(joint): + return status.joint[joint]["homing"] + + +def issue(function, expected=linuxcnc.RCS_DONE): + function() + result = command.wait_complete(TIMEOUT) + assert result == expected, "command returned %s, expected %s" % (result, expected) + + +def wait_error(fragment): + deadline = time.time() + TIMEOUT + while time.time() < deadline: + error = errors.poll() + if error is not None and fragment in error[1]: + return + time.sleep(0.01) + raise AssertionError("missing error containing %r" % fragment) + + +def wait_for_start(*joints): + wait( + lambda: all(state(joint) == HOME_UNLOCK_WAIT for joint in joints), + "joints %s to wait for unlock" % (joints,), + ) + + +def finish_joint(joint, wait_for_published_completion=True): + component["is-unlocked-%d" % joint] = True + wait(lambda: state(joint) == HOME_LOCK_WAIT, "joint %d lock wait" % joint) + component["is-unlocked-%d" % joint] = False + wait( + lambda: state(joint) == HOME_IDLE + and status.joint[joint]["homed"] + and (not wait_for_published_completion or not homing(joint)), + "joint %d homing completion" % joint, + ) + + +def finish_synchronized_group(): + wait_for_start(3, 4) + component["is-unlocked-3"] = True + wait(lambda: state(3) == HOME_FINAL_MOVE_START, "joint 3 synchronized wait") + time.sleep(0.05) + assert state(3) == HOME_FINAL_MOVE_START + assert state(4) == HOME_UNLOCK_WAIT + component["is-unlocked-4"] = True + wait( + lambda: state(3) == HOME_LOCK_WAIT and state(4) == HOME_LOCK_WAIT, + "synchronized final moves", + ) + component["is-unlocked-3"] = False + component["is-unlocked-4"] = False + wait( + lambda: all( + state(joint) == HOME_IDLE + and status.joint[joint]["homed"] + and not homing(joint) + for joint in (3, 4) + ), + "synchronized group completion", + poll_interval=0.0001, + ) + + +wait( + lambda: status.task_state == linuxcnc.STATE_ESTOP + and status.exec_state == linuxcnc.EXEC_DONE, + "LinuxCNC startup", + timeout=10.0, +) +issue(lambda: command.state(linuxcnc.STATE_ESTOP_RESET)) +issue(lambda: command.state(linuxcnc.STATE_ON)) +issue(lambda: command.mode(linuxcnc.MODE_MANUAL)) +issue(lambda: command.teleop_enable(0)) +wait(lambda: status.motion_mode == linuxcnc.TRAJ_MODE_FREE, "joint mode") + +# Positive individual requests run concurrently and a third can join later. +issue(lambda: command.home(0)) +wait_for_start(0) +issue(lambda: command.home(2)) +wait_for_start(0, 2) +issue(lambda: command.home(1)) +wait_for_start(0, 1, 2) +assert all(homing(joint) for joint in (0, 1, 2)) + +# A duplicate request is rejected without restarting the joint. +issue(lambda: command.home(0), linuxcnc.RCS_ERROR) +wait_error("joint 0 is already homing") +assert state(0) == HOME_UNLOCK_WAIT + +# One joint can finish while the others continue and publish independent state. +finish_joint(2) +assert not homing(2) +assert homing(0) and homing(1) + +# Aborting one independent home does not cancel the other. +issue(lambda: command.jog(linuxcnc.JOG_STOP, 1, 0)) +wait( + lambda: state(0) == HOME_IDLE and not homing(0) and not status.joint[0]["homed"], + "joint 0 abort", +) +assert state(1) == HOME_UNLOCK_WAIT and homing(1) + +# HOME ALL and synchronized groups cannot be mixed into independent homing. +issue(lambda: command.home(-1), linuxcnc.RCS_ERROR) +wait_error("Homing sequence not possible") +issue(lambda: command.home(3), linuxcnc.RCS_ERROR) +wait_error("Homing sequence not possible") + +# A joint whose home input may be tripped by another joint (HOME_IS_SHARED +# or HOME_IGNORE_LIMITS) cannot start while another joint is homing. +for joint in (5, 6): + issue(lambda: command.home(joint), linuxcnc.RCS_ERROR) + wait_error("Cannot home joint %d while joint 1 is homing" % joint) + assert state(joint) == HOME_IDLE and not homing(joint) +assert state(1) == HOME_UNLOCK_WAIT and homing(1) + +finish_joint(1) + +# Upstream's closed shared home switch check still applies. +component["joint-5-home-switch"] = True +issue(lambda: command.home(5)) +wait( + lambda: state(5) == HOME_IDLE and not homing(5) and not status.joint[5]["homed"], + "joint 5 homing error cleanup", +) +wait_error("Cannot home while shared home switch is closed j=5") +component["joint-5-home-switch"] = False + +# While such a joint homes, no other joint can start homing. +for joint in (5, 6): + issue(lambda: command.home(joint)) + wait_for_start(joint) + for other in (0, 5 if joint == 6 else 6): + issue(lambda: command.home(other), linuxcnc.RCS_ERROR) + wait_error("Cannot home joint %d while joint %d is homing" % (other, joint)) + assert state(other) == HOME_IDLE and not homing(other) + finish_joint(joint) + +issue(lambda: command.home(0)) +wait_for_start(0) +finish_joint(0) + +# A synchronized group must not publish completion until its sequence +# controller can accept the next request. Leave joint 2 unhomed so completing +# the group does not take finish_homing_cycle()'s all-homed fast path. +issue(lambda: command.unhome(2)) +wait(lambda: not status.joint[2]["homed"], "joint 2 unhome") +issue(lambda: command.home(3)) +finish_synchronized_group() +issue(lambda: command.home(2)) +wait_for_start(2) +finish_joint(2) + +# HOME ALL retains HOME_SEQUENCE ordering and starts the synchronized group last. +issue(lambda: command.teleop_enable(0)) +wait(lambda: status.motion_mode == linuxcnc.TRAJ_MODE_FREE, "joint mode for HOME ALL") +issue(lambda: command.home(-1)) +wait_for_start(0) +assert all(state(joint) == HOME_IDLE for joint in (1, 2, 3, 4)) +finish_joint(0, wait_for_published_completion=False) +wait_for_start(1) +assert all(state(joint) == HOME_IDLE for joint in (2, 3, 4)) +finish_joint(1, wait_for_published_completion=False) +wait_for_start(2) +assert all(state(joint) == HOME_IDLE for joint in (3, 4)) +finish_joint(2, wait_for_published_completion=False) +finish_synchronized_group() +wait(lambda: all(status.homed[:7]), "HOME ALL completion") +wait( + lambda: status.motion_mode == linuxcnc.TRAJ_MODE_TELEOP, + "automatic teleop transition", +) +x_before_jog = status.joint_position[0] +issue(lambda: command.jog(linuxcnc.JOG_INCREMENT, 0, 0, 1, 0.1)) +wait( + lambda: abs(status.joint_position[0] - x_before_jog - 0.1) < 1e-6, + "axis jog after HOME ALL", +) + +print("concurrent homing regression passed") diff --git a/linuxcnc-tests/homing-concurrent/test.ini b/linuxcnc-tests/homing-concurrent/test.ini new file mode 100644 index 00000000..ffae4709 --- /dev/null +++ b/linuxcnc-tests/homing-concurrent/test.ini @@ -0,0 +1,170 @@ +[EMC] +VERSION = 1.1 +MACHINE = homing-concurrent +DEBUG = 0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[EMCIO] +TOOL_TABLE = tool.tbl + +[HAL] +HALFILE = homing.hal + +[TRAJ] +AXES = 7 +COORDINATES = XYZUVWA +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 10 +MAX_LINEAR_VELOCITY = 50 + +[KINS] +KINEMATICS = trivkins coordinates=XYZUVWA +JOINTS = 7 + +[AXIS_X] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[AXIS_Y] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[AXIS_Z] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[AXIS_U] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[AXIS_V] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[AXIS_W] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[AXIS_A] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[JOINT_0] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +LOCKING_INDEXER = 1 +HOME_SEQUENCE = 1 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[JOINT_1] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +LOCKING_INDEXER = 1 +HOME_SEQUENCE = 2 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[JOINT_2] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +LOCKING_INDEXER = 1 +HOME_SEQUENCE = 3 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[JOINT_3] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +LOCKING_INDEXER = 1 +HOME_SEQUENCE = -4 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[JOINT_4] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +LOCKING_INDEXER = 1 +HOME_SEQUENCE = -4 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[JOINT_5] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +LOCKING_INDEXER = 1 +HOME_IS_SHARED = 1 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[JOINT_6] +TYPE = ANGULAR +HOME = 0 +HOME_OFFSET = 0 +LOCKING_INDEXER = 1 +HOME_IGNORE_LIMITS = 1 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 diff --git a/linuxcnc-tests/homing-concurrent/test.sh b/linuxcnc-tests/homing-concurrent/test.sh new file mode 100755 index 00000000..3e0b5169 --- /dev/null +++ b/linuxcnc-tests/homing-concurrent/test.sh @@ -0,0 +1,4 @@ +#!/bin/sh +set -e +rm -f sim.var sim.var.bak +linuxcnc -r test.ini diff --git a/linuxcnc-tests/homing-concurrent/tool.tbl b/linuxcnc-tests/homing-concurrent/tool.tbl new file mode 100644 index 00000000..e69de29b diff --git a/linuxcnc-tests/interp/availability-mcodes/README b/linuxcnc-tests/interp/availability-mcodes/README new file mode 100644 index 00000000..6054ffdd --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/README @@ -0,0 +1,6 @@ +Exercise the native M54/M55 joint and spindle selectors, generic standalone +block validation, and interpreter checks limited to selector representation. +Configured resource topology is deliberately left to task and motion. + +Execute-status coverage checks zero queue-buster returns for legacy M54/M55 +remaps and two for each built-in acquire/release program. Requires a built RIP tree. diff --git a/linuxcnc-tests/interp/availability-mcodes/bad-joint.ngc b/linuxcnc-tests/interp/availability-mcodes/bad-joint.ngc new file mode 100644 index 00000000..da0115cf --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/bad-joint.ngc @@ -0,0 +1,2 @@ +M54 P999999999999999 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/comp-m54.ngc b/linuxcnc-tests/interp/availability-mcodes/comp-m54.ngc new file mode 100644 index 00000000..d6d1cc89 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/comp-m54.ngc @@ -0,0 +1,5 @@ +G0 X0 Y0 +G41.1 D2 G1 X10 Y0 F100 +G1 X10 Y10 +M54 P1 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/comp-m55.ngc b/linuxcnc-tests/interp/availability-mcodes/comp-m55.ngc new file mode 100644 index 00000000..91bba273 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/comp-m55.ngc @@ -0,0 +1,5 @@ +G0 X0 Y0 +G41.1 D2 G1 X10 Y0 F100 +G1 X10 Y10 +M55 P1 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/double-selector.ngc b/linuxcnc-tests/interp/availability-mcodes/double-selector.ngc new file mode 100644 index 00000000..a851ea02 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/double-selector.ngc @@ -0,0 +1,2 @@ +M54 P2 $0 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/execute-status.cc b/linuxcnc-tests/interp/availability-mcodes/execute-status.cc new file mode 100644 index 00000000..f2f707c0 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/execute-status.cc @@ -0,0 +1,29 @@ +#include "rs274ngc.hh" +#include "interp_return.hh" +#include +#include +int _task = 0; +// taskclass.o reports tool-table errors to the operator; milltask and rs274 +// provide this, a standalone interpreter driver has to. +int emcOperatorError(const char *, ...) { return 0; } +InterpBase *pinterp; +int main(int argc, char **argv) { + assert(argc == 4); + setenv("INI_FILE_NAME", argv[1], 1); + auto interp = pinterp = makeInterp(); + assert(interp->init() == INTERP_OK); + assert(interp->open(argv[2]) == INTERP_OK); + int finishes = 0; + for (int n = 0; n < 100; n++) { + int read = interp->read(); + assert(read == INTERP_OK); + int result = interp->execute(); + if (result == INTERP_EXIT) { + assert(finishes == atoi(argv[3])); + return 0; + } + assert(result == INTERP_OK || result == INTERP_EXECUTE_FINISH); + if (result == INTERP_EXECUTE_FINISH) finishes++; + } + abort(); +} diff --git a/linuxcnc-tests/interp/availability-mcodes/execute-status.py b/linuxcnc-tests/interp/availability-mcodes/execute-status.py new file mode 100644 index 00000000..8d424805 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/execute-status.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Check actual execute return codes using the production interpreter/canon.""" +import os +from pathlib import Path +import subprocess +import tempfile +root = Path(os.environ['EMC2_HOME']) +with tempfile.TemporaryDirectory() as directory: + binary = str(Path(directory) / 'execute-status') + objects = root / 'src/objects/emc' + command = [os.environ.get('CXX', 'c++'), 'execute-status.cc', + '-I' + str(root / 'include'), + '-I' + str(root / 'src'), + '-I' + str(root / 'src/emc'), + '-I' + str(root / 'src/emc/nml_intf'), + '-I' + str(root / 'src/emc/rs274ngc'), + str(objects / 'sai/saicanon.o'), + str(objects / 'sai/dummyemcstat.o'), + str(objects / 'task/taskclass.o'), + '-L' + str(root / 'lib'), '-Wl,-rpath,' + str(root / 'lib'), + '-lrs274', '-llinuxcnc', '-lnml', '-llinuxcnchal', + '-llinuxcncini', '-lpyplugin', '-ltooldata'] + command += subprocess.check_output(['python3-config', '--embed', '--ldflags'], text=True).split() + subprocess.run(command + ['-o', binary], check=True) + for ini, program, finishes in [('remap.ini', 'remapped.ngc', '0'), + ('test.ini', 'valid-joint.ngc', '2'), + ('test.ini', 'valid-spindle.ngc', '2')]: + result = subprocess.run([binary, ini, program, finishes], capture_output=True, text=True) + if result.returncode: + raise AssertionError(f'{ini} {program}: {result.returncode}\n{result.stdout}\n{result.stderr}') diff --git a/linuxcnc-tests/interp/availability-mcodes/expected b/linuxcnc-tests/interp/availability-mcodes/expected new file mode 100644 index 00000000..e69de29b diff --git a/linuxcnc-tests/interp/availability-mcodes/fractional-joint.ngc b/linuxcnc-tests/interp/availability-mcodes/fractional-joint.ngc new file mode 100644 index 00000000..e5488fbd --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/fractional-joint.ngc @@ -0,0 +1,2 @@ +M54 P2.5 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/fractional-spindle.ngc b/linuxcnc-tests/interp/availability-mcodes/fractional-spindle.ngc new file mode 100644 index 00000000..26ff05c8 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/fractional-spindle.ngc @@ -0,0 +1,2 @@ +M54 $0.5 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/group-spindle.ngc b/linuxcnc-tests/interp/availability-mcodes/group-spindle.ngc new file mode 100644 index 00000000..3b2f3fbb --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/group-spindle.ngc @@ -0,0 +1,2 @@ +M54 $-1 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/huge-spindle.ngc b/linuxcnc-tests/interp/availability-mcodes/huge-spindle.ngc new file mode 100644 index 00000000..584fa3b7 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/huge-spindle.ngc @@ -0,0 +1,2 @@ +M54 $999999999999 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/legacy54.ngc b/linuxcnc-tests/interp/availability-mcodes/legacy54.ngc new file mode 100644 index 00000000..6947d8a6 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/legacy54.ngc @@ -0,0 +1,5 @@ +o sub +(msg, legacy M54 override) +# = # +o endsub +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/legacy55.ngc b/linuxcnc-tests/interp/availability-mcodes/legacy55.ngc new file mode 100644 index 00000000..c48d1b9d --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/legacy55.ngc @@ -0,0 +1,5 @@ +o sub +(msg, legacy M55 override) +# = # +o endsub +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/missing-selector.ngc b/linuxcnc-tests/interp/availability-mcodes/missing-selector.ngc new file mode 100644 index 00000000..96cb26cf --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/missing-selector.ngc @@ -0,0 +1,2 @@ +M54 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-feed.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-feed.ngc new file mode 100644 index 00000000..1a45e38e --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-feed.ngc @@ -0,0 +1,2 @@ +M54 P2 F10 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-modal.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-modal.ngc new file mode 100644 index 00000000..dd567c47 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-modal.ngc @@ -0,0 +1,2 @@ +M54 P2 G91 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-motion.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-motion.ngc new file mode 100644 index 00000000..a52d2d4f --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-motion.ngc @@ -0,0 +1,2 @@ +M54 P0 G0 X10 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-parameter.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-parameter.ngc new file mode 100644 index 00000000..1054e7e0 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-parameter.ngc @@ -0,0 +1,2 @@ +M54 P2 #100=7 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-polar.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-polar.ngc new file mode 100644 index 00000000..1d22b228 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-polar.ngc @@ -0,0 +1,2 @@ +M54 P2 @1 ^45 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-speed.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-speed.ngc new file mode 100644 index 00000000..1cf09ae4 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-speed.ngc @@ -0,0 +1,2 @@ +M54 P2 S500 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-stop.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-stop.ngc new file mode 100644 index 00000000..8fd4be95 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-stop.ngc @@ -0,0 +1,2 @@ +M55 $0 M2 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-tool.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-tool.ngc new file mode 100644 index 00000000..6fc9e05d --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-tool.ngc @@ -0,0 +1,2 @@ +M54 P2 T1 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/mixed-word.ngc b/linuxcnc-tests/interp/availability-mcodes/mixed-word.ngc new file mode 100644 index 00000000..37e7a2e4 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/mixed-word.ngc @@ -0,0 +1,2 @@ +M55 P2 Q1 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/negative-fractional-spindle.ngc b/linuxcnc-tests/interp/availability-mcodes/negative-fractional-spindle.ngc new file mode 100644 index 00000000..5153e911 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/negative-fractional-spindle.ngc @@ -0,0 +1,2 @@ +M54 $-0.5 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/negative-joint.ngc b/linuxcnc-tests/interp/availability-mcodes/negative-joint.ngc new file mode 100644 index 00000000..dea8ef76 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/negative-joint.ngc @@ -0,0 +1,2 @@ +M55 P-1 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/remap.ini b/linuxcnc-tests/interp/availability-mcodes/remap.ini new file mode 100644 index 00000000..3a6b2030 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/remap.ini @@ -0,0 +1,5 @@ +[RS274NGC] +PARAMETER_FILE = linuxcnc.var +SUBROUTINE_PATH = . +REMAP=M54 modalgroup=9 argspec=Q ngc=legacy54 +REMAP=M55 modalgroup=9 argspec=Q ngc=legacy55 diff --git a/linuxcnc-tests/interp/availability-mcodes/remapped.ngc b/linuxcnc-tests/interp/availability-mcodes/remapped.ngc new file mode 100644 index 00000000..24122063 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/remapped.ngc @@ -0,0 +1,3 @@ +M54 Q12 +M55 Q34 +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/test.ini b/linuxcnc-tests/interp/availability-mcodes/test.ini new file mode 100644 index 00000000..03afbfaa --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/test.ini @@ -0,0 +1,2 @@ +[RS274NGC] +PARAMETER_FILE = linuxcnc.var diff --git a/linuxcnc-tests/interp/availability-mcodes/test.sh b/linuxcnc-tests/interp/availability-mcodes/test.sh new file mode 100755 index 00000000..367dd32d --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/test.sh @@ -0,0 +1,84 @@ +#!/bin/bash +set -e + +output_dir=$(mktemp -d) +trap 'rm -rf "$output_dir"' EXIT + +check_valid() { + program=$1 + kind=$2 + selector=$3 + if ! rs274 -n 0 -i test.ini -g "$program" >"$output_dir/canon" 2>"$output_dir/diagnostics"; then + cat "$output_dir/diagnostics" >&2 + exit 1 + fi + # rs274 can return zero on interpreter errors. Only its normal startup + # message is permitted on stderr; also verify every resource operation. + sed '/^executing$/d; /^[[:space:]]*$/d' "$output_dir/diagnostics" >"$output_dir/errors" + if test -s "$output_dir/errors"; then + cat "$output_dir/errors" >&2 + exit 1 + fi + sed -nE 's/^[[:space:]]*[0-9]+[[:space:]]+N[^[:space:]]+[[:space:]]+(SET_(JOINT|SPINDLE)_AVAILABILITY\(.*\))$/\1/p' \ + "$output_dir/canon" >"$output_dir/actual" + printf 'SET_%s_AVAILABILITY(%s, 1)\nSET_%s_AVAILABILITY(%s, 0)\n' \ + "$kind" "$selector" "$kind" "$selector" >"$output_dir/expected" + diff -u "$output_dir/expected" "$output_dir/actual" +} +check_valid valid-joint.ngc JOINT 99 +check_valid valid-spindle.ngc SPINDLE 99 + +check_rejected() { + program=$1 + expected=$2 + output=$(rs274 -n 0 -i test.ini -g "$program" 2>&1) || : + case "$output" in + *"$expected"*) ;; + *) + echo "expected $program to report: $expected" >&2 + echo "$output" >&2 + exit 1 + ;; + esac +} + +check_rejected missing-selector.ngc "requires exactly one P joint selector or $ spindle selector" +check_rejected double-selector.ngc "requires exactly one P joint selector or $ spindle selector" +check_rejected fractional-joint.ngc "P selector must be a non-negative integer joint number" +check_rejected group-spindle.ngc '$ selector must be a non-negative integer spindle number' +check_rejected mixed-motion.ngc "must be the only command in its block" +check_rejected mixed-stop.ngc "must be the only command in its block" +check_rejected mixed-feed.ngc "must be the only command in its block" +check_rejected mixed-speed.ngc "must be the only command in its block" +check_rejected mixed-modal.ngc "must be the only command in its block" +check_rejected mixed-tool.ngc "must be the only command in its block" +check_rejected mixed-polar.ngc "Cannot use axis values without a g code that uses them" +check_rejected mixed-parameter.ngc "must be the only command in its block" +check_rejected mixed-word.ngc "must be the only command in its block" +check_rejected bad-joint.ngc "P selector must be a non-negative integer joint number" +check_rejected negative-joint.ngc "P selector must be a non-negative integer joint number" + +check_rejected fractional-spindle.ngc '$ selector must be a non-negative integer spindle number' +check_rejected negative-fractional-spindle.ngc '$ selector must be a non-negative integer spindle number' +check_rejected huge-spindle.ngc '$ selector must be a non-negative integer spindle number' + +# The cutter comp queue still holds the preceding move. +check_rejected comp-m54.ngc "Cannot change joint or spindle availability with cutter radius compensation on" +check_rejected comp-m55.ngc "Cannot change joint or spindle availability with cutter radius compensation on" + +# Legacy remaps accept their own words without built-in resource selectors. +rs274 -n 0 -i remap.ini -g remapped.ngc >"$output_dir/remap" 2>"$output_dir/diagnostics" +sed '/^executing$/d; /^[[:space:]]*$/d' "$output_dir/diagnostics" >"$output_dir/errors" +if test -s "$output_dir/errors"; then + cat "$output_dir/errors" >&2 + exit 1 +fi +grep -q 'MESSAGE(" legacy M54 override")' "$output_dir/remap" +grep -q 'MESSAGE(" legacy M55 override")' "$output_dir/remap" +if grep -q 'SET_.*_AVAILABILITY' "$output_dir/remap"; then + cat "$output_dir/remap" >&2 + exit 1 +fi + +# Remaps must not inherit the built-in interpreter synchronization return. +python3 execute-status.py diff --git a/linuxcnc-tests/interp/availability-mcodes/valid-joint.ngc b/linuxcnc-tests/interp/availability-mcodes/valid-joint.ngc new file mode 100644 index 00000000..d697df4d --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/valid-joint.ngc @@ -0,0 +1,3 @@ +N10 M54 P99 (joint resource) +N20 M55 P99 ; release +M2 diff --git a/linuxcnc-tests/interp/availability-mcodes/valid-spindle.ngc b/linuxcnc-tests/interp/availability-mcodes/valid-spindle.ngc new file mode 100644 index 00000000..10632c21 --- /dev/null +++ b/linuxcnc-tests/interp/availability-mcodes/valid-spindle.ngc @@ -0,0 +1,3 @@ +M54 $99 +M55 $99 +M2 diff --git a/linuxcnc-tests/interp/g28.2/instant-home/README b/linuxcnc-tests/interp/g28.2/instant-home/README new file mode 100644 index 00000000..277dcb59 --- /dev/null +++ b/linuxcnc-tests/interp/g28.2/instant-home/README @@ -0,0 +1,7 @@ +G28.2 for homes that finish within a few servo cycles: an absolute encoder +joint, the same joint again while homed (HOME_NO_REHOME), and a joint with zero +homing velocities. Task's coarse cycle means it never sees homing active, and +it must still see that the home was accepted and ran. + +A home motion rejects (motion.homing-inhibit) still reports that it did not +start. diff --git a/linuxcnc-tests/interp/g28.2/instant-home/checkresult b/linuxcnc-tests/interp/g28.2/instant-home/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/interp/g28.2/instant-home/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/interp/g28.2/instant-home/sim.tbl b/linuxcnc-tests/interp/g28.2/instant-home/sim.tbl new file mode 100644 index 00000000..e69de29b diff --git a/linuxcnc-tests/interp/g28.2/instant-home/test-ui.py b/linuxcnc-tests/interp/g28.2/instant-home/test-ui.py new file mode 100755 index 00000000..86439223 --- /dev/null +++ b/linuxcnc-tests/interp/g28.2/instant-home/test-ui.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 + +import linuxcnc +import hal + +import sys +import time + +h = hal.component("python-ui") +h.ready() + +c = linuxcnc.command() +s = linuxcnc.stat() +e = linuxcnc.error_channel() + + +def fail(msg): + print("FAIL: " + msg) + sys.exit(1) + + +def wait_for(cond, what, timeout=10.0): + start = time.time() + while time.time() - start < timeout: + s.poll() + if cond(): + return + time.sleep(0.01) + fail("timeout waiting for " + what) + + +def errors(): + found = [] + while True: + err = e.poll() + if not err: + return found + found.append(err[1]) + + +def home(joint, what): + s.poll() + mode = s.motion_mode + c.mdi("G28.2 P%d" % joint) + result = c.wait_complete(8) + s.poll() + reported = errors() + if result != linuxcnc.RCS_DONE or reported: + fail("%s: status %s, errors %s" % (what, result, reported)) + if not s.homed[joint]: + fail("%s: joint %d is not homed" % (what, joint)) + if s.motion_mode != mode: + fail("%s: motion mode %d, was %d" % (what, s.motion_mode, mode)) + print("%s: ok" % what, flush=True) + + +wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP, "task to start") +c.state(linuxcnc.STATE_ESTOP_RESET) +c.wait_complete() +c.state(linuxcnc.STATE_ON) +c.wait_complete() +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() + +home(0, "absolute encoder") +home(1, "absolute encoder with final move") +home(1, "already homed, HOME_NO_REHOME") +home(2, "zero homing velocities") + +hal.set_p("motion.homing-inhibit", "1") +c.mdi("G28.2 P2") +result = c.wait_complete(8) +reported = errors() +if result != linuxcnc.RCS_ERROR or not any("did not start" in m for m in reported): + fail("inhibited home: status %s, errors %s" % (result, reported)) +hal.set_p("motion.homing-inhibit", "0") +print("inhibited home: ok", flush=True) + +print("all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/interp/g28.2/instant-home/test.ini b/linuxcnc-tests/interp/g28.2/instant-home/test.ini new file mode 100644 index 00000000..f1b2352e --- /dev/null +++ b/linuxcnc-tests/interp/g28.2/instant-home/test.ini @@ -0,0 +1,103 @@ +[EMC] +DEBUG = 0 +VERSION = 1.1 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[TASK] +TASK = milltask +# coarse enough that a home ending within a few servo cycles falls between +# two status reads of task +CYCLE_TIME = 0.05 + +[RS274NGC] +PARAMETER_FILE = sim.var + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[HAL] +HALUI = halui +HALFILE = LIB:core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +AXES = 3 +COORDINATES = X Y Z +HOME = 0 0 0 +LINEAR_UNITS = inch +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 1.2 +MAX_LINEAR_VELOCITY = 4 + +[KINS] +JOINTS = 3 +KINEMATICS = trivkins + +[AXIS_X] +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 + +[AXIS_Y] +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 + +[AXIS_Z] +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +MIN_LIMIT = -4.0 +MAX_LIMIT = 4.0 + +[JOINT_0] +TYPE = LINEAR +HOME = 0.000 +HOME_ABSOLUTE_ENCODER = 2 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +FERROR = 0.050 +MIN_FERROR = 0.010 + +[JOINT_1] +TYPE = LINEAR +HOME = 0.000 +HOME_ABSOLUTE_ENCODER = 1 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +FERROR = 0.050 +MIN_FERROR = 0.010 + +[JOINT_2] +TYPE = LINEAR +HOME = 0.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -4.0 +MAX_LIMIT = 4.0 +FERROR = 0.050 +MIN_FERROR = 0.010 + +[EMCIO] +TOOL_CHANGE_QUILL_UP = 1 +RANDOM_TOOLCHANGER = 0 +TOOL_TABLE = sim.tbl diff --git a/linuxcnc-tests/interp/g28.2/instant-home/test.sh b/linuxcnc-tests/interp/g28.2/instant-home/test.sh new file mode 100755 index 00000000..a16f6fa8 --- /dev/null +++ b/linuxcnc-tests/interp/g28.2/instant-home/test.sh @@ -0,0 +1,2 @@ +#!/bin/bash +exec linuxcnc -r test.ini diff --git a/linuxcnc-tests/interp/g76-tapered/README b/linuxcnc-tests/interp/g76-tapered/README new file mode 100644 index 00000000..57dbfb9b --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/README @@ -0,0 +1,14 @@ +Verify that optional G76 X endpoints produce tapered XZ drive lines while +preserving axial P pitch. The canonical trace covers absolute and incremental +endpoints, radius and diameter mode, internal and external threads, both drive +line slopes, entry/exit taper in both Z directions, compound infeed, and spring +passes. Compound-infeed coverage verifies fixed-direction G76 and +alternating-flank G76.1 on tapered and cylindrical drive lines, plus centered Q0 +paths, and that no G76.1 pass, mirrored ones included, feeds past either end +of the programmed Z range (alternating-z-range.ngc). Every cycle runs inside the spindle override hold (LOCK_SPEED_OVERRIDE +before the first pass, ENABLE_SPEED_OVERRIDE after the last). Negative tests +verify, by message, that G76 rejects a Y endpoint, a tapered drive line with no +Z length, a D word, and G76 together with G76.1 in one block. + +The pitch check against the axis velocity limits needs a machine and is tested +in ../../g76-tapered-pitch. diff --git a/linuxcnc-tests/interp/g76-tapered/alternating-z-range.ngc b/linuxcnc-tests/interp/g76-tapered/alternating-z-range.ngc new file mode 100644 index 00000000..979eccde --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/alternating-z-range.ngc @@ -0,0 +1,31 @@ +(G76.1 feeds must stay between the start Z and the programmed end Z) +(Each cycle is preceded by a "range" comment giving those two Z values) + +g20 g18 g8 +s100 m3 + +(range 0 -1) +g0 x1 z0 +g76.1 p.1 z-1 i-.1 j.03 k.1 r1 h1 q30 + +(range 0 -1) +g0 x1 z0 +g76.1 p.1 x.8 z-1 i-.1 j.03 k.1 r1 h1 q30 + +(range 0 -1) +g0 x1 z0 +g76.1 p.1 z-1 i-.1 j.03 k.1 r1 h1 q30 e.1 l3 + +(range -1 0) +g0 x1 z-1 +g76.1 p.1 z0 i-.1 j.03 k.1 r1 h1 q30 e.1 l3 + +(range 0 -1) +g0 x.5 z0 +g76.1 p.1 z-1 i.1 j.03 k.1 r1 h1 q30 + +(range 0 -1) +g0 x1 z0 +g76.1 p.1 x.8 z-1 i-.1 j.02 k.1 r2 h0 q45 e.1 l3 + +m2 diff --git a/linuxcnc-tests/interp/g76-tapered/expected b/linuxcnc-tests/interp/g76-tapered/expected new file mode 100644 index 00000000..ab056506 --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/expected @@ -0,0 +1,424 @@ + N..... USE_LENGTH_UNITS(CANON_UNITS_MM) + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SET_FEED_REFERENCE(CANON_XYZ) + N..... ON_RESET() + N..... COMMENT("Test tapered G76 drive lines") + N..... SELECT_PLANE(CANON_PLANE_XZ) + N..... USE_LENGTH_UNITS(CANON_UNITS_INCHES) + N..... SET_SPINDLE_SPEED(0, 100.0000) + N..... START_SPINDLE_CLOCKWISE(0) + N..... COMMENT("basic external, decreasing X") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("basic external, increasing X") + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.6100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.6000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("incremental endpoint") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("interpreter: distance mode changed to incremental") + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("interpreter: distance mode changed to absolute") + N..... COMMENT("diameter mode endpoint and depths") + N..... COMMENT("interpreter: Lathe diameter mode changed to diameter") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("radius mode endpoint and depths") + N..... COMMENT("interpreter: Lathe diameter mode changed to radius") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("internal thread") + N..... STRAIGHT_TRAVERSE(0.5000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.4900, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.6900, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.8900, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.6900, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.5000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.9000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.7000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.7000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("entry and exit taper") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.157731,0) + N..... STRAIGHT_FEED(0.9100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_FEED(0.7904, 0.0000, -0.0981, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6296, 0.0000, -0.9019, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.129309,0) + N..... STRAIGHT_FEED(0.7100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.157731,0) + N..... STRAIGHT_FEED(0.9000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_FEED(0.7804, 0.0000, -0.0981, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6196, 0.0000, -0.9019, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.129309,0) + N..... STRAIGHT_FEED(0.7000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("positive Z entry and exit taper") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.157731,0) + N..... STRAIGHT_FEED(0.9100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_FEED(0.7904, 0.0000, 0.0981, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6296, 0.0000, 0.9019, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.129309,0) + N..... STRAIGHT_FEED(0.7100, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.157731,0) + N..... STRAIGHT_FEED(0.9000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_FEED(0.7804, 0.0000, 0.0981, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6196, 0.0000, 0.9019, 0.0000, 0.0000, 0.0000) + N..... START_SPEED_FEED_SYNC(0.129309,0) + N..... STRAIGHT_FEED(0.7000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("fixed-direction compound infeed") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.9998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("alternating-flank compound infeed") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0666, 0.0000, -0.0170, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8666, 0.0000, -0.0170, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6779, 0.0000, -0.9604, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8779, 0.0000, -0.9604, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0241, 0.0000, -0.0793, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8241, 0.0000, -0.0793, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.9998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("alternating mode with centered Q0 infeed") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8700, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8700, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8400, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("cylindrical alternating-flank compound infeed") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, -0.0173, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8700, 0.0000, -0.0173, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8700, 0.0000, -0.9596, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0700, 0.0000, -0.9596, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, -0.0808, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8400, 0.0000, -0.0808, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0400, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -0.0520, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -0.0520, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8100, 0.0000, -0.9942, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, -0.9942, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -0.0577, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.100000,0) + N..... STRAIGHT_FEED(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("G76 after G76.1 goes back to fixed-direction infeed") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.9998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7998, 0.0000, -0.0510, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8111, 0.0000, -0.9943, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(0.9887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.7887, 0.0000, -0.0566, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("spring passes") + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... LOCK_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(1.0100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8100, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... STRAIGHT_TRAVERSE(1.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... DISABLE_FEED_OVERRIDE() + N..... START_SPEED_FEED_SYNC(0.101980,0) + N..... STRAIGHT_FEED(0.6000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPEED_FEED_SYNCH() + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... ENABLE_FEED_OVERRIDE() + N..... ENABLE_SPEED_OVERRIDE(0) + N..... STRAIGHT_TRAVERSE(0.8000, 0.0000, -1.0000, 0.0000, 0.0000, 0.0000) + N..... STOP_SPINDLE_TURNING(0) + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SELECT_PLANE(CANON_PLANE_XY) + N..... SET_FEED_MODE(0, 0) + N..... SET_FEED_RATE(0.0000) + N..... STOP_SPINDLE_TURNING(0) + N..... SET_SPINDLE_MODE(0 0.0000) + N..... PROGRAM_END() + N..... ON_RESET() + N..... ON_RESET() diff --git a/linuxcnc-tests/interp/g76-tapered/invalid-both-modes.ngc b/linuxcnc-tests/interp/g76-tapered/invalid-both-modes.ngc new file mode 100644 index 00000000..110edb24 --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/invalid-both-modes.ngc @@ -0,0 +1,5 @@ +g20 g18 g8 +s100 m3 +g0 x1 z0 +g76 g76.1 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 +m2 diff --git a/linuxcnc-tests/interp/g76-tapered/invalid-d.ngc b/linuxcnc-tests/interp/g76-tapered/invalid-d.ngc new file mode 100644 index 00000000..c6a6349d --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/invalid-d.ngc @@ -0,0 +1,5 @@ +g20 g18 g8 +s100 m3 +g0 x1 z0 +g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 d1 +m2 diff --git a/linuxcnc-tests/interp/g76-tapered/invalid-y.ngc b/linuxcnc-tests/interp/g76-tapered/invalid-y.ngc new file mode 100644 index 00000000..f79aa858 --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/invalid-y.ngc @@ -0,0 +1,5 @@ +g20 g18 g8 +s100 m3 +g0 x1 y0 z0 +g76 p.1 x.8 y.1 z-1 i-.1 j.09 k.1 h0 q0 +m2 diff --git a/linuxcnc-tests/interp/g76-tapered/invalid-zero-z.ngc b/linuxcnc-tests/interp/g76-tapered/invalid-zero-z.ngc new file mode 100644 index 00000000..93848031 --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/invalid-zero-z.ngc @@ -0,0 +1,5 @@ +g20 g18 g8 +s100 m3 +g0 x1 z0 +g76 p.1 x.8 z0 i-.1 j.09 k.1 h0 q0 +m2 diff --git a/linuxcnc-tests/interp/g76-tapered/test.ngc b/linuxcnc-tests/interp/g76-tapered/test.ngc new file mode 100644 index 00000000..46d331bd --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/test.ngc @@ -0,0 +1,67 @@ +(Test tapered G76 drive lines) + +g20 g18 g8 +s100 m3 + +(basic external, decreasing X) +g0 x1 z0 +g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q0 + +(basic external, increasing X) +g0 x.8 z0 +g76 p.1 x1 z-1 i-.1 j.09 k.1 h0 q0 + +(incremental endpoint) +g0 x1 z0 +g91 +g76 p.1 x-.2 z-1 i-.1 j.09 k.1 h0 q0 +g90 + +(diameter mode endpoint and depths) +g7 +g0 x2 z0 +g76 p.1 x1.6 z-1 i-.2 j.18 k.2 h0 q0 + +(radius mode endpoint and depths) +g8 +g0 x1 z0 +g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q0 + +(internal thread) +g0 x.5 z0 +g76 p.1 x.7 z-1 i.1 j.09 k.1 h0 q0 + +(entry and exit taper) +g0 x1 z0 +g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q0 e.1 l3 + +(positive Z entry and exit taper) +g0 x1 z0 +g76 p.1 x.8 z1 i-.1 j.09 k.1 h0 q0 e.1 l3 + +(fixed-direction compound infeed) +g0 x1 z0 +g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 + +(alternating-flank compound infeed) +g0 x1 z0 +g76.1 p.1 x.8 z-1 i-.1 j.03 k.1 r1 h2 q30 + +(alternating mode with centered Q0 infeed) +g0 x1 z0 +g76.1 p.1 z-1 i-.1 j.03 k.1 r1 h0 q0 + +(cylindrical alternating-flank compound infeed) +g0 x1 z0 +g76.1 p.1 z-1 i-.1 j.03 k.1 r1 h1 q30 + +(G76 after G76.1 goes back to fixed-direction infeed) +g0 x1 z0 +g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 + +(spring passes) +g0 x1 z0 +g76 p.1 x.8 z-1 i-.1 j.09 k.1 h2 q0 + +m5 +m2 diff --git a/linuxcnc-tests/interp/g76-tapered/test.sh b/linuxcnc-tests/interp/g76-tapered/test.sh new file mode 100644 index 00000000..73b58bcf --- /dev/null +++ b/linuxcnc-tests/interp/g76-tapered/test.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +rs274 -g test.ngc | awk '{$1=""; print}' +result=${PIPESTATUS[0]} +if (( result != 0 )); then + exit "$result" +fi + +# A G76.1 pass must not feed past either end of the programmed Z range, even +# on the mirrored passes of alternating infeed. +range_output=$(rs274 -g alternating-z-range.ngc 2>&1) || { + echo "alternating-z-range.ngc failed" >&2 + echo "$range_output" >&2 + exit 1 +} +if ! LC_ALL=C awk -F'[(),]' ' + /COMMENT\("range / { + gsub(/"/, "", $2); split($2, r, " "); a = r[2] + 0; b = r[3] + 0 + lo = a < b ? a : b; hi = a < b ? b : a; cycles++; next + } + /STRAIGHT_FEED\(/ { + feeds++ + z = $4 + 0 + if (z < lo - 1e-4 || z > hi + 1e-4) { + printf "feed to Z%s outside Z%s..Z%s\n", $4, lo, hi > "/dev/stderr" + bad = 1 + } + } + END { exit bad || cycles != 6 || feeds == 0 }' <<< "$range_output"; then + echo "alternating-z-range.ngc: a G76.1 feed leaves the programmed Z range" >&2 + exit 1 +fi + +# Each invalid program must be rejected with its own message. +declare -A expected_error=( + [invalid-both-modes.ngc]="Two g codes used from same modal group" + [invalid-d.ngc]="D word with no G41, G41.1, G42, G42.1, G71, G71.1, G71.2 G73, G83 or G96 to use it" + [invalid-y.ngc]="Cannot move Y axis with G76" + [invalid-zero-z.ngc]="In G76, a tapered drive line must have nonzero Z length" +) + +for invalid_program in invalid-*.ngc; do + message=${expected_error[$invalid_program]} + if [[ -z $message ]]; then + echo "$invalid_program has no expected error message" >&2 + exit 1 + fi + output=$(rs274 -g "$invalid_program" 2>&1) + if ! grep -qxF "$message" <<< "$output"; then + echo "$invalid_program was not rejected with: $message" >&2 + echo "$output" >&2 + exit 1 + fi +done diff --git a/linuxcnc-tests/interp/tool-line-length/expected b/linuxcnc-tests/interp/tool-line-length/expected new file mode 100644 index 00000000..43d9c1a4 --- /dev/null +++ b/linuxcnc-tests/interp/tool-line-length/expected @@ -0,0 +1,23 @@ + N..... USE_LENGTH_UNITS(CANON_UNITS_MM) + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SET_FEED_REFERENCE(CANON_XYZ) + N..... ON_RESET() + N..... USE_LENGTH_UNITS(CANON_UNITS_MM) + N..... USE_TOOL_LENGTH_OFFSET(38.1000 0.0000 44.4500, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... MESSAGE("T1 510 chars: 1.500000 1.750000") + N..... USE_TOOL_LENGTH_OFFSET(79.3750 0.0000 100.0125, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... MESSAGE("T5 after the long lines: 3.125000 3.937500") + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SET_FEED_MODE(0, 0) + N..... SET_FEED_RATE(0.0000) + N..... STOP_SPINDLE_TURNING(0) + N..... SET_SPINDLE_MODE(0 0.0000) + N..... PROGRAM_END() + N..... ON_RESET() + N..... ON_RESET() +File: test.tbl line 2: tool line longer than 510 characters refused +File: test.tbl line 3: tool line longer than 510 characters refused +File: test.tbl line 4: tool line longer than 510 characters refused diff --git a/linuxcnc-tests/interp/tool-line-length/missing-t2.ngc b/linuxcnc-tests/interp/tool-line-length/missing-t2.ngc new file mode 100644 index 00000000..a05d8bdc --- /dev/null +++ b/linuxcnc-tests/interp/tool-line-length/missing-t2.ngc @@ -0,0 +1,3 @@ +g21 +g43 h2 +m2 diff --git a/linuxcnc-tests/interp/tool-line-length/missing-t3.ngc b/linuxcnc-tests/interp/tool-line-length/missing-t3.ngc new file mode 100644 index 00000000..c7e3b127 --- /dev/null +++ b/linuxcnc-tests/interp/tool-line-length/missing-t3.ngc @@ -0,0 +1,3 @@ +g21 +g43 h3 +m2 diff --git a/linuxcnc-tests/interp/tool-line-length/missing-t4.ngc b/linuxcnc-tests/interp/tool-line-length/missing-t4.ngc new file mode 100644 index 00000000..369efa73 --- /dev/null +++ b/linuxcnc-tests/interp/tool-line-length/missing-t4.ngc @@ -0,0 +1,3 @@ +g21 +g43 h4 +m2 diff --git a/linuxcnc-tests/interp/tool-line-length/test.ngc b/linuxcnc-tests/interp/tool-line-length/test.ngc new file mode 100644 index 00000000..aea66da8 --- /dev/null +++ b/linuxcnc-tests/interp/tool-line-length/test.ngc @@ -0,0 +1,12 @@ +; Tool table lines up to 510 characters load whole; longer ones are refused +; with an error rather than cut. G43 H applies geometry plus wear, so the +; applied offset shows every number of a loaded line. +; test.tbl: T1's line is 510 characters, T2's 511, T3's 600, T4's 521 (a +; 511-byte read would cut its closing WZ number), T5's ordinary. Each long +; line ends in WZ, so a cut line would lose or shorten its Z wear. +g21 +g43 h1 +(debug,T1 510 chars: #5081 #5083) +g43 h5 +(debug,T5 after the long lines: #5081 #5083) +m2 diff --git a/linuxcnc-tests/interp/tool-line-length/test.sh b/linuxcnc-tests/interp/tool-line-length/test.sh new file mode 100755 index 00000000..0822c767 --- /dev/null +++ b/linuxcnc-tests/interp/tool-line-length/test.sh @@ -0,0 +1,17 @@ +#!/bin/bash +# Canon output, then the loader's refusals (stderr), in a stable order. +rs274 -g test.ngc -t test.tbl 2> err.txt | awk '{$1=""; print}' +result=${PIPESTATUS[0]} +grep "longer than" err.txt +rm -f err.txt +if (( result != 0 )); then + exit "$result" +fi + +# a refused line's tool is not in the table at all +for missing in missing-t*.ngc; do + if rs274 -g "$missing" -t test.tbl >/dev/null 2>&1; then + echo "$missing: tool loaded from an over-long line" >&2 + exit 1 + fi +done diff --git a/linuxcnc-tests/interp/tool-line-length/test.tbl b/linuxcnc-tests/interp/tool-line-length/test.tbl new file mode 100644 index 00000000..134455e1 --- /dev/null +++ b/linuxcnc-tests/interp/tool-line-length/test.tbl @@ -0,0 +1,5 @@ +T1 P1 X+1 Z+2 WX+0.5 D0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 WZ-0.25 +T2 P2 X+1 Z+2 WX+0.5 D0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 WZ-0.25 +T3 P3 X+1 Z+2 WX+0.5 D0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 WZ-0.25 +T4 P4 X+1 Z+2 WX+0.5 D0.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 WZ-0.7555555555 +T5 P5 X+3 Z+4 WX+0.125 WZ-0.0625 diff --git a/linuxcnc-tests/interp/tool-wear/expected b/linuxcnc-tests/interp/tool-wear/expected new file mode 100644 index 00000000..e9e62dce --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/expected @@ -0,0 +1,69 @@ + N..... USE_LENGTH_UNITS(CANON_UNITS_MM) + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SET_FEED_REFERENCE(CANON_XYZ) + N..... ON_RESET() + N..... USE_LENGTH_UNITS(CANON_UNITS_INCHES) + N..... SELECT_TOOL(7) + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() + N..... USE_TOOL_LENGTH_OFFSET(10.1000 20.2000 30.3000, 40.4000 50.5000 60.6000, 70.7000 80.8000 90.9000) + N..... MESSAGE("auto applied 10.100000-90.900000: 10.100000 20.200000 30.300000 40.400000 50.500000 60.600000 70.700000 80.800000 90.900000") + N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... MESSAGE("applied unchanged: 10.100000 20.200000 30.300000 40.400000 50.500000 60.600000 70.700000 80.800000 90.900000") + N..... MESSAGE("geometry unchanged: 10.000000 20.000000 30.000000 40.000000 50.000000 60.000000 70.000000 80.000000 90.000000") + N..... MESSAGE("edited wear: 0.000000 -0.200000 0.030000 -0.400000 0.050000 -0.060000 0.700000 0.800000 0.900000") + N..... USE_TOOL_LENGTH_OFFSET(10.0000 19.8000 30.0300, 39.6000 50.0500 59.9400, 70.7000 80.8000 90.9000) + N..... MESSAGE("composed 10.000000-90.900000: 10.000000 19.800000 30.030000 39.600000 50.050000 59.940000 70.700000 80.800000 90.900000") + N..... USE_TOOL_LENGTH_OFFSET(10.0000 19.8000 30.0300, 39.6000 50.0500 59.9400, 70.7000 80.8000 90.9000) + N..... MESSAGE("idempotent 10.000000-90.900000: 10.000000 19.800000 30.030000 39.600000 50.050000 59.940000 70.700000 80.800000 90.900000") + N..... USE_TOOL_LENGTH_OFFSET(11.0000 21.8000 33.0300, 43.6000 55.0500 65.9400, 70.7000 80.8000 90.9000) + N..... COMMENT("interpreter: motion mode set to none") + N..... MESSAGE("additive 11.000000-90.900000: 11.000000 21.800000 33.030000 43.600000 55.050000 65.940000 70.700000 80.800000 90.900000") + N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... MESSAGE("cancelled 0.0000000.000000: 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000") + N..... MESSAGE("stored after g49: 10.000000 30.000000 / 0.000000 -0.200000 0.030000 -0.400000 0.050000 -0.060000 0.700000 0.800000 0.900000") + N..... USE_TOOL_LENGTH_OFFSET(10.0000 19.8000 30.0300, 39.6000 50.0500 59.9400, 70.7000 80.8000 90.9000) + N..... MESSAGE("g43.4 composed 10.000000-90.900000: 10.000000 19.800000 30.030000 39.600000 50.050000 59.940000 70.700000 80.800000 90.900000") + N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... USE_LENGTH_UNITS(CANON_UNITS_MM) + N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... MESSAGE("metric edit in machine units: 1.000000 -0.200000 -0.100000 -0.400000 0.050000 -0.060000 0.700000 0.800000 0.900000") + N..... USE_TOOL_LENGTH_OFFSET(279.4000 502.9200 759.4600, 39.6000 50.0500 59.9400, 1795.7800 2052.3200 2308.8600) + N..... MESSAGE("metric composition in machine units: 11.000000 19.800000 29.900000 39.600000 50.050000 59.940000 70.700000 80.800000 90.900000") + N..... USE_LENGTH_UNITS(CANON_UNITS_INCHES) + N..... COMMENT("interpreter: Lathe diameter mode changed to diameter") + N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... MESSAGE("g7 diameter x interpretation: 1.000000") + N..... COMMENT("interpreter: Lathe diameter mode changed to radius") + N..... SET_TOOL_TABLE_ENTRY(1, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... SET_TOOL_TABLE_ENTRY(0, 7, 10.0000 20.0000 30.0000 40.0000 50.0000 60.0000 70.0000 80.0000 90.0000, 0.0000, 0.0000, 0) + N..... MESSAGE("g8 radius x interpretation: 2.000000") + N..... CHANGE_TOOL_NUMBER(2) + N..... USE_TOOL_LENGTH_OFFSET(-1.1000 -2.2000 -3.3000, -4.4000 -5.5000 -6.6000, -7.7000 -8.8000 -9.9000) + N..... MESSAGE("m61 auto -1.100000--9.900000: -1.100000 -2.200000 -3.300000 -4.400000 -5.500000 -6.600000 -7.700000 -8.800000 -9.900000") + N..... CHANGE_TOOL_NUMBER(3) + N..... USE_TOOL_LENGTH_OFFSET(123456789.2469 123456789.2469 123456789.2469, 123456789.2469 123456789.2469 123456789.2469, 123456789.2469 123456789.2469 123456789.2469) + N..... MESSAGE("long complete record: 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912 123456789.246912") + N..... CHANGE_TOOL_NUMBER(1) + N..... USE_TOOL_LENGTH_OFFSET(12.0000 19.8000 29.9000, 39.6000 50.0500 59.9400, 70.7000 80.8000 90.9000) + N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... MESSAGE("same-block g49: 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000") + N..... SELECT_TOOL(0) + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() + N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... MESSAGE("t0 m6 applied: 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000") + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SET_FEED_MODE(0, 0) + N..... SET_FEED_RATE(0.0000) + N..... STOP_SPINDLE_TURNING(0) + N..... SET_SPINDLE_MODE(0 0.0000) + N..... PROGRAM_END() + N..... ON_RESET() + N..... ON_RESET() diff --git a/linuxcnc-tests/interp/tool-wear/invalid-i.ngc b/linuxcnc-tests/interp/tool-wear/invalid-i.ngc new file mode 100644 index 00000000..3ee52a24 --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/invalid-i.ngc @@ -0,0 +1,3 @@ +g20 +g10 l3 p7 x1 i1 +m2 diff --git a/linuxcnc-tests/interp/tool-wear/invalid-j.ngc b/linuxcnc-tests/interp/tool-wear/invalid-j.ngc new file mode 100644 index 00000000..3613d398 --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/invalid-j.ngc @@ -0,0 +1,3 @@ +g20 +g10 l3 p7 x1 j1 +m2 diff --git a/linuxcnc-tests/interp/tool-wear/invalid-m61-comp.ngc b/linuxcnc-tests/interp/tool-wear/invalid-m61-comp.ngc new file mode 100644 index 00000000..1f2d11ac --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/invalid-m61-comp.ngc @@ -0,0 +1,5 @@ +g20 +t7 m6 +g1 f10 g42 x1 y1 +m61 q8 +m2 diff --git a/linuxcnc-tests/interp/tool-wear/invalid-missing-tool.ngc b/linuxcnc-tests/interp/tool-wear/invalid-missing-tool.ngc new file mode 100644 index 00000000..c9cf7995 --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/invalid-missing-tool.ngc @@ -0,0 +1,3 @@ +g20 +g10 l3 p99 x1 +m2 diff --git a/linuxcnc-tests/interp/tool-wear/invalid-q.ngc b/linuxcnc-tests/interp/tool-wear/invalid-q.ngc new file mode 100644 index 00000000..c995e9ba --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/invalid-q.ngc @@ -0,0 +1,3 @@ +g20 +g10 l3 p7 x1 q1 +m2 diff --git a/linuxcnc-tests/interp/tool-wear/invalid-r.ngc b/linuxcnc-tests/interp/tool-wear/invalid-r.ngc new file mode 100644 index 00000000..8ef7a87d --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/invalid-r.ngc @@ -0,0 +1,3 @@ +g20 +g10 l3 p7 x1 r1 +m2 diff --git a/linuxcnc-tests/interp/tool-wear/invalid-zero-tool.ngc b/linuxcnc-tests/interp/tool-wear/invalid-zero-tool.ngc new file mode 100644 index 00000000..3a172d8f --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/invalid-zero-tool.ngc @@ -0,0 +1,3 @@ +g20 +g10 l3 p0 x1 +m2 diff --git a/linuxcnc-tests/interp/tool-wear/test.ngc b/linuxcnc-tests/interp/tool-wear/test.ngc new file mode 100644 index 00000000..9568e630 --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/test.ngc @@ -0,0 +1,46 @@ +; The standalone interpreter's canon does not copy the new tool into +; pocket 0 on a tool change, so the stored offsets (5401-5409 geometry, +; 5430-5438 wear) are read here only after G10, which updates pocket 0 +; itself. The task path is covered by ../../tool-wear-task. +g20 +t7 m6 +(debug,auto applied #5081-#5089: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) + +g10 l3 p7 x0 y-0.2 z0.03 a-0.4 b0.05 c-0.06 +(debug,applied unchanged: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +(debug,geometry unchanged: #5401 #5402 #5403 #5404 #5405 #5406 #5407 #5408 #5409) +(debug,edited wear: #5430 #5431 #5432 #5433 #5434 #5435 #5436 #5437 #5438) + +g43 h7 +(debug,composed #5081-#5089: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +g43 h7 +(debug,idempotent #5081-#5089: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +g43.2 x1 y2 z3 a4 b5 c6 +(debug,additive #5081-#5089: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +g49 +(debug,cancelled #5081-#5089: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +(debug,stored after g49: #5401 #5403 / #5430 #5431 #5432 #5433 #5434 #5435 #5436 #5437 #5438) +g43.4 +(debug,g43.4 composed #5081-#5089: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +g49 + +g21 +g10 l3 p7 x25.4 z-2.54 +(debug,metric edit in machine units: #5430 #5431 #5432 #5433 #5434 #5435 #5436 #5437 #5438) +g43 h7 +(debug,metric composition in machine units: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +g20 +g7 g10 l3 p7 x2 +(debug,g7 diameter x interpretation: #5430) +g8 g10 l3 p7 x2 +(debug,g8 radius x interpretation: #5430) + +m61 q8 +(debug,m61 auto #5081-#5089: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +m61 q9 +(debug,long complete record: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +m61 q7 g49 +(debug,same-block g49: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +t0 m6 +(debug,t0 m6 applied: #5081 #5082 #5083 #5084 #5085 #5086 #5087 #5088 #5089) +m2 diff --git a/linuxcnc-tests/interp/tool-wear/test.sh b/linuxcnc-tests/interp/tool-wear/test.sh new file mode 100755 index 00000000..955dbcd8 --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/test.sh @@ -0,0 +1,27 @@ +#!/bin/bash +rs274 -g test.ngc -t test.tbl | awk '{$1=""; print}' | sed 's/-0\.0000/0.0000/g' +result=${PIPESTATUS[0]} +if (( result != 0 )); then + exit "$result" +fi + +for invalid_program in invalid-*.ngc; do + if rs274 -g "$invalid_program" -t test.tbl >/dev/null 2>&1; then + echo "$invalid_program unexpectedly succeeded" >&2 + exit 1 + fi +done + +# M61 under cutter compensation is refused like M6, before anything reaches +# canon: no tool number change and no offset are emitted. +out=$(rs274 -g invalid-m61-comp.ngc -t test.tbl 2>&1) +if ! grep -q "Cannot change tools with cutter radius compensation on" <<<"$out"; then + echo "invalid-m61-comp.ngc: not refused as a tool change under compensation" >&2 + echo "$out" >&2 + exit 1 +fi +if grep -q "CHANGE_TOOL_NUMBER" <<<"$out"; then + echo "invalid-m61-comp.ngc: M61 changed the tool before failing" >&2 + echo "$out" >&2 + exit 1 +fi diff --git a/linuxcnc-tests/interp/tool-wear/test.tbl b/linuxcnc-tests/interp/tool-wear/test.tbl new file mode 100644 index 00000000..1a6d140b --- /dev/null +++ b/linuxcnc-tests/interp/tool-wear/test.tbl @@ -0,0 +1,3 @@ +T7 P7 X+10 Y+20 Z+30 A+40 B+50 C+60 U+70 V+80 W+90 WX+0.1 WY+0.2 WZ+0.3 WA+0.4 WB+0.5 WC+0.6 WU+0.7 WV+0.8 WW+0.9 ;all positive +T8 P8 X-1 Y-2 Z-3 A-4 B-5 C-6 U-7 V-8 W-9 WX-0.1 WY-0.2 WZ-0.3 WA-0.4 WB-0.5 WC-0.6 WU-0.7 WV-0.8 WW-0.9 ;all negative +T9 P9 X+123456789.123456 Y+123456789.123456 Z+123456789.123456 A+123456789.123456 B+123456789.123456 C+123456789.123456 U+123456789.123456 V+123456789.123456 W+123456789.123456 WX+0.123456 WY+0.123456 WZ+0.123456 WA+0.123456 WB+0.123456 WC+0.123456 WU+0.123456 WV+0.123456 WW+0.123456 ;over 256 bytes diff --git a/linuxcnc-tests/motion-target-preparation/README b/linuxcnc-tests/motion-target-preparation/README new file mode 100644 index 00000000..7958c18d --- /dev/null +++ b/linuxcnc-tests/motion-target-preparation/README @@ -0,0 +1,5 @@ +Compiles production target preparation with deterministic inverse-kinematics +doubles and the real cubic implementation. Checks that inverse-kinematics, +interpolation, and unavailable-joint target failures cannot partially update +the joint command vector. Also checks the isolated legacy activation guard. +No runtime or realtime privileges are required. diff --git a/linuxcnc-tests/motion-target-preparation/availability-cases.h b/linuxcnc-tests/motion-target-preparation/availability-cases.h new file mode 100644 index 00000000..00099d2d --- /dev/null +++ b/linuxcnc-tests/motion-target-preparation/availability-cases.h @@ -0,0 +1,21 @@ +static void test_availability(EmcPose *pose, double *positions, CUBIC_STRUCT *staged) { + availability_status_t *a = &status.joint_status[2].availability; + a->controlled = 1; a->held_position = 2; + unsigned char before[sizeof(joints)]; memcpy(before, joints, sizeof(joints)); + int saved_fflags = fflags; + solution[0] = 10; solution[2] = 3; + assert(prepare_joint_targets(pose, positions, staged) != 0); + assert(memcmp(before, joints, sizeof(joints)) == 0); + assert(fflags == saved_fflags); + solution[2] = 2; + assert(prepare_joint_targets(pose, positions, staged) == 0); + assert(fflags == saved_fflags + 1); + assert(positions[0] == 10 && positions[2] == 2); + for (int n=1; n<100; n++) { + solution[2] = 2 + n*1e-10; + int result = prepare_joint_targets(pose, positions, staged); + if (n <= 9) { assert(result == 0); assert(positions[2] == 2); } + if (n >= 11) assert(result != 0); + assert(a->held_position == 2); + } +} diff --git a/linuxcnc-tests/motion-target-preparation/availability-fixture.h b/linuxcnc-tests/motion-target-preparation/availability-fixture.h new file mode 100644 index 00000000..dd4b2be8 --- /dev/null +++ b/linuxcnc-tests/motion-target-preparation/availability-fixture.h @@ -0,0 +1,5 @@ +#define TEST_AVAILABILITY 1 +#define EMCMOT_AVAILABILITY_AVAILABLE 3 +typedef struct { int controlled, state; double held_position; } availability_status_t; +static struct { EmcPose carte_pos_cmd; int overrideLimitMask; struct { availability_status_t availability; } joint_status[3]; } status; +#define emcmotStatus (&status) diff --git a/linuxcnc-tests/motion-target-preparation/expected b/linuxcnc-tests/motion-target-preparation/expected new file mode 100644 index 00000000..e69de29b diff --git a/linuxcnc-tests/motion-target-preparation/test.py b/linuxcnc-tests/motion-target-preparation/test.py new file mode 100644 index 00000000..3c78d029 --- /dev/null +++ b/linuxcnc-tests/motion-target-preparation/test.py @@ -0,0 +1,147 @@ +import os +import re +from pathlib import Path +import subprocess +import tempfile +root = Path(os.environ['EMC2_HOME']) +source = (root / 'src/emc/motion/control.c').read_text() +def function(name, source=source): + start = re.search(r'^(?:static )?(?:int|void) ' + name + r'\(', source, re.M).start() + brace = source.index('{', start) + depth = 1 + end = brace + 1 + while depth: + depth += (source[end] == '{') - (source[end] == '}') + end += 1 + return source[start:end] +preamble = r""" +#include +#include +#include +#include "cubic.h" +#define _(s) s +#define reportError(...) ((void)0) +#define NO_OF_KINS_JOINTS 3 +typedef struct { double x; } EmcPose; +typedef struct { + double coarse_pos; + CUBIC_STRUCT cubic; +} emcmot_joint_t; +static emcmot_joint_t joints[3]; +typedef int KINEMATICS_FORWARD_FLAGS; +static int iflags, fflags; +static int ik_result; +static double solution[3]; +static int kinematicsInverse(const EmcPose *p, double *out, int *i, int *f) { + *f = *f + 1; + memcpy(out, solution, sizeof(solution)); return ik_result; +} +""" +# The second patch supplies additional lifecycle/held-reference test fixtures. +extension = Path(__file__).with_name('availability-fixture.h') +if extension.exists(): preamble += extension.read_text() +main = r""" +int main(void) { + double positions[3]; CUBIC_STRUCT staged[3]; EmcPose pose = {0}; + for (int n=0; n<3; n++) { + cubicInit(&joints[n].cubic); + cubicSetSegmentTime(&joints[n].cubic, .004); + cubicSetInterpolationRate(&joints[n].cubic, 4); + joints[n].coarse_pos = 20+n; + solution[n] = n; + } + unsigned char before[sizeof(joints)]; memcpy(before, joints, sizeof(joints)); + fflags = 10; + ik_result = -1; + assert(prepare_joint_targets(&pose, positions, staged) != 0); + assert(fflags == 10); + ik_result = 0; + solution[2] = NAN; + assert(prepare_joint_targets(&pose, positions, staged) != 0); + assert(memcmp(before, joints, sizeof(joints)) == 0); + assert(fflags == 10); + solution[2] = 2; + assert(prepare_joint_targets(&pose, positions, staged) == 0); + assert(memcmp(before, joints, sizeof(joints)) == 0); + assert(fflags == 11); + assert(positions[0] == 0 && positions[1] == 1 && positions[2] == 2); + joints[2].cubic.configured = 0; + memcpy(before, joints, sizeof(joints)); + assert(prepare_joint_targets(&pose, positions, staged) != 0); + assert(memcmp(before, joints, sizeof(joints)) == 0); + assert(fflags == 11); + joints[2].cubic.configured = joints[0].cubic.configured; +#ifdef TEST_AVAILABILITY + test_availability(&pose, positions, staged); +#endif +} +""" +with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + # Only the math header is shimmed; cubic.c is compiled unchanged. + (tmp/'rtapi_math.h').write_text('#include \n') + text = preamble + '\n' + function('prepare_joint_targets') + extra = Path(__file__).with_name('availability-cases.h') + if extra.exists(): text += '\n' + extra.read_text() + (tmp/'test.c').write_text(text + '\n' + main) + subprocess.run([os.environ.get('CC', 'cc'), '-std=c99', '-I'+str(tmp), + '-I'+str(root/'src/emc/kinematics'), '-I'+str(root/'src/emc/motion'), str(tmp/'test.c'), + str(root/'src/emc/kinematics/cubic.c'), '-lm', '-o', str(tmp/'test')], check=True) + subprocess.run([str(tmp/'test')], check=True) + +# Exercise the production legacy activation command handlers in every lifecycle +# state: controlled joints must retain ACTIVE and all lifecycle fields on error. +command_source = (root / 'src/emc/motion/command.c').read_text() +start = command_source.index('\tcase EMCMOT_JOINT_ACTIVATE:') +end = command_source.index('\tcase EMCMOT_JOINT_HOME:', start) +activation_cases = command_source[start:end] +activation_test = r""" +#include +#include +#define _(s) s +#define reportError(...) ((void)0) +#define rtapi_print_msg(...) ((void)0) +#define SET_JOINT_ACTIVE_FLAG(j, v) ((j)->active = (v)) +enum { EMCMOT_JOINT_ACTIVATE, EMCMOT_JOINT_DEACTIVATE, + EMCMOT_COMMAND_INVALID_COMMAND }; +typedef struct { int active; } joint_t; +static struct { + int commandStatus; + struct { struct { int controlled, state, phase; } availability; } joint_status[1]; +} status, *emcmotStatus = &status; +static void command(int cmd, joint_t *joint) { + int joint_num = 0; + switch (cmd) { +""" + activation_cases + r""" + } +} +int main(void) { + for (int state = 0; state <= 5; ++state) + for (int active = 0; active <= 1; ++active) + for (int cmd = 0; cmd <= 1; ++cmd) { + joint_t joint = {active}; + status.joint_status[0].availability.controlled = 1; + status.joint_status[0].availability.state = state; + status.joint_status[0].availability.phase = 42; + status.commandStatus = 0; + command(cmd, &joint); + assert(joint.active == active); + assert(status.commandStatus == EMCMOT_COMMAND_INVALID_COMMAND); + assert(status.joint_status[0].availability.state == state); + assert(status.joint_status[0].availability.phase == 42); + } + joint_t joint = {0}; + status.joint_status[0].availability.controlled = 0; + status.commandStatus = 0; + command(EMCMOT_JOINT_ACTIVATE, &joint); + assert(joint.active == 1 && status.commandStatus == 0); + command(EMCMOT_JOINT_DEACTIVATE, &joint); + assert(joint.active == 0 && status.commandStatus == 0); +} +""" +with tempfile.TemporaryDirectory() as directory: + source_file = Path(directory) / 'activation.c' + binary = Path(directory) / 'activation' + source_file.write_text(activation_test) + subprocess.run(['cc', '-Wall', '-Werror', str(source_file), '-o', str(binary)], check=True) + subprocess.run([str(binary)], check=True) diff --git a/linuxcnc-tests/motion-target-preparation/test.sh b/linuxcnc-tests/motion-target-preparation/test.sh new file mode 100755 index 00000000..0cd44bb0 --- /dev/null +++ b/linuxcnc-tests/motion-target-preparation/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +python3 test.py diff --git a/linuxcnc-tests/power-jog/.gitignore b/linuxcnc-tests/power-jog/.gitignore new file mode 100644 index 00000000..d070f216 --- /dev/null +++ b/linuxcnc-tests/power-jog/.gitignore @@ -0,0 +1,3 @@ +nonlathe.ini +scurve.ini +sim.var* diff --git a/linuxcnc-tests/power-jog/checkresult b/linuxcnc-tests/power-jog/checkresult new file mode 100755 index 00000000..305bdc41 --- /dev/null +++ b/linuxcnc-tests/power-jog/checkresult @@ -0,0 +1,4 @@ +#!/bin/sh +set -eu +test "$(grep -c '^native power jog scenarios ok$' "$1")" = 2 +grep -q '^nonlathe pins absent$' "$1" diff --git a/linuxcnc-tests/power-jog/core_sim.hal b/linuxcnc-tests/power-jog/core_sim.hal new file mode 100644 index 00000000..80225af5 --- /dev/null +++ b/linuxcnc-tests/power-jog/core_sim.hal @@ -0,0 +1,11 @@ +loadrt trivkins coordinates=XZ +loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=2000000 num_joints=2 num_spindles=2 +addf motion-command-handler servo-thread +addf motion-controller servo-thread +net x-pos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net z-pos joint.1.motor-pos-cmd => joint.1.motor-pos-fb +net estop iocontrol.0.user-enable-out => iocontrol.0.emc-enable-in +setp spindle.0.at-speed true +setp spindle.1.at-speed true +setp spindle.0.speed-in 10 +setp spindle.1.speed-in -20 diff --git a/linuxcnc-tests/power-jog/test-ui.py b/linuxcnc-tests/power-jog/test-ui.py new file mode 100755 index 00000000..463e5c34 --- /dev/null +++ b/linuxcnc-tests/power-jog/test-ui.py @@ -0,0 +1,213 @@ +#!/usr/bin/env python3 +"""Exercise HALUI -> NML -> real motion, observing simulated axis positions.""" +import math +import os +import sys +import time +import hal +import linuxcnc + +c, s, errors = linuxcnc.command(), linuxcnc.stat(), linuxcnc.error_channel() +h = hal.component('power-jog-test') +h.ready() + + +def wait(predicate, label, timeout=8): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + s.poll() + if predicate(): + return + time.sleep(.005) + raise AssertionError((label, s.position, s.task_state, errors.poll())) + + +def done(): + assert c.wait_complete(8) == linuxcnc.RCS_DONE, errors.poll() + + +def pin(name, value): + hal.set_p(name, str(value)) + + +def velocity(axis): + return hal.get_value('axis.' + axis + '.teleop-vel-cmd') + + +def position(): + s.poll() + return s.position[0], s.position[2] + + +def release(): + for axis in ('x', 'z'): + for direction in ('plus', 'minus'): + pin('halui.power-feed.' + axis + '.' + direction, 0) + pin('halui.axis.' + axis + '.' + direction, 0) + wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'stop') + time.sleep(.1) # let HALUI consume the complete release + + +def origin(): + release() + c.mode(linuxcnc.MODE_MDI); done() + c.mdi('G21 G90 G94 F120 G1 X0 Z0'); done() + c.mode(linuxcnc.MODE_MANUAL); done() + c.teleop_enable(1); done() + + +wait(lambda: hal.component_exists('halui'), 'HALUI startup') +wait(lambda: any(p['NAME'] == 'halui.axis.jog-speed' for p in hal.get_info_pins()), 'HALUI pins') +if os.environ.get('POWER_JOG_NONLATHE'): + assert not any(p['NAME'].startswith('halui.power-feed.') for p in hal.get_info_pins()) + print('nonlathe pins absent', flush=True) + sys.exit(0) +c.state(linuxcnc.STATE_ESTOP_RESET); done() +c.state(linuxcnc.STATE_ON); done() +c.mode(linuxcnc.MODE_MANUAL); done() +c.home(-1); done() +wait(lambda: all(s.homed[:2]), 'homing') +c.teleop_enable(1); done() +c.spindle(linuxcnc.SPINDLE_FORWARD, 600, 0); done() +c.spindle(linuxcnc.SPINDLE_REVERSE, 1200, 1); done() +pin('halui.power-feed.per-rev', .1) +time.sleep(.1) + +# Feed/rev is independent of the interpreter F and is captured until release. +pin('halui.power-feed.z.plus', 1) +wait(lambda: abs(velocity('z') - 1) < .01, 'initial feed') +pin('halui.power-feed.per-rev', .2) +time.sleep(.15) +assert abs(velocity('z') - 1) < .01 +c.feedrate(.5) +wait(lambda: abs(velocity('z') - .5) < .01, 'live override') +c.feedrate(0) +wait(lambda: abs(velocity('z')) < 1e-8, 'zero override pauses') +c.feedrate(.5) +wait(lambda: abs(velocity('z') - .5) < .01, 'override resumes held feed') +pin('halui.power-feed.x.plus', 1) +wait(lambda: abs(velocity('x') - math.sqrt(.125)) < .01 and + abs(velocity('z') - math.sqrt(.125)) < .01, + 'direction change retains captured feed') +release() +c.feedrate(1); done() +pin('halui.power-feed.z.plus', 1) +wait(lambda: abs(velocity('z') - 2) < .01, 'next press captures feed') +release() +pin('halui.power-feed.spindle', 1) +pin('halui.power-feed.z.minus', 1) +wait(lambda: abs(velocity('z') + 4) < .01, 'selected reverse spindle magnitude') +release() +# The spindle pin is 64 bits wide; indices that do not fit the command must +# be refused, not wrapped onto spindle 0 or 1. +for invalid in (1 << 31, 1 << 32, (1 << 32) + 1): + pin('halui.power-feed.spindle', invalid) + pin('halui.power-feed.z.plus', 1) + time.sleep(.3) + assert abs(velocity('z')) < 1e-8, ('invalid spindle fed', invalid) + release() + +# Unequal X/Z constraints must preserve geometry throughout acceleration/stop. +pin('halui.power-feed.spindle', 0) +pin('halui.power-feed.per-rev', 1) +for axis, slope in [(a, k) for a in ('x', 'z') for k in (-1, -.5, 0, .5, 1)]: + origin() + pin('halui.power-feed.taper-slope', slope) + start_x, start_z = position() + pin('halui.power-feed.' + axis + '.plus', 1) + wait(lambda: velocity(axis) > .1, 'taper starts') + for _ in range(35): + x, z = position() + error = ((x-start_x) - slope*(z-start_z) if axis == 'z' + else (z-start_z) + slope*(x-start_x)) + assert abs(error) < .002, (axis, slope, x, z) + assert abs(velocity('x')) <= 3.001 + time.sleep(.005) + pin('halui.power-feed.' + axis + '.plus', 0) + wait(lambda: abs(velocity(axis)) < 1e-8, 'taper stops') + x, z = position() + error = ((x-start_x) - slope*(z-start_z) if axis == 'z' + else (z-start_z) + slope*(x-start_x)) + assert abs(error) < .002 + release() + +origin() +pin('halui.power-feed.taper-slope', 0) +pin('halui.power-feed.per-rev', .1) +pin('halui.power-feed.x.plus', 1) +pin('halui.power-feed.z.plus', 1) +wait(lambda: abs(velocity('x') - math.sqrt(.5)) < .01 and + abs(velocity('z') - math.sqrt(.5)) < .01, 'combined directions') +c.jog(linuxcnc.JOG_STOP, 0, 0); done() +wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'existing stop stops both') +time.sleep(.1) +assert abs(velocity('z')) < 1e-8 +release() + +origin() +pin('halui.power-feed.taper-slope', .5) +pin('halui.power-feed.per-rev', 1) +pin('halui.power-feed.z.plus', 1) +wait(lambda: s.position[2] > 9.99, 'coupled travel limit', 10) +wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'limit stops both') +x, z = position() +assert z <= 10.000001 and abs(x - .5*z) < .002 +release() +# Like an ordinary jog it stops just inside the limit, so motion does not +# keep reporting a teleop limit hit once the jog has ended. +x, z = position() +assert 9.99 < z < 10, z +time.sleep(.2) +assert not hal.get_value('motion.eoffset-limited'), 'power jog left a soft limit hit' + +origin() +pin('halui.power-feed.z.plus', 1) +wait(lambda: velocity('z') > .1, 'jog before inhibit') +pin('motion.jog-inhibit', 1) +wait(lambda: abs(velocity('z')) < 1e-8, 'inhibit cancels') +pin('motion.jog-inhibit', 0) +time.sleep(.15) +assert abs(velocity('z')) < 1e-8 +pin('halui.power-feed.x.plus', 1) +time.sleep(.15) +assert abs(velocity('x')) + abs(velocity('z')) < 1e-8 +release() + +# A new vector must settle before starting in its new direction. +origin() +pin('halui.power-feed.taper-slope', 0) +pin('halui.power-feed.per-rev', .1) +pin('halui.power-feed.z.plus', 1) +wait(lambda: abs(velocity('z') - 1) < .01, 'before vector change') +pin('halui.power-feed.x.plus', 1) +wait(lambda: abs(velocity('x') - math.sqrt(.5)) < .01 and + abs(velocity('z') - math.sqrt(.5)) < .01, 'new combined vector') +pin('motion.jog-stop-immediate', 1) +wait(lambda: abs(velocity('x')) + abs(velocity('z')) < 1e-8, 'immediate group stop') +pin('motion.jog-stop-immediate', 0) +time.sleep(.15) +assert abs(velocity('x')) + abs(velocity('z')) < 1e-8 +release() + +# The two direction routes are independent. An ordinary jog cannot take over +# a reserved power-feed path, and a power request cannot steal an ordinary jog. +origin() +pin('halui.axis.jog-speed', 30) +pin('halui.power-feed.z.plus', 1) +wait(lambda: abs(velocity('z') - 1) < .01, 'power feed before ordinary press') +pin('halui.axis.z.minus', 1) +time.sleep(.15) +assert velocity('z') > 0 +pin('halui.axis.z.minus', 0) +release() + +origin() +pin('halui.axis.z.minus', 1) +wait(lambda: abs(velocity('z') + .5) < .01, 'ordinary jog before power press') +pin('halui.power-feed.z.plus', 1) +time.sleep(.15) +assert velocity('z') < 0 +pin('halui.power-feed.z.plus', 0) +release() + +print('native power jog scenarios ok', flush=True) diff --git a/linuxcnc-tests/power-jog/test.ini b/linuxcnc-tests/power-jog/test.ini new file mode 100644 index 00000000..98afc6f1 --- /dev/null +++ b/linuxcnc-tests/power-jog/test.ini @@ -0,0 +1,69 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0 +[DISPLAY] +DISPLAY = ./test-ui.py +LATHE = 1 +[RS274NGC] +PARAMETER_FILE = sim.var +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4 +SERVO_PERIOD = 1000000 +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 +[HAL] +HALFILE = core_sim.hal +HALUI = halui +[TRAJ] +COORDINATES = XZ +SPINDLES = 2 +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 5 +MAX_LINEAR_VELOCITY = 30 +MAX_LINEAR_JERK = 10000 +[EMCIO] +TOOL_TABLE = tool.tbl +[KINS] +KINEMATICS = trivkins coordinates=XZ +JOINTS = 2 +[AXIS_X] +MIN_LIMIT = -10 +MAX_LIMIT = 10 +MAX_VELOCITY = 3 +MAX_ACCELERATION = 15 +MAX_JERK = 5000 +[AXIS_Z] +MIN_LIMIT = -10 +MAX_LIMIT = 10 +MAX_VELOCITY = 10 +MAX_ACCELERATION = 100 +MAX_JERK = 10000 +[JOINT_0] +TYPE = LINEAR +MIN_LIMIT = -10 +MAX_LIMIT = 10 +MAX_VELOCITY = 3 +MAX_ACCELERATION = 15 +MAX_JERK = 5000 +FERROR = 1 +MIN_FERROR = 0.25 +HOME = 0 +HOME_SEQUENCE = 0 +HOME_SEARCH_VEL = 0 +HOME_LATCH_VEL = 0 +[JOINT_1] +TYPE = LINEAR +MIN_LIMIT = -10 +MAX_LIMIT = 10 +MAX_VELOCITY = 10 +MAX_ACCELERATION = 100 +MAX_JERK = 10000 +FERROR = 1 +MIN_FERROR = 0.25 +HOME = 0 +HOME_SEQUENCE = 0 +HOME_SEARCH_VEL = 0 +HOME_LATCH_VEL = 0 diff --git a/linuxcnc-tests/power-jog/test.sh b/linuxcnc-tests/power-jog/test.sh new file mode 100755 index 00000000..43970297 --- /dev/null +++ b/linuxcnc-tests/power-jog/test.sh @@ -0,0 +1,7 @@ +#!/bin/sh +set -eu +linuxcnc -r test.ini +sed '/\[TRAJ\]/a PLANNER_TYPE = 1' test.ini > scurve.ini +linuxcnc -r scurve.ini +sed 's/LATHE = 1/LATHE = 0/' test.ini > nonlathe.ini +POWER_JOG_NONLATHE=1 linuxcnc -r nonlathe.ini diff --git a/linuxcnc-tests/power-jog/tool.tbl b/linuxcnc-tests/power-jog/tool.tbl new file mode 100644 index 00000000..68840ea7 --- /dev/null +++ b/linuxcnc-tests/power-jog/tool.tbl @@ -0,0 +1 @@ +T1 P1 Z0 D0 diff --git a/linuxcnc-tests/remap/dollar-argspec/README b/linuxcnc-tests/remap/dollar-argspec/README new file mode 100644 index 00000000..3758b4fb --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/README @@ -0,0 +1 @@ +Exercise passing the optional $ spindle selector to Python and NGC remaps. diff --git a/linuxcnc-tests/remap/dollar-argspec/expected b/linuxcnc-tests/remap/dollar-argspec/expected new file mode 100644 index 00000000..518d1fe2 --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/expected @@ -0,0 +1,29 @@ + + N..... USE_LENGTH_UNITS(CANON_UNITS_MM) + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_G92_OFFSET(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SET_FEED_REFERENCE(CANON_XYZ) + N..... ON_RESET() + Python P=0 spindle=omitted + Python P=1 spindle=1 + Python P=2 spindle=-1 + N..... MESSAGE(" NGC spindle omitted") + N..... MESSAGE(" NGC spindle=2.000000") + N..... MESSAGE(" positional n_args=2.000000 P=7.000000 spindle=1.000000") + N..... SET_SPINDLE_SPEED(0, 1000.0000) + N..... SET_SPINDLE_SPEED(1, 2000.0000) + Python spindle=0 speed=1000 + Python spindle=1 speed=2000 + N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... SET_XY_ROTATION(0.0000) + N..... SET_FEED_MODE(0, 0) + N..... SET_FEED_RATE(0.0000) + N..... STOP_SPINDLE_TURNING(0) + N..... SET_SPINDLE_MODE(0 0.0000) + N..... STOP_SPINDLE_TURNING(1) + N..... SET_SPINDLE_MODE(1 0.0000) + N..... STOP_SPINDLE_TURNING(2) + N..... SET_SPINDLE_MODE(2 0.0000) + N..... PROGRAM_END() + N..... ON_RESET() diff --git a/linuxcnc-tests/remap/dollar-argspec/m501.ngc b/linuxcnc-tests/remap/dollar-argspec/m501.ngc new file mode 100644 index 00000000..e5495df8 --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/m501.ngc @@ -0,0 +1,9 @@ +o sub +o100 if [EXISTS[#]] + (debug, NGC spindle=#) +o100 else + (debug, NGC spindle omitted) +o100 endif +o endsub +m2 +% diff --git a/linuxcnc-tests/remap/dollar-argspec/m502.ngc b/linuxcnc-tests/remap/dollar-argspec/m502.ngc new file mode 100644 index 00000000..600c9a95 --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/m502.ngc @@ -0,0 +1,5 @@ +o sub +(debug, positional n_args=# P=#1 spindle=#2) +o endsub +m2 +% diff --git a/linuxcnc-tests/remap/dollar-argspec/remap.py b/linuxcnc-tests/remap/dollar-argspec/remap.py new file mode 100644 index 00000000..95f0e7b8 --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/remap.py @@ -0,0 +1,10 @@ +def m500(self, **words): + spindle = words.get("spindle", "omitted") + if spindle != "omitted": + spindle = int(spindle) + print("M500 Python P={} spindle={}".format(int(words["p"]), spindle)) + + +def m503(self, **words): + spindle = int(words.get("spindle", 0)) + print("M503 Python spindle={} speed={}".format(spindle, int(words["s"]))) diff --git a/linuxcnc-tests/remap/dollar-argspec/test.ini b/linuxcnc-tests/remap/dollar-argspec/test.ini new file mode 100644 index 00000000..36abfcbc --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/test.ini @@ -0,0 +1,18 @@ +[EMC] +DEBUG=0 + +[RS274NGC] +SUBROUTINE_PATH = . +LOG_LEVEL=0 +OWORD_NARGS = 1 +REMAP=M500 py=m500 modalgroup=10 argspec=P$ +REMAP=M501 ngc=m501 modalgroup=10 argspec=$ +REMAP=M502 ngc=m502 modalgroup=10 argspec=@P$ +REMAP=M503 py=m503 modalgroup=10 argspec=^$ + +[TRAJ] +SPINDLES=3 + +[PYTHON] +PATH_PREPEND=. +TOPLEVEL=toplevel.py diff --git a/linuxcnc-tests/remap/dollar-argspec/test.ngc b/linuxcnc-tests/remap/dollar-argspec/test.ngc new file mode 100644 index 00000000..b4755649 --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/test.ngc @@ -0,0 +1,11 @@ +M500 P0 +M500 P1 $1 +M500 P2 $-1 +M501 +M501 $2 +M502 P7 $1 +S1000 +S2000 $1 +M503 +M503 $1 +M2 diff --git a/linuxcnc-tests/remap/dollar-argspec/test.sh b/linuxcnc-tests/remap/dollar-argspec/test.sh new file mode 100755 index 00000000..7a389520 --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +rs274 -i test.ini -n 0 -g test.ngc 2>&1 | awk '{$1=""; print}' +exit "${PIPESTATUS[0]}" diff --git a/linuxcnc-tests/remap/dollar-argspec/toplevel.py b/linuxcnc-tests/remap/dollar-argspec/toplevel.py new file mode 100644 index 00000000..0dc38fa2 --- /dev/null +++ b/linuxcnc-tests/remap/dollar-argspec/toplevel.py @@ -0,0 +1 @@ +import remap diff --git a/linuxcnc-tests/remap/executor/.gitignore b/linuxcnc-tests/remap/executor/.gitignore new file mode 100644 index 00000000..cbaede89 --- /dev/null +++ b/linuxcnc-tests/remap/executor/.gitignore @@ -0,0 +1 @@ +/test.ini diff --git a/linuxcnc-tests/remap/executor/checkresult b/linuxcnc-tests/remap/executor/checkresult new file mode 100755 index 00000000..bfa99e94 --- /dev/null +++ b/linuxcnc-tests/remap/executor/checkresult @@ -0,0 +1,6 @@ +#!/bin/sh + +set -e +test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 10 +grep -q '^executor remap preview ok$' "$1" +grep -q '^executor remap scenarios complete$' "$1" diff --git a/linuxcnc-tests/remap/executor/comp.ngc b/linuxcnc-tests/remap/executor/comp.ngc new file mode 100644 index 00000000..1b8267e0 --- /dev/null +++ b/linuxcnc-tests/remap/executor/comp.ngc @@ -0,0 +1,6 @@ +G21 G90 G0 X0 Y0 +G41.1 D2 G1 X10 Y0 F100 +G1 X10 Y10 +M10 +G40 G1 X20 +M2 diff --git a/linuxcnc-tests/remap/executor/hold-timeout.ngc b/linuxcnc-tests/remap/executor/hold-timeout.ngc new file mode 100644 index 00000000..73e97224 --- /dev/null +++ b/linuxcnc-tests/remap/executor/hold-timeout.ngc @@ -0,0 +1,4 @@ +G21 G90 G0 X0 +M11 +G1 X2 F120 +M2 diff --git a/linuxcnc-tests/remap/executor/hold.ngc b/linuxcnc-tests/remap/executor/hold.ngc new file mode 100644 index 00000000..f87cbffa --- /dev/null +++ b/linuxcnc-tests/remap/executor/hold.ngc @@ -0,0 +1,4 @@ +G21 G90 G0 X0 +M10 +G1 X2 F120 +M2 diff --git a/linuxcnc-tests/remap/executor/preview.ngc b/linuxcnc-tests/remap/executor/preview.ngc new file mode 100644 index 00000000..bf3931ce --- /dev/null +++ b/linuxcnc-tests/remap/executor/preview.ngc @@ -0,0 +1,7 @@ +G21 G90 G0 X0 +M10 +M11 +M20 +M21 +G1 X1 F100 +M2 diff --git a/linuxcnc-tests/remap/executor/readahead.ngc b/linuxcnc-tests/remap/executor/readahead.ngc new file mode 100644 index 00000000..c7ec2329 --- /dev/null +++ b/linuxcnc-tests/remap/executor/readahead.ngc @@ -0,0 +1,4 @@ +G21 G90 G0 X0 +G1 X4 F120 +M10 +M2 diff --git a/linuxcnc-tests/remap/executor/remap.py b/linuxcnc-tests/remap/executor/remap.py new file mode 100644 index 00000000..0198feb3 --- /dev/null +++ b/linuxcnc-tests/remap/executor/remap.py @@ -0,0 +1,52 @@ +from stdglue import * + + +def m10_execute(self, **words): + yield from executor_execute(self, self.chuck, request=0) + + +def m11_execute(self, **words): + yield from executor_execute(self, self.chuck, request=1, timeout=0.2) + + +def m20_transact(self, **words): + response = yield from executor_transact(self, self.tailstock, request=7) + if not self.task: + return + self.executor_component["raw-result"] = response.result + + +def m21_non_hal(self, **words): + response = yield from executor_execute(self, self.memory_executor, request=41) + if not self.task: + return + if self.memory_executor.last_operation.released: + self.executor_component["transport-result"] = response.result + + +class MemoryExecutor: + name = "memory" + + def begin(self, request): + self.last_operation = MemoryOperation(request) + return self.last_operation + + +class MemoryOperation: + def __init__(self, request): + self.request = request + self.polls = 0 + self.released = False + self.cancelled = False + + def poll(self): + self.polls += 1 + if self.polls == 1: + return None + return ExecutorResponse(EXECUTOR_SUCCEEDED, result=self.request + 1) + + def release(self): + self.released = True + + def cancel(self): + self.cancelled = True diff --git a/linuxcnc-tests/remap/executor/test-ui.py b/linuxcnc-tests/remap/executor/test-ui.py new file mode 100755 index 00000000..c6738581 --- /dev/null +++ b/linuxcnc-tests/remap/executor/test-ui.py @@ -0,0 +1,340 @@ +#!/usr/bin/env python3 + +import os +import sys +import time + +import hal +import linuxcnc + + +def fail(message): + print(message) + sys.exit(1) + + +def wait_for(predicate, message, timeout=5.0): + start = time.time() + while time.time() - start < timeout: + status.poll() + if predicate(): + return + time.sleep(0.01) + fail(message) + + +def wait_complete(message, timeout=5.0): + if command.wait_complete(timeout) != linuxcnc.RCS_DONE: + fail(message) + + +def pin_value(name): + try: + return hal.get_value(name) + except RuntimeError: + return None + + +def wait_request(executor, opcode): + prefix = "remap.executor.%s." % executor + wait_for( + lambda: hal.get_value(prefix + "request"), + "executor request was not asserted", + ) + request_id = int(hal.get_value(prefix + "request-id")) + if request_id == 0: + fail("executor used reserved request ID zero") + if int(hal.get_value(prefix + "opcode")) != opcode: + fail("executor published the wrong opcode") + if hal.get_value(prefix + "cancel"): + fail("executor cancel was asserted for a new request") + return prefix, request_id + + +def wait_error(expected, timeout=5.0): + start = time.time() + while time.time() - start < timeout: + message = errors.poll() + if message is None: + time.sleep(0.01) + continue + kind, text = message + if kind in (linuxcnc.NML_ERROR, linuxcnc.OPERATOR_ERROR) and expected in text: + return + print("ignoring message: %s" % text) + fail("no error containing %r" % expected) + + +def wait_interp_idle(message): + wait_for(lambda: status.interp_state == linuxcnc.INTERP_IDLE, message) + + +def respond(prefix, request_id, state, result): + hal.set_p(prefix + "state", str(state)) + hal.set_p(prefix + "result", str(result)) + hal.set_p(prefix + "response-id", str(request_id)) + + +def assert_released(prefix): + wait_for( + lambda: not hal.get_value(prefix + "request"), + "completed executor request was not released", + ) + if hal.get_value(prefix + "cancel"): + fail("completed executor request was cancelled") + + +command = linuxcnc.command() +status = linuxcnc.stat() +errors = linuxcnc.error_channel() +test_component = hal.component("executor-test-ui") +test_component.ready() + +wait_for( + lambda: status.task_state == linuxcnc.STATE_ESTOP, + "LinuxCNC did not initialize", +) + +for pin in ( + "remap.executor.chuck.request-id", + "remap.executor.chuck.response-id", + "remap.executor.tailstock.request-id", + "remap.owner-marker", +): + wait_for( + lambda pin=pin: pin_value(pin) is not None, + "missing caller-owned executor component pin %s" % pin, + ) + +if not hal.get_value("remap.owner-marker"): + fail("executor endpoint did not share its caller-owned HAL component") + +command.state(linuxcnc.STATE_ESTOP_RESET) +command.state(linuxcnc.STATE_ON) +wait_complete("machine did not turn on") +command.mode(linuxcnc.MODE_MDI) +wait_complete("machine did not enter MDI") + +scenario = os.environ["EXECUTOR_SCENARIO"] + +if scenario == "success": + command.mdi("M10") + prefix, first_id = wait_request("chuck", 0) + respond(prefix, first_id, 4, 0) + wait_complete("successful executor request did not complete") + assert_released(prefix) + + command.mdi("M11") + prefix, second_id = wait_request("chuck", 1) + if second_id != first_id + 1: + fail("executor request IDs were not monotonic") + respond(prefix, second_id, 4, 7) + wait_complete("second successful executor request did not complete") + assert_released(prefix) + + command.mdi("M20") + prefix, request_id = wait_request("tailstock", 7) + respond(prefix, request_id, 5, 42) + wait_complete("raw executor transaction did not return to its remap") + assert_released(prefix) + if int(hal.get_value("remap.raw-result")) != 42: + fail("custom remap did not receive the raw executor result") + + command.mdi("M21") + wait_complete("non-HAL executor transport did not complete") + if int(hal.get_value("remap.transport-result")) != 42: + fail("executor helper required a HAL transport") + +elif scenario == "failure": + command.mdi("M10") + prefix, request_id = wait_request("chuck", 0) + respond(prefix, request_id, 5, 42) + wait_for( + lambda: not hal.get_value(prefix + "request"), + "failed executor request was not released", + ) + if hal.get_value(prefix + "cancel"): + fail("terminal executor failure was incorrectly cancelled") + # Only a succeeded response continues; anything else ends the MDI in error. + wait_error("executor 'chuck': ") + wait_interp_idle("failed executor request did not stop the MDI command") + +elif scenario == "timeout": + command.mdi("M11") + prefix, timed_out_id = wait_request("chuck", 1) + wait_for( + lambda: hal.get_value(prefix + "cancel") + and not hal.get_value(prefix + "request"), + "timed-out executor request was not cancelled", + timeout=2.0, + ) + wait_error("executor 'chuck': timed out") + wait_interp_idle("timed-out executor request did not stop the MDI command") + + command.abort() + wait_complete("timeout recovery abort did not complete") + command.mdi("M10") + prefix, next_id = wait_request("chuck", 0) + respond(prefix, timed_out_id, 4, 0) + time.sleep(0.1) + if not hal.get_value(prefix + "request"): + fail("a stale response completed the next executor request") + respond(prefix, next_id, 4, 0) + wait_complete("request following a timeout did not complete") + assert_released(prefix) + +elif scenario == "abort": + command.mdi("M10") + prefix, unused_request_id = wait_request("chuck", 0) + command.abort() + wait_complete("abort command did not complete") + wait_for( + lambda: hal.get_value(prefix + "cancel") + and not hal.get_value(prefix + "request"), + "aborted executor request was not cancelled", + ) + +elif scenario == "readahead": + # The interpreter reads M10 while the 2 s move before it still runs; the + # request must not start until the move has finished. + command.mode(linuxcnc.MODE_AUTO) + wait_complete("machine did not enter AUTO") + command.program_open(os.path.join(os.getcwd(), "readahead.ngc")) + wait_complete("program did not open") + command.auto(linuxcnc.AUTO_RUN, 0) + wait_for(lambda: status.current_vel > 0.0, "move before M10 did not start") + prefix = "remap.executor.chuck." + while True: + status.poll() + if hal.get_value(prefix + "request"): + break + if status.interp_state == linuxcnc.INTERP_IDLE: + fail("program ended without an executor request") + time.sleep(0.005) + status.poll() + if abs(status.position[0] - 4.0) > 0.001 or status.current_vel != 0.0: + fail("executor request started during the earlier move at X%.4f" + % status.position[0]) + prefix, request_id = wait_request("chuck", 0) + respond(prefix, request_id, 4, 0) + assert_released(prefix) + wait_interp_idle("program did not finish after the executor request") + +elif scenario in ("stop", "pause"): + # A request already started runs to its end while Stop or Pause holds; + # the program reads nothing past the remap until Resume. + command.mode(linuxcnc.MODE_AUTO) + wait_complete("machine did not enter AUTO") + command.program_open(os.path.join(os.getcwd(), "hold.ngc")) + wait_complete("program did not open") + command.auto(linuxcnc.AUTO_RUN, 0) + prefix, request_id = wait_request("chuck", 0) + if scenario == "stop": + command.program_stop() + holding = lambda: status.stop_state == linuxcnc.STOP_STOPPING + else: + command.auto(linuxcnc.AUTO_PAUSE) + holding = lambda: status.interp_state == linuxcnc.INTERP_PAUSED + wait_for( + lambda: holding() and status.hold_wait == linuxcnc.HOLD_WAIT_EXECUTOR, + "%s did not wait for the executor request" % scenario, + ) + time.sleep(0.3) + if not hal.get_value(prefix + "request") or hal.get_value(prefix + "cancel"): + fail("%s ended the executor request" % scenario) + respond(prefix, request_id, 4, 0) + assert_released(prefix) + if scenario == "stop": + wait_for( + lambda: status.stop_state == linuxcnc.STOP_STOPPED, + "Stop did not complete after the executor request", + ) + else: + wait_for( + lambda: status.hold_wait == linuxcnc.HOLD_WAIT_NONE + and status.interp_state == linuxcnc.INTERP_PAUSED, + "Pause did not hold after the executor request", + ) + time.sleep(0.3) + status.poll() + if abs(status.position[0]) > 0.001: + fail("%s: program continued past the executor remap" % scenario) + command.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: status.interp_state == linuxcnc.INTERP_IDLE + and abs(status.position[0] - 2.0) < 0.001, + "program did not finish after Resume", + ) + +elif scenario == "mdi-pause": + # In MDI too a request already started runs to its end while paused, + # and the program stays paused. + command.mdi("M10") + prefix, request_id = wait_request("chuck", 0) + command.auto(linuxcnc.AUTO_PAUSE) + wait_for( + lambda: status.interp_state == linuxcnc.INTERP_PAUSED + and status.hold_wait == linuxcnc.HOLD_WAIT_EXECUTOR, + "MDI pause did not wait for the executor request", + ) + respond(prefix, request_id, 4, 0) + assert_released(prefix) + time.sleep(0.2) + status.poll() + if status.interp_state != linuxcnc.INTERP_PAUSED: + fail("the executor request ended the MDI pause") + command.auto(linuxcnc.AUTO_RESUME) + wait_interp_idle("MDI did not finish after Resume") + # Once the request has ended, a later Pause holds as usual. + command.mdi("G4 P2") + wait_for( + lambda: status.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY, + "G4 did not start", + ) + command.auto(linuxcnc.AUTO_PAUSE) + wait_for( + lambda: status.interp_state == linuxcnc.INTERP_PAUSED, + "MDI pause during G4 did not hold", + ) + if status.hold_wait != linuxcnc.HOLD_WAIT_NONE: + fail("a finished executor request still reported a hold wait") + command.auto(linuxcnc.AUTO_RESUME) + wait_interp_idle("G4 did not finish after Resume") + +elif scenario == "stop-timeout": + # The request keeps its timeout while Stop waits for it; a timeout ends + # the program as usual. + command.mode(linuxcnc.MODE_AUTO) + wait_complete("machine did not enter AUTO") + command.program_open(os.path.join(os.getcwd(), "hold-timeout.ngc")) + wait_complete("program did not open") + command.auto(linuxcnc.AUTO_RUN, 0) + prefix, unused_request_id = wait_request("chuck", 1) + command.program_stop() + wait_error("executor 'chuck': timed out") + wait_for( + lambda: status.stop_state == linuxcnc.STOP_IDLE + and status.interp_state == linuxcnc.INTERP_IDLE, + "timeout during Stop did not end the program", + ) + if abs(status.position[0]) > 0.001: + fail("program continued after the executor timed out") + +elif scenario == "comp": + # Under cutter radius compensation the move before the remap is still + # held back, so the request is refused instead of starting early. + command.mode(linuxcnc.MODE_AUTO) + wait_complete("machine did not enter AUTO") + command.program_open(os.path.join(os.getcwd(), "comp.ngc")) + wait_complete("program did not open") + command.auto(linuxcnc.AUTO_RUN, 0) + wait_error("cutter radius compensation") + wait_interp_idle("refused executor request did not end the program") + if hal.get_value("remap.executor.chuck.request"): + fail("executor request started under cutter radius compensation") + +else: + fail("unknown executor scenario %s" % scenario) + +print("executor remap scenario ok: %s" % scenario) +sys.exit(0) diff --git a/linuxcnc-tests/remap/executor/test.ini.in b/linuxcnc-tests/remap/executor/test.ini.in new file mode 100644 index 00000000..b9a4ee52 --- /dev/null +++ b/linuxcnc-tests/remap/executor/test.ini.in @@ -0,0 +1,95 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0x0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var +REMAP = M10 modalgroup=10 python=m10_execute +REMAP = M11 modalgroup=10 python=m11_execute +REMAP = M20 modalgroup=10 python=m20_transact +REMAP = M21 modalgroup=10 python=m21_non_hal + +[PYTHON] +TOPLEVEL = toplevel.py +PATH_PREPEND = . +PATH_APPEND = @EMC2_HOME@/nc_files/remap_lib/python-stdglue/ + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = @EMC2_HOME@/tests/remap/remap-io/core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +AXES = 3 +COORDINATES = X Y Z +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 1 +MAX_LINEAR_VELOCITY = 4 + +[EMCIO] +TOOL_TABLE = @EMC2_HOME@/tests/remap/remap-io/simpockets.tbl + +[KINS] +KINEMATICS = trivkins +JOINTS = 3 + +[AXIS_X] +MIN_LIMIT = -40 +MAX_LIMIT = 40 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000 + +[JOINT_0] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000 +MIN_LIMIT = -40 +MAX_LIMIT = 40 +FERROR = 0.05 +MIN_FERROR = 0.01 + +[AXIS_Y] +MIN_LIMIT = -40 +MAX_LIMIT = 40 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000 + +[JOINT_1] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000 +MIN_LIMIT = -40 +MAX_LIMIT = 40 +FERROR = 0.05 +MIN_FERROR = 0.01 + +[AXIS_Z] +MIN_LIMIT = -40 +MAX_LIMIT = 40 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000 + +[JOINT_2] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000 +MIN_LIMIT = -40 +MAX_LIMIT = 40 +FERROR = 0.05 +MIN_FERROR = 0.01 diff --git a/linuxcnc-tests/remap/executor/test.sh b/linuxcnc-tests/remap/executor/test.sh new file mode 100755 index 00000000..9ffc590b --- /dev/null +++ b/linuxcnc-tests/remap/executor/test.sh @@ -0,0 +1,23 @@ +#!/bin/bash -e + +# The configuration borrows the remap-io HAL file and tool table and the +# stdglue library from the LinuxCNC tree. +sed "s#@EMC2_HOME@#${EMC2_HOME}#g" test.ini.in > test.ini + +for scenario in success failure timeout abort readahead stop pause stop-timeout comp mdi-pause; do + echo "Running executor remap scenario: ${scenario}" + EXECUTOR_SCENARIO="${scenario}" linuxcnc -r test.ini +done + +# The preview runs the same remaps without task; they must not fail there. +preview=$(rs274 -i test.ini -n 0 -g preview.ngc 2>&1) +# Importing hal there leaves the HAL shared memory behind. +halrun -U >/dev/null 2>&1 || true +echo "$preview" +if grep -q StopIteration <<<"$preview" || ! grep -q STRAIGHT_FEED <<<"$preview"; then + echo "executor remaps failed in the preview" >&2 + exit 1 +fi +echo "executor remap preview ok" + +echo "executor remap scenarios complete" diff --git a/linuxcnc-tests/remap/executor/toplevel.py b/linuxcnc-tests/remap/executor/toplevel.py new file mode 100644 index 00000000..4be91bac --- /dev/null +++ b/linuxcnc-tests/remap/executor/toplevel.py @@ -0,0 +1,18 @@ +import hal +import remap + + +def __init__(self): + remap.init_stdglue(self) + component = hal.component("remap") if self.task else None + self.chuck = remap.HalExecutor(self, "chuck", component) + self.tailstock = remap.HalExecutor(self, "tailstock", component) + self.memory_executor = remap.MemoryExecutor() + + if component is not None: + component.newpin("owner-marker", hal.Type.BOOL, hal.Dir.OUT) + component.newpin("raw-result", hal.Type.SINT, hal.Dir.OUT) + component.newpin("transport-result", hal.Type.SINT, hal.Dir.OUT) + component["owner-marker"] = True + component.ready() + self.executor_component = component diff --git a/linuxcnc-tests/remap/mdi-remap-abort/README b/linuxcnc-tests/remap/mdi-remap-abort/README new file mode 100644 index 00000000..03bb42dd --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/README @@ -0,0 +1,18 @@ +Interrupt an MDI command whose remap is mid-execution with an E-stop, a +machine off, a mode change to AUTO and back, and an abort followed by an +interpreter re-init (EMC_TASK_PLAN_INIT) once idle, then bring the machine back +and check that milltask is still alive and MDI still works. + +Each of these resets the interpreter, which unwinds the remap's call frame. +Task used to keep its MDI continuation state (mdi_execute_next/_wait/_level) +and resumed the unwound call once the machine was back in MDI, which +crashed milltask in Interp::execute_call() for a Python remap. + +M400 is an NGC remap that waits on M66; M401 is a Python generator remap +that keeps yielding INTERP_EXECUTE_FINISH. + +An MDI G0 X5 sent while the remap waits is queued behind it and must be +dropped by each interrupt, never run. + +A re-init of a busy machine is not covered: it is only valid when idle, and +the native server refuses it otherwise. diff --git a/linuxcnc-tests/remap/mdi-remap-abort/checkresult b/linuxcnc-tests/remap/mdi-remap-abort/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/remap/mdi-remap-abort/m400.ngc b/linuxcnc-tests/remap/mdi-remap-abort/m400.ngc new file mode 100644 index 00000000..b841fc77 --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/m400.ngc @@ -0,0 +1,5 @@ +o sub + (wait up to 3 s for digital input 0, which nothing sets) + M66 P0 L3 Q3 +o endsub +M2 diff --git a/linuxcnc-tests/remap/mdi-remap-abort/remap.py b/linuxcnc-tests/remap/mdi-remap-abort/remap.py new file mode 100644 index 00000000..b616b527 --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/remap.py @@ -0,0 +1,9 @@ +import emccanon +from interpreter import INTERP_EXECUTE_FINISH + + +def m401(self, **words): + # Keep the remap mid-execution: dwell, wait for it to finish, repeat. + while True: + emccanon.DWELL(0.05) + yield INTERP_EXECUTE_FINISH diff --git a/linuxcnc-tests/remap/mdi-remap-abort/test-ui.py b/linuxcnc-tests/remap/mdi-remap-abort/test-ui.py new file mode 100755 index 00000000..33416176 --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/test-ui.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# +# Interrupt an MDI command whose remap is mid-execution in every way that +# resets the interpreter (E-stop, machine off, mode change, abort followed by +# an interpreter re-init once idle), then bring the machine back and check that +# task is still alive and MDI still works. + +import os +import sys +import time + +import linuxcnc + +c = linuxcnc.command() +s = linuxcnc.stat() + + +def fail(msg): + print("FAIL: %s" % msg) + sys.exit(1) + + +def task_alive(): + for pid in os.listdir("/proc"): + if not pid.isdigit(): + continue + try: + with open("/proc/%s/comm" % pid) as f: + if f.read().strip() == "milltask": + return True + except OSError: + pass + return False + + +def wait_for(cond, what, timeout=10.0): + start = time.time() + while time.time() - start < timeout: + s.poll() + if cond(): + return + time.sleep(0.02) + if not task_alive(): + fail("milltask died (waiting for %s)" % what) + fail("timeout waiting for %s: task_state=%d mode=%d interp_state=%d " + "exec_state=%d call_level=%d" % (what, s.task_state, s.task_mode, + s.interp_state, s.exec_state, s.call_level)) + + +def set_state(state, reported=None): + c.state(state) + c.wait_complete() + if reported is None: + reported = state + wait_for(lambda: s.task_state == reported, "task state %d" % reported) + + +def set_mode(mode): + c.mode(mode) + c.wait_complete() + wait_for(lambda: s.task_mode == mode, "task mode %d" % mode) + + +def machine_on(): + set_state(linuxcnc.STATE_ESTOP_RESET) + set_state(linuxcnc.STATE_ON) + + +def estop(): + set_state(linuxcnc.STATE_ESTOP) + machine_on() + + +def machine_off(): + # task reports a machine that is out of E-stop but off as ESTOP_RESET + set_state(linuxcnc.STATE_OFF, linuxcnc.STATE_ESTOP_RESET) + set_state(linuxcnc.STATE_ON) + + +def abort_then_plan_init(): + # A re-init is only valid on an idle machine, so stop the work first. + c.abort() + c.wait_complete() + wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE + and s.exec_state == linuxcnc.EXEC_DONE + and s.queue == 0 and s.inpos, "abort to finish") + c.reset_interpreter() + c.wait_complete() + + +def mode_auto(): + set_mode(linuxcnc.MODE_AUTO) + set_mode(linuxcnc.MODE_MDI) + + +target = [0.0] + + +def check_mdi_works(name): + # The machine may have dropped out of MDI mode; select it as a GUI would, + # then give task's main loop time to act on any stale MDI state. + set_mode(linuxcnc.MODE_MDI) + time.sleep(0.5) + if not task_alive(): + fail("%s: milltask died" % name) + target[0] = 1.0 if target[0] != 1.0 else 2.0 + c.mdi("G0 X%.1f" % target[0]) + c.wait_complete() + wait_for(lambda: abs(s.position[0] - target[0]) < 1e-6 + and s.interp_state == linuxcnc.INTERP_IDLE, + "%s: MDI G0 X%.1f" % (name, target[0])) + if not task_alive(): + fail("%s: milltask died" % name) + + +def scenario(name, code, interrupt): + set_mode(linuxcnc.MODE_MDI) + c.mdi(code) + wait_for(lambda: s.interp_state != linuxcnc.INTERP_IDLE, + "%s: %s to start" % (name, code)) + # M400 waits for 3 s, M401 until interrupted; make sure it is waiting. + time.sleep(0.3) + s.poll() + if s.interp_state == linuxcnc.INTERP_IDLE: + fail("%s: %s is not waiting inside its remap" % (name, code)) + # An MDI command sent meanwhile is queued behind the waiting remap; the + # interrupt drops it together with the remap's call. + c.mdi("G0 X5") + wait_for(lambda: s.queued_mdi_commands == 1, + "%s: G0 X5 to be queued behind %s" % (name, code)) + interrupt() + # Check before set_mode: selecting a mode clears the queue by itself. + s.poll() + if s.queued_mdi_commands != 0: + fail("%s: %d queued MDI commands survived" + % (name, s.queued_mdi_commands)) + if s.command != "": + fail("%s: interrupted command still reported: %r" % (name, s.command)) + set_mode(linuxcnc.MODE_MDI) + time.sleep(0.5) + s.poll() + if abs(s.position[0] - target[0]) > 1e-6: + fail("%s: queued G0 X5 ran (X=%.4f)" % (name, s.position[0])) + check_mdi_works(name) + print("%s: ok" % name, flush=True) + + +wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP, "task to start") +machine_on() +set_mode(linuxcnc.MODE_MDI) +check_mdi_works("startup") + +for code in ("M400", "M401"): + scenario("%s E-stop" % code, code, estop) + scenario("%s machine off" % code, code, machine_off) + scenario("%s abort and re-init" % code, code, abort_then_plan_init) + scenario("%s mode change" % code, code, mode_auto) + +print("all scenarios passed") +set_state(linuxcnc.STATE_ESTOP) +sys.exit(0) diff --git a/linuxcnc-tests/remap/mdi-remap-abort/test.ini b/linuxcnc-tests/remap/mdi-remap-abort/test.ini new file mode 100644 index 00000000..7a707634 --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/test.ini @@ -0,0 +1,101 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var +SUBROUTINE_PATH = . +# NGC remap whose body waits on a digital input (M66 L3) +REMAP = M400 modalgroup=10 ngc=m400 +# Python generator remap that keeps yielding INTERP_EXECUTE_FINISH +REMAP = M401 modalgroup=10 python=m401 + +[PYTHON] +TOPLEVEL = toplevel.py +PATH_PREPEND = . + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = LIB:core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +AXES = 3 +COORDINATES = X Y Z +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 4 +MAX_LINEAR_VELOCITY = 4 + +[KINS] +KINEMATICS = trivkins +JOINTS = 3 + +[AXIS_X] +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 + +[JOINT_0] +TYPE = LINEAR +HOME = 0.000 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +FERROR = 0.050 +MIN_FERROR = 0.010 + +[AXIS_Y] +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 + +[JOINT_1] +TYPE = LINEAR +HOME = 0.000 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +FERROR = 0.050 +MIN_FERROR = 0.010 + +[AXIS_Z] +MIN_LIMIT = -4.0 +MAX_LIMIT = 4.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 + +[JOINT_2] +TYPE = LINEAR +HOME = 0.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -4.0 +MAX_LIMIT = 4.0 +FERROR = 0.050 +MIN_FERROR = 0.010 diff --git a/linuxcnc-tests/remap/mdi-remap-abort/test.sh b/linuxcnc-tests/remap/mdi-remap-abort/test.sh new file mode 100755 index 00000000..a16f6fa8 --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/test.sh @@ -0,0 +1,2 @@ +#!/bin/bash +exec linuxcnc -r test.ini diff --git a/linuxcnc-tests/remap/mdi-remap-abort/toplevel.py b/linuxcnc-tests/remap/mdi-remap-abort/toplevel.py new file mode 100644 index 00000000..0dc38fa2 --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/toplevel.py @@ -0,0 +1 @@ +import remap diff --git a/linuxcnc-tests/resumable-stop/M101 b/linuxcnc-tests/resumable-stop/M101 new file mode 100755 index 00000000..5ffe22df --- /dev/null +++ b/linuxcnc-tests/resumable-stop/M101 @@ -0,0 +1,4 @@ +#!/bin/sh +# A user M-code that takes a while, for Stop to wait for. +sleep 2 +exit 0 diff --git a/linuxcnc-tests/resumable-stop/README b/linuxcnc-tests/resumable-stop/README new file mode 100644 index 00000000..6c8eb257 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/README @@ -0,0 +1,100 @@ +Verify resumable Stop preserves an active AUTO program and resumes or +single-steps it. + +This directory holds the shared configuration (test.ini, core_sim.hal, +tool.tbl), the G-code programs and test-ui.py, which runs one scenario per +LinuxCNC session (selected by RESUMABLE_STOP_SCENARIO). The runtests tests +are its subdirectories, which can run in parallel: + + g76-stop G76 Stop and clearance, the G76 cut/retract handoff stress test, + fperrev + g76-step G76 Single Step (fresh, after Stop, in flight), exit tapers, and + the trapezoidal re-run of fperrev + threading G33, G33.1 and G95 Stop cases, commands queued behind them, and + the trapezoidal re-run of g33-chain + general everything else, including the at-speed, dwell, orientation and + homing scenarios and the trapezoidal re-runs of ordinary and + single-step + +Each group lists its scenarios in its "scenarios" file. Its test.sh runs them +through run-scenarios.sh, which starts each from a fresh LinuxCNC session in a +private copy of the configuration, so groups never share files LinuxCNC +writes. Its checkresult (check-result.sh) fails unless every listed scenario +reported success and the count matches the number given in checkresult. + +This regression test exercises the task-level Stop operation directly through +the Python command API. It checks that an active feed move stops without +aborting queued AUTO state, that spindle and coolant outputs are disabled +while stopped, and that Resume restores them before continuing the same +program to completion. test.ini selects the jerk-limited trajectory planner +(PLANNER_TYPE = 1) for every scenario, although position-synchronized moves +(G33, G76, G33.1) always use the trapezoidal planner; the ordinary, +single-step, fperrev and g33-chain scenarios run a second time with the +default trapezoidal planner (PLANNER_TYPE = 0), which joins the end of a G33 +to the following feed with a blend arc. Every run rejects zero-limit Ruckig +fallback errors, which the G95 scenario could provoke while spindle feedback +recovers after Resume. The dwell-atspeed scenario checks that a +spindle at-speed barrier armed before Stop still holds the next feed after +Resume. The homing scenario issues Stop during a queued G28.2 +and checks that the homing cycle completes before the program holds in +STOPPED. +The homing-interrupted scenario ends a queued G28.2 early by Abort, E-stop, +machine off, a mode change, and Stop followed at once by Abort and AUTO (from +homing-long.ngc, whose 8 s final homing move leaves time for that), and +checks that a later program runs, that Stop is rejected for an MDI command +and that it still reaches STOPPED in a new AUTO program. +The speed-change-atspeed scenario checks that an S-word after two Stop and +Resume cycles still makes the next feed wait for spindle at-speed. +The queued-feed-atspeed scenario stops while a queued feed waits for spindle +at-speed and checks that the feed still waits for at-speed after Resume. +The g33-chain scenario stops during the first of two consecutive G33 moves +and checks that Stop lets both finish before STOPPED, and that after Resume +Z stays put and nothing moves faster than the following feed. +The step-resume-stopping scenario sends Step and then Resume while Stop waits +for G33 and checks that the program then runs on without single-stepping. +The g95-between-g33 scenario stops during a G95 move between two G33 moves +and checks that the second G33 waits for a fresh spindle index after Resume. +The command-after-sync scenario stops during a G33 followed by M5, an S-word +or M9, and during a rigid tap followed by M5, and checks that the command +takes effect after Resume, in program order. +The resume-atspeed scenario checks that Resume, and Single Step from STOPPED, +wait in STARTING until the restored spindle reports at-speed before motion +continues: not at all while spindle.0.at-speed has never read false with the +spindle on (tied true), until at-speed goes true when it was false while +stopped, and, when at-speed stayed true through the Stop, until it has +dropped after the restore and come back. It also checks that a second Stop +returns to STOPPED and that Abort ends the program while waiting. Since +Resume waits for at-speed, rapid-no-atspeed checks that an interrupted rapid +also waits and that the feed after it still waits for the program's M3 +barrier, and queued-g33 drops and restores at-speed after Resume as a +spindle would while spinning up. +The pause-starting scenario pauses while Resume waits in STARTING and checks +that the program returns to STOPPED with the spindle off and stays there when +at-speed arrives, then resumes normally; pause-latched-resume pauses after a +Resume latched while Stop waits for G33 and checks that the program stays +STOPPED once G33 ends. The resume-s0 scenario checks that Resume does not +wait for at-speed for a spindle restored at S0. +The spindle-state scenario checks that an S-word for a spindle stopped by M5 +leaves it stopped after a Stop and Resume of the other spindle. +The G76 scenarios check that Stop executes only the +explicitly marked post-cut rapid retract, leaving the tool clear of the +finished thread rather than stopped at cutting depth. Coverage includes +cylindrical and tapered drive lines, synchronized exit tapers, repeated Stop +requests across the cut/retract handoff, and a negative G33 test proving that +an unrelated following rapid is not executed. Single Step coverage enters the +first G76 pass directly and verifies every cylindrical and tapered safe +approach step followed by its combined infeed, synchronized-cut, and clearance +step. It also starts G76 in normal AUTO_RUN, stops after the first pass with +later passes already queued, and verifies that each following AUTO_STEP +reaches exactly one cylindrical or tapered safe approach endpoint, and the +next AUTO_STEP completes that pass's infeed, thread, and clearance. +In-flight Single Step coverage arms during an ordinary source block with three +later motion blocks already queued and during an active G76 cut with later +passes queued. It verifies that the active block or thread-plus-clearance unit +finishes normally and motion remains at its boundary until Resume. While the +step is armed and the active unit is still moving, both task and motion report +unpaused; they change to paused only when motion reaches the latched boundary. +Arc blending is enabled for all scenarios, so the exact-clearance assertions +also prove that a marked G76 retract endpoint is not trimmed by a following +rapid. The handoff stress case uses a slow synchronized feed and issues Stop at +least 20 task cycles before the cut endpoint. diff --git a/linuxcnc-tests/resumable-stop/after-abort.ngc b/linuxcnc-tests/resumable-stop/after-abort.ngc new file mode 100644 index 00000000..df711f6b --- /dev/null +++ b/linuxcnc-tests/resumable-stop/after-abort.ngc @@ -0,0 +1,4 @@ +G21 G90 +F600 +G1 X6 +M2 diff --git a/linuxcnc-tests/resumable-stop/after-tap-m5.ngc b/linuxcnc-tests/resumable-stop/after-tap-m5.ngc new file mode 100644 index 00000000..c6a68680 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/after-tap-m5.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X0 Z0 +S300 M3 +G33.1 Z-5 K1 +M5 +G1 X5 F300 +M2 diff --git a/linuxcnc-tests/resumable-stop/after-thread-m5.ngc b/linuxcnc-tests/resumable-stop/after-thread-m5.ngc new file mode 100644 index 00000000..e96d6e65 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/after-thread-m5.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X0 Z0 +S300 M3 +G33 Z-10 K1 +M5 +G1 X5 F300 +M2 diff --git a/linuxcnc-tests/resumable-stop/after-thread-m9.ngc b/linuxcnc-tests/resumable-stop/after-thread-m9.ngc new file mode 100644 index 00000000..cfbf6871 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/after-thread-m9.ngc @@ -0,0 +1,8 @@ +G21 G18 G90 +G0 X0 Z0 +M8 +S300 M3 +G33 Z-10 K1 +M9 +G1 X5 F300 +M2 diff --git a/linuxcnc-tests/resumable-stop/after-thread-s.ngc b/linuxcnc-tests/resumable-stop/after-thread-s.ngc new file mode 100644 index 00000000..6e468d1e --- /dev/null +++ b/linuxcnc-tests/resumable-stop/after-thread-s.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X0 Z0 +S300 M3 +G33 Z-10 K1 +S500 +G1 X5 F300 +M2 diff --git a/linuxcnc-tests/resumable-stop/check-result.sh b/linuxcnc-tests/resumable-stop/check-result.sh new file mode 100755 index 00000000..84280ec6 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/check-result.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# Shared checkresult for the resumable-stop/ tests. +# Usage: check-result.sh RESULT SCENARIO-FILE COUNT +# Passes only if the group ran exactly COUNT scenarios, COUNT is the number +# of entries in SCENARIO-FILE, and every entry reported success. +set -e +result=$1 list=$2 count=$3 +entries=$(grep -cv '^[[:space:]]*\(#\|$\)' "$list") +test "$entries" -eq "$count" +test "$(grep -c '^resumable stop scenario ok:' "$result")" -eq "$count" +test "$(grep -c '^resumable stop scenario passed:' "$result")" -eq "$count" +grep -v '^[[:space:]]*\(#\|$\)' "$list" | while read -r item; do + grep -qxF "resumable stop scenario passed: $item" "$result" +done +grep -q '^resumable stop scenarios complete$' "$result" diff --git a/linuxcnc-tests/resumable-stop/core_sim.hal b/linuxcnc-tests/resumable-stop/core_sim.hal new file mode 100644 index 00000000..5723428c --- /dev/null +++ b/linuxcnc-tests/resumable-stop/core_sim.hal @@ -0,0 +1,50 @@ +# core HAL config file for simulation + +loadrt [KINS]KINEMATICS +loadrt [EMCMOT]EMCMOT base_period_nsec=[EMCMOT]BASE_PERIOD servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS num_spindles=[TRAJ]SPINDLES +loadrt encoder names=encoder_0 +loadrt sim_encoder names=sim_encoder_0 + +addf motion-command-handler servo-thread +addf motion-controller servo-thread + +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Ypos joint.1.motor-pos-cmd => joint.1.motor-pos-fb +net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb + +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in + +net tool-prepare <= iocontrol.0.tool-prepare +net tool-prepared => iocontrol.0.tool-prepared + +net tool-change <= iocontrol.0.tool-change +net tool-changed => iocontrol.0.tool-changed + +net spindle-speed-cmd spindle.0.speed-out => sim_encoder_0.speed +setp sim_encoder_0.ppr 12 +setp sim_encoder_0.scale 60 + +net spindle-phase-A sim_encoder_0.phase-A => encoder_0.phase-A +net spindle-phase-B sim_encoder_0.phase-B => encoder_0.phase-B +net spindle-phase-Z sim_encoder_0.phase-Z => encoder_0.phase-Z +setp encoder_0.position-scale 48 + +net spindle-index-enable spindle.0.index-enable <=> encoder_0.index-enable +net spindle-pos encoder_0.position => spindle.0.revs +net spindle-rps encoder_0.velocity => spindle.0.speed-in + +addf encoder.capture-position servo-thread +addf sim-encoder.update-speed servo-thread +addf sim-encoder.make-pulses servo-thread +addf encoder.update-counters servo-thread + +setp spindle.0.at-speed true +setp spindle.1.at-speed true + +# Peak tangential deceleration, read by the short-block in-flight Step scenario. +loadrt ddt names=vel-ddt +loadrt minmax names=accel-peak +net tp-vel motion.current-vel => vel-ddt.in +net tp-accel vel-ddt.out => accel-peak.in +addf vel-ddt servo-thread +addf accel-peak servo-thread diff --git a/linuxcnc-tests/resumable-stop/css.ngc b/linuxcnc-tests/resumable-stop/css.ngc new file mode 100644 index 00000000..8a70da2f --- /dev/null +++ b/linuxcnc-tests/resumable-stop/css.ngc @@ -0,0 +1,6 @@ +G21 G18 G90 +G0 X20 Z0 +G96 D1000 S60 M3 +G1 X10 F150 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/dwell-atspeed.ngc b/linuxcnc-tests/resumable-stop/dwell-atspeed.ngc new file mode 100644 index 00000000..be7e5af6 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/dwell-atspeed.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 +S300 M3 +G4 P2 +G1 X5 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/dwell.ngc b/linuxcnc-tests/resumable-stop/dwell.ngc new file mode 100644 index 00000000..f7a54f80 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/dwell.ngc @@ -0,0 +1,5 @@ +G21 G90 +G0 X0 +G4 P3 +G1 X5 F600 +M2 diff --git a/linuxcnc-tests/resumable-stop/feed-atspeed.ngc b/linuxcnc-tests/resumable-stop/feed-atspeed.ngc new file mode 100644 index 00000000..8af98dcf --- /dev/null +++ b/linuxcnc-tests/resumable-stop/feed-atspeed.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 +F600 +S300 M3 +G1 X5 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/fperrev.ngc b/linuxcnc-tests/resumable-stop/fperrev.ngc new file mode 100644 index 00000000..92dbe874 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/fperrev.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 +S60 M3 +G95 +G1 X10 F1 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g33-followed-by-rapid.ngc b/linuxcnc-tests/resumable-stop/g33-followed-by-rapid.ngc new file mode 100644 index 00000000..a12bcb30 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g33-followed-by-rapid.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X10 Z0 +S60 M3 +G33 Z-5 K1 +G0 X30 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g76-exit-taper.ngc b/linuxcnc-tests/resumable-stop/g76-exit-taper.ngc new file mode 100644 index 00000000..5b04e692 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-exit-taper.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X10 Z0 +S60 M3 +G76 P1 Z-5 I-1 J0.2 K0.6 R1 E1 L2 +G1 X20 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g76-handoff.ngc b/linuxcnc-tests/resumable-stop/g76-handoff.ngc new file mode 100644 index 00000000..01a62a26 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-handoff.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X10 Z0 +S60 M3 +G76 P1 Z-1 I-1 J0.2 K0.21 R1 +G1 X20 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g76-step.ngc b/linuxcnc-tests/resumable-stop/g76-step.ngc new file mode 100644 index 00000000..c8ee28f7 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-step.ngc @@ -0,0 +1,4 @@ +G21 G18 G90 G76 P1 Z-5 I-1 J0.2 K0.6 R1 +G1 X20 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g76-step/checkresult b/linuxcnc-tests/resumable-stop/g76-step/checkresult new file mode 100755 index 00000000..05624046 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-step/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 6 diff --git a/linuxcnc-tests/resumable-stop/g76-step/scenarios b/linuxcnc-tests/resumable-stop/g76-step/scenarios new file mode 100644 index 00000000..df2a2ab3 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-step/scenarios @@ -0,0 +1,6 @@ +g76-single-step +g76-tapered-single-step +g76-inflight-single-step +g76-exit-taper +g76-tapered-exit-taper +trapezoidal:fperrev diff --git a/linuxcnc-tests/resumable-stop/g76-step/test.sh b/linuxcnc-tests/resumable-stop/g76-step/test.sh new file mode 100755 index 00000000..713f5769 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-step/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +# Runs the resumable-stop scenarios listed in ./scenarios (see ../README). +exec bash ../run-scenarios.sh scenarios diff --git a/linuxcnc-tests/resumable-stop/g76-stop/checkresult b/linuxcnc-tests/resumable-stop/g76-stop/checkresult new file mode 100755 index 00000000..92d147c3 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-stop/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 5 diff --git a/linuxcnc-tests/resumable-stop/g76-stop/scenarios b/linuxcnc-tests/resumable-stop/g76-stop/scenarios new file mode 100644 index 00000000..e39cc37d --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-stop/scenarios @@ -0,0 +1,5 @@ +g76-handoff-stress +g76 +g76-tapered +g76-waiting-index +fperrev diff --git a/linuxcnc-tests/resumable-stop/g76-stop/test.sh b/linuxcnc-tests/resumable-stop/g76-stop/test.sh new file mode 100755 index 00000000..713f5769 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-stop/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +# Runs the resumable-stop scenarios listed in ./scenarios (see ../README). +exec bash ../run-scenarios.sh scenarios diff --git a/linuxcnc-tests/resumable-stop/g76-tapered-exit-taper.ngc b/linuxcnc-tests/resumable-stop/g76-tapered-exit-taper.ngc new file mode 100644 index 00000000..488d2a93 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-tapered-exit-taper.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X10 Z0 +S60 M3 +G76 P1 X8 Z-5 I-1 J0.2 K0.6 R1 E1 L2 +G1 X20 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g76-tapered-step.ngc b/linuxcnc-tests/resumable-stop/g76-tapered-step.ngc new file mode 100644 index 00000000..241f7776 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-tapered-step.ngc @@ -0,0 +1,4 @@ +G21 G18 G90 G76 P1 X8 Z-5 I-1 J0.2 K0.6 R1 +G1 X20 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g76-tapered.ngc b/linuxcnc-tests/resumable-stop/g76-tapered.ngc new file mode 100644 index 00000000..b0eb997e --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76-tapered.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X10 Z0 +S60 M3 +G76 P1 X8 Z-5 I-1 J0.2 K0.6 R1 +G1 X20 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/g76.ngc b/linuxcnc-tests/resumable-stop/g76.ngc new file mode 100644 index 00000000..1c6a3ea8 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/g76.ngc @@ -0,0 +1,7 @@ +G21 G18 G90 +G0 X10 Z0 +S60 M3 +G76 P1 Z-5 I-1 J0.2 K0.6 R1 +G1 X20 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/general/checkresult b/linuxcnc-tests/resumable-stop/general/checkresult new file mode 100755 index 00000000..f5ef75dc --- /dev/null +++ b/linuxcnc-tests/resumable-stop/general/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 29 diff --git a/linuxcnc-tests/resumable-stop/general/scenarios b/linuxcnc-tests/resumable-stop/general/scenarios new file mode 100644 index 00000000..d184309a --- /dev/null +++ b/linuxcnc-tests/resumable-stop/general/scenarios @@ -0,0 +1,29 @@ +idle-rejected +ordinary +trapezoidal:ordinary +single-step +trapezoidal:single-step +inflight-single-step +rapid-no-atspeed +paused-resume +paused-run +abort-empty +abort-armed-step +orientation +dwell +dwell-atspeed +multi-spindle +css +homing +homing-interrupted +speed-change-atspeed +queued-feed-atspeed +spindle-state +resume-atspeed +pause-starting +resume-s0 +pause-inflight-step +trapezoidal:inflight-step-short +system-command +set-auto-stopped +step-after-dwell-stop diff --git a/linuxcnc-tests/resumable-stop/general/test.sh b/linuxcnc-tests/resumable-stop/general/test.sh new file mode 100755 index 00000000..713f5769 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/general/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +# Runs the resumable-stop scenarios listed in ./scenarios (see ../README). +exec bash ../run-scenarios.sh scenarios diff --git a/linuxcnc-tests/resumable-stop/homing-long.ngc b/linuxcnc-tests/resumable-stop/homing-long.ngc new file mode 100644 index 00000000..2cc583c8 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/homing-long.ngc @@ -0,0 +1,6 @@ +G21 G90 +F3000 +G1 X-60 +G28.2 P0 +G1 X30 +M2 diff --git a/linuxcnc-tests/resumable-stop/homing.ngc b/linuxcnc-tests/resumable-stop/homing.ngc new file mode 100644 index 00000000..4f214ea0 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/homing.ngc @@ -0,0 +1,6 @@ +G21 G90 +F600 +G1 X5 +G28.2 P0 +G1 X30 +M2 diff --git a/linuxcnc-tests/resumable-stop/inflight-step-short.ngc b/linuxcnc-tests/resumable-stop/inflight-step-short.ngc new file mode 100644 index 00000000..090a7b9a --- /dev/null +++ b/linuxcnc-tests/resumable-stop/inflight-step-short.ngc @@ -0,0 +1,25 @@ +G21 G90 G64 +F3000 +G1 X10 +G1 X10.5 +G1 X11 +G1 X11.5 +G1 X12 +G1 X12.5 +G1 X13 +G1 X13.5 +G1 X14 +G1 X14.5 +G1 X15 +G1 X15.5 +G1 X16 +G1 X16.5 +G1 X17 +G1 X17.5 +G1 X18 +G1 X18.5 +G1 X19 +G1 X19.5 +G1 X20 +G1 X40 +M2 diff --git a/linuxcnc-tests/resumable-stop/inflight-step.ngc b/linuxcnc-tests/resumable-stop/inflight-step.ngc new file mode 100644 index 00000000..1f725449 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/inflight-step.ngc @@ -0,0 +1,7 @@ +G21 G90 +F600 +G1 X10 +G1 X20 +G1 X30 +G1 X40 +M2 diff --git a/linuxcnc-tests/resumable-stop/multi-spindle.ngc b/linuxcnc-tests/resumable-stop/multi-spindle.ngc new file mode 100644 index 00000000..3811387b --- /dev/null +++ b/linuxcnc-tests/resumable-stop/multi-spindle.ngc @@ -0,0 +1,4 @@ +G21 G90 +G0 X0 +G1 X10 F150 +M2 diff --git a/linuxcnc-tests/resumable-stop/orient.ngc b/linuxcnc-tests/resumable-stop/orient.ngc new file mode 100644 index 00000000..6927a717 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/orient.ngc @@ -0,0 +1,6 @@ +G21 G90 +G0 X0 +M19 R90 P1 Q30 +M19 R180 P0 Q1 +G1 X20 F600 +M2 diff --git a/linuxcnc-tests/resumable-stop/pause.ngc b/linuxcnc-tests/resumable-stop/pause.ngc new file mode 100644 index 00000000..6fe71e34 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/pause.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 +F600 +G1 X5 +M0 +G1 X10 +M2 diff --git a/linuxcnc-tests/resumable-stop/rapid-then-feed.ngc b/linuxcnc-tests/resumable-stop/rapid-then-feed.ngc new file mode 100644 index 00000000..531480c1 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/rapid-then-feed.ngc @@ -0,0 +1,7 @@ +G21 G90 +F60 +S300 M3 +G0 X80 +G1 X90 F300 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/resume-atspeed.ngc b/linuxcnc-tests/resumable-stop/resume-atspeed.ngc new file mode 100644 index 00000000..cf661237 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/resume-atspeed.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 +F60 +S300 M3 +G1 X4 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/resume-s0.ngc b/linuxcnc-tests/resumable-stop/resume-s0.ngc new file mode 100644 index 00000000..69d6ce76 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/resume-s0.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 +F60 +S0 M3 +G1 X4 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/run-scenarios.sh b/linuxcnc-tests/resumable-stop/run-scenarios.sh new file mode 100755 index 00000000..a3043999 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/run-scenarios.sh @@ -0,0 +1,61 @@ +#!/bin/bash -e +# Shared driver for the resumable-stop/ runtests tests. +# +# Usage, from a group's test.sh: exec ../run-scenarios.sh scenarios +# where the file "scenarios" lists one scenario of test-ui.py per line. An +# entry trapezoidal:NAME runs NAME with PLANNER_TYPE = 0 instead of the +# jerk-limited planner test.ini selects. The group's checkresult +# (check-result.sh) requires every entry to report success. +# +# Every scenario runs in a fresh LinuxCNC session started from a private copy +# of the shared configuration, so groups can run in parallel (also in one +# directory tree) without sharing sim.var or other files LinuxCNC writes next +# to its INI file. + +set -o pipefail + +shared=$(cd "$(dirname "$0")" && pwd) + +if nm -D -u "$EMC2_HOME/rtlib/motmod.so" | grep -q '[[:space:]]tpStop$'; then + echo "motmod unexpectedly requires the nonstandard tpStop symbol" >&2 + exit 1 +fi + +if nm -D -u "$EMC2_HOME/rtlib/motmod.so" | grep -q '[[:space:]]tpStep$'; then + echo "motmod unexpectedly requires the nonstandard tpStep symbol" >&2 + exit 1 +fi + +[ $# -eq 1 ] && [ -f "$1" ] || { echo "usage: run-scenarios.sh SCENARIO-FILE" >&2; exit 1; } +mapfile -t items < <(grep -v '^[[:space:]]*\(#\|$\)' "$1") +[ ${#items[@]} -gt 0 ] || { echo "run-scenarios.sh: no scenarios in $1" >&2; exit 1; } + +config=$(mktemp -d) +scenario_log=$(mktemp) +trap 'rm -rf "$config" "$scenario_log"' EXIT +cp "$shared"/test-ui.py "$shared"/test.ini "$shared"/core_sim.hal \ + "$shared"/tool.tbl "$shared"/*.ngc "$shared"/M101 "$config"/ +sed 's/^PLANNER_TYPE = 1$/PLANNER_TYPE = 0/' "$config/test.ini" \ + > "$config/test-trapezoidal.ini" +grep -q '^PLANNER_TYPE = 0$' "$config/test-trapezoidal.ini" + +for item in "${items[@]}"; do + case "$item" in + trapezoidal:*) ini=test-trapezoidal.ini; scenario=${item#trapezoidal:} ;; + *) ini=test.ini; scenario=$item ;; + esac + echo "Running resumable-stop scenario: $scenario ($ini)" + : > "$scenario_log" + (cd "$config" && RESUMABLE_STOP_SCENARIO="$scenario" linuxcnc -r "$ini") 2>&1 | + tee "$scenario_log" + if grep -Eq 'ruckig_plan_(position|velocity): invalid limits|Ruckig (velocity control )?planning failed' "$scenario_log"; then + echo "$scenario emitted a Ruckig invalid-limit or planning failure" >&2 + exit 1 + fi + if ! grep -qxF "resumable stop scenario ok: $scenario" "$scenario_log"; then + echo "$item did not report success" >&2 + exit 1 + fi + echo "resumable stop scenario passed: $item" +done +echo "resumable stop scenarios complete" diff --git a/linuxcnc-tests/resumable-stop/set-auto.ngc b/linuxcnc-tests/resumable-stop/set-auto.ngc new file mode 100644 index 00000000..a3b0082c --- /dev/null +++ b/linuxcnc-tests/resumable-stop/set-auto.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 Z0 +M3 S600 +M8 +G1 X5 F60 +M5 M9 +M2 diff --git a/linuxcnc-tests/resumable-stop/single-step.ngc b/linuxcnc-tests/resumable-stop/single-step.ngc new file mode 100644 index 00000000..8955e51e --- /dev/null +++ b/linuxcnc-tests/resumable-stop/single-step.ngc @@ -0,0 +1,10 @@ +G21 G90 +G0 X0 +F600 +S300 M3 +M8 +G1 X10 +G1 X20 +M9 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/speed-change.ngc b/linuxcnc-tests/resumable-stop/speed-change.ngc new file mode 100644 index 00000000..927c3ca4 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/speed-change.ngc @@ -0,0 +1,9 @@ +G21 G90 +G0 X0 +F60 +S300 M3 +G1 X4 +S600 +G1 X6 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/spindle-state.ngc b/linuxcnc-tests/resumable-stop/spindle-state.ngc new file mode 100644 index 00000000..c5f21abe --- /dev/null +++ b/linuxcnc-tests/resumable-stop/spindle-state.ngc @@ -0,0 +1,10 @@ +G21 G90 +G0 X0 +F60 +M3 $0 S300 +M5 $1 +G1 X4 +S800 $1 +G1 X8 +M5 $0 +M2 diff --git a/linuxcnc-tests/resumable-stop/system-command.ngc b/linuxcnc-tests/resumable-stop/system-command.ngc new file mode 100644 index 00000000..7ba66fba --- /dev/null +++ b/linuxcnc-tests/resumable-stop/system-command.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 +M3 S600 +M101 +G1 X5 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/tap.ngc b/linuxcnc-tests/resumable-stop/tap.ngc new file mode 100644 index 00000000..2182f18a --- /dev/null +++ b/linuxcnc-tests/resumable-stop/tap.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 Z0 +S60 M3 +G33.1 Z-5 K1 +G1 X10 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/test-ui.py b/linuxcnc-tests/resumable-stop/test-ui.py new file mode 100755 index 00000000..74dcbf1e --- /dev/null +++ b/linuxcnc-tests/resumable-stop/test-ui.py @@ -0,0 +1,2290 @@ +#!/usr/bin/env python3 + +import math +import os +import subprocess +import sys +import time + +import hal +import linuxcnc + + +ORIENT_IN_PROGRESS = 2 + + +def fail(message): + print(message) + sys.exit(1) + + +def wait_for(predicate, message, timeout=10.0, poll_interval=0.02): + start = time.time() + while time.time() - start < timeout: + s.poll() + if predicate(): + return + time.sleep(poll_interval) + if callable(message): + message = message() + fail( + "%s: X=%.6f Z=%.6f vel=%.6f queue=%d task_paused=%s " + "motion_paused=%s stepping=%s " + "interp=%d exec=%d" + % ( + message, + s.position[0], + s.position[2], + s.current_vel, + s.queue, + s.task_paused, + s.paused, + s.single_stepping, + s.interp_state, + s.exec_state, + ) + ) + + +def wait_complete(message, timeout=10.0): + if c.wait_complete(timeout) != linuxcnc.RCS_DONE: + fail(message) + s.poll() + + +c = linuxcnc.command() +s = linuxcnc.stat() +e = linuxcnc.error_channel() +comp = hal.component("resumable-stop-test") + +wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP, "LinuxCNC did not initialize") + +c.state(linuxcnc.STATE_ESTOP_RESET) +c.state(linuxcnc.STATE_ON) +wait_complete("machine did not turn on") + + +def open_auto_program(path): + c.mode(linuxcnc.MODE_AUTO) + wait_complete("machine did not enter AUTO") + c.program_open(path) + wait_complete("%s did not open" % path) + + +# Simulated motion runs slower than real time on a loaded machine, so allow +# well beyond a program's nominal run time; a passing run never waits longer. +def wait_for_program_complete(expected_x, expected_z=0.0, timeout=60.0): + wait_for( + lambda: s.interp_state == linuxcnc.INTERP_IDLE + and s.exec_state == linuxcnc.EXEC_DONE + and s.queue == 0 + and math.isclose(s.position[0], expected_x, abs_tol=0.01) + and math.isclose(s.position[2], expected_z, abs_tol=0.01), + "program did not complete at expected position", + timeout=timeout, + ) + + +def assert_outputs_stopped_after_program(): + if abs(hal.get_value("spindle.0.speed-out")) > 0.001: + fail("spindle was not stopped by program completion") + + if hal.get_value("iocontrol.0.coolant-flood"): + fail("flood coolant was not stopped by program completion") + + +def run_idle_program_stop_rejected_test(): + c.mode(linuxcnc.MODE_AUTO) + wait_complete("machine did not enter AUTO") + + c.program_stop() + if c.wait_complete(10.0) != linuxcnc.RCS_ERROR: + fail("program Stop was not rejected without an active AUTO program") + + s.poll() + if s.stop_state != linuxcnc.STOP_IDLE: + fail("rejected program Stop changed Stop state") + + +def resume_and_wait_for_x_motion(stopped_x, on_poll=None, on_resume=None): + c.auto(linuxcnc.AUTO_RESUME) + if on_resume: + on_resume() + + saw_restored_spindle = False + saw_restored_coolant = False + start = time.time() + while time.time() - start < 10.0: + s.poll() + if on_poll: + on_poll() + if hal.get_value("spindle.0.speed-out") > 0.0: + saw_restored_spindle = True + if hal.get_value("iocontrol.0.coolant-flood"): + saw_restored_coolant = True + if s.position[0] > stopped_x + 0.05: + break + time.sleep(0.02) + + if not saw_restored_spindle: + fail("resume did not restore spindle") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05, + "program did not resume motion from stopped position", + ) + + return saw_restored_coolant + + +def spin_up_after_restore(message): + # at-speed has read false with the spindle on earlier, so after a Stop + # restore task waits for at-speed to drop and come back, as a real + # spindle reports it while spinning up again. + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STARTING + and hal.get_value("spindle.0.on"), + "%s: Resume did not restore the spindle and wait for at-speed" % message, + ) + hal.set_p("spindle.0.at-speed", "false") + time.sleep(0.05) + hal.set_p("spindle.0.at-speed", "true") + + +def run_ordinary_stop_resume_test(): + open_auto_program("test.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.task_mode == linuxcnc.MODE_AUTO + and s.interp_state != linuxcnc.INTERP_IDLE + and s.queue > 0 + and s.position[0] > 0.05 + and s.position[0] < 9.0 + and hal.get_value("spindle.0.speed-out") > 0.0 + and hal.get_value("iocontrol.0.coolant-flood"), + "program did not reach active motion with spindle and coolant on", + ) + + line_before_stop = s.read_line + queue_before_stop = s.queue + + c.program_stop() + # Spindle and coolant are switched off on entry to STOPPED, so it must not + # be reported while the feed is still decelerating. + start = time.time() + while time.time() - start < 10.0: + s.poll() + if s.stop_state == linuxcnc.STOP_STOPPED: + if abs(s.current_vel) > 1e-9: + fail("STOPPED reported while still moving at %.6f" % s.current_vel) + break + time.sleep(0.001) + wait_complete("stop command did not complete") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED state", + ) + + stopped_x = s.position[0] + stopped_read_line = s.read_line + stopped_queue = s.queue + + time.sleep(0.25) + s.poll() + + if abs(s.position[0] - stopped_x) > 0.001: + fail("position changed while stopped: %.6f -> %.6f" % (stopped_x, s.position[0])) + + if stopped_read_line < line_before_stop: + fail("read line regressed across stop: %d -> %d" % (line_before_stop, stopped_read_line)) + + if stopped_queue <= 0 or stopped_queue > queue_before_stop: + fail("queue was not preserved across stop: before=%d stopped=%d" % (queue_before_stop, stopped_queue)) + + if abs(hal.get_value("spindle.0.speed-out")) > 0.001: + fail("spindle speed-out was not disabled while stopped") + + if hal.get_value("iocontrol.0.coolant-flood"): + fail("flood coolant was not disabled while stopped") + + if not resume_and_wait_for_x_motion(stopped_x): + fail("resume did not restore coolant") + + wait_for_program_complete(10.0) + assert_outputs_stopped_after_program() + + +def run_stop_single_step_test(): + open_auto_program("single-step.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.queue > 0 + and s.position[0] > 0.05 + and s.position[0] < 9.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "program did not reach active motion before single-step test", + ) + + c.program_stop() + wait_complete("single-step stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED before single-step", + ) + + stopped_x = s.position[0] + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.task_paused + and s.position[0] > stopped_x + 0.05 + and abs(s.current_vel) < 0.001, + "single-step did not execute one queued motion and pause", + timeout=15.0, + ) + + stepped_x = s.position[0] + time.sleep(0.25) + s.poll() + if abs(s.position[0] - stepped_x) > 0.001: + fail("program continued after stop-to-single-step") + + if abs(hal.get_value("spindle.0.speed-out")) < 0.001: + fail("single-step did not restore spindle") + if not hal.get_value("iocontrol.0.coolant-flood"): + fail("single-step did not restore coolant") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(20.0) + assert_outputs_stopped_after_program() + +def run_inflight_single_step_test(): + open_auto_program("inflight-step.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.queue >= 3 + and s.position[0] > 1.0 + and s.position[0] < 9.0, + "program did not prequeue later blocks during its first move", + ) + + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.single_stepping and not s.task_paused and not s.paused, + "in-flight Single Step did not remain unpaused while armed", + ) + wait_for( + lambda: s.task_paused + and s.paused + and math.isclose(s.position[0], 10.0, abs_tol=0.01) + and abs(s.current_vel) < 0.001, + "in-flight Single Step did not finish the active source block", + timeout=15.0, + ) + + if s.queue < 3: + fail("in-flight Single Step did not preserve prequeued later blocks") + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], 10.0, abs_tol=0.001): + fail("in-flight Single Step advanced into the next source block") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(40.0, timeout=10.0) + + +def run_inflight_short_block_step_test(): + # Step armed at full speed among blocks shorter than the stopping + # distance must stop on the first block end it can reach within the + # acceleration limit, not cut the speed at the end of the current block. + # Runs with the trapezoidal planner: the S-curve planner already limits + # the speed in short blocks to one each block can stop in. + open_auto_program("inflight-step-short.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: 10.0 < s.position[0] < 13.0 and s.current_vel > 45.0, + "program did not reach full speed in its short blocks", + timeout=15.0, + poll_interval=0.001, + ) + hal.set_p("accel-peak.reset", "1") + time.sleep(0.01) + hal.set_p("accel-peak.reset", "0") + armed_x = s.position[0] + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.task_paused and s.paused and abs(s.current_vel) < 0.001, + "in-flight Single Step did not stop", + timeout=15.0, + ) + stopped_x = s.position[0] + peak_decel = -hal.get_value("accel-peak.min") + print( + "short-block Step armed at X=%.4f, stopped at X=%.4f, peak " + "deceleration %.1f" % (armed_x, stopped_x, peak_decel) + ) + if peak_decel > 500.0 * 1.05: + fail( + "in-flight Single Step decelerated at %.1f, above the 500 limit" + % peak_decel + ) + block_end = round(stopped_x * 2.0) / 2.0 + if not math.isclose(stopped_x, block_end, abs_tol=0.001) or not ( + 10.5 <= block_end <= 20.0 + ): + fail( + "in-flight Single Step stopped at X=%.4f, not on a short block end" + % stopped_x + ) + if block_end <= armed_x: + fail("in-flight Single Step stopped behind where it was armed") + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], stopped_x, abs_tol=0.001): + fail("in-flight Single Step advanced past its block end") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(40.0, timeout=10.0) + + +def run_pause_inflight_single_step_test(): + # Pause during an armed Single Step is an ordinary Pause: motion stops + # where it is instead of finishing the block, and Resume continues. + open_auto_program("inflight-step.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.queue >= 3 and 1.0 < s.position[0] < 5.0, + "program did not prequeue later blocks during its first move", + ) + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.single_stepping and not s.task_paused and not s.paused, + "in-flight Single Step did not remain unpaused while armed", + ) + c.auto(linuxcnc.AUTO_PAUSE) + wait_for( + lambda: s.task_paused and s.paused and abs(s.current_vel) < 0.001, + "Pause did not stop the in-flight Single Step", + timeout=15.0, + ) + paused_x = s.position[0] + if paused_x > 9.5: + fail("Pause let the Single Step finish its block: X=%.3f" % paused_x) + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], paused_x, abs_tol=0.001): + fail("motion continued after Pause during Single Step") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(40.0, timeout=10.0) + + +def run_rapid_resume_without_at_speed_test(): + hal.set_p("spindle.0.at-speed", "false") + open_auto_program("rapid-then-feed.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.task_mode == linuxcnc.MODE_AUTO + and s.position[0] > 1.0 + and s.position[0] < 70.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "program did not enter active rapid with spindle at-speed false", + ) + + c.program_stop() + wait_complete("rapid stop command did not complete") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not stop during active rapid", + ) + + stopped_x = s.position[0] + c.auto(linuxcnc.AUTO_RESUME) + + # Resume waits for the restored spindle to report at-speed before any + # motion continues, also an interrupted rapid. + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STARTING + and hal.get_value("spindle.0.speed-out") > 0.0, + "Resume did not restore the spindle and wait for at-speed", + ) + time.sleep(0.25) + s.poll() + if s.stop_state != linuxcnc.STOP_STARTING or \ + abs(s.position[0] - stopped_x) > 0.001: + fail("rapid resumed before the restored spindle was at speed") + hal.set_p("spindle.0.at-speed", "true") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05, + "rapid did not resume once the spindle was at speed", + ) + # The program's own M3 barrier still holds the following feed. + hal.set_p("spindle.0.at-speed", "false") + + wait_for( + lambda: math.isclose(s.position[0], 80.0, abs_tol=0.05) + and abs(s.current_vel) < 0.001 + and s.queue > 0, + "rapid did not complete and wait at following feed with at-speed false", + ) + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], 80.0, abs_tol=0.05): + fail("following feed moved before spindle at-speed became true") + + hal.set_p("spindle.0.at-speed", "true") + wait_for_program_complete(90.0) + assert_outputs_stopped_after_program() + + +def run_stop_while_program_paused_test(restart_with_run): + open_auto_program("pause.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.interp_state == linuxcnc.INTERP_PAUSED + and s.task_paused + and math.isclose(s.position[0], 5.0, abs_tol=0.01), + "program did not reach M0 pause", + ) + + c.program_stop() + wait_complete("stop command did not complete from M0 pause") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED from M0 pause", + ) + + if restart_with_run: + c.auto(linuxcnc.AUTO_RUN, 0) + else: + c.auto(linuxcnc.AUTO_RESUME) + + wait_for_program_complete(10.0) + + +def run_abort_armed_step_test(): + # Abort while an in-flight Step is armed. Motion must not pause the + # planner again for the dropped Step and leave paused set. + open_auto_program("inflight-step.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.queue >= 3 + and s.position[0] > 1.0 + and s.position[0] < 7.0, + "program did not prequeue later blocks during its first move", + ) + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.single_stepping and not s.task_paused and not s.paused, + "in-flight Single Step was not armed", + ) + c.abort() + wait_complete("abort with an armed Step did not complete") + wait_for( + lambda: s.queue == 0 and abs(s.current_vel) < 0.001, + "abort with an armed Step did not stop motion", + ) + time.sleep(0.3) + s.poll() + if s.paused: + fail("abort with an armed Step left motion paused") + open_auto_program("after-abort.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for_program_complete(6.0) + + +def run_abort_from_empty_stopped_queue_test(): + open_auto_program("pause.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.interp_state == linuxcnc.INTERP_PAUSED + and s.task_paused + and math.isclose(s.position[0], 5.0, abs_tol=0.01), + "program did not reach M0 pause before abort test", + ) + + c.program_stop() + wait_complete("stop command did not complete from M0 pause before abort") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED from M0 pause before abort", + ) + + c.abort() + wait_complete("abort command did not complete from empty stopped queue") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and not s.task_paused + and s.interp_state == linuxcnc.INTERP_IDLE + and s.exec_state == linuxcnc.EXEC_DONE + and s.queue == 0, + "abort did not clear empty STOPPED state", + ) + + open_auto_program("after-abort.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.position[0] > 5.05, + "motion did not start after aborting empty STOPPED queue", + ) + + wait_for_program_complete(6.0) + + +def stop_during_sync_motion(program, active_predicate, complete_predicate, message, expected_z, + resume_max_vel=None): + open_auto_program(program) + + c.auto(linuxcnc.AUTO_RUN, 0) + + start = time.time() + while time.time() - start < 15.0: + s.poll() + if ( + s.task_mode == linuxcnc.MODE_AUTO + and hal.get_value("spindle.0.speed-out") > 0.0 + and active_predicate() + ): + break + time.sleep(0.02) + else: + err = e.poll() + fail( + "%s did not enter synchronized motion: X=%.6f Z=%.6f " + "interp=%d exec=%d queue=%d spindle=%.3f error=%s" + % ( + message, + s.position[0], + s.position[2], + s.interp_state, + s.exec_state, + s.queue, + hal.get_value("spindle.0.speed-out"), + err, + ) + ) + + c.program_stop() + wait_complete("%s stop command did not complete" % message) + + start = time.time() + while time.time() - start < 15.0: + s.poll() + if s.stop_state == linuxcnc.STOP_STOPPED: + break + time.sleep(0.02) + + if s.stop_state != linuxcnc.STOP_STOPPED: + fail("%s did not enter STOPPED state" % message) + + if not complete_predicate(): + fail( + "%s STOPPED before synchronized motion endpoint/cycle completion: " + "X=%.6f Z=%.6f" + % (message, s.position[0], s.position[2]) + ) + + # With the trapezoidal planner a blend arc joins the synchronized move + # to the following X move; Stop finishes it, which moves X a little. + if s.position[0] > 0.1: + fail("%s allowed following X move to start before STOPPED: X=%.6f" % (message, s.position[0])) + + if abs(hal.get_value("spindle.0.speed-out")) > 0.001: + fail("%s spindle speed-out was not disabled while stopped" % message) + + stopped_x = s.position[0] + stopped_z = s.position[2] + peak = [0.0] + + def check_resume(): + # Nothing synchronized is left after Stop: a lunge to catch up with + # the spindle shows as Z motion or as speed above the next feed. + peak[0] = max(peak[0], abs(s.current_vel)) + if abs(s.position[2] - stopped_z) > 0.01: + fail("%s moved Z after Resume: %.4f -> %.4f at %.3f" + % (message, stopped_z, s.position[2], peak[0])) + + if resume_max_vel is None: + resume_and_wait_for_x_motion(stopped_x) + else: + resume_and_wait_for_x_motion(stopped_x, check_resume) + start = time.time() + while time.time() - start < 15.0: + s.poll() + check_resume() + if s.interp_state == linuxcnc.INTERP_IDLE and s.queue == 0: + break + time.sleep(0.002) + if peak[0] > resume_max_vel: + fail("%s moved at %.3f after Resume, above %.3f" + % (message, peak[0], resume_max_vel)) + wait_for_program_complete(10.0, expected_z=expected_z) + assert_outputs_stopped_after_program() + + +def run_threading_stop_resume_test(): + stop_during_sync_motion( + "thread.ngc", + lambda: s.position[2] < -0.5 and s.position[2] > -4.5, + lambda: s.position[2] <= -4.90, + "G33 threading", + expected_z=-5.0, + ) + + +def run_g33_does_not_execute_following_rapid_test(): + open_auto_program("g33-followed-by-rapid.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.position[2] < -0.5 and s.position[2] > -4.5, + "G33 did not enter synchronized motion before negative Stop test", + timeout=15.0, + ) + c.program_stop() + wait_complete("G33 negative Stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "G33 negative test did not reach STOPPED", + timeout=15.0, + ) + + if s.position[2] > -4.90: + fail("G33 negative test stopped before its synchronized move completed") + if not math.isclose(s.position[0], 10.0, abs_tol=0.05): + fail( + "Stop executed the unmarked rapid following G33: X=%.6f" + % s.position[0] + ) + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], 10.0, abs_tol=0.05): + fail("unmarked post-G33 rapid moved while stopped") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(30.0, expected_z=-5.0, timeout=20.0) + assert_outputs_stopped_after_program() + + +def run_fperrev_stop_resume_test(): + open_auto_program("fperrev.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.task_mode == linuxcnc.MODE_AUTO + and s.position[0] > 0.5 + and s.position[0] < 9.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G95 G1 did not enter feed-per-revolution motion", + timeout=15.0, + ) + + c.program_stop() + wait_complete("G95 G1 stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not stop during G95 G1 motion", + ) + + stopped_x = s.position[0] + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], stopped_x, abs_tol=0.001): + fail("G95 G1 moved while stopped") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G95 G1 did not resume with the spindle active", + ) + + wait_for_program_complete(10.0) + assert_outputs_stopped_after_program() + + +def run_g76_stop_resume_test(): + open_auto_program("g76.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.task_mode == linuxcnc.MODE_AUTO + and s.position[0] < 9.5 + and s.position[2] < -0.5 + and s.position[2] > -4.5, + "G76 did not enter its first synchronized pass", + timeout=15.0, + ) + + c.program_stop() + wait_complete("G76 stop command did not complete") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not stop after the active G76 threading TC", + timeout=15.0, + ) + + if s.position[2] > -4.90: + fail("G76 stopped before its active threading TC completed") + + if not math.isclose(s.position[0], 10.4, abs_tol=0.05): + fail( + "G76 did not stop at the first pass clearance: X=%.6f" + % s.position[0] + ) + + stopped_x = s.position[0] + stopped_z = s.position[2] + time.sleep(0.25) + s.poll() + if ( + not math.isclose(s.position[0], stopped_x, abs_tol=0.001) + or not math.isclose(s.position[2], stopped_z, abs_tol=0.001) + ): + fail("G76 moved while stopped") + + resume_and_wait_for_x_motion(stopped_x) + wait_for_program_complete(20.0, expected_z=-5.0) + assert_outputs_stopped_after_program() + + +def run_g76_stop_while_waiting_for_index_test(): + subprocess.run(["halcmd", "unlinkp", "encoder_0.phase-Z"], check=True) + hal.set_p("encoder_0.phase-Z", "false") + open_auto_program("g76.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: hal.get_value("spindle.0.index-enable") + and s.position[0] < 9.95 + and math.isclose(s.position[2], 0.0, abs_tol=0.001) + and abs(s.current_vel) < 0.001, + "G76 did not arm its first cut while waiting for spindle index", + timeout=15.0, + ) + + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "G76 did not stop with its index-waiting cut preserved", + ) + + # Deliver the delayed index after Stop. The armed cut must remain queued + # for Resume rather than starting merely because its prerequisite arrived. + subprocess.run( + ["halcmd", "net", "spindle-phase-Z", "encoder_0.phase-Z"], + check=True, + ) + + if not math.isclose(s.position[2], 0.0, abs_tol=0.001): + fail("G76 started its cut after Stop: Z=%.6f" % s.position[2]) + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[2], 0.0, abs_tol=0.001): + fail("index-waiting G76 moved while stopped: Z=%.6f" % s.position[2]) + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(20.0, expected_z=-5.0, timeout=40.0) + assert_outputs_stopped_after_program() + + +def run_tapered_g76_stop_resume_test(): + open_auto_program("g76-tapered.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.task_mode == linuxcnc.MODE_AUTO + and s.position[0] < 8.6 + and s.position[2] < -0.5 + and s.position[2] > -4.5, + "tapered G76 did not enter its first synchronized pass", + timeout=15.0, + ) + + c.program_stop() + wait_complete("tapered G76 stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not stop after the active tapered G76 pass", + timeout=15.0, + ) + + if s.position[2] > -4.90: + fail("tapered G76 stopped before its synchronized cut completed") + if not math.isclose(s.position[0], 8.4, abs_tol=0.05): + fail( + "tapered G76 did not stop at the first pass clearance: X=%.6f Z=%.6f" + % (s.position[0], s.position[2]) + ) + + stopped_x = s.position[0] + stopped_z = s.position[2] + time.sleep(0.25) + s.poll() + if ( + not math.isclose(s.position[0], stopped_x, abs_tol=0.001) + or not math.isclose(s.position[2], stopped_z, abs_tol=0.001) + ): + fail("tapered G76 moved while stopped") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(20.0, expected_z=-5.0) + assert_outputs_stopped_after_program() + + +def step_g76_approach(expected_approach_x, label="G76"): + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.task_paused + and abs(s.current_vel) < 0.001 + and math.isclose(s.position[2], 0.0, abs_tol=0.05) + and math.isclose(s.position[0], expected_approach_x, abs_tol=0.05), + "%s Single Step did not stop at the approach endpoint X%.3f" + % (label, expected_approach_x), + timeout=20.0, + ) + + stepped_x = s.position[0] + stepped_z = s.position[2] + time.sleep(0.25) + s.poll() + if ( + not math.isclose(s.position[0], stepped_x, abs_tol=0.001) + or not math.isclose(s.position[2], stepped_z, abs_tol=0.001) + ): + fail("%s advanced into its synchronized cut" % label) + + +def step_g76_thread_and_clearance(expected_clear_x, label="G76"): + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.task_paused + and abs(s.current_vel) < 0.001 + and s.position[2] <= -4.90 + and math.isclose(s.position[0], expected_clear_x, abs_tol=0.05), + "%s Single Step did not finish the thread and clearance at X%.3f" + % (label, expected_clear_x), + timeout=20.0, + ) + + stepped_x = s.position[0] + stepped_z = s.position[2] + time.sleep(0.25) + s.poll() + if ( + not math.isclose(s.position[0], stepped_x, abs_tol=0.001) + or not math.isclose(s.position[2], stepped_z, abs_tol=0.001) + ): + fail("%s advanced into another pass after the thread Step" % label) + + +def run_g76_single_step_program(program, expected_steps, label): + c.mode(linuxcnc.MODE_MDI) + wait_complete("G76 Single Step setup did not enter MDI") + c.mdi("G21 G18 G90 G0 X10 Z0") + wait_complete("G76 Single Step setup did not reach X10 Z0") + c.spindle(linuxcnc.SPINDLE_FORWARD, 60.0, 0) + wait_complete("G76 Single Step setup did not start the spindle") + + open_auto_program(program) + + # LinuxCNC's first AUTO_STEP from IDLE primes the program in PAUSED state. + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.interp_state == linuxcnc.INTERP_PAUSED and s.task_paused, + "G76 Single Step did not prime the program", + ) + + for expected_approach, expected_clearance in expected_steps: + step_g76_approach(expected_approach, label) + step_g76_thread_and_clearance(expected_clearance, label) + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(20.0, expected_z=-5.0) + assert_outputs_stopped_after_program() + + +def run_g76_single_step_test(): + run_g76_single_step_program( + "g76-step.ngc", ((10.4, 10.4), (10.2, 10.2), (10.0, 10.0)), + "cylindrical G76", + ) + + +def run_tapered_g76_single_step_test(): + run_g76_single_step_program( + "g76-tapered-step.ngc", + ((10.4, 8.4), (10.2, 8.2), (10.0, 8.0)), + "tapered-drive G76", + ) + +def run_inflight_g76_single_step_test(): + open_auto_program("g76.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.queue > 3 + and s.position[0] < 9.5 + and s.position[2] < -0.5 + and s.position[2] > -4.5, + "G76 did not prequeue later passes during its first cut", + timeout=15.0, + ) + + c.auto(linuxcnc.AUTO_STEP) + wait_for( + lambda: s.single_stepping and not s.task_paused and not s.paused, + "in-flight G76 Single Step did not remain unpaused while armed", + ) + wait_for( + lambda: s.task_paused + and s.paused + and abs(s.current_vel) < 0.001 + and s.position[2] <= -4.90 + and math.isclose(s.position[0], 10.4, abs_tol=0.01), + "in-flight G76 Single Step did not finish the active thread and clearance", + timeout=20.0, + ) + + stepped_x = s.position[0] + stepped_z = s.position[2] + time.sleep(0.25) + s.poll() + if ( + not math.isclose(s.position[0], stepped_x, abs_tol=0.001) + or not math.isclose(s.position[2], stepped_z, abs_tol=0.001) + ): + fail("in-flight G76 Single Step advanced into the next approach") + + # Later passes are still prequeued. The next Step must end exactly at the + # pass 2 approach point (no blend into the infeed may trim it), and the + # one after it must run the pass 2 infeed, thread and clearance. + step_g76_approach(10.2, "prequeued G76") + if not ( + math.isclose(s.position[0], 10.2, abs_tol=0.001) + and math.isclose(s.position[2], 0.0, abs_tol=0.001) + ): + fail( + "prequeued G76 Single Step stopped at X=%.6f Z=%.6f, not exactly " + "at the approach point X10.2 Z0" % (s.position[0], s.position[2]) + ) + step_g76_thread_and_clearance(10.2, "prequeued G76") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(20.0, expected_z=-5.0, timeout=20.0) + assert_outputs_stopped_after_program() + + +def run_g76_exit_taper_stop_test(program, expected_clear_x, label): + open_auto_program(program) + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.position[2] < -0.5 + and s.position[2] > -3.5 + and s.position[0] < 9.5, + "%s did not enter its first synchronized pass" % label, + timeout=15.0, + ) + c.program_stop() + wait_complete("%s Stop command did not complete" % label) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "%s did not reach STOPPED" % label, + timeout=15.0, + ) + + if s.position[2] > -4.90 or not math.isclose( + s.position[0], expected_clear_x, abs_tol=0.05 + ): + fail( + "%s did not complete its synchronized exit taper and clearance: " + "X=%.6f Z=%.6f" % (label, s.position[0], s.position[2]) + ) + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(20.0, expected_z=-5.0) + assert_outputs_stopped_after_program() + + +def run_cylindrical_g76_exit_taper_stop_test(): + run_g76_exit_taper_stop_test( + "g76-exit-taper.ngc", 10.4, "cylindrical exit-taper G76" + ) + + +def run_tapered_g76_exit_taper_stop_test(): + run_g76_exit_taper_stop_test( + "g76-tapered-exit-taper.ngc", 8.4, "tapered-drive exit-taper G76" + ) + + +def run_g76_cut_retract_handoff_stress_test(): + # At S60 and P1 the synchronized feed is 1 mm/s. Even the closest + # trigger remains 20 task cycles before the endpoint, so Python polling + # reliably submits Stop while the cut is active instead of after retract. + thresholds = (-0.92, -0.94, -0.96, -0.97, -0.98) * 2 + + for attempt, threshold in enumerate(thresholds, 1): + open_auto_program("g76-handoff.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[2] <= threshold and s.position[0] < 9.5, + "G76 handoff attempt %d missed the cut/retract boundary" % attempt, + timeout=10.0, + poll_interval=0.001, + ) + + c.program_stop() + wait_complete( + "G76 handoff attempt %d Stop command did not complete" % attempt + ) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "G76 handoff attempt %d did not reach STOPPED" % attempt, + timeout=10.0, + poll_interval=0.001, + ) + + if s.position[2] > -0.99 or not math.isclose( + s.position[0], 10.01, abs_tol=0.01 + ): + fail( + "G76 handoff attempt %d missed complete clearance: " + "X=%.6f Z=%.6f" % (attempt, s.position[0], s.position[2]) + ) + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(20.0, expected_z=-1.0, timeout=10.0) + assert_outputs_stopped_after_program() + + +def run_queued_threading_stop_resume_test(): + hal.set_p("spindle.0.at-speed", "false") + open_auto_program("thread.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.task_mode == linuxcnc.MODE_AUTO + and s.interp_state != linuxcnc.INTERP_IDLE + and s.queue > 0 + and math.isclose(s.position[0], 0.0, abs_tol=0.001) + and math.isclose(s.position[2], 0.0, abs_tol=0.001) + and abs(s.current_vel) < 0.001 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G33 did not queue while waiting for spindle at-speed", + ) + + # Let the stationary queue state persist so the G0 before G33 is gone. + time.sleep(0.25) + s.poll() + if s.queue <= 0 or abs(s.current_vel) >= 0.001: + fail("G33 did not remain queued while spindle at-speed was false") + + c.program_stop() + wait_complete("queued G33 stop command did not complete") + + # Simulate the delayed prerequisite arriving after Stop. The queued G33 + # must remain inactive and preserved for Resume. + time.sleep(0.05) + hal.set_p("spindle.0.at-speed", "true") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not stop with an inactive G33 queued", + ) + + if not math.isclose(s.position[2], 0.0, abs_tol=0.001): + fail("queued G33 started after Stop: Z=%.6f" % s.position[2]) + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[2], 0.0, abs_tol=0.001): + fail("queued G33 moved while stopped: Z=%.6f" % s.position[2]) + + resume_and_wait_for_x_motion( + s.position[0], + on_resume=lambda: spin_up_after_restore("queued G33")) + wait_for_program_complete(10.0, expected_z=-5.0) + assert_outputs_stopped_after_program() + + +def run_rigid_tap_stop_resume_test(): + saw_downstroke = False + + def active_predicate(): + nonlocal saw_downstroke + if s.position[2] < -0.5: + saw_downstroke = True + return True + return False + + def complete_predicate(): + return saw_downstroke and s.position[2] >= -0.05 + + stop_during_sync_motion( + "tap.ngc", + active_predicate, + complete_predicate, + "G33.1 rigid tapping", + expected_z=0.0, + ) + + +def run_spindle_orientation_stop_test(): + hal.set_p("spindle.0.is-oriented", "false") + open_auto_program("orient.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: hal.get_value("spindle.0.orient") + and s.spindle[0]["orient_state"] == ORIENT_IN_PROGRESS, + "M19 did not start spindle orientation", + ) + + x_before_stop = s.position[0] + c.program_stop() + wait_complete("M19 stop command did not complete") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED during M19", + ) + + if hal.get_value("spindle.0.orient"): + fail("task reported STOPPED while spindle orientation remained active") + + if s.spindle[0]["orient_state"] == ORIENT_IN_PROGRESS: + fail("task reported STOPPED while spindle orientation was in progress") + + if not math.isclose(s.position[0], x_before_stop, abs_tol=0.001): + fail("following motion started while stopping M19") + + c.auto(linuxcnc.AUTO_RESUME) + + wait_for( + lambda: hal.get_value("spindle.0.orient") + and s.spindle[0]["orient_state"] == ORIENT_IN_PROGRESS, + "resume did not restore spindle orientation", + ) + + if not math.isclose( + hal.get_value("spindle.0.orient-angle"), 90.0, abs_tol=0.001 + ): + fail("resume did not restore the requested spindle orientation angle") + + if hal.get_value("spindle.0.orient-mode") != 1: + fail("resume did not restore the requested spindle orientation mode") + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], x_before_stop, abs_tol=0.001): + fail("following motion started before spindle orientation completed") + + hal.set_p("spindle.0.is-oriented", "true") + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > x_before_stop + 0.05, + "program did not continue after spindle orientation completed", + ) + + wait_for_program_complete(20.0, timeout=25.0) + + +def run_dwell_stop_resume_test(): + open_auto_program("dwell.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY + and s.delay_left > 2.0, + "G4 did not enter its dwell", + ) + + c.program_stop() + wait_complete("G4 stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED during G4", + ) + + stopped_delay = s.delay_left + time.sleep(0.5) + s.poll() + if not math.isclose(s.position[0], 0.0, abs_tol=0.001): + fail("motion started while G4 was stopped") + if s.delay_left < stopped_delay - 0.1: + fail("G4 delay elapsed while stopped") + + c.auto(linuxcnc.AUTO_RESUME) + time.sleep(0.5) + s.poll() + if not math.isclose(s.position[0], 0.0, abs_tol=0.001): + fail("motion started before the restored G4 delay elapsed") + + wait_for_program_complete(5.0) + + +def run_system_command_stop_test(): + # A user M-code already running finishes before Stop switches the + # spindle off and reports STOPPED; the program then waits for Resume. + open_auto_program("system-command.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_SYSTEM_CMD + and hal.get_value("spindle.0.speed-out") > 0.0, + "M101 did not start", + ) + # Stop completes only on STOPPED, so do not wait for it here. + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPING + and s.hold_wait == linuxcnc.HOLD_WAIT_SYSTEM_COMMAND, + "Stop did not wait for M101", + timeout=1.0, + ) + if hal.get_value("spindle.0.speed-out") <= 0.0: + fail("Stop switched the spindle off while M101 ran") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "Stop did not complete after M101", + ) + if s.hold_wait != linuxcnc.HOLD_WAIT_NONE: + fail("hold_wait still set once STOPPED") + if abs(hal.get_value("spindle.0.speed-out")) > 0.001: + fail("spindle not off once STOPPED") + time.sleep(0.3) + s.poll() + if not math.isclose(s.position[0], 0.0, abs_tol=0.001): + fail("program continued past M101 while stopped") + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(5.0) + assert_outputs_stopped_after_program() + + +def run_set_auto_while_stopped_test(): + # Set mode AUTO aborts the program even when the mode does not change. + # The Stop state goes with it, so a later Resume does not restore the + # spindle and coolant of the aborted program. + open_auto_program("set-auto.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[0] > 0.3 + and hal.get_value("spindle.0.speed-out") > 0.0, + "feed with spindle on did not start", + ) + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED", + ) + c.mode(linuxcnc.MODE_AUTO) + wait_complete("set mode AUTO while stopped did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.interp_state == linuxcnc.INTERP_IDLE, + "set mode AUTO left the Stop state behind", + ) + c.auto(linuxcnc.AUTO_RESUME) + time.sleep(0.5) + s.poll() + if abs(hal.get_value("spindle.0.speed-out")) > 0.001: + fail("Resume after the aborted program switched the spindle on") + if hal.get_value("iocontrol.0.coolant-flood"): + fail("Resume after the aborted program switched coolant on") + + # The same while Stop still waits in STOPPING for a thread to finish. + open_auto_program("thread-then-steps.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[2] < -0.5 + and s.position[2] > -3.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G33 did not start", + timeout=15.0, + ) + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPING, + "Stop did not wait for the active G33", + timeout=1.0, + ) + c.mode(linuxcnc.MODE_AUTO) + wait_complete("set mode AUTO while stopping did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.interp_state == linuxcnc.INTERP_IDLE, + "set mode AUTO left STOPPING behind", + ) + # The program can be run again; dwell.ngc does not move Z. + aborted_z = s.position[2] + open_auto_program("dwell.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for_program_complete(5.0, expected_z=aborted_z) + + +def run_step_after_dwell_stop_test(): + # Stop during a dwell leaves an empty motion queue. Step from STOPPED + # must not mark the program finished: it runs on, and afterwards the + # program can be run again. + open_auto_program("dwell.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY + and s.delay_left > 2.0, + "G4 did not enter its dwell", + ) + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED during G4", + ) + c.auto(linuxcnc.AUTO_STEP) + # Nothing is queued, so motion has no Step to take; task resumes it + # instead of leaving the Stop's hold on the planner. + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE and not s.paused, + "Step from STOPPED with an empty queue left motion held", + ) + time.sleep(0.3) + s.poll() + if s.interp_state == linuxcnc.INTERP_IDLE: + fail("Step from STOPPED marked the program finished") + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(5.0) + # The program file was closed at its end, so Run starts it again. + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for(lambda: s.position[0] < 1.0, "Run after the program did not start it again") + wait_for_program_complete(5.0) + + +def run_dwell_atspeed_barrier_test(): + # M3 arms motion's next-feed at-speed barrier before the dwell, and the + # following feed is not queued until the dwell ends. Turning the spindle + # off and on around Stop must leave that barrier armed. + hal.set_p("spindle.0.at-speed", "false") + open_auto_program("dwell-atspeed.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY + and s.delay_left > 1.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G4 did not enter its dwell with the spindle running", + ) + + c.program_stop() + wait_complete("G4 stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED during G4", + ) + if abs(hal.get_value("spindle.0.speed-out")) > 0.001: + fail("spindle was not stopped while STOPPED") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STARTING + and hal.get_value("spindle.0.speed-out") > 0.0, + "Resume did not restore the spindle and wait for at-speed", + ) + # Resume waits for at-speed; once it is reached, the spindle drops out of + # speed again before the dwell ends, and the barrier armed by M3 must + # still hold the feed. + hal.set_p("spindle.0.at-speed", "true") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE, + "program did not resume once the spindle was at speed", + ) + hal.set_p("spindle.0.at-speed", "false") + s.poll() + if s.exec_state != linuxcnc.EXEC_WAITING_FOR_DELAY: + fail("G4 ended before the test could drop at-speed again") + wait_for( + lambda: s.exec_state != linuxcnc.EXEC_WAITING_FOR_DELAY + and s.queue > 0, + "feed after G4 was not queued after Resume", + ) + + time.sleep(0.5) + s.poll() + if hal.get_value("spindle.0.speed-out") <= 0.0: + fail("Resume did not restore the spindle") + if not math.isclose(s.position[0], 0.0, abs_tol=0.001): + fail("feed after Stop ignored the at-speed barrier armed by M3") + + hal.set_p("spindle.0.at-speed", "true") + wait_for_program_complete(5.0) + assert_outputs_stopped_after_program() + + +def run_command_after_sync_motion_test(): + # Stop lets a G33 or rigid tap finish. The program's next command (M5, + # an S-word or M9) must not run while Stop is still completing: it must + # take effect once, after Resume, in program order. + cases = ( + ("after-thread-m5.ngc", lambda: s.position[2] < -1.0 and s.position[2] > -8.0, + lambda: not hal.get_value("spindle.0.on"), "M5 after G33"), + ("after-thread-s.ngc", lambda: s.position[2] < -1.0 and s.position[2] > -8.0, + lambda: hal.get_value("spindle.0.on") + and math.isclose(hal.get_value("spindle.0.speed-out"), 500.0, abs_tol=1.0), + "S500 after G33"), + ("after-thread-m9.ngc", lambda: s.position[2] < -1.0 and s.position[2] > -8.0, + lambda: not hal.get_value("iocontrol.0.coolant-flood"), "M9 after G33"), + ("after-tap-m5.ngc", lambda: s.position[2] < -1.0, + lambda: not hal.get_value("spindle.0.on"), "M5 after G33.1"), + ) + for program, during_sync, expected_after, name in cases: + open_auto_program(program) + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: hal.get_value("spindle.0.speed-out") > 0.0 and during_sync(), + "%s: synchronized motion did not start" % name, + timeout=15.0, + ) + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "%s: task did not enter STOPPED" % name, + timeout=15.0, + ) + if s.position[0] > 0.1: + fail("%s: the move after the command started before STOPPED" % name) + if hal.get_value("spindle.0.on"): + fail("%s: spindle on while STOPPED" % name) + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE and s.position[0] > 0.5, + "%s: program did not resume to the following move" % name, + ) + s.poll() + if not expected_after(): + fail( + "%s: outputs after Resume do not match the program: " + "spindle.on=%d speed-out=%.1f flood=%d" + % (name, hal.get_value("spindle.0.on"), + hal.get_value("spindle.0.speed-out"), + hal.get_value("iocontrol.0.coolant-flood")) + ) + wait_for_program_complete(5.0, expected_z=s.position[2], timeout=15.0) + + +def stop_feed_at(min_x, message): + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and hal.get_value("spindle.0.on") + and s.current_vel > 0.0 + and min_x < s.position[0] < 3.5, + "%s: feed did not reach X%.1f" % (message, min_x), + ) + c.program_stop() + wait_complete("%s: Stop command did not complete" % message) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "%s: task did not enter STOPPED" % message, + ) + if hal.get_value("spindle.0.on"): + fail("%s: spindle on while STOPPED" % message) + return s.position[0] + + +def assert_held_in_starting(stopped_x, message, hold=0.4): + # The spindle is back on, but motion must not continue before at-speed. + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STARTING + and hal.get_value("spindle.0.on") + and hal.get_value("spindle.0.speed-out") > 0.0, + "%s: Resume did not restore the spindle and wait in STARTING" % message, + ) + time.sleep(hold) + s.poll() + if s.stop_state != linuxcnc.STOP_STARTING: + fail("%s: left STARTING before spindle at-speed" % message) + if abs(s.position[0] - stopped_x) > 0.001: + fail("%s: feed moved before spindle at-speed: %.6f -> %.6f" + % (message, stopped_x, s.position[0])) + + +def wait_resumed_after_atspeed(stopped_x, message): + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05, + "%s: feed did not continue once the spindle was at speed" % message, + ) + + +def run_resume_atspeed_wait_test(): + # Resume restarts an interrupted feed only once the restored spindle + # reports at-speed again, and an at-speed left over from the stopped + # spindle does not count. + open_auto_program("resume-atspeed.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + # 1. at-speed has never read false with the spindle on (tied true, as in + # a simulation or a machine without feedback): Resume does not wait. + stopped_x = stop_feed_at(0.3, "tied at-speed") + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05, + "tied at-speed: Resume waited although at-speed never dropped", + timeout=3.0, + ) + + # 2. at-speed false while stopped (a speed-reached output): the feed + # waits in STARTING until it goes true. + stopped_x = stop_feed_at(stopped_x + 0.3, "at-speed false while stopped") + hal.set_p("spindle.0.at-speed", "false") + c.auto(linuxcnc.AUTO_RESUME) + assert_held_in_starting(stopped_x, "at-speed false while stopped") + hal.set_p("spindle.0.at-speed", "true") + wait_resumed_after_atspeed(stopped_x, "at-speed false while stopped") + + # 3. at-speed true throughout the Stop (a stopped spindle reported as at + # speed, or a VFD that reports late): the stale true does not release + # the feed; at-speed must drop after the restore and come back. + stopped_x = stop_feed_at(stopped_x + 0.3, "stale at-speed") + c.auto(linuxcnc.AUTO_RESUME) + assert_held_in_starting(stopped_x, "stale at-speed") + hal.set_p("spindle.0.at-speed", "false") + assert_held_in_starting(stopped_x, "stale at-speed, then false", hold=0.2) + hal.set_p("spindle.0.at-speed", "true") + wait_resumed_after_atspeed(stopped_x, "stale at-speed") + + # 4. A second Stop while waiting leaves STARTING for STOPPED with the + # spindle off; Single Step from there waits for at-speed again. + stopped_x = stop_feed_at(stopped_x + 0.3, "Stop while waiting") + c.auto(linuxcnc.AUTO_RESUME) + assert_held_in_starting(stopped_x, "Stop while waiting") + c.program_stop() + wait_complete("Stop while waiting: Stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED + and not hal.get_value("spindle.0.on"), + "Stop while waiting: second Stop did not return to STOPPED", + ) + c.auto(linuxcnc.AUTO_STEP) + assert_held_in_starting(stopped_x, "Step after Stop while waiting") + hal.set_p("spindle.0.at-speed", "false") + time.sleep(0.05) + hal.set_p("spindle.0.at-speed", "true") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and math.isclose(s.position[0], 4.0, abs_tol=0.001) + and abs(s.current_vel) < 1e-9 + and s.task_paused, + "Step after Stop while waiting: feed did not step to its end", + ) + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(4.0) + assert_outputs_stopped_after_program() + + # 5. Abort while waiting ends the program cleanly. + open_auto_program("resume-atspeed.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + stopped_x = stop_feed_at(0.3, "Abort while waiting") + c.auto(linuxcnc.AUTO_RESUME) + assert_held_in_starting(stopped_x, "Abort while waiting") + c.abort() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.interp_state == linuxcnc.INTERP_IDLE + and s.queue == 0 + and not hal.get_value("spindle.0.on"), + "Abort while waiting did not end the program", + ) + time.sleep(0.25) + s.poll() + if abs(s.position[0] - stopped_x) > 0.001: + fail("Abort while waiting: the feed moved") + + +def run_pause_while_starting_test(): + # Pause while Resume waits in STARTING for spindle at-speed cancels the + # Resume: the program returns to STOPPED with the restored spindle off, + # and at-speed arriving later does not release the queued feed. + open_auto_program("resume-atspeed.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + stopped_x = stop_feed_at(0.3, "Pause while starting") + hal.set_p("spindle.0.at-speed", "false") + c.auto(linuxcnc.AUTO_RESUME) + assert_held_in_starting(stopped_x, "Pause while starting") + c.auto(linuxcnc.AUTO_PAUSE) + wait_complete("Pause while starting: Pause did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED + and s.task_paused + and not hal.get_value("spindle.0.on"), + "Pause while starting: Pause did not return to STOPPED", + ) + hal.set_p("spindle.0.at-speed", "true") + time.sleep(0.4) + s.poll() + if s.stop_state != linuxcnc.STOP_STOPPED or not s.task_paused: + fail("Pause while starting: left STOPPED once at-speed arrived") + if hal.get_value("spindle.0.on"): + fail("Pause while starting: spindle switched back on") + if abs(s.position[0] - stopped_x) > 0.001: + fail("Pause while starting: feed moved while paused: %.6f -> %.6f" + % (stopped_x, s.position[0])) + + c.auto(linuxcnc.AUTO_RESUME) + spin_up_after_restore("Resume after Pause while starting") + wait_resumed_after_atspeed(stopped_x, "Resume after Pause while starting") + if s.task_paused or s.interp_state == linuxcnc.INTERP_PAUSED: + fail("Resume after Pause while starting: task still paused") + wait_for_program_complete(4.0) + assert_outputs_stopped_after_program() + + +def run_refused_while_stopping_test(label, send): + # Resume, Run or Step during STOPPING is refused, not remembered: the + # operator resumes once the machine has stopped. Stop then completes and + # the program stays STOPPED until the next Resume. + open_auto_program("thread-then-steps.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[2] < -0.5 + and s.position[2] > -3.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G33 did not start", + timeout=15.0, + ) + while e.poll(): + pass + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPING, + "Stop did not wait for the active G33", + timeout=1.0, + ) + send() + if c.wait_complete(2.0) != linuxcnc.RCS_ERROR: + fail("%s during STOPPING was not refused" % label) + deadline = time.time() + 2.0 + while True: + err = e.poll() + if err and "while the program is stopping" in err[1]: + break + if time.time() > deadline: + fail("%s during STOPPING gave no operator error" % label) + time.sleep(0.02) + s.poll() + if s.stop_state != linuxcnc.STOP_STOPPING: + fail("G33 finished before %s was sent" % label) + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED + and math.isclose(s.position[2], -5.0, abs_tol=0.01), + lambda: "Stop did not complete after a refused %s: X=%.3f Z=%.3f " + "stop=%d" % (label, s.position[0], s.position[2], s.stop_state), + timeout=15.0, + ) + time.sleep(0.4) + s.poll() + if s.stop_state != linuxcnc.STOP_STOPPED or not s.task_paused: + fail("refused %s: program left STOPPED" % label) + if hal.get_value("spindle.0.on"): + fail("refused %s: spindle on while STOPPED" % label) + if abs(s.position[0]) > 0.001: + fail("refused %s: feed after G33 moved" % label) + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.interp_state == linuxcnc.INTERP_IDLE + and s.exec_state == linuxcnc.EXEC_DONE + and math.isclose(s.position[0], 10.0, abs_tol=0.01), + "program did not run to completion after Resume", + timeout=20.0, + ) + assert_outputs_stopped_after_program() + +def run_resume_zero_speed_test(): + # A spindle restored at S0 does not spin up, so Resume does not wait for + # an at-speed comparator that never drops for it. + open_auto_program("resume-s0.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: hal.get_value("spindle.0.on") + and s.current_vel > 0.0 + and 0.05 < s.position[0] < 0.2, + "S0: feed did not start", + ) + # at-speed has read false with the spindle on, as from a comparator at a + # speed change, so task knows it is connected. + hal.set_p("spindle.0.at-speed", "false") + time.sleep(0.05) + hal.set_p("spindle.0.at-speed", "true") + stopped_x = stop_feed_at(0.3, "S0") + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05, + "S0: Resume waited for at-speed of a spindle restored at S0", + timeout=3.0, + ) + wait_for_program_complete(4.0) + + +def run_multi_spindle_stop_resume_test(): + open_auto_program("multi-spindle.ngc") + c.spindle(linuxcnc.SPINDLE_FORWARD, 120.0, 0) + wait_complete("primary spindle command did not complete") + c.spindle(linuxcnc.SPINDLE_REVERSE, 180.0, 1) + wait_complete("secondary spindle command did not complete") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.position[0] > 0.05 + and s.position[0] < 9.0 + and s.spindle[0]["direction"] == 1 + and s.spindle[1]["direction"] == -1 + and hal.get_value("spindle.0.on") + and hal.get_value("spindle.1.on"), + "both spindles did not remain active during motion", + ) + + c.program_stop() + wait_complete("multi-spindle stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED with two spindles", + ) + if hal.get_value("spindle.0.on") or hal.get_value("spindle.1.on"): + fail("a spindle remained enabled while stopped") + + stopped_x = s.position[0] + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05 + and s.spindle[0]["direction"] == 1 + and s.spindle[1]["direction"] == -1 + and hal.get_value("spindle.0.on") + and hal.get_value("spindle.1.on"), + "resume did not restore both spindles", + ) + + wait_for_program_complete(10.0) + if hal.get_value("spindle.0.on") or hal.get_value("spindle.1.on"): + fail("a spindle remained enabled after program completion") + + +def run_css_stop_resume_test(): + open_auto_program("css.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.position[0] < 18.0 + and s.position[0] > 12.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G96 did not enter active CSS motion", + ) + speed_before_stop = hal.get_value("spindle.0.speed-out") + + c.program_stop() + wait_complete("G96 stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED during G96", + ) + if abs(hal.get_value("spindle.0.speed-out")) > 0.001: + fail("CSS spindle remained active while stopped") + + stopped_x = s.position[0] + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] < stopped_x - 0.05 + and hal.get_value("spindle.0.speed-out") > 0.0, + "G96 motion did not resume with the spindle active", + ) + wait_for( + lambda: hal.get_value("spindle.0.speed-out") > speed_before_stop * 1.02, + "G96 spindle speed did not continue tracking diameter after Resume", + ) + + wait_for_program_complete(10.0) + assert_outputs_stopped_after_program() + + +EXEC_WAITING_FOR_HOMING = getattr(linuxcnc, "EXEC_WAITING_FOR_HOMING", 12) + + +def run_homing_stop_resume_test(): + open_auto_program("homing.ngc") + + c.auto(linuxcnc.AUTO_RUN, 0) + + wait_for( + lambda: s.exec_state == EXEC_WAITING_FOR_HOMING + and s.joint[0]["homing"], + "program did not enter the queued G28.2 homing cycle", + ) + + c.program_stop() + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPING, + "Stop was not accepted during a queued G28.2 homing cycle", + timeout=1.0, + ) + if not s.joint[0]["homing"]: + fail("G28.2 homing finished before Stop could be observed in STOPPING") + + wait_complete("Stop during G28.2 did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED after the G28.2 homing cycle", + ) + + if not s.homed[0] or s.joint[0]["homing"]: + fail("Stop entered STOPPED before the G28.2 homing cycle completed") + if not math.isclose(s.position[0], 20.0, abs_tol=0.01): + fail("G28.2 final move did not finish at HOME before STOPPED") + if s.task_mode != linuxcnc.MODE_AUTO: + fail("task did not return to AUTO after the G28.2 mode dip") + + time.sleep(0.25) + s.poll() + if not math.isclose(s.position[0], 20.0, abs_tol=0.01): + fail("program continued after G28.2 while STOPPED") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(30.0) + + +def wait_for_queued_homing(message, program="homing.ngc"): + open_auto_program(program) + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.exec_state == EXEC_WAITING_FOR_HOMING + and s.joint[0]["homing"], + message, + ) + + +def check_stop_reaches_stopped(message): + open_auto_program("test.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.interp_state != linuxcnc.INTERP_IDLE + and s.position[0] > 0.05 + and s.position[0] < 9.0 + and hal.get_value("spindle.0.speed-out") > 0.0, + "%s: program did not reach active motion" % message, + ) + c.program_stop() + wait_complete("%s: Stop command did not complete" % message) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "%s: Stop did not reach STOPPED" % message, + timeout=5.0, + ) + c.abort() + wait_complete("%s: abort did not complete" % message) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.interp_state == linuxcnc.INTERP_IDLE, + "%s: abort did not clear STOPPED" % message, + ) + + +def run_interrupted_homing_test(): + # Each way of leaving a queued G28.2 early must leave nothing behind that + # a later Stop depends on. + def interrupt_abort(): + c.abort() + wait_complete("abort during G28.2 did not complete") + + def interrupt_estop(): + c.state(linuxcnc.STATE_ESTOP) + wait_complete("E-stop during G28.2 did not complete") + c.state(linuxcnc.STATE_ESTOP_RESET) + c.state(linuxcnc.STATE_ON) + wait_complete("machine did not turn on after E-stop") + + def interrupt_off(): + c.state(linuxcnc.STATE_OFF) + wait_complete("machine off during G28.2 did not complete") + c.state(linuxcnc.STATE_ON) + wait_complete("machine did not turn on after machine off") + + def interrupt_mode(): + c.mode(linuxcnc.MODE_MDI) + wait_complete("MDI mode switch during G28.2 did not complete") + + def interrupt_stop_abort(): + # Abort while Stop waits for G28.2 reaches motion in FREE mode. + # homing-long.ngc gives an 8 s final homing move to do this in. + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPING, + "Stop was not accepted during G28.2", + timeout=5.0, + ) + if not s.joint[0]["homing"]: + fail("G28.2 finished before Stop and Abort could be sent") + c.abort() + c.mode(linuxcnc.MODE_AUTO) + wait_complete("abort and AUTO during G28.2 did not complete") + wait_for( + lambda: s.task_mode == linuxcnc.MODE_AUTO + and s.exec_state == linuxcnc.EXEC_DONE + and not s.joint[0]["homing"], + "abort and AUTO did not end the queued G28.2", + ) + # Run without another mode command: its abort would hide a stale + # Stop in motion. + c.program_open("after-abort.ngc") + wait_complete("after-abort.ngc did not open") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for_program_complete(6.0) + + for name, interrupt in ( + ("abort", interrupt_abort), + ("estop", interrupt_estop), + ("off", interrupt_off), + ("mode", interrupt_mode), + ("stop and abort", interrupt_stop_abort), + ): + wait_for_queued_homing( + "program did not enter G28.2 before %s" % name, + "homing-long.ngc" if name == "stop and abort" else "homing.ngc", + ) + interrupt() + wait_for( + lambda: s.exec_state == linuxcnc.EXEC_DONE + and s.interp_state == linuxcnc.INTERP_IDLE + and not s.joint[0]["homing"], + "%s did not end the queued G28.2" % name, + ) + + if name == "abort": + # An MDI command is not an AUTO program, whatever mode the + # interrupted G28.2 was issued from. + c.mode(linuxcnc.MODE_MDI) + wait_complete("machine did not enter MDI") + c.mdi("G1 X0 F60") + wait_for( + lambda: abs(s.current_vel) > 0.1, + "MDI move did not start", + ) + c.program_stop() + if c.wait_complete(10.0) != linuxcnc.RCS_ERROR: + fail("Stop was accepted for an MDI command after G28.2 was aborted") + s.poll() + if s.stop_state != linuxcnc.STOP_IDLE: + fail("rejected MDI Stop changed Stop state") + c.abort() + wait_complete("abort of MDI move did not complete") + + check_stop_reaches_stopped("after %s during G28.2" % name) + + +def run_speed_change_atspeed_test(): + # An S-word after Stop and Resume must still make the next feed wait for + # spindle at-speed, also after back-to-back Stops. + open_auto_program("speed-change.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[0] > 0.3 + and s.position[0] < 1.5 + and hal.get_value("spindle.0.speed-out") > 0.0, + "first feed did not start", + ) + + for _ in range(2): + c.program_stop() + wait_complete("Stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED", + ) + stopped_x = s.position[0] + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.3, + "program did not resume", + ) + + hal.set_p("spindle.0.at-speed", "false") + wait_for( + lambda: s.position[0] > 3.99, + "first feed did not finish", + ) + time.sleep(0.5) + s.poll() + if hal.get_value("spindle.0.speed-out") < 590.0: + fail("S600 was not applied") + if not math.isclose(s.position[0], 4.0, abs_tol=0.01): + fail( + "feed after S600 did not wait for spindle at-speed after Stop: " + "X=%.6f" % s.position[0] + ) + + hal.set_p("spindle.0.at-speed", "true") + wait_for_program_complete(6.0) + assert_outputs_stopped_after_program() + + +def run_queued_feed_atspeed_test(): + # A feed already queued and held for spindle at-speed when Stop arrives + # must still wait for at-speed after Resume. + hal.set_p("spindle.0.at-speed", "false") + open_auto_program("feed-atspeed.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.queue > 0 + and math.isclose(s.position[0], 0.0, abs_tol=0.001) + and abs(s.current_vel) < 0.001 + and hal.get_value("spindle.0.speed-out") > 0.0, + "feed did not queue while waiting for spindle at-speed", + ) + time.sleep(0.25) + + c.program_stop() + wait_complete("Stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED with a feed waiting for at-speed", + ) + + # at-speed reports the stopped spindle while STOPPED, then drops again + # when Resume restarts the spindle. + hal.set_p("spindle.0.at-speed", "true") + time.sleep(0.25) + hal.set_p("spindle.0.at-speed", "false") + s.poll() + if not math.isclose(s.position[0], 0.0, abs_tol=0.001): + fail("feed moved while STOPPED") + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state != linuxcnc.STOP_STOPPED + and hal.get_value("spindle.0.speed-out") > 0.0, + "Resume did not restore the spindle", + ) + time.sleep(0.5) + s.poll() + if not math.isclose(s.position[0], 0.0, abs_tol=0.001): + fail("feed started after Resume without waiting for spindle at-speed") + + hal.set_p("spindle.0.at-speed", "true") + wait_for_program_complete(5.0) + assert_outputs_stopped_after_program() + + +def run_threading_chain_stop_resume_test(): + # Consecutive G33 moves stay synchronized to one index pulse, so Stop + # must let the whole chain finish, not just the move active at Stop. + stop_during_sync_motion( + "thread-chain.ngc", + lambda: s.position[2] < -0.5 and s.position[2] > -1.5, + lambda: s.position[2] <= -4.90, + "consecutive G33 threading", + expected_z=-5.0, + resume_max_vel=1.05, + ) + + +def run_inflight_step_g33_chain_test(): + # Consecutive G33 moves stay synchronized to one index pulse. A Single + # Step armed during the first ends at the end of the whole synchronized + # run, as Stop does, and never inside it; Resume finishes the program. + open_auto_program("thread-chain-g64.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[2] < -0.5 + and s.position[2] > -1.5 + and hal.get_value("spindle.0.speed-out") > 0.0, + "first G33 did not start", + timeout=15.0, + ) + c.auto(linuxcnc.AUTO_STEP) + # G64 blends the last G33 into the following G1, so the run ends where + # that blend begins, short of Z-5. + wait_for( + lambda: s.position[2] < -4.0 and s.current_vel == 0.0, + lambda: "Step did not end after the G33 chain: Z=%.4f" % s.position[2], + timeout=15.0, + ) + time.sleep(0.5) + s.poll() + if s.position[2] > -4.0 or abs(s.position[0]) > 0.5: + fail("Step did not hold after the G33 chain: X=%.4f Z=%.4f" + % (s.position[0], s.position[2])) + c.auto(linuxcnc.AUTO_RESUME) + wait_for_program_complete(10.0, expected_z=-5.0) + + +def run_g95_between_g33_stop_resume_test(): + # A G33 that follows velocity-synchronized G95 motion keeps the earlier + # G33's spindle synchronization. After a Stop during the G95 move the + # spindle has been stopped and restarted, so the next G33 must wait for + # a fresh index pulse instead of chasing the revolutions turned since. + open_auto_program("thread-g95-thread.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[0] > 0.2 + and s.position[0] < 0.7 + and math.isclose(s.position[2], -2.0, abs_tol=0.01), + "G95 move between the G33 moves did not start", + timeout=15.0, + ) + + c.program_stop() + wait_complete("Stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED during the G95 move", + ) + if s.position[0] >= 0.99 or not math.isclose(s.position[2], -2.0, abs_tol=0.01): + fail("Stop did not hold the G95 move: X=%.4f Z=%.4f" % (s.position[0], s.position[2])) + + c.auto(linuxcnc.AUTO_RESUME) + saw_index_wait = False + start = time.time() + while time.time() - start < 15.0: + s.poll() + if s.position[2] < -2.05: + break + if s.position[0] > 0.99 and hal.get_value("spindle.0.index-enable"): + saw_index_wait = True + time.sleep(0.005) + else: + fail("second G33 did not start after Resume") + if not saw_index_wait: + fail("second G33 did not wait for a fresh spindle index after Stop") + + wait_for_program_complete(10.0, expected_z=-4.0, timeout=20.0) + assert_outputs_stopped_after_program() + + +def run_stopped_spindle_s_word_test(): + # An S-word for a spindle stopped with M5 must leave it stopped after a + # Stop and Resume of another spindle. + open_auto_program("spindle-state.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( + lambda: s.position[0] > 0.5 + and s.position[0] < 2.5 + and hal.get_value("spindle.0.on"), + "feed with spindle 0 on did not start", + ) + c.program_stop() + wait_complete("Stop command did not complete") + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED and s.task_paused, + "task did not enter STOPPED", + ) + stopped_x = s.position[0] + c.auto(linuxcnc.AUTO_RESUME) + wait_for( + lambda: s.stop_state == linuxcnc.STOP_IDLE + and s.position[0] > stopped_x + 0.05, + "program did not resume", + ) + wait_for( + lambda: s.position[0] > 4.3 and s.position[0] < 7.0, + "feed after S800 $1 did not start", + ) + if not hal.get_value("spindle.0.on"): + fail("spindle 0 was not restored") + if hal.get_value("spindle.1.on"): + fail("S800 $1 switched on spindle 1, which M5 had stopped") + wait_for_program_complete(8.0) + + +SCENARIOS = { + "idle-rejected": run_idle_program_stop_rejected_test, + "ordinary": run_ordinary_stop_resume_test, + "single-step": run_stop_single_step_test, + "inflight-single-step": run_inflight_single_step_test, + "rapid-no-atspeed": run_rapid_resume_without_at_speed_test, + "paused-resume": lambda: run_stop_while_program_paused_test(False), + "paused-run": lambda: run_stop_while_program_paused_test(True), + "abort-empty": run_abort_from_empty_stopped_queue_test, + "abort-armed-step": run_abort_armed_step_test, + "queued-g33": run_queued_threading_stop_resume_test, + "g33": run_threading_stop_resume_test, + "g33-no-following-rapid": run_g33_does_not_execute_following_rapid_test, + "fperrev": run_fperrev_stop_resume_test, + "g76": run_g76_stop_resume_test, + "g76-waiting-index": run_g76_stop_while_waiting_for_index_test, + "g76-tapered": run_tapered_g76_stop_resume_test, + "g76-single-step": run_g76_single_step_test, + "g76-tapered-single-step": run_tapered_g76_single_step_test, + "g76-inflight-single-step": run_inflight_g76_single_step_test, + "g76-exit-taper": run_cylindrical_g76_exit_taper_stop_test, + "g76-tapered-exit-taper": run_tapered_g76_exit_taper_stop_test, + "g76-handoff-stress": run_g76_cut_retract_handoff_stress_test, + "rigid-tap": run_rigid_tap_stop_resume_test, + "orientation": run_spindle_orientation_stop_test, + "dwell": run_dwell_stop_resume_test, + "system-command": run_system_command_stop_test, + "set-auto-stopped": run_set_auto_while_stopped_test, + "step-after-dwell-stop": run_step_after_dwell_stop_test, + "dwell-atspeed": run_dwell_atspeed_barrier_test, + "command-after-sync": run_command_after_sync_motion_test, + "resume-atspeed": run_resume_atspeed_wait_test, + "pause-starting": run_pause_while_starting_test, + "resume-stopping-refused": lambda: run_refused_while_stopping_test( + "Resume", lambda: c.auto(linuxcnc.AUTO_RESUME)), + "step-stopping-refused": lambda: run_refused_while_stopping_test( + "Step", lambda: c.auto(linuxcnc.AUTO_STEP)), + "pause-inflight-step": run_pause_inflight_single_step_test, + "inflight-step-short": run_inflight_short_block_step_test, + "resume-s0": run_resume_zero_speed_test, + "multi-spindle": run_multi_spindle_stop_resume_test, + "css": run_css_stop_resume_test, + "homing": run_homing_stop_resume_test, + "homing-interrupted": run_interrupted_homing_test, + "speed-change-atspeed": run_speed_change_atspeed_test, + "queued-feed-atspeed": run_queued_feed_atspeed_test, + "g33-chain": run_threading_chain_stop_resume_test, + "g95-between-g33": run_g95_between_g33_stop_resume_test, + "inflight-step-g33-chain": run_inflight_step_g33_chain_test, + "spindle-state": run_stopped_spindle_s_word_test, +} + +scenario = os.environ.get("RESUMABLE_STOP_SCENARIO") +if scenario not in SCENARIOS: + fail("unknown resumable-stop scenario: %s" % scenario) + +SCENARIOS[scenario]() +print("resumable stop scenario ok: %s" % scenario) +sys.exit(0) diff --git a/linuxcnc-tests/resumable-stop/test.ini b/linuxcnc-tests/resumable-stop/test.ini new file mode 100644 index 00000000..6c0370fa --- /dev/null +++ b/linuxcnc-tests/resumable-stop/test.ini @@ -0,0 +1,100 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0x0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var +USER_M_PATH = . + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +AXES = 3 +COORDINATES = X Y Z +SPINDLES = 2 +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +PLANNER_TYPE = 1 +ARC_BLEND_ENABLE = 1 +DEFAULT_LINEAR_VELOCITY = 10 +MAX_LINEAR_VELOCITY = 50 +MAX_LINEAR_JERK = 5000 + +[EMCIO] +TOOL_TABLE = tool.tbl + +[KINS] +KINEMATICS = trivkins +JOINTS = 3 + +[AXIS_X] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MAX_JERK = 5000 + +[JOINT_0] +TYPE = LINEAR +# Home at the current position, then make a final move to HOME so that a +# queued G28.2 P0 takes long enough to be stopped part way. +HOME = 20 +HOME_FINAL_VEL = 10 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MAX_JERK = 5000 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[AXIS_Y] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MAX_JERK = 5000 + +[JOINT_1] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MAX_JERK = 5000 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +[AXIS_Z] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MAX_JERK = 5000 + +[JOINT_2] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MAX_JERK = 5000 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 diff --git a/linuxcnc-tests/resumable-stop/test.ngc b/linuxcnc-tests/resumable-stop/test.ngc new file mode 100644 index 00000000..c44a2cdc --- /dev/null +++ b/linuxcnc-tests/resumable-stop/test.ngc @@ -0,0 +1,9 @@ +G21 G90 +G0 X0 +F150 +S300 M3 +M8 +G1 X10 +M9 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/thread-chain-g64.ngc b/linuxcnc-tests/resumable-stop/thread-chain-g64.ngc new file mode 100644 index 00000000..a9f48652 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/thread-chain-g64.ngc @@ -0,0 +1,8 @@ +G21 G90 G64 +G0 X0 Z0 +S6 M3 +G33 Z-2 K10 +G33 Z-5 K10 +G1 X10 F60 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/thread-chain.ngc b/linuxcnc-tests/resumable-stop/thread-chain.ngc new file mode 100644 index 00000000..ca808391 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/thread-chain.ngc @@ -0,0 +1,8 @@ +G21 G90 +G0 X0 Z0 +S6 M3 +G33 Z-2 K10 +G33 Z-5 K10 +G1 X10 F60 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/thread-g95-thread.ngc b/linuxcnc-tests/resumable-stop/thread-g95-thread.ngc new file mode 100644 index 00000000..2bc7489c --- /dev/null +++ b/linuxcnc-tests/resumable-stop/thread-g95-thread.ngc @@ -0,0 +1,9 @@ +G21 G18 G90 +G0 X0 Z0 +S60 M3 +G33 Z-2 K1 +G95 G1 X1 F0.5 +G33 Z-4 K1 +G94 G1 X10 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/thread-then-steps.ngc b/linuxcnc-tests/resumable-stop/thread-then-steps.ngc new file mode 100644 index 00000000..44aa11e6 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/thread-then-steps.ngc @@ -0,0 +1,10 @@ +G21 G90 +G0 X0 Z0 +S60 M3 +G33 Z-5 K1 +G1 X5 F600 +M8 +G1 X10 +M9 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/thread.ngc b/linuxcnc-tests/resumable-stop/thread.ngc new file mode 100644 index 00000000..c3ec6d07 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/thread.ngc @@ -0,0 +1,7 @@ +G21 G90 +G0 X0 Z0 +S60 M3 +G33 Z-5 K1 +G1 X10 F600 +M5 +M2 diff --git a/linuxcnc-tests/resumable-stop/threading/checkresult b/linuxcnc-tests/resumable-stop/threading/checkresult new file mode 100755 index 00000000..664eed87 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/threading/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 11 diff --git a/linuxcnc-tests/resumable-stop/threading/scenarios b/linuxcnc-tests/resumable-stop/threading/scenarios new file mode 100644 index 00000000..36e8cc90 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/threading/scenarios @@ -0,0 +1,11 @@ +rigid-tap +g33 +queued-g33 +g33-chain +trapezoidal:g33-chain +g95-between-g33 +g33-no-following-rapid +command-after-sync +resume-stopping-refused +step-stopping-refused +inflight-step-g33-chain diff --git a/linuxcnc-tests/resumable-stop/threading/test.sh b/linuxcnc-tests/resumable-stop/threading/test.sh new file mode 100755 index 00000000..713f5769 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/threading/test.sh @@ -0,0 +1,3 @@ +#!/bin/bash +# Runs the resumable-stop scenarios listed in ./scenarios (see ../README). +exec bash ../run-scenarios.sh scenarios diff --git a/linuxcnc-tests/resumable-stop/tool.tbl b/linuxcnc-tests/resumable-stop/tool.tbl new file mode 100644 index 00000000..68840ea7 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/tool.tbl @@ -0,0 +1 @@ +T1 P1 Z0 D0 diff --git a/linuxcnc-tests/rtmod-path/expected b/linuxcnc-tests/rtmod-path/expected new file mode 100644 index 00000000..55233dce --- /dev/null +++ b/linuxcnc-tests/rtmod-path/expected @@ -0,0 +1 @@ +rtmod-path: all tests passed diff --git a/linuxcnc-tests/rtmod-path/load.hal b/linuxcnc-tests/rtmod-path/load.hal new file mode 100644 index 00000000..b4439275 --- /dev/null +++ b/linuxcnc-tests/rtmod-path/load.hal @@ -0,0 +1,2 @@ +loadrt and2 count=1 +unloadrt all diff --git a/linuxcnc-tests/rtmod-path/test.c b/linuxcnc-tests/rtmod-path/test.c new file mode 100644 index 00000000..fffdf474 --- /dev/null +++ b/linuxcnc-tests/rtmod-path/test.c @@ -0,0 +1,109 @@ +#include "config.h" +#include "rtapi/rtmod_path.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +static void touch_file(const char *path, const char *value) { + int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600); + assert(fd >= 0); + assert(write(fd, value, strlen(value)) == (ssize_t)strlen(value)); + close(fd); +} + +int main(void) { + rtmod_path_t path = {0}; + char extras[PATH_MAX * 2], *a, *b, *colon; + char ordered[PATH_MAX * 2], result[PATH_MAX], error[1024]; + char fa[PATH_MAX], fb[PATH_MAX], escaped[PATH_MAX], outside[PATH_MAX]; + const char *name = "rtmod_path_fixture"; + + assert(rtmod_path_init(&path, NULL, error, sizeof(error)) == 0); + assert(path.count == 1 && !strcmp(path.dirs[0], EMC2_RTLIB_DIR)); + rtmod_path_free(&path); + assert(rtmod_path_init(&path, "", error, sizeof(error)) < 0); + assert(rtmod_path_init(&path, "relative", error, sizeof(error)) < 0); + assert(rtmod_path_init(&path, "/tmp::/var", error, sizeof(error)) < 0); + assert(rtmod_path_init(&path, "/definitely/not/trusted", error, sizeof(error)) < 0); + assert(!rtmod_name_valid("../bad") && !rtmod_name_valid("bad/name")); + + /* The standard directory: real components resolve there, and the + protected rtapi/hal_lib lookups never leave it. */ + assert(rtmod_path_init(&path, EMC2_RTLIB_DIR "/", error, sizeof(error)) == 0); + assert(path.count == 1 && !strcmp(path.dirs[0], EMC2_RTLIB_DIR)); + snprintf(fa, sizeof(fa), "%s/and2%s", EMC2_RTLIB_DIR, MODULE_EXT); + assert(rtmod_path_resolve(&path, "and2", 0, result, sizeof(result), error, sizeof(error)) == 0); + assert(!strcmp(result, fa)); + assert(rtmod_path_resolve(&path, "hal_lib", 1, result, sizeof(result), error, sizeof(error)) == 0); + assert(rtmod_path_resolve(&path, "../and2", 0, result, sizeof(result), error, sizeof(error)) < 0); + rtmod_path_free(&path); + { + char name[64]; + assert(rtmod_path_is_trusted_file(fa, name, sizeof(name)) && !strcmp(name, "and2")); + } + + strcpy(extras, EMC2_EXTRA_RTLIB_DIRS); + colon = strchr(extras, ':'); + if (!colon) { + /* Ordered lookup needs two trusted extra directories + (--with-extra-rtlib-dirs=DIR_A:DIR_B); this build has fewer. */ + fputs("rtmod-path: ordered lookup checks need two extra rtlib directories; not run\n", stderr); + puts("rtmod-path: all tests passed"); + return 0; + } + *colon = 0; a = extras; b = colon + 1; + assert(*a && *b && !strchr(b, ':')); + mkdir(a, 0700); mkdir(b, 0700); + snprintf(fa, sizeof(fa), "%s/%s%s", a, name, MODULE_EXT); + snprintf(fb, sizeof(fb), "%s/%s%s", b, name, MODULE_EXT); + touch_file(fa, "first-broken-copy"); touch_file(fb, "second-copy"); + + snprintf(ordered, sizeof(ordered), "%s:%s:%s", a, a, b); + assert(rtmod_path_init(&path, ordered, error, sizeof(error)) == 0 && path.count == 2); + assert(rtmod_path_resolve(&path, name, 0, result, sizeof(result), error, sizeof(error)) == 0); + assert(!strcmp(result, fa)); /* selection is final; loaders must not fall through */ + rtmod_path_free(&path); + + snprintf(ordered, sizeof(ordered), "%s:%s", b, a); + assert(rtmod_path_init(&path, ordered, error, sizeof(error)) == 0); + assert(rtmod_path_resolve(&path, name, 0, result, sizeof(result), error, sizeof(error)) == 0); + assert(!strcmp(result, fb)); + assert(rtmod_path_resolve(&path, "missing_fixture", 0, result, sizeof(result), error, sizeof(error)) < 0); + assert(strstr(error, a) && strstr(error, b)); + + snprintf(outside, sizeof(outside), "/tmp/rtmod-path-outside-%ld%s", (long)getpid(), MODULE_EXT); + touch_file(outside, "outside"); + snprintf(escaped, sizeof(escaped), "%s/rtmod_path_escape%s", a, MODULE_EXT); + unlink(escaped); assert(symlink(outside, escaped) == 0); + assert(rtmod_path_resolve(&path, "rtmod_path_escape", 0, result, sizeof(result), error, sizeof(error)) < 0); + assert(strstr(error, "escapes trusted directory")); + { + char name[64]; + /* the module helper's check: trusted extra file yes, symlink escape + no, and the protected names only from the standard directory */ + assert(rtmod_path_is_trusted_file(fb, name, sizeof(name)) && !strcmp(name, "rtmod_path_fixture")); + assert(!rtmod_path_is_trusted_file(escaped, name, sizeof(name))); + assert(!rtmod_path_is_trusted_file(outside, name, sizeof(name))); + snprintf(result, sizeof(result), "%s/hal_lib%s", a, MODULE_EXT); + touch_file(result, "shadow"); + assert(!rtmod_path_is_trusted_file(result, name, sizeof(name))); + { + char core[PATH_MAX], std_core[PATH_MAX]; + snprintf(std_core, sizeof(std_core), "%s/hal_lib%s", EMC2_RTLIB_DIR, MODULE_EXT); + assert(rtmod_path_resolve(&path, "hal_lib", 1, core, sizeof(core), error, sizeof(error)) == 0); + assert(!strcmp(core, std_core)); + } + unlink(result); + } + rtmod_path_free(&path); + + unlink(fa); unlink(fb); unlink(escaped); unlink(outside); + puts("rtmod-path: all tests passed"); + return 0; +} diff --git a/linuxcnc-tests/rtmod-path/test.sh b/linuxcnc-tests/rtmod-path/test.sh new file mode 100755 index 00000000..dde6c2f9 --- /dev/null +++ b/linuxcnc-tests/rtmod-path/test.sh @@ -0,0 +1,8 @@ +#!/bin/sh +set -eu + +cc -std=c11 -D_GNU_SOURCE -Wall -Wextra -Wno-format-truncation \ + -I"$EMC2_HOME/src" -I"$EMC2_HOME/src/rtapi" \ + "$EMC2_HOME/src/rtapi/rtmod_path.c" test.c -o test_rtmod_path +./test_rtmod_path +rm -f test_rtmod_path diff --git a/linuxcnc-tests/run.sh b/linuxcnc-tests/run.sh new file mode 100755 index 00000000..76ed546c --- /dev/null +++ b/linuxcnc-tests/run.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Runs the LinuxCNC regression suite for the patched build: the upstream tests +# in the LinuxCNC tree plus this directory's tests, leaving out tests for +# LinuxCNC features that are out of scope for this repository. +# +# Usage: run.sh /path/to/linuxcnc [runtests options] +# +# Set SHARD_INDEX and SHARD_COUNT to run one shard of the suite. + +set -euo pipefail + +if [[ $# -lt 1 ]]; then + echo "Usage: $0 /path/to/linuxcnc [runtests options]" >&2 + exit 2 +fi + +readonly TESTS_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" +readonly LINUXCNC_DIR="$(cd -- "$1" && pwd)" +shift +readonly SHARD_COUNT="${SHARD_COUNT:-1}" +readonly SHARD_INDEX="${SHARD_INDEX:-0}" + +cd -- "${LINUXCNC_DIR}" + +# linuxcnc-tests/resumable-stop/* are the longest tests (about 2.5 minutes +# each); spread them one per shard. Everything else is hashed across shards. +selected=() +resumable_index=0 +while IFS= read -r -d '' test_path; do + name="${test_path#"${TESTS_DIR}/"}" + [[ "${name}" == "${test_path}" ]] || name="linuxcnc-tests/${name}" + # Out of scope: GUIs and GUI tools, older remote interfaces, and tool + # database programs. + case "${name}" in + tests/build/ui/* | tests/glcanon/* | tests/halrmt/* | \ + tests/linuxcncrsh/* | tests/linuxcncrsh-tcp/* | \ + tests/pyvcp/* | tests/tooldb/* | tests/tooledit/* | \ + tests/ui-smoke/*) + continue + ;; + esac + if [[ "${name}" == linuxcnc-tests/resumable-stop/* ]]; then + shard=$((resumable_index % SHARD_COUNT)) + resumable_index=$((resumable_index + 1)) + else + checksum="$(printf '%s' "${name}" | cksum)" + shard=$((${checksum%% *} % SHARD_COUNT)) + fi + if ((shard == SHARD_INDEX)); then + selected+=("${test_path}") + fi +done < <( + find tests "${TESTS_DIR}" \ + \( -name test -o -name test.sh -o -name test.hal \) -print0 | sort -z +) + +((${#selected[@]} > 0)) || { echo "No tests selected" >&2; exit 1; } +echo "Running ${#selected[@]} tests (shard $((SHARD_INDEX + 1))/${SHARD_COUNT})" +exec scripts/rip-environment runtests "$@" "${selected[@]}" diff --git a/linuxcnc-tests/runtime-availability-regressions/.gitignore b/linuxcnc-tests/runtime-availability-regressions/.gitignore new file mode 100644 index 00000000..425d52b6 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/.gitignore @@ -0,0 +1,2 @@ +/*.ini +!/base.ini diff --git a/linuxcnc-tests/runtime-availability-regressions/README b/linuxcnc-tests/runtime-availability-regressions/README new file mode 100644 index 00000000..2a461517 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/README @@ -0,0 +1,22 @@ +Production-path availability regressions. Each case starts LinuxCNC with POSIX +simulation and uses its NML command/status channels and real HAL servo thread. +The amplifier and homing latches run after motion-controller every servo cycle. +Select individual cases with AVAILABILITY_REGRESSION_CASES for mutation checks. +The extra-joint case verifies configuration rejection before Machine On because +no external posthome command ownership/completion contract is supported. +The fault case records EMC_ABORT_MOTION_OR_IO_RCS_ERROR through the standard +ON_ABORT_COMMAND hook, distinguishing error handling from a machine-off abort +without polling transient status. The sequence case verifies that an +availability-controlled joint cannot define a Home All sequence. + +INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local +*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before +launching an individual case directly. @unset explicitly removes an inherited +key. Generated INIs are ignored; edit the base or the case override instead. +Handoff regressions cover abort during a spindle index wait followed by release +and reacquisition (including a fresh encoder handshake), X/Z/C Machine Off/On +while released C feedback moves externally, and JOG_STOP during acknowledgment +and volatile acquisition homing waits. Released motion state remains frozen +while the raw HAL feedback pin stays live. +The slowtask case acquires joints whose homes end between two status reads of +a slow task cycle: task must still see that the home ran. diff --git a/linuxcnc-tests/runtime-availability-regressions/atspeed.hal b/linuxcnc-tests/runtime-availability-regressions/atspeed.hal new file mode 100644 index 00000000..218d2bc5 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/atspeed.hal @@ -0,0 +1,20 @@ +loadrt trivkins coordinates=XYZ +loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_spindles=2 +loadrt mux2 count=1 +addf mux2.0 servo-thread +addf motion-command-handler servo-thread +addf motion-controller servo-thread +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Ycmd joint.1.motor-pos-cmd => mux2.0.in0 +net Yfb mux2.0.out => joint.1.motor-pos-fb +net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in +# Spindle 0 is released and its owner leaves at-speed false; spindle 1 +# runs this program. +setp spindle.0.at-speed false +setp spindle.1.at-speed true +loadrt flipflop count=5 +addf flipflop.0 servo-thread +addf flipflop.1 servo-thread +net amp-seen joint.1.amp-enable-out => flipflop.0.set +net other-home-seen joint.2.homing => flipflop.1.set diff --git a/linuxcnc-tests/runtime-availability-regressions/atspeed.ini.in b/linuxcnc-tests/runtime-availability-regressions/atspeed.ini.in new file mode 100644 index 00000000..f1e6f3ed --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/atspeed.ini.in @@ -0,0 +1,6 @@ +[FIXTURE] +BASE = base.ini +[HAL] +HALFILE = atspeed.hal +[TRAJ] +SPINDLES = 2 diff --git a/linuxcnc-tests/runtime-availability-regressions/atspeed.ngc b/linuxcnc-tests/runtime-availability-regressions/atspeed.ngc new file mode 100644 index 00000000..1099c4f1 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/atspeed.ngc @@ -0,0 +1,5 @@ +G21 G90 G0 X0 +M3 $1 S500 +G1 X1 F100 +M5 $1 +M2 diff --git a/linuxcnc-tests/runtime-availability-regressions/base.ini b/linuxcnc-tests/runtime-availability-regressions/base.ini new file mode 100644 index 00000000..71f455ae --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/base.ini @@ -0,0 +1,94 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0 +[DISPLAY] +DISPLAY = ./test-ui.py +[RS274NGC] +PARAMETER_FILE = sim.var +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4 +SERVO_PERIOD = 1000000 +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 +[HAL] +HALFILE = core.hal +[TRAJ] +NO_FORCE_HOMING = 1 +COORDINATES = XYZ +SPINDLES = 1 +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 10 +MAX_LINEAR_VELOCITY = 50 +[EMCIO] +TOOL_TABLE = tool.tbl +[KINS] +KINEMATICS = trivkins coordinates=XYZ +JOINTS = 3 +[AXIS_X] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +[AXIS_Y] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +[AXIS_Z] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +[JOINT_0] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +HOME_SEARCH_VEL = 0 +HOME_LATCH_VEL = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 +AVAILABILITY_CONTROL = 1 +AVAILABILITY_TIMEOUT = 5 +VOLATILE_HOME = 0 +[JOINT_1] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +HOME_SEARCH_VEL = 0 +HOME_LATCH_VEL = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 +AVAILABILITY_CONTROL = 1 +AVAILABILITY_TIMEOUT = 5 +VOLATILE_HOME = 0 +[JOINT_2] +TYPE = LINEAR +HOME = 0 +HOME_OFFSET = 0 +HOME_SEQUENCE = 0 +HOME_SEARCH_VEL = 0 +HOME_LATCH_VEL = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 +AVAILABILITY_CONTROL = 0 +AVAILABILITY_TIMEOUT = 5 +VOLATILE_HOME = 0 +[SPINDLE_0] +AVAILABILITY_CONTROL = 1 +INITIAL_AVAILABILITY = 0 +AVAILABILITY_TIMEOUT = 5 diff --git a/linuxcnc-tests/runtime-availability-regressions/checkresult b/linuxcnc-tests/runtime-availability-regressions/checkresult new file mode 100755 index 00000000..65ed2d73 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/checkresult @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +for scenario in ${AVAILABILITY_REGRESSION_CASES:-fault wheel tail amp power index jogstop joghome atspeed extra sequence}; do + grep -q "^availability regression $scenario ok$" "$1" +done diff --git a/linuxcnc-tests/runtime-availability-regressions/core.hal b/linuxcnc-tests/runtime-availability-regressions/core.hal new file mode 100644 index 00000000..7e0cffcf --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/core.hal @@ -0,0 +1,17 @@ +loadrt trivkins coordinates=XYZ +loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_spindles=1 +loadrt mux2 count=1 +addf mux2.0 servo-thread +addf motion-command-handler servo-thread +addf motion-controller servo-thread +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Ycmd joint.1.motor-pos-cmd => mux2.0.in0 +net Yfb mux2.0.out => joint.1.motor-pos-fb +net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in +setp spindle.0.at-speed true +loadrt flipflop count=5 +addf flipflop.0 servo-thread +addf flipflop.1 servo-thread +net amp-seen joint.1.amp-enable-out => flipflop.0.set +net other-home-seen joint.2.homing => flipflop.1.set diff --git a/linuxcnc-tests/runtime-availability-regressions/dwell.ngc b/linuxcnc-tests/runtime-availability-regressions/dwell.ngc new file mode 100644 index 00000000..b69d67a1 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/dwell.ngc @@ -0,0 +1,4 @@ +G90 G94 +G4 P1 +M64 P0 +M2 diff --git a/linuxcnc-tests/runtime-availability-regressions/extra.hal b/linuxcnc-tests/runtime-availability-regressions/extra.hal new file mode 100644 index 00000000..36c2c7ee --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/extra.hal @@ -0,0 +1,17 @@ +loadrt trivkins coordinates=XY kinstype=B +loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_extrajoints=1 num_spindles=1 +loadrt mux2 count=1 +addf mux2.0 servo-thread +addf motion-command-handler servo-thread +addf motion-controller servo-thread +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Ycmd joint.1.motor-pos-cmd => mux2.0.in0 +net Yfb mux2.0.out => joint.1.motor-pos-fb +net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in +setp spindle.0.at-speed true +loadrt flipflop count=2 +addf flipflop.0 servo-thread +addf flipflop.1 servo-thread +net amp-seen joint.1.amp-enable-out => flipflop.0.set +net other-home-seen joint.2.homing => flipflop.1.set diff --git a/linuxcnc-tests/runtime-availability-regressions/extra.ini.in b/linuxcnc-tests/runtime-availability-regressions/extra.ini.in new file mode 100644 index 00000000..5048be90 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/extra.ini.in @@ -0,0 +1,16 @@ +# Case-specific overrides; unspecified values come from FIXTURE.BASE. +[FIXTURE] +BASE = base.ini + +[HAL] +HALFILE = extra.hal + +[TRAJ] +COORDINATES = XY + +[KINS] +KINEMATICS = trivkins coordinates=XY kinstype=B + +[JOINT_2] +HOME_SEQUENCE = @unset +AVAILABILITY_CONTROL = 1 diff --git a/linuxcnc-tests/runtime-availability-regressions/fault.ini.in b/linuxcnc-tests/runtime-availability-regressions/fault.ini.in new file mode 100644 index 00000000..b39d68b9 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/fault.ini.in @@ -0,0 +1,13 @@ +# Case-specific overrides; unspecified values come from FIXTURE.BASE. +[FIXTURE] +BASE = base.ini + +[RS274NGC] +SUBROUTINE_PATH = . +ON_ABORT_COMMAND = O call + +[JOINT_0] +AVAILABILITY_CONTROL = 0 + +[JOINT_1] +AVAILABILITY_CONTROL = 0 diff --git a/linuxcnc-tests/runtime-availability-regressions/fixture.py b/linuxcnc-tests/runtime-availability-regressions/fixture.py new file mode 100644 index 00000000..c4c8307e --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/fixture.py @@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +import os +import time +import hal +import linuxcnc + +h = hal.component('availability-regression') +h.ready() +c = linuxcnc.command() +s = linuxcnc.stat() +e = linuxcnc.error_channel() +errors = [] +case = os.environ.get('AVAILABILITY_REGRESSION_CASE', 'extra') + +def pin(name, value): + hal.set_p(name, str(value)) + +def wait(predicate, message, timeout=8): + until = time.monotonic() + timeout + while time.monotonic() < until: + s.poll() + while (error := e.poll()) is not None: + errors.append(error) + if predicate(): + return + time.sleep(.005) + raise AssertionError(f'{case}: {message}: task={s.task_state} ' + f'interp={s.interp_state} exec={s.exec_state} errors={errors}') + +def settle(seconds=.1): + until = time.monotonic() + seconds + wait(lambda: time.monotonic() >= until, 'settle') + +def done(): + assert c.wait_complete(8) == linuxcnc.RCS_DONE, (case, errors) + s.poll() + +def acquire(resource): + kind, number = resource.split('.') + getattr(c, f'set_{kind}_availability')(int(number), True) + wait(lambda: hal.get_value(resource + '.availability-request'), 'acquire ' + resource) + pin(resource + '.availability-ack', 1) + done() + +def release(resource): + kind, number = resource.split('.') + getattr(c, f'set_{kind}_availability')(int(number), False) + wait(lambda: not hal.get_value(resource + '.availability-request'), 'release ' + resource) + pin(resource + '.availability-ack', 0) + done() + +def run(name): + c.mode(linuxcnc.MODE_AUTO); done() + c.program_open(os.path.abspath(name)); done() + c.auto(linuxcnc.AUTO_RUN, 0) + +wait(lambda: s.task_state == linuxcnc.STATE_ESTOP, 'startup') +if case == 'extra': + raise AssertionError('unsupported extra-joint configuration reached UI') +c.state(linuxcnc.STATE_ESTOP_RESET); done() +c.state(linuxcnc.STATE_ON); done() +c.teleop_enable(0); done() +if case != 'fault': + acquire('joint.0') +if case not in ('fault', 'joghome', 'slowtask'): + acquire('joint.1') +if case == 'joghome': + c.set_joint_availability(1, True) + wait(lambda: hal.get_value('joint.1.availability-request'), 'runtime acquisition') + pin('joint.1.availability-ack', 1) + wait(lambda: hal.get_value('joint.1.index-enable'), 'runtime homing index') + pin('joint.1.index-enable', 0) + done() +if case == 'slowtask': + # an unhomed joint is homed when acquired at runtime + c.set_joint_availability(1, True) + wait(lambda: hal.get_value('joint.1.availability-request'), 'runtime acquisition') + pin('joint.1.availability-ack', 1) + done() +c.home(2); done() +wait(lambda: s.homed[2], 'home ordinary joint') diff --git a/linuxcnc-tests/runtime-availability-regressions/joghome.ini.in b/linuxcnc-tests/runtime-availability-regressions/joghome.ini.in new file mode 100644 index 00000000..949adc12 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/joghome.ini.in @@ -0,0 +1,6 @@ +[FIXTURE] +BASE = base.ini +[JOINT_1] +VOLATILE_HOME = 1 +HOME_USE_INDEX = YES +HOME_LATCH_VEL = 1 diff --git a/linuxcnc-tests/runtime-availability-regressions/record_abort.ngc b/linuxcnc-tests/runtime-availability-regressions/record_abort.ngc new file mode 100644 index 00000000..5ca302ff --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/record_abort.ngc @@ -0,0 +1,6 @@ +o sub +(LOGAPPEND,abort-reasons.log) +(LOG,#1) +(LOGCLOSE) +o endsub +M2 diff --git a/linuxcnc-tests/runtime-availability-regressions/sequence.ini.in b/linuxcnc-tests/runtime-availability-regressions/sequence.ini.in new file mode 100644 index 00000000..3786b153 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/sequence.ini.in @@ -0,0 +1,6 @@ +# Availability-controlled joints are referenced only by individual acquisition. +[FIXTURE] +BASE = base.ini + +[JOINT_1] +HOME_SEQUENCE = 1 diff --git a/linuxcnc-tests/runtime-availability-regressions/slowtask.ini.in b/linuxcnc-tests/runtime-availability-regressions/slowtask.ini.in new file mode 100644 index 00000000..75125d88 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/slowtask.ini.in @@ -0,0 +1,7 @@ +# Task reads status less often than this absolute encoder home takes to finish. +[FIXTURE] +BASE = base.ini +[TASK] +CYCLE_TIME = 0.05 +[JOINT_1] +HOME_ABSOLUTE_ENCODER = 2 diff --git a/linuxcnc-tests/runtime-availability-regressions/tail.hal b/linuxcnc-tests/runtime-availability-regressions/tail.hal new file mode 100644 index 00000000..c9eea9dd --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/tail.hal @@ -0,0 +1,30 @@ +source core.hal +# Observe the interpolation tail every servo cycle, after motion-controller. +# Tail: the axis planner stopped but the joint interpolator still has velocity. +loadrt near count=2 +loadrt not count=2 +loadrt and2 count=3 +addf near.0 servo-thread +addf near.1 servo-thread +addf not.0 servo-thread +addf and2.0 servo-thread +addf and2.1 servo-thread +addf not.1 servo-thread +addf and2.2 servo-thread +addf flipflop.2 servo-thread +addf flipflop.3 servo-thread +addf flipflop.4 servo-thread +setp near.0.difference 1e-12 +setp near.1.difference 1e-12 +net axis-velocity axis.y.teleop-vel-cmd => near.0.in1 +net joint-velocity joint.1.vel-cmd => near.1.in1 +net axis-stopped near.0.out => and2.0.in0 +net joint-stopped near.1.out => not.0.in +net joint-moving not.0.out => and2.0.in1 +net interpolation-tail and2.0.out => flipflop.2.set and2.1.in0 +net motion-inpos motion.in-position => and2.1.in1 +net premature-inpos and2.1.out => flipflop.3.set +net amp-seen => not.1.in +net amplifier-off not.1.out => and2.2.in0 +net joint-owned joint.1.availability-request => and2.2.in1 +net premature-amplifier-off and2.2.out => flipflop.4.set diff --git a/linuxcnc-tests/runtime-availability-regressions/tail.ini.in b/linuxcnc-tests/runtime-availability-regressions/tail.ini.in new file mode 100644 index 00000000..cdf6f940 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/tail.ini.in @@ -0,0 +1,7 @@ +# TELEOP release: latch the real servo-cycle tail and upstream INPOS during it. +[FIXTURE] +BASE = base.ini +[HAL] +HALFILE = tail.hal +[JOINT_1] +BACKLASH = 0.4 diff --git a/linuxcnc-tests/runtime-availability-regressions/test-ui.py b/linuxcnc-tests/runtime-availability-regressions/test-ui.py new file mode 100755 index 00000000..62770f37 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/test-ui.py @@ -0,0 +1,206 @@ +#!/usr/bin/env python3 +from fixture import * +from pathlib import Path + +if case == 'power': + release('joint.1') + pin('mux2.0.in1', 180); pin('mux2.0.sel', 1) + wait(lambda: abs(hal.get_value('joint.1.motor-pos-fb') - 180) < 1e-6, + 'live released C HAL feedback') + settle() + assert abs(s.actual_position[5]) < 1e-9 + assert abs(s.joint_position[1]) < 1e-9 + c.state(linuxcnc.STATE_OFF) + wait(lambda: not hal.get_value('joint.0.availability-request'), 'Machine Off release') + pin('joint.0.availability-ack', 0) + done(); settle() + assert abs(s.position[5]) < 1e-9, s.position + assert abs(hal.get_value('joint.1.pos-cmd')) < 1e-9 + c.state(linuxcnc.STATE_ON); done() + acquire('joint.0') + c.mode(linuxcnc.MODE_MDI); done() + c.mdi('G0 X2 Z3'); done() + assert abs(s.position[0] - 2) < 1e-6 and abs(s.position[2] - 3) < 1e-6 + assert abs(s.position[5]) < 1e-9 + assert abs(s.actual_position[5]) < 1e-9 + +elif case == 'index': + acquire('spindle.0') + c.mode(linuxcnc.MODE_MDI); done() + c.mdi('M3 S60'); done() + c.mdi('G33 Z1 K1') + wait(lambda: hal.get_value('spindle.0.index-enable'), 'first index wait') + c.abort(); done(); settle() + c.mode(linuxcnc.MODE_MANUAL); done() + release('spindle.0') + assert not hal.get_value('spindle.0.index-enable'), 'index latch survived release' + assert not hal.get_value('spindle.0.on') + assert hal.get_value('spindle.0.speed-out') == 0 + pin('spindle.0.index-enable', 1) + settle() + assert not hal.get_value('spindle.0.index-enable'), 'index latch reasserted while released' + acquire('spindle.0') + assert not hal.get_value('spindle.0.index-enable') + c.mode(linuxcnc.MODE_MDI); done() + c.mdi('M3 S60'); done() + c.mdi('G33 Z1 K1') + wait(lambda: hal.get_value('spindle.0.index-enable'), 'fresh index edge after reacquire') + pin('spindle.0.index-enable', 0) + settle() + assert not hal.get_value('spindle.0.index-enable'), 'encoder index handshake failed' + c.abort(); done() + +elif case in ('jogstop', 'joghome'): + release('joint.1') + c.teleop_enable(0); done() + c.set_joint_availability(1, True) + wait(lambda: hal.get_value('joint.1.availability-request'), 'acquisition waiting for ACK') + c.jog(linuxcnc.JOG_STOP, 1, 1) + settle() + assert hal.get_value('joint.1.availability-request'), 'jog stop canceled acquisition' + pin('joint.1.availability-ack', 1) + if case == 'joghome': + wait(lambda: hal.get_value('joint.1.index-enable'), 'acquisition homing index') + c.jog(linuxcnc.JOG_STOP, 1, 1) + settle() + assert hal.get_value('joint.1.index-enable'), 'jog stop canceled acquisition homing' + assert hal.get_value('joint.1.availability-request') + pin('joint.1.index-enable', 0) + done() + wait(lambda: s.joint[1]['available'], 'acquisition completed after jog stop') + +elif case == 'fault': + acquire('spindle.0') + run('dwell.ngc') + wait(lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY and + s.motion_mode == linuxcnc.TRAJ_MODE_COORD, 'coordinated dwell') + assert s.spindle[0]['availability_state'] == 3 + Path('abort-reasons.log').unlink(missing_ok=True) + pin('spindle.0.availability-ack', 0) + wait(lambda: s.interp_state == linuxcnc.INTERP_IDLE, 'task abort') + settle(1.3) + assert not hal.get_value('motion.digital-out-00'), 'program continued after ACK loss' + assert not s.enabled + reasons = [float(line) for line in Path('abort-reasons.log').read_text().splitlines()] + assert 3 in reasons, f'task did not handle motion RCS_ERROR: {reasons}' + # The resource fault stays visible, but acknowledged motion errors must + # not prevent a deliberate release, re-enable and new program. + c.abort(); done() + for resource in ('spindle.0',): + pin(resource + '.availability-ack', 0) + settle() + c.mode(linuxcnc.MODE_MANUAL); done() + for resource in ('spindle.0',): + release(resource) + c.state(linuxcnc.STATE_ON); done() + acquire('spindle.0') + run('dwell.ngc'); done() + wait(lambda: bool(hal.get_value('motion.digital-out-00')), 'deliberate recovery') + +elif case == 'wheel': + c.teleop_enable(1); done() + pin('axis.x.jog-enable', 1) + pin('axis.x.jog-scale', .1) + for cancel in (False, True): + before = hal.get_value('joint.0.pos-cmd') + c.set_spindle_availability(0, True) + wait(lambda: hal.get_value('spindle.0.availability-request'), 'wheel ACK wait') + counts = hal.get_value('axis.x.jog-counts') + pin('axis.x.jog-counts', counts + 10) + settle() + assert hal.get_value('joint.0.pos-cmd') == before + if cancel: + c.abort(); done() + else: + pin('spindle.0.availability-ack', 1); done() + settle(.3) + assert abs(hal.get_value('joint.0.pos-cmd') - before) < 1e-9, 'delayed inhibited wheel jog' + pin('axis.x.jog-counts', counts + 11) + wait(lambda: abs(hal.get_value('joint.0.pos-cmd') - before - .1) < 1e-6, + 'fresh wheel count') + if not cancel: + release('spindle.0') + +elif case == 'jointwheel': + c.teleop_enable(0); done() + release('joint.1') + pin('joint.1.jog-enable', 1) + pin('joint.1.jog-scale', .1) + before = hal.get_value('joint.1.pos-cmd') + counts = hal.get_value('joint.1.jog-counts') + pin('joint.1.jog-counts', counts + 10) + settle() + acquire('joint.1') + settle(.3) + assert abs(hal.get_value('joint.1.pos-cmd') - before) < 1e-9, \ + 'unavailable joint replayed stale wheel counts' + pin('joint.1.jog-counts', counts + 11) + wait(lambda: abs(hal.get_value('joint.1.pos-cmd') - before - .1) < 1e-6, + 'fresh joint wheel count') + wait(lambda: s.inpos, 'FREE jog completion') + release('joint.1') + assert not s.joint[1]['availability_fault'], 'FREE-mode release faulted' + +elif case == 'tail': + c.teleop_enable(1); done() + # Release may begin after logical motion finishes, but it must keep the + # hardware request asserted until interpolation and compensation settle. + for increment in (.01, .019): + before = hal.get_value('joint.1.pos-cmd') + for latch in (2, 3, 4): pin(f'flipflop.{latch}.reset', 1) + settle() + for latch in (2, 3, 4): pin(f'flipflop.{latch}.reset', 0) + c.jog(linuxcnc.JOG_INCREMENT, 0, 1, 1, increment) + wait(lambda: abs(s.joint_position[1] - before - increment) < 1e-6 + and hal.get_value('motion.in-position'), 'TELEOP endpoint') + # Task admission observes NML completion after the servo endpoint. + done() + assert hal.get_value('flipflop.2.out'), 'TELEOP interpolation tail not exercised' + assert hal.get_value('flipflop.3.out'), 'upstream INPOS did not precede interpolation completion' + c.set_joint_availability(1, False) + wait(lambda: not hal.get_value('joint.1.availability-request'), 'settled release') + assert not hal.get_value('flipflop.4.out'), \ + 'amplifier disabled before release tail settled' + held = hal.get_value('joint.1.pos-cmd') + settle(.02) + assert abs(hal.get_value('joint.1.backlash-vel')) < 1e-12 + assert abs(hal.get_value('joint.1.backlash-corr') - + hal.get_value('joint.1.backlash-filt')) < 1e-12 + pin('joint.1.availability-ack', 0); done() + x = s.joint_position[0] + c.jog(linuxcnc.JOG_INCREMENT, 0, 0, 1, .01) + wait(lambda: abs(s.joint_position[0] - x - .01) < 1e-6 + and hal.get_value('motion.in-position'), 'unrelated TELEOP move') + settle() + assert abs(hal.get_value('joint.1.pos-cmd') - held) < 1e-12, 'released TELEOP joint moved' + acquire('joint.1') + +elif case == 'amp': + release('joint.1') + pin('joint.1.amp-fault-in', 1) + pin('flipflop.0.reset', 1); settle() + pin('flipflop.0.reset', 0) + c.set_joint_availability(1, True) + wait(lambda: hal.get_value('joint.1.availability-request'), 'faulted acquisition') + pin('joint.1.availability-ack', 1) + wait(lambda: not s.enabled, 'fault inhibit') + settle() + assert not hal.get_value('flipflop.0.out'), 'amp-enable pulsed with amp-fault asserted' + +elif case == 'atspeed': + # A released spindle's at-speed input does not hold the at-speed wait of + # a feed on another spindle. + assert not s.spindle[0]['available'], 'spindle 0 not released' + run('atspeed.ngc') + wait(lambda: s.interp_state == linuxcnc.INTERP_IDLE + and abs(s.position[0] - 1) < .001, 'feed on spindle 1 held by released spindle 0') + +elif case == 'slowtask': + # fixture.py acquired joint 1, which homes through the queued home cycle + assert s.homed[1], s.homed + assert s.joint[1]['available'] + assert not errors, errors + +else: + raise AssertionError('unknown scenario ' + case) +print(f'availability regression {case} ok') diff --git a/linuxcnc-tests/runtime-availability-regressions/test.ini.in b/linuxcnc-tests/runtime-availability-regressions/test.ini.in new file mode 100644 index 00000000..67dab70a --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/test.ini.in @@ -0,0 +1,3 @@ +# Case-specific overrides; unspecified values come from FIXTURE.BASE. +[FIXTURE] +BASE = base.ini diff --git a/linuxcnc-tests/runtime-availability-regressions/test.sh b/linuxcnc-tests/runtime-availability-regressions/test.sh new file mode 100755 index 00000000..9ce4700d --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/test.sh @@ -0,0 +1,36 @@ +#!/bin/sh +set -eu +python3 ../runtime-availability/make-fixtures.py +for scenario in ${AVAILABILITY_REGRESSION_CASES:-fault wheel jointwheel tail amp power index jogstop joghome slowtask atspeed extra sequence}; do + ini=test.ini + case "$scenario" in + fault) ini=fault.ini ;; + tail) ini=tail.ini ;; + power) ini=xzc.ini ;; + joghome) ini=joghome.ini ;; + slowtask) ini=slowtask.ini ;; + atspeed) ini=atspeed.ini ;; + extra) + # Unsupported ownership must fail configuration, before Machine On. + if linuxcnc -r extra.ini >extra.log 2>&1; then + cat extra.log + echo 'extra-joint configuration unexpectedly accepted' >&2 + exit 1 + fi + cat extra.log + grep -q 'JOINT_2: availability configuration rejected' extra.log + echo 'availability regression extra ok' + continue ;; + sequence) + if linuxcnc -r sequence.ini >sequence.log 2>&1; then + cat sequence.log + echo 'availability HOME_SEQUENCE configuration unexpectedly accepted' >&2 + exit 1 + fi + cat sequence.log + grep -q 'JOINT_1: HOME_SEQUENCE cannot be used with AVAILABILITY_CONTROL' sequence.log + echo 'availability regression sequence ok' + continue ;; + esac + AVAILABILITY_REGRESSION_CASE=$scenario linuxcnc -r "$ini" +done diff --git a/linuxcnc-tests/runtime-availability-regressions/tool.tbl b/linuxcnc-tests/runtime-availability-regressions/tool.tbl new file mode 100644 index 00000000..a5800196 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/tool.tbl @@ -0,0 +1 @@ +T1 P1 Z0 ; test diff --git a/linuxcnc-tests/runtime-availability-regressions/xzc.hal b/linuxcnc-tests/runtime-availability-regressions/xzc.hal new file mode 100644 index 00000000..5c7ef3f3 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/xzc.hal @@ -0,0 +1,12 @@ +loadrt trivkins coordinates=XCZ +loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_spindles=1 +loadrt mux2 count=1 +addf mux2.0 servo-thread +addf motion-command-handler servo-thread +addf motion-controller servo-thread +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Ccmd joint.1.motor-pos-cmd => mux2.0.in0 +net Cfb mux2.0.out => joint.1.motor-pos-fb +net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in +setp spindle.0.at-speed true diff --git a/linuxcnc-tests/runtime-availability-regressions/xzc.ini.in b/linuxcnc-tests/runtime-availability-regressions/xzc.ini.in new file mode 100644 index 00000000..ada93986 --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/xzc.ini.in @@ -0,0 +1,17 @@ +[FIXTURE] +BASE = base.ini +[TRAJ] +COORDINATES = XCZ +[KINS] +KINEMATICS = trivkins coordinates=XCZ +[HAL] +HALFILE = xzc.hal +[AXIS_C] +MIN_LIMIT = -360 +MAX_LIMIT = 360 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +[JOINT_1] +TYPE = ANGULAR +MIN_LIMIT = -360 +MAX_LIMIT = 360 diff --git a/linuxcnc-tests/runtime-availability/.gitignore b/linuxcnc-tests/runtime-availability/.gitignore new file mode 100644 index 00000000..425d52b6 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/.gitignore @@ -0,0 +1,2 @@ +/*.ini +!/base.ini diff --git a/linuxcnc-tests/runtime-availability/README b/linuxcnc-tests/runtime-availability/README new file mode 100644 index 00000000..bdfd8cc4 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/README @@ -0,0 +1,8 @@ +Userspace POSIX simulation: actual target enforcement, released-joint MDI eligibility, late ACK cancellation, held-position validation, and homing abort cleanup. +Cancellation waits for actual homing velocity and checks stationary completion and reacquisition. +Direct admission rejects dwell/queued MDI and paused AUTO, overlaps (including no-ops and other resources), and interpretation/jogging before completion. With forced homing enabled, Home All skips unavailable controlled joints, first acquisition homes an unhomed nonvolatile joint, and controlled joints reject user HOME/UNHOME outside acquisition. Later nonvolatile acquisition preserves a matching held position and rejects changed or non-finite feedback without publishing availability. Volatile acquisition accepts arbitrary unavailable movement only through successful homing. Abort during ACK wait and moving homing cannot be revived by late ACK; later reacquisition succeeds. + +INI fixtures are generated by test.sh from the shared FIXTURE.BASE and local +*.ini.in overrides. Run python3 ../runtime-availability/make-fixtures.py before +launching an individual case directly. @unset explicitly removes an inherited +key. Generated INIs are ignored; edit the base or the case override instead. diff --git a/linuxcnc-tests/runtime-availability/base.ini b/linuxcnc-tests/runtime-availability/base.ini new file mode 100644 index 00000000..c8e0eab3 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/base.ini @@ -0,0 +1,99 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0x0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 0 +AXES = 3 +COORDINATES = XYZ +SPINDLES = 1 +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 10 +MAX_LINEAR_VELOCITY = 50 + +[EMCIO] +TOOL_TABLE = tool.tbl + +[KINS] +KINEMATICS = trivkins coordinates=XYZ +JOINTS = 3 + +[AXIS_X] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 + +[JOINT_0] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 + +HOME_SEQUENCE = 0 +HOME_SEARCH_VEL = 0 +HOME_LATCH_VEL = 0 +[AXIS_Y] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +[AXIS_Z] +MIN_LIMIT = -100 +MAX_LIMIT = 100 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +[JOINT_1] +TYPE = LINEAR +HOME = 0 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 +AVAILABILITY_CONTROL = 1 +AVAILABILITY_TIMEOUT = 2 +VOLATILE_HOME = 0 +[JOINT_2] +TYPE = LINEAR +HOME = 0 +HOME_SEARCH_VEL = 1 +HOME_LATCH_VEL = 0.1 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 +MIN_LIMIT = -100 +MAX_LIMIT = 100 +FERROR = 1 +MIN_FERROR = 0.25 +AVAILABILITY_CONTROL = 1 +AVAILABILITY_TIMEOUT = 2 +VOLATILE_HOME = 1 +[SPINDLE_0] +AVAILABILITY_CONTROL = 1 +INITIAL_AVAILABILITY = 0 +AVAILABILITY_TIMEOUT = 2 diff --git a/linuxcnc-tests/runtime-availability/checkresult b/linuxcnc-tests/runtime-availability/checkresult new file mode 100755 index 00000000..12624ae5 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/checkresult @@ -0,0 +1,4 @@ +#!/bin/sh +set -e +grep -q "^runtime availability scenarios ok$" "$1" +grep -q "^initial availability scenarios ok$" "$1" diff --git a/linuxcnc-tests/runtime-availability/core_sim.hal b/linuxcnc-tests/runtime-availability/core_sim.hal new file mode 100644 index 00000000..62edf534 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/core_sim.hal @@ -0,0 +1,17 @@ +loadrt trivkins coordinates=XYZ +loadrt motmod base_period_nsec=0 servo_period_nsec=1000000 traj_period_nsec=4000000 num_joints=3 num_spindles=1 +loadrt mux2 count=2 +addf mux2.0 servo-thread +addf mux2.1 servo-thread +addf motion-command-handler servo-thread +addf motion-controller servo-thread +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Ycmd joint.1.motor-pos-cmd => mux2.0.in0 +net Yfb mux2.0.out => joint.1.motor-pos-fb +net Zcmd joint.2.motor-pos-cmd => mux2.1.in0 +net Zfb mux2.1.out => joint.2.motor-pos-fb +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in +setp spindle.0.at-speed true +loadrt flipflop count=1 +addf flipflop.0 servo-thread +net enable-seen motion.motion-enabled => flipflop.0.set diff --git a/linuxcnc-tests/runtime-availability/initial-ui.py b/linuxcnc-tests/runtime-availability/initial-ui.py new file mode 100755 index 00000000..1c30ffab --- /dev/null +++ b/linuxcnc-tests/runtime-availability/initial-ui.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +import time +import linuxcnc +import hal +h = hal.component('initial-availability-test'); h.ready() +c = linuxcnc.command(); s = linuxcnc.stat() +def wait(fn, msg): + end = time.monotonic() + 8 + while time.monotonic() < end: + s.poll() + if fn(): return + time.sleep(.005) + raise AssertionError(msg) +def pin(n, v): hal.set_p(n, str(v)) +wait(lambda: s.task_state == linuxcnc.STATE_ESTOP, 'startup') +c.state(linuxcnc.STATE_ESTOP_RESET); c.wait_complete(3) +c.state(linuxcnc.STATE_ON) +wait(lambda: hal.get_value('spindle.0.availability-request'), 'initial request') +pin('motion.enable', 0) +pin('spindle.0.availability-ack', 1) +time.sleep(.05); s.poll() +assert not s.enabled and not hal.get_value('flipflop.0.out') +assert not hal.get_value('spindle.0.available') +pin('spindle.0.availability-ack', 0) +c.state(linuxcnc.STATE_OFF); c.wait_complete(3) +c.set_spindle_availability(0, False); c.wait_complete(3) +pin('motion.enable', 1) +c.state(linuxcnc.STATE_ON) +wait(lambda: hal.get_value('spindle.0.availability-request'), 'retry request') +c.abort() +wait(lambda: not hal.get_value('spindle.0.availability-request'), 'abort request') +pin('spindle.0.availability-ack', 1) +time.sleep(.05); s.poll() +assert not s.enabled and not hal.get_value('flipflop.0.out') +pin('spindle.0.availability-ack', 0) +c.state(linuxcnc.STATE_OFF); c.wait_complete(3) +c.set_spindle_availability(0, False); c.wait_complete(3) +c.state(linuxcnc.STATE_ON) +wait(lambda: hal.get_value('spindle.0.availability-request'), 'initial spindle request') +# Repeated On while the initial scan is already pending must not restart it. +c.state(linuxcnc.STATE_ON) +time.sleep(.02) +assert hal.get_value('spindle.0.availability-request') +pin('spindle.0.availability-ack', 1) +assert c.wait_complete(5) == linuxcnc.RCS_DONE +wait(lambda: s.enabled, 'machine on') +assert not s.joint[1]['available'] and not s.joint[2]['available'] +# Initial availability is startup policy, not a permanent ownership requirement. +c.set_spindle_availability(0, False) +wait(lambda: not hal.get_value('spindle.0.availability-request'), 'release initial spindle') +pin('spindle.0.availability-ack', 0) +assert c.wait_complete(5) == linuxcnc.RCS_DONE +c.state(linuxcnc.STATE_ON) +assert c.wait_complete(5) == linuxcnc.RCS_DONE +time.sleep(.1); s.poll() +assert s.enabled and not s.spindle[0]['available'] +assert not hal.get_value('spindle.0.availability-request') +print('initial availability scenarios ok') diff --git a/linuxcnc-tests/runtime-availability/initial.ini.in b/linuxcnc-tests/runtime-availability/initial.ini.in new file mode 100644 index 00000000..3b9c37cc --- /dev/null +++ b/linuxcnc-tests/runtime-availability/initial.ini.in @@ -0,0 +1,9 @@ +# Case-specific overrides; unspecified values come from FIXTURE.BASE. +[FIXTURE] +BASE = base.ini + +[DISPLAY] +DISPLAY = ./initial-ui.py + +[SPINDLE_0] +INITIAL_AVAILABILITY = 1 diff --git a/linuxcnc-tests/runtime-availability/make-fixtures.py b/linuxcnc-tests/runtime-availability/make-fixtures.py new file mode 100644 index 00000000..3e7e61f9 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/make-fixtures.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Materialize local *.ini.in cases from a shared base and explicit overrides. + +Run in the suite directory (test.sh does this automatically). @unset removes +an inherited key; all other strings are copied verbatim. Paths remain relative +to the suite, just as in the original standalone fixtures. +""" +import configparser +from pathlib import Path + + +def read(path): + ini = configparser.ConfigParser(interpolation=None) + ini.optionxform = str + with path.open() as stream: + ini.read_file(stream) + return ini + + +for template in sorted(Path('.').glob('*.ini.in')): + overrides = read(template) + ini = read(template.parent / overrides['FIXTURE']['BASE']) + overrides.remove_section('FIXTURE') + for section in overrides.sections(): + if not ini.has_section(section): + ini.add_section(section) + for key, value in overrides[section].items(): + if value == '@unset': + ini.remove_option(section, key) + else: + ini[section][key] = value + with template.with_suffix('').open('w') as stream: + stream.write('# Generated by make-fixtures.py; edit the .ini.in case.\n') + ini.write(stream) diff --git a/linuxcnc-tests/runtime-availability/paused.ngc b/linuxcnc-tests/runtime-availability/paused.ngc new file mode 100644 index 00000000..c9e6f8a6 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/paused.ngc @@ -0,0 +1,3 @@ +M0 +G90 G0 X0.5 +M2 diff --git a/linuxcnc-tests/runtime-availability/test-ui.py b/linuxcnc-tests/runtime-availability/test-ui.py new file mode 100755 index 00000000..1f435daf --- /dev/null +++ b/linuxcnc-tests/runtime-availability/test-ui.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +import time +import os +import linuxcnc +import hal +h = hal.component("availability-test") +h.ready() +c = linuxcnc.command() +s = linuxcnc.stat() +e = linuxcnc.error_channel() +def wait(fn, message, timeout=8): + end = time.monotonic() + timeout + while time.monotonic() < end: + s.poll() + # Expected rejection diagnostics must not fill the bounded NML error + # channel and block task while later scenarios wait for completion. + while e.poll() is not None: + pass + if fn(): return + time.sleep(.005) + raise AssertionError('%s: task=%s exec=%s joints=%r spindle=%r error=%r' % + (message, s.task_state, s.exec_state, + [(j['availability_state'], j['availability_fault']) for j in s.joint], + s.spindle[0], e.poll())) +def done(): + assert c.wait_complete(8) == linuxcnc.RCS_DONE, "command failed: %r" % (e.poll(),) + s.poll() +def pin(name, value): hal.set_p(name, str(value)) +def manual(): + c.mode(linuxcnc.MODE_MANUAL); done() + c.teleop_enable(0); done() +def mdi(code): c.mdi(code); done() +def reset(): + c.state(linuxcnc.STATE_OFF); c.wait_complete(2) + for n in (1, 2): pin('joint.%d.availability-ack' % n, 0) + pin('spindle.0.availability-ack', 0) + time.sleep(.05) + for n in (1, 2): + c.set_joint_availability(n, False); c.wait_complete(2) + c.set_spindle_availability(0, False); c.wait_complete(2) + wait(lambda: all(s.joint[n]['availability_state'] == 0 for n in (1,2)), 'release') + pin('motion.enable', 1) + c.state(linuxcnc.STATE_ESTOP_RESET); done() + c.state(linuxcnc.STATE_ON); done() + manual() + c.home(-1); done() + wait(lambda: s.homed[0], 'Home All homes X') + assert all(not s.joint[n]['homing'] for n in (1,2)) + assert not s.joint[2]['homed'] + assert all(not hal.get_value('joint.%d.availability-request' % n) for n in (1,2)) +wait(lambda: s.task_state == linuxcnc.STATE_ESTOP, 'startup') +reset() +# Motion can be DONE while task is dwelling with more MDI work queued. +c.mode(linuxcnc.MODE_MDI); done() +c.mdi('G4 P2') +wait(lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY, 'active dwell') +c.mdi('G0 X0.25') +assert c.wait_complete(.05) == -1 +c.mdi('G0 X0.5') +wait(lambda: s.queued_mdi_commands > 0, 'queued MDI') +for request in (lambda: c.set_joint_availability(1, True), + lambda: c.set_spindle_availability(0, True)): + request() + assert c.wait_complete(.2) == linuxcnc.RCS_ERROR, 'busy direct request queued' + assert not hal.get_value('joint.1.availability-request') + assert not hal.get_value('spindle.0.availability-request') +wait(lambda: s.interp_state == linuxcnc.INTERP_IDLE and + s.exec_state == linuxcnc.EXEC_DONE, 'queued work completion') +assert abs(s.joint_position[0] - .5) < .001 +c.mode(linuxcnc.MODE_AUTO); done() +c.program_open(os.path.abspath('paused.ngc')); done() +c.auto(linuxcnc.AUTO_RUN, 0) +wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED, 'paused AUTO') +c.set_joint_availability(1, False) +assert c.wait_complete(.2) == linuxcnc.RCS_ERROR, 'paused AUTO accepted direct no-op' +c.auto(linuxcnc.AUTO_RESUME); done() +manual() +# All overlaps, including duplicate/no-op requests, must leave the first intact. +c.set_spindle_availability(0, True) +wait(lambda: hal.get_value('spindle.0.availability-request'), 'original spindle request') +for request in (lambda: c.set_spindle_availability(0, True), + lambda: c.set_spindle_availability(0, False), + lambda: c.set_joint_availability(1, True), + lambda: c.set_joint_availability(1, False), + lambda: c.mode(linuxcnc.MODE_MDI), + lambda: c.jog(linuxcnc.JOG_INCREMENT, 1, 0, 1, 1)): + request() + assert c.wait_complete(.2) == linuxcnc.RCS_ERROR + assert hal.get_value('spindle.0.availability-request'), 'overlap canceled owner' + assert not hal.get_value('joint.1.availability-request') +pin('spindle.0.availability-ack', 1) +wait(lambda: s.spindle[0]['available'] and s.exec_state == linuxcnc.EXEC_DONE, + 'original request completion') +c.set_spindle_availability(0, False) +wait(lambda: not hal.get_value('spindle.0.availability-request'), 'spindle release') +pin('spindle.0.availability-ack', 0); done() +# A released spindle's amplifier may report not-ready while axes remain usable. +pin('spindle.0.amp-fault-in', 1) +c.mode(linuxcnc.MODE_MDI); done() +mdi('G0 X0.75') +assert s.enabled and abs(s.joint_position[0] - .75) < .001 +manual() +c.set_spindle_availability(0, True) +wait(lambda: hal.get_value('spindle.0.availability-request'), 'faulted spindle acquire') +assert s.enabled, 'pending spindle acquisition enabled fault checking too early' +pin('spindle.0.availability-ack', 1) +wait(lambda: not s.enabled, 'reacquired spindle amplifier fault did not disable motion') +pin('spindle.0.amp-fault-in', 0) +reset() +# Deliberately released unhomed joints permit unrelated MDI and explicit no-op Y. +c.mode(linuxcnc.MODE_MDI); done() +mdi('G0 X1 Y0 Z0') +assert abs(s.joint_position[0]-1) < .01 +# First prohibited actual target faults the whole coordinated operation. +c.mdi('G1 X10 Y10 F60') +wait(lambda: s.task_state != linuxcnc.STATE_ON, 'illegal Y did not fault') +assert abs(s.joint_position[1]) < 1e-9 +reset() +# Direct joint jogging is rejected; teleop uses the same actual-target guard. +c.teleop_enable(0); done() +wait(lambda: s.motion_mode == linuxcnc.TRAJ_MODE_FREE, "joint mode") +c.jog(linuxcnc.JOG_INCREMENT, 1, 1, 1, 1) +assert c.wait_complete(3) == linuxcnc.RCS_ERROR +assert abs(s.joint_position[1]) < 1e-9 +c.abort(); done() +c.teleop_enable(1); done() +wait(lambda: s.motion_mode == linuxcnc.TRAJ_MODE_TELEOP, "teleop mode") +c.jog(linuxcnc.JOG_INCREMENT, 0, 1, 1, 1) +wait(lambda: not s.enabled, 'illegal teleop target did not fault') +assert abs(s.joint_position[1]) < 1e-9 +reset() +# Abort then late ACK cannot complete a pending acquisition. +c.set_joint_availability(1, True) +wait(lambda: s.joint[1]['availability_state'] == 1, 'pending acquisition') +c.abort(); c.wait_complete(2) +pin('joint.1.availability-ack', 1) +time.sleep(.05); s.poll() +assert not s.joint[1]['available'] +assert not hal.get_value('joint.1.amp-enable-out') +# Clear the fault explicitly after hardware ACK goes low. +pin('joint.1.availability-ack', 0) +c.set_joint_availability(1, False); c.wait_complete(2) +reset() +# Enable withdrawal followed by a late ACK revokes runtime acquisition. +c.set_joint_availability(1, True) +wait(lambda: s.joint[1]['availability_state'] == 1, 'second acquisition') +pin('motion.enable', 0) +pin('joint.1.availability-ack', 1) +time.sleep(.05); s.poll() +assert not s.enabled and not s.joint[1]['available'] +pin('joint.1.availability-ack', 0) +c.set_joint_availability(1, False); c.wait_complete(2) +reset() +# Establish synchronization while acquired, then clear it after release. +c.set_spindle_availability(0, True) +wait(lambda: hal.get_value('spindle.0.availability-request'), 'spindle request') +pin('spindle.0.availability-ack', 1); done() +c.mode(linuxcnc.MODE_MDI); done() +mdi('G95 F1') +manual() +c.set_spindle_availability(0, False) +wait(lambda: not hal.get_value('spindle.0.availability-request'), 'spindle release') +pin('spindle.0.availability-ack', 0); done() +c.mode(linuxcnc.MODE_MDI); done() +mdi('G94') +manual() +# An unhomed nonvolatile joint homes on first acquisition. Ordinary individual +# HOME/UNHOME commands cannot bypass availability ownership. +held = hal.get_value('joint.1.pos-cmd') +c.set_joint_availability(1, True) +wait(lambda: hal.get_value('joint.1.availability-request'), 'request Y') +pin('joint.1.availability-ack', 1); done() +wait(lambda: s.joint[1]['available'] and s.joint[1]['homed'], 'home and acquire Y') +assert abs(hal.get_value('joint.1.pos-cmd') - held) < 1e-12 +c.home(1) +assert c.wait_complete(3) == linuxcnc.RCS_ERROR +c.abort(); done(); manual() +c.unhome(1) +assert c.wait_complete(3) == linuxcnc.RCS_ERROR +c.unhome(-1) +assert c.wait_complete(3) == linuxcnc.RCS_ERROR +c.abort(); done(); manual() +assert s.homed[0] and s.joint[1]['available'] and s.joint[1]['homed'] +# Release freezes the logical joint and Cartesian pose. External feedback remains +# visible at HAL, but a material mismatch rejects acquisition. +held = hal.get_value('joint.1.pos-cmd') +c.set_joint_availability(1, False) +wait(lambda: not hal.get_value('joint.1.availability-request'), 'direct release') +pin('joint.1.availability-ack', 0); done() +pin('mux2.0.in1', hal.get_value('joint.1.motor-pos-fb') + 3) +pin('mux2.0.sel', 1) +time.sleep(.05); s.poll() +assert abs(hal.get_value('joint.1.motor-pos-fb') - (held + 3)) < 1e-6 +assert abs(s.joint_position[1] - held) < 1e-9 +assert abs(hal.get_value('joint.1.pos-fb') - held) < 1e-9 +c.set_joint_availability(1, True) +wait(lambda: hal.get_value('joint.1.availability-request'), 'mismatching acquire') +pin('joint.1.availability-ack', 1) +wait(lambda: s.joint[1]['availability_fault'] == 8, 'position mismatch fault') +assert not s.joint[1]['available'] +assert not hal.get_value('joint.1.amp-enable-out') +assert abs(hal.get_value('joint.1.pos-cmd') - held) < 1e-12 +assert abs(s.joint_position[1] - held) < 1e-9 +pin('joint.1.availability-ack', 0) +pin('mux2.0.sel', 0) +reset() +# Runtime volatile acquisition may home, but cancellation must clean it up. +pin('mux2.1.in1', 7); pin('mux2.1.sel', 1) +time.sleep(.05); s.poll() +assert abs(hal.get_value('joint.2.motor-pos-fb') - 7) < 1e-6 +assert abs(s.joint_position[2]) < 1e-9 +c.set_joint_availability(2, True) +wait(lambda: hal.get_value('joint.2.availability-request'), 'request Z') +pin('joint.2.availability-ack', 1) +wait(lambda: s.joint[2]['availability_state'] == 2, 'hardware ACK enters homing') +assert not s.joint[2]['available'] and not s.joint[2]['homed'] +pin('mux2.1.sel', 0) +for state, switch in [(7, 1), (10, 0), (12, 1)]: + wait(lambda: hal.get_value('joint.2.home-state') == state, 'home switch phase %d' % state) + assert not hal.get_value('joint.2.available') + assert c.wait_complete(.02) == -1, 'completed before required homing' + pin('joint.2.home-sw-in', switch) +done() +wait(lambda: s.joint[2]['available'] and s.joint[2]['homed'], 'completed home') +c.set_joint_availability(2, False) +wait(lambda: not hal.get_value('joint.2.availability-request'), 'release homed Z') +pin('joint.2.availability-ack', 0); done() + +# A later volatile acquisition remains unavailable until homing completes, and +# cancellation leaves it unavailable and unreferenced. +c.set_joint_availability(2, True) +wait(lambda: hal.get_value('joint.2.availability-request'), 'request Z') +pin('joint.2.availability-ack', 1) +wait(lambda: abs(hal.get_value('joint.2.vel-cmd')) > .1, 'moving runtime home Z') +c.set_joint_availability(2, False) +assert c.wait_complete(.2) == linuxcnc.RCS_ERROR, 'release canceled acquisition homing' +assert hal.get_value('joint.2.availability-request') +c.abort() +wait(lambda: not hal.get_value('joint.2.availability-request'), 'cancel request') +assert c.wait_complete(.03) == -1, 'Abort completed before release ACK/cleanup' +pin('joint.2.availability-ack', 0) +done() +wait(lambda: not s.joint[2]['homing'] and s.joint[2]['availability_state'] == 0, 'homing abort cleanup') +assert not hal.get_value('joint.2.amp-enable-out') +assert not hal.get_value('joint.2.active') +assert s.joint[2]['inpos'], 'released joint not complete' +wait(lambda: hal.get_value('joint.2.vel-cmd') == 0, 'homing velocity stopped') +wait(lambda: s.state == linuxcnc.RCS_DONE, 'normal completion after cancellation') +# Late hardware acknowledgement cannot revive cancelled homing. +pin('joint.2.availability-ack', 1) +time.sleep(.05); s.poll() +assert not s.joint[2]['available'] and not hal.get_value('joint.2.amp-enable-out') +pin('joint.2.availability-ack', 0) +reset() +# A fresh acquisition can complete homing and only then become available. +pin('joint.2.home-sw-in', 0) +c.set_joint_availability(2, True) +wait(lambda: hal.get_value('joint.2.availability-request'), 'fresh request Z') +pin('joint.2.availability-ack', 1) +for state, switch in [(7, 1), (10, 0), (12, 1)]: + wait(lambda: hal.get_value('joint.2.home-state') == state, 'home switch phase %d' % state) + assert not hal.get_value('joint.2.available') + assert c.wait_complete(.02) == -1, 'completed before required homing' + pin('joint.2.home-sw-in', switch) +done() +wait(lambda: s.joint[2]['available'] and s.joint[2]['homed'], 'completed home') +time.sleep(.05) +assert abs(hal.get_value('joint.2.free-pos-cmd') - s.joint_position[2]) < 1e-5 +# Losing an acquired ACK inhibits the actuator and propagates a fault. +pin('joint.2.availability-ack', 0) +wait(lambda: s.joint[2]['availability_fault'] != 0, 'ACK loss fault') +assert not hal.get_value('joint.2.amp-enable-out') +# A release timeout is failure, even though the actuator is already inhibited. +reset() +c.set_spindle_availability(0, True) +wait(lambda: hal.get_value('spindle.0.availability-request'), 'timeout setup acquire') +pin('spindle.0.availability-ack', 1); done() +c.set_spindle_availability(0, False) +assert c.wait_complete(5) == linuxcnc.RCS_ERROR, 'release timeout reported success' +s.poll() +assert s.spindle[0]['availability_fault'] == 3 +# Invalid reacquisition feedback must fail explicitly, never publish AVAILABLE. +reset() +c.set_joint_availability(1, True) +wait(lambda: hal.get_value('joint.1.availability-request'), 'invalid-feedback home setup') +pin('joint.1.availability-ack', 1); done() +assert s.joint[1]['available'] and s.joint[1]['homed'] +c.set_joint_availability(1, False) +wait(lambda: not hal.get_value('joint.1.availability-request'), 'invalid-feedback release setup') +pin('joint.1.availability-ack', 0); done() +pin('mux2.0.in1', 'nan'); pin('mux2.0.sel', 1) +c.set_joint_availability(1, True) +wait(lambda: hal.get_value('joint.1.availability-request'), 'invalid-feedback request') +pin('joint.1.availability-ack', 1) +wait(lambda: s.joint[1]['availability_fault'] == 8, 'invalid-feedback position mismatch') +assert not s.joint[1]['available'] and not hal.get_value('joint.1.amp-enable-out') +print('runtime availability scenarios ok') diff --git a/linuxcnc-tests/runtime-availability/test.ini.in b/linuxcnc-tests/runtime-availability/test.ini.in new file mode 100644 index 00000000..67dab70a --- /dev/null +++ b/linuxcnc-tests/runtime-availability/test.ini.in @@ -0,0 +1,3 @@ +# Case-specific overrides; unspecified values come from FIXTURE.BASE. +[FIXTURE] +BASE = base.ini diff --git a/linuxcnc-tests/runtime-availability/test.sh b/linuxcnc-tests/runtime-availability/test.sh new file mode 100755 index 00000000..9a17bf24 --- /dev/null +++ b/linuxcnc-tests/runtime-availability/test.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -e +python3 ../runtime-availability/make-fixtures.py +linuxcnc -r test.ini +linuxcnc -r initial.ini diff --git a/linuxcnc-tests/runtime-availability/tool.tbl b/linuxcnc-tests/runtime-availability/tool.tbl new file mode 100644 index 00000000..e69de29b diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/.gitignore b/linuxcnc-tests/task/interp-reset-requires-idle/.gitignore new file mode 100644 index 00000000..f7f21f13 --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/.gitignore @@ -0,0 +1 @@ +/tool.tbl diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/README b/linuxcnc-tests/task/interp-reset-requires-idle/README new file mode 100644 index 00000000..ef58eb27 --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/README @@ -0,0 +1,5 @@ +An interpreter re-init (EMC_TASK_PLAN_INIT, reset_interpreter() in Python) +restores the startup modes, so task refuses it unless the machine is at +rest. The test checks that a reset during an MDI move, a dwell and a +continuous jog is refused with an operator error and leaves the modes alone, +and that the same reset succeeds once the machine is idle again. diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/checkresult b/linuxcnc-tests/task/interp-reset-requires-idle/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py b/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py new file mode 100755 index 00000000..d7b20920 --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py @@ -0,0 +1,192 @@ +#!/usr/bin/env python3 +# +# Check that task refuses an interpreter reset while the machine is busy and +# accepts it once the machine is idle. + +import sys +import time + +import linuxcnc + +c = linuxcnc.command() +s = linuxcnc.stat() +e = linuxcnc.error_channel() + + +def fail(msg): + print("FAIL: %s" % msg) + sys.exit(1) + + +def wait_for(cond, what, timeout=10.0): + start = time.time() + while time.time() - start < timeout: + s.poll() + if cond(): + return + time.sleep(0.02) + fail("timeout waiting for %s: task_state=%d mode=%d interp_state=%d " + "exec_state=%d queue=%d inpos=%d" % (what, s.task_state, s.task_mode, + s.interp_state, s.exec_state, s.queue, s.inpos)) + + +def set_state(state): + c.state(state) + c.wait_complete() + wait_for(lambda: s.task_state == state, "task state %d" % state) + + +def set_mode(mode): + c.mode(mode) + c.wait_complete() + wait_for(lambda: s.task_mode == mode, "task mode %d" % mode) + + +def drain_errors(): + while e.poll(): + pass + + +def wait_idle(what): + wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE + and s.exec_state == linuxcnc.EXEC_DONE + and s.queue == 0 and s.inpos and s.current_vel == 0.0, + what) + + +def incremental(): + s.poll() + return 910 in s.gcodes + + +def mdi(code): + set_mode(linuxcnc.MODE_MDI) + c.mdi(code) + c.wait_complete() + + +def expect_reset_refused(name): + drain_errors() + c.reset_interpreter() + c.wait_complete() + deadline = time.time() + 5.0 + while time.time() < deadline: + msg = e.poll() + if msg: + if "interpreter reset refused" in msg[1]: + break + fail("%s: unexpected error %r" % (name, msg[1])) + time.sleep(0.02) + else: + fail("%s: reset was not refused" % name) + if not incremental(): + fail("%s: refused reset still restored the startup modes" % name) + print("%s: refused" % name, flush=True) + + +def expect_reset_accepted(name): + drain_errors() + c.reset_interpreter() + c.wait_complete() + wait_for(lambda: 900 in s.gcodes, "%s: reset to restore G90" % name) + msg = e.poll() + if msg: + fail("%s: unexpected error %r" % (name, msg[1])) + print("%s: ok" % name, flush=True) + + +def abort_and_settle(name): + c.abort() + c.wait_complete() + wait_idle("%s: abort to finish" % name) + + +wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP, "task to start") +# Task is still busy with its startup work for a few cycles. +wait_idle("task startup to finish") + +# Startup work that status does not show (the interpreter synch task queues) +# can still refuse the first reset on a loaded machine; retry until it ends. +deadline = time.time() + 10.0 +while True: + drain_errors() + c.reset_interpreter() + c.wait_complete() + time.sleep(0.2) + msg = e.poll() + if not msg: + break + if "interpreter reset refused" not in msg[1] or time.time() > deadline: + fail("startup: unexpected error %r" % msg[1]) + +# Resets of a machine at rest are allowed in every state and mode. +mdi_g91 = lambda: mdi("G91") +expect_reset_accepted("E-stop") +set_state(linuxcnc.STATE_ESTOP_RESET) +set_state(linuxcnc.STATE_ON) +mdi_g91() +expect_reset_accepted("idle MDI") +mdi_g91() +set_mode(linuxcnc.MODE_MANUAL) +expect_reset_accepted("idle manual") + +# An MDI move at 60 mm/min takes 5 s for 5 mm. +mdi_g91() +c.mdi("G1 X5 F60") +wait_for(lambda: s.current_vel > 0.0, "MDI move to start") +expect_reset_refused("MDI move") +s.poll() +if s.current_vel <= 0.0: + fail("MDI move: the refused reset stopped the move") +abort_and_settle("MDI move") +expect_reset_accepted("after aborted MDI move") + +# A dwell keeps task busy without any motion. +mdi_g91() +c.mdi("G4 P3") +wait_for(lambda: s.exec_state != linuxcnc.EXEC_DONE, "dwell to start") +expect_reset_refused("dwell") +abort_and_settle("dwell") +expect_reset_accepted("after aborted dwell") + +# A continuous teleop jog moves the machine outside any program. +mdi_g91() +set_mode(linuxcnc.MODE_MANUAL) +c.teleop_enable(1) +c.wait_complete() +c.jog(linuxcnc.JOG_CONTINUOUS, False, 0, 1.0) +wait_for(lambda: s.current_vel > 0.0, "jog to start") +expect_reset_refused("jog") +c.jog(linuxcnc.JOG_STOP, False, 0) +c.wait_complete() +wait_idle("jog to stop") +expect_reset_accepted("after stopped jog") + +# A tool edit holds the interpreter back until it is done, and the wait must +# not outlive the edit: an idle machine accepts a reset afterwards. +def edit_tool(z): + c.tool_offset(1, z, 0.0, 0.0, 0.0, 0.0, 0) + c.wait_complete() + + +mdi_g91() +edit_tool(1.0) +wait_idle("tool edit in idle MDI to finish") +expect_reset_accepted("after tool edit in idle MDI") +mdi_g91() +set_mode(linuxcnc.MODE_MANUAL) +edit_tool(2.0) +wait_idle("tool edit in manual to finish") +expect_reset_accepted("after tool edit in manual") + +# The same edit sent while an MDI move runs. +mdi_g91() +c.mdi("G1 X-3 F60") +wait_for(lambda: s.current_vel > 0.0, "MDI move to start") +edit_tool(3.0) +wait_idle("MDI move with tool edit to finish") +expect_reset_accepted("after tool edit during MDI move") + +print("all scenarios passed") +set_state(linuxcnc.STATE_ESTOP) +sys.exit(0) diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/test.ini b/linuxcnc-tests/task/interp-reset-requires-idle/test.ini new file mode 100644 index 00000000..2b489c08 --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test.ini @@ -0,0 +1,96 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var +RS274NGC_STARTUP_CODE = G21 G90 + +[EMCIO] +TOOL_TABLE = tool.tbl + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = LIB:core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +AXES = 3 +COORDINATES = X Y Z +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 4 +MAX_LINEAR_VELOCITY = 4 + +[KINS] +KINEMATICS = trivkins +JOINTS = 3 + +[AXIS_X] +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 + +[JOINT_0] +TYPE = LINEAR +HOME = 0.000 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +FERROR = 0.050 +MIN_FERROR = 0.010 + +[AXIS_Y] +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 + +[JOINT_1] +TYPE = LINEAR +HOME = 0.000 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -40.0 +MAX_LIMIT = 40.0 +FERROR = 0.050 +MIN_FERROR = 0.010 + +[AXIS_Z] +MIN_LIMIT = -4.0 +MAX_LIMIT = 4.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 + +[JOINT_2] +TYPE = LINEAR +HOME = 0.0 +MAX_VELOCITY = 4 +MAX_ACCELERATION = 1000.0 +BACKLASH = 0.000 +INPUT_SCALE = 4000 +OUTPUT_SCALE = 1.000 +MIN_LIMIT = -4.0 +MAX_LIMIT = 4.0 +FERROR = 0.050 +MIN_FERROR = 0.010 diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/test.sh b/linuxcnc-tests/task/interp-reset-requires-idle/test.sh new file mode 100755 index 00000000..f3f52ecd --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test.sh @@ -0,0 +1,4 @@ +#!/bin/bash +# Tool edits save the table, so start from a fresh copy. +printf 'T1 P1 Z0 ;\n' > tool.tbl +exec linuxcnc -r test.ini diff --git a/linuxcnc-tests/thread-period-stats-arithmetic/arithmetic.c b/linuxcnc-tests/thread-period-stats-arithmetic/arithmetic.c new file mode 100644 index 00000000..1c0b04eb --- /dev/null +++ b/linuxcnc-tests/thread-period-stats-arithmetic/arithmetic.c @@ -0,0 +1,109 @@ +#include +#include + +#include "hal_period_stats.h" + +#define V(name) (stats.value[HAL_PERIOD_STAT_##name]) + +int main(void) +{ + hal_period_stats_t stats; + + memset(&stats, 0, sizeof(stats)); + V(PERIOD_TARGET) = 1000000; + + assert(!hal_period_stats_record_start(&stats, 1000000)); + assert(V(SAMPLES) == 0); + + assert(hal_period_stats_record_start(&stats, 2100000)); + hal_period_stats_record_execution(&stats, 80000); + assert(V(PERIOD_LAST) == 1100000); + assert(V(JITTER) == 100000); + assert(V(PERIOD_MIN) == 1100000); + assert(V(PERIOD_MAX) == 1100000); + assert(V(OUTLIER_Q) == 0); + assert(V(MISSED) == 0); + + assert(hal_period_stats_record_start(&stats, 3700000)); + hal_period_stats_record_execution(&stats, 120000); + assert(V(SAMPLES) == 2); + assert(V(PERIOD_AVG) == 1350000); + assert(V(JITTER_AVG) == 350000); + assert(V(JITTER_MAX) == 600000); + assert(V(OUTLIER_Q) == 1); + assert(V(OUTLIER_H) == 1); + assert(V(OUTLIER_AT) == 2); + assert(V(EXEC_AVG) == 100000); + assert(V(EXEC_MAX) == 120000); + + assert(hal_period_stats_record_start(&stats, 6800000)); + hal_period_stats_record_execution(&stats, 40000); + assert(V(SAMPLES) == 3); + assert(V(PERIOD_LAST) == 3100000); + assert(V(PERIOD_MIN) == 1100000); + assert(V(PERIOD_MAX) == 3100000); + assert(V(JITTER) == 2100000); + assert(V(PERIOD_AVG) == 1933333); + assert(V(JITTER_AVG) == 933333); + assert(V(JITTER_MAX) == 2100000); + assert(V(OUTLIER_Q) == 2); + assert(V(OUTLIER_H) == 2); + assert(V(OUTLIER_AT) == 3); + assert(V(MISSED) == 1); + assert(V(EXEC_AVG) == 80000); + assert(V(EXEC_MAX) == 120000); + + /* A shorter interval lowers the minimum; a quarter-period outlier that + is below half a period counts only as a quarter outlier. */ + assert(hal_period_stats_record_start(&stats, 7500000)); + hal_period_stats_record_execution(&stats, 40000); + assert(V(PERIOD_MIN) == 700000); + assert(V(JITTER) == 300000); + assert(V(OUTLIER_Q) == 3); + assert(V(OUTLIER_H) == 2); + assert(V(OUTLIER_AT) == 4); + + /* A reset clears everything except the target, and the next start only + begins a new interval. */ + hal_period_stats_clear(&stats); + assert(V(SAMPLES) == 0); + assert(V(PERIOD_MAX) == 0); + assert(V(PERIOD_MIN) == 0); + assert(V(JITTER_MAX) == 0); + assert(V(EXEC_MAX) == 0); + assert(V(OUTLIER_Q) == 0); + assert(V(MISSED) == 0); + assert(V(PERIOD_TARGET) == 1000000); + assert(!hal_period_stats_record_start(&stats, 7800000)); + assert(V(SAMPLES) == 0); + + assert(hal_period_stats_record_start(&stats, 8800000)); + hal_period_stats_record_execution(&stats, 60000); + assert(V(SAMPLES) == 1); + assert(V(PERIOD_AVG) == 1000000); + assert(V(JITTER_AVG) == 0); + assert(V(EXEC_AVG) == 60000); + + /* Values are 64-bit: counts and times beyond 32 bits are kept. */ + V(SAMPLES) = 4294967295LL; + assert(hal_period_stats_record_start(&stats, 9800000)); + hal_period_stats_record_execution(&stats, 200000); + assert(V(SAMPLES) == 4294967296LL); + assert(V(EXEC_MAX) == 200000); + + assert(hal_period_stats_record_start(&stats, 9800000 + 5000000000LL)); + assert(V(PERIOD_LAST) == 5000000000LL); + assert(V(PERIOD_MAX) == 5000000000LL); + + /* Counters saturate instead of wrapping. */ + V(SAMPLES) = RTAPI_SINT_MAX; + V(MISSED) = RTAPI_SINT_MAX; + assert(hal_period_stats_record_start(&stats, 9800000 + 15000000000LL)); + assert(V(SAMPLES) == RTAPI_SINT_MAX); + assert(V(MISSED) == RTAPI_SINT_MAX); + + /* Time going backwards is not an interval. */ + assert(!hal_period_stats_record_start(&stats, 1000000)); + + return 0; +} diff --git a/linuxcnc-tests/thread-period-stats-arithmetic/expected b/linuxcnc-tests/thread-period-stats-arithmetic/expected new file mode 100644 index 00000000..e69de29b diff --git a/linuxcnc-tests/thread-period-stats-arithmetic/test.sh b/linuxcnc-tests/thread-period-stats-arithmetic/test.sh new file mode 100644 index 00000000..09d59c23 --- /dev/null +++ b/linuxcnc-tests/thread-period-stats-arithmetic/test.sh @@ -0,0 +1,9 @@ +#!/bin/sh +set -eu + +test_dir=$(mktemp -d) +trap 'rm -rf -- "$test_dir"' EXIT +cc -std=gnu11 -Wall -Wextra -Werror -DULAPI -I"$EMC2_HOME/src/hal" -I"$EMC2_HOME/src/rtapi" \ + -I"$EMC2_HOME/src" -I"$EMC2_HOME/src/include" \ + -o "$test_dir/arithmetic" arithmetic.c +"$test_dir/arithmetic" diff --git a/linuxcnc-tests/thread-period-stats/README b/linuxcnc-tests/thread-period-stats/README new file mode 100644 index 00000000..dd01becf --- /dev/null +++ b/linuxcnc-tests/thread-period-stats/README @@ -0,0 +1,4 @@ +Period statistics use fixed short suffixes. A 41-character thread name is the +longest that holds them within HAL_NAME_LEN; a longer valid name still creates +its thread, without statistics. The sample counter is a 64-bit decimal HAL +parameter and advances after the thread starts. diff --git a/linuxcnc-tests/thread-period-stats/checkresult b/linuxcnc-tests/thread-period-stats/checkresult new file mode 100755 index 00000000..753ff32f --- /dev/null +++ b/linuxcnc-tests/thread-period-stats/checkresult @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +import sys + +samples = {"servo-thread.samples": [], "period-statistics-boundary-thread-name-41.samples": []} +resets = {"servo-thread.stats-reset": False, "period-statistics-boundary-thread-name-41.stats-reset": False} +unpublished = [] +with open(sys.argv[1], encoding="utf-8") as output: + for line in output: + fields = line.split() + if len(fields) < 5: + continue + if fields[-1] in samples: + if fields[1] != "sint" or fields[2] != "RO": + raise SystemExit("sample counter has an unexpected type") + samples[fields[-1]].append(int(fields[-2], 0)) + if fields[-1] in resets: + resets[fields[-1]] = fields[1] == "bool" and fields[2] == "RW" + if fields[-1].startswith("period-statistics-boundary-thread-name-41x."): + unpublished.append(fields[-1]) + +if not all(resets.values()): + raise SystemExit("thread reset parameter was not published") +for name, observed in samples.items(): + if len(observed) != 2 or observed[0] != 0 or observed[1] <= 0: + raise SystemExit("sample counter did not advance after thread start: " + name) +if any(name not in ("period-statistics-boundary-thread-name-41x.time", "period-statistics-boundary-thread-name-41x.tmax") for name in unpublished): + raise SystemExit("statistics published for a name that cannot hold them: " + str(unpublished)) +if "period-statistics-boundary-thread-name-41x.tmax" not in unpublished: + raise SystemExit("thread with a long name was not created") diff --git a/linuxcnc-tests/thread-period-stats/test.hal b/linuxcnc-tests/thread-period-stats/test.hal new file mode 100644 index 00000000..452dd588 --- /dev/null +++ b/linuxcnc-tests/thread-period-stats/test.hal @@ -0,0 +1,11 @@ +setexact_for_test_suite_only +loadrt threads name1=servo-thread period1=1000000 name2=period-statistics-boundary-thread-name-41 period2=2000000 name3=period-statistics-boundary-thread-name-41x period3=2000000 +show param servo-thread.samples +show param servo-thread.stats-reset +show param period-statistics-boundary-thread-name-41.samples +show param period-statistics-boundary-thread-name-41.stats-reset +show param period-statistics-boundary-thread-name-41x. +start +loadusr -w sleep 0.05 +show param servo-thread.samples +show param period-statistics-boundary-thread-name-41.samples diff --git a/linuxcnc-tests/tool-crud-refusal/.gitignore b/linuxcnc-tests/tool-crud-refusal/.gitignore new file mode 100644 index 00000000..89772f72 --- /dev/null +++ b/linuxcnc-tests/tool-crud-refusal/.gitignore @@ -0,0 +1,5 @@ +sim.var +sim.var.bak +tool.tbl +run.ini +tool-cmd diff --git a/linuxcnc-tests/tool-crud-refusal/README b/linuxcnc-tests/tool-crud-refusal/README new file mode 100644 index 00000000..1535c26e --- /dev/null +++ b/linuxcnc-tests/tool-crud-refusal/README @@ -0,0 +1,7 @@ +EMC_TOOL_UPDATE and EMC_TOOL_DELETE have no Python binding, so tool-cmd.cc sends +them over NML the way the native server does and reports the result from the +echoed serial number and the RCS status. + +A refused update or delete fails that command with an operator error. The +machine keeps its state: no abort, spindle and coolant stay on, an open program +stays open, and the next command succeeds. diff --git a/linuxcnc-tests/tool-crud-refusal/checkresult b/linuxcnc-tests/tool-crud-refusal/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/tool-crud-refusal/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/tool-crud-refusal/program.ngc b/linuxcnc-tests/tool-crud-refusal/program.ngc new file mode 100644 index 00000000..1f0eacc3 --- /dev/null +++ b/linuxcnc-tests/tool-crud-refusal/program.ngc @@ -0,0 +1,2 @@ +G0 X1 +M2 diff --git a/linuxcnc-tests/tool-crud-refusal/test-ui.py b/linuxcnc-tests/tool-crud-refusal/test-ui.py new file mode 100755 index 00000000..8d6ef702 --- /dev/null +++ b/linuxcnc-tests/tool-crud-refusal/test-ui.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""A refused tool update or delete fails that command and tells the operator; +the machine goes on as it was.""" + +import os +import subprocess +import sys + +sys.path.insert(0, "../tool-table-load") +from common import * + + +def tool_cmd(*args): + return subprocess.run(["./tool-cmd", linuxcnc.nmlfile] + [str(a) for a in args], + timeout=30).returncode + + +def check_running(what): + s.poll() + if s.spindle[0]["enabled"] == 0 or s.spindle[0]["direction"] != 1: + fail("%s: the spindle stopped" % what) + if s.flood != linuxcnc.FLOOD_ON: + fail("%s: the coolant stopped" % what) + if s.task_state != linuxcnc.STATE_ON or s.task_mode != linuxcnc.MODE_MDI: + fail("%s: state %d, mode %d" % (what, s.task_state, s.task_mode)) + if s.interp_state != linuxcnc.INTERP_IDLE: + fail("%s: interpreter state %d" % (what, s.interp_state)) + + +def refused(what, message, *args): + print("*** " + what) + before = table() + rc = tool_cmd(*args) + if rc != 1: + fail("%s: tool-cmd returned %d, expected the command to fail" % (what, rc)) + time.sleep(0.2) + check_running(what) + wait_error(message) + if table() != before: + fail("%s: the table file was rewritten:\n%s" % (what, table())) + + +start() +mdi("M3 S100") +mdi("M8") +check_running("start") + +refused("delete of an unknown tool", "can't delete tool 99", "delete", 99) +refused("update of an unknown tool without a pocket", "can't update tool 9", + "update", 9) +refused("update to a pocket another tool has", "can't update tool 1", + "update", 1, 2) +mdi("M61 Q1") +refused("delete of the tool in the spindle", "can't delete tool 1", "delete", 1) + +print("*** the next command succeeds") +if tool_cmd("delete", 2) != 0: + fail("delete of T2 did not succeed after the refusals") +wait_for(lambda: 2 not in tools(), "T2 to go") +check_running("after the delete") +if tool_cmd("update", 4, 4) != 0: + fail("create of T4 did not succeed after the refusals") +wait_for(lambda: 4 in tools(), "T4 to appear") +check_running("after the create") + +print("*** a refusal leaves an open program open") +program = os.path.abspath("program.ngc") +c.mode(linuxcnc.MODE_AUTO) +c.wait_complete() +c.program_open(program) +c.wait_complete() +if tool_cmd("delete", 99) != 1: + fail("delete of an unknown tool in AUTO did not fail") +wait_error("can't delete tool 99") +s.poll() +if s.file != program: + fail("the program was closed: file is %r" % s.file) +c.auto(linuxcnc.AUTO_RUN, 0) +wait_for(lambda: abs(s.position[0] - 1.0) < 1e-6 + and s.interp_state == linuxcnc.INTERP_IDLE, "the program to run") + +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-crud-refusal/test.sh b/linuxcnc-tests/tool-crud-refusal/test.sh new file mode 100755 index 00000000..bad1a01d --- /dev/null +++ b/linuxcnc-tests/tool-crud-refusal/test.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +# RIP layout: $HEADERS is $TOPDIR/include; the NML headers are not installed +TOPDIR=$(dirname "$HEADERS") +g++ -I"$HEADERS" -I"$TOPDIR/src" -I"$TOPDIR/src/emc" \ + -I"$TOPDIR/src/emc/nml_intf" -I"$TOPDIR/src/libnml" \ + tool-cmd.cc -L"$LIBDIR" -Wl,-rpath,"$LIBDIR" \ + -lnml -llinuxcnc -o tool-cmd +printf 'T1 P1 Z+1.000000\nT2 P2 Z+2.000000\nT3 P3 Z+3.000000\n' > tool.tbl +rm -f sim.var +../tool-wear-common/make-ini.sh run.ini +linuxcnc -r run.ini diff --git a/linuxcnc-tests/tool-crud-refusal/tool-cmd.cc b/linuxcnc-tests/tool-crud-refusal/tool-cmd.cc new file mode 100644 index 00000000..226cf793 --- /dev/null +++ b/linuxcnc-tests/tool-crud-refusal/tool-cmd.cc @@ -0,0 +1,50 @@ +// Send one tool command over NML and report how it ended: +// tool-cmd NMLFILE delete TOOL +// tool-cmd NMLFILE update TOOL [POCKET] +// Exit status: 0 RCS_DONE, 1 RCS_ERROR, 2 no result. +#include "emc.hh" +#include "emc_nml.hh" +#include +#include +#include +#include + +static int finish(RCS_STAT_CHANNEL &stat, int serial) +{ + for (int i = 0; i < 10000; i++) { + if (stat.peek() == EMC_STAT_TYPE) { + auto *status = static_cast(stat.get_address()); + if (status->echo_serial_number - serial >= 0) { + if (status->status == RCS_STATUS::DONE) return 0; + if (status->status == RCS_STATUS::ERROR) return 1; + } + } + usleep(1000); + } + return 2; +} + +int main(int argc, char **argv) +{ + if (argc < 4) return 2; + RCS_CMD_CHANNEL cmd(emcFormat, "emcCommand", "xemc", argv[1]); + RCS_STAT_CHANNEL stat(emcFormat, "emcStatus", "xemc", argv[1]); + if (!cmd.valid() || !stat.valid()) return 2; + int serial; + if (!strcmp(argv[2], "delete")) { + EMC_TOOL_DELETE msg; + msg.toolno = atoi(argv[3]); + if (cmd.write(&msg)) return 2; + serial = msg.serial_number; + } else { + EMC_TOOL_UPDATE msg; + msg.toolno = atoi(argv[3]); + if (argc > 4) { + msg.pocket = atoi(argv[4]); + msg.fields |= EMC_TOOL_UPDATE_POCKET; + } + if (cmd.write(&msg)) return 2; + serial = msg.serial_number; + } + return finish(stat, serial); +} diff --git a/linuxcnc-tests/tool-line-length-save/.gitignore b/linuxcnc-tests/tool-line-length-save/.gitignore new file mode 100644 index 00000000..61ad1bde --- /dev/null +++ b/linuxcnc-tests/tool-line-length-save/.gitignore @@ -0,0 +1,6 @@ +sim.var +sim.var.bak +tool.tbl +random.ini +g10.ngc +lathe.ini diff --git a/linuxcnc-tests/tool-line-length-save/checkresult b/linuxcnc-tests/tool-line-length-save/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/tool-line-length-save/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/tool-line-length-save/make-table.py b/linuxcnc-tests/tool-line-length-save/make-table.py new file mode 100755 index 00000000..624f03b4 --- /dev/null +++ b/linuxcnc-tests/tool-line-length-save/make-table.py @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +# T1 is ordinary; T3's line is 600 characters, longer than a tool line may +# be, and is refused when the table is loaded. With "random", the table is +# for a random toolchanger: T2 is in the spindle (pocket 0). +import sys +head = "T3 P3 X+1 Z+2 D0." +tail = " WZ-0.25 ;too long" +t3 = head + "0" * (600 - len(head) - len(tail)) + tail +assert len(t3) == 600 +if sys.argv[1:] == ["random"]: + print("T2 P0 Z+1.000000 ;in the spindle") +print("T1 P1 X+5.000000 Z+10.000000 WX+0.200000 WZ-0.100000 Q3 ;front tool") +print(t3) diff --git a/linuxcnc-tests/tool-line-length-save/random-ui.py b/linuxcnc-tests/tool-line-length-save/random-ui.py new file mode 100755 index 00000000..4b2e2672 --- /dev/null +++ b/linuxcnc-tests/tool-line-length-save/random-ui.py @@ -0,0 +1,93 @@ +#!/usr/bin/env python3 +"""A random toolchanger saves the table after every change. With a line +refused on load the save is refused, so M6 fails with an operator error +instead of reporting success: the tools are swapped in memory (as they are +in the changer) and the file is left as it was.""" + +import linuxcnc +import linuxcnc_util + +import sys +import time + +c = linuxcnc.command() +e = linuxcnc.error_channel() +s = linuxcnc.stat() +l = linuxcnc_util.LinuxCNC(command=c, status=s, error=e) + + +def fail(msg): + print("ERROR: " + msg) + sys.exit(1) + + +def table(): + with open("tool.tbl") as f: + return f.read() + + +def wait_error(text, timeout=10): + start = time.time() + while time.time() - start < timeout: + err = e.poll() + if err is None: + time.sleep(0.01) + continue + print("(error channel: %s)" % (err[1],)) + if err[0] in (linuxcnc.OPERATOR_ERROR, linuxcnc.NML_ERROR) and text in err[1]: + return + fail("no error containing '%s'" % text) + + +l.wait_for_linuxcnc_startup() +c.state(linuxcnc.STATE_ESTOP_RESET) +c.state(linuxcnc.STATE_ON) +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() + +before = table() +print("*** M6 with a table that may not be saved reports an error") +c.mdi("t1 m6") +c.wait_complete() +wait_error("not saved after the tool change") +s.poll() +if s.tool_in_spindle != 1: + fail("tool in spindle %d, expected 1" % s.tool_in_spindle) +if s.tool_table[0].id != 1: + fail("spindle pocket holds T%d, expected T1" % s.tool_table[0].id) +if table() != before: + fail("the table file was rewritten:\n" + table()) +print("tool.tbl unchanged, T3's line kept") + +print("*** a reload is refused while pocket 0 does not show the spindle tool") +short_t3 = "T3 P3 Z+2.000000 ;shortened\n" +with open("tool.tbl", "w") as f: + f.write("T2 P0 Z+1.000000\nT1 P1 Z+10.000000\n" + short_t3) +c.load_tool_table() +c.wait_complete() +wait_error("pocket 0") +s.poll() +if s.tool_in_spindle != 1 or s.tool_table[0].id != 1: + fail("reload changed the spindle: status T%d, pocket 0 T%d" + % (s.tool_in_spindle, s.tool_table[0].id)) + +print("*** with the file matching the machine, the reload and changes work") +with open("tool.tbl", "w") as f: + f.write("T1 P0 Z+10.000000\nT2 P1 Z+1.000000\n" + short_t3) +c.load_tool_table() +c.wait_complete() +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() +c.mdi("t2 m6") +c.wait_complete() +deadline = time.time() + 10 +while time.time() < deadline: + s.poll() + lines = [" ".join(line.split()) for line in table().split("\n")] + if s.tool_in_spindle == 2 and any(l.startswith("T2 P0") for l in lines): + break + time.sleep(0.01) +else: + fail("T2 M6 after the reload was not saved:\n" + table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-line-length-save/test-ui.py b/linuxcnc-tests/tool-line-length-save/test-ui.py new file mode 100755 index 00000000..08ce5ff4 --- /dev/null +++ b/linuxcnc-tests/tool-line-length-save/test-ui.py @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +"""A tool table with a line refused on load (too long) is not saved: the +save would delete the user's line. A G10 edit is refused, the file is kept +as it was and the edit is not kept in memory; once the line is fixed and +the table reloaded, saving works again.""" + +import linuxcnc +import linuxcnc_util + +import math +import os +import sys +import time + +c = linuxcnc.command() +e = linuxcnc.error_channel() +s = linuxcnc.stat() +l = linuxcnc_util.LinuxCNC(command=c, status=s, error=e) + + +def fail(msg): + print("ERROR: " + msg) + sys.exit(1) + + +def check(what, got, expected): + print("%s = %.6f (expecting %.6f)" % (what, got, expected)) + if math.fabs(got - expected) > 1e-6: + fail("%s = %f, expected %f" % (what, got, expected)) + + +def wait_for(predicate, what, timeout=10): + start = time.time() + while not predicate(): + if time.time() - start > timeout: + fail("timeout waiting for " + what) + time.sleep(0.01) + s.poll() + + +def tools(): + s.poll() + return {t.id: t for t in s.tool_table[1:] if t.id > 0} + + +def table(): + with open("tool.tbl") as f: + return f.read() + + +def wait_error(text, timeout=10): + start = time.time() + while time.time() - start < timeout: + err = e.poll() + if err is None: + time.sleep(0.01) + continue + print("(error channel: %s)" % (err[1],)) + if err[0] in (linuxcnc.OPERATOR_ERROR, linuxcnc.NML_ERROR) and text in err[1]: + return + fail("no error containing '%s'" % text) + + +l.wait_for_linuxcnc_startup() +c.state(linuxcnc.STATE_ESTOP_RESET) +c.state(linuxcnc.STATE_ON) +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() + +print("*** T3's line was refused on load") +if 3 in tools(): + fail("T3 was loaded from a 600-character line") +check("T1 wxoffset", tools()[1].wxoffset, 0.2) + +print("*** a G10 edit is refused: file and memory unchanged") +before = table() +c.mdi("g10 l3 p1 x0.1") +result = c.wait_complete() +if result != linuxcnc.RCS_ERROR: + fail("MDI G10 with a refused save finished with status %d" % result) +wait_error("offsets not stored") +if table() != before: + fail("the table file was rewritten:\n" + table()) +print("tool.tbl unchanged, T3's line kept") +check("T1 wxoffset after the refused save", tools()[1].wxoffset, 0.2) +check("toolinfo(1) wxoffset after the refused save", s.toolinfo(1)["wxoffset"], 0.2) + +print("*** a program with a G10 that cannot be saved stops and says why") +with open("g10.ngc", "w") as f: + f.write("g10 l3 p1 x0.1\ng4 p30\nm2\n") +c.mode(linuxcnc.MODE_AUTO) +c.wait_complete() +c.program_open(os.path.abspath("g10.ngc")) +c.wait_complete() +c.auto(linuxcnc.AUTO_RUN, 0) +wait_error("offsets not stored") +wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE, "the program to stop") +check("T1 wxoffset after the program", tools()[1].wxoffset, 0.2) +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() + +print("*** with T3's line fixed and the table reloaded, saving works") +with open("tool.tbl", "w") as f: + f.write(before.splitlines()[0] + "\nT3 P3 X+1 Z+2 WZ-0.25 ;fixed\n") +c.load_tool_table() +c.wait_complete() +wait_for(lambda: 3 in tools(), "T3 after the reload") +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() +c.mdi("g10 l3 p1 x0.1") +c.wait_complete() +wait_for(lambda: "WX+0.100000" in table(), "the saved edit") +check("T1 wxoffset after the save", tools()[1].wxoffset, 0.1) +print(table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-line-length-save/test.sh b/linuxcnc-tests/tool-line-length-save/test.sh new file mode 100755 index 00000000..346c022b --- /dev/null +++ b/linuxcnc-tests/tool-line-length-save/test.sh @@ -0,0 +1,12 @@ +#!/bin/bash +set -e +python3 make-table.py > tool.tbl +rm -f sim.var +../tool-wear-common/make-ini.sh lathe.ini +linuxcnc -r lathe.ini + +# a random toolchanger: M6 cannot save the table and fails +python3 make-table.py random > tool.tbl +rm -f sim.var +../tool-wear-common/make-ini.sh random.ini ui=./random-ui.py random=1 +linuxcnc -r random.ini diff --git a/linuxcnc-tests/tool-table-load/.gitignore b/linuxcnc-tests/tool-table-load/.gitignore new file mode 100644 index 00000000..ebe01445 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/.gitignore @@ -0,0 +1,6 @@ +sim.var +sim.var.bak +tool.tbl +other.tbl +linked/ +run.ini diff --git a/linuxcnc-tests/tool-table-load/checkresult b/linuxcnc-tests/tool-table-load/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/tool-table-load/common.py b/linuxcnc-tests/tool-table-load/common.py new file mode 100644 index 00000000..fe72033e --- /dev/null +++ b/linuxcnc-tests/tool-table-load/common.py @@ -0,0 +1,121 @@ +import hal +import linuxcnc +import linuxcnc_util + +import math +import socket +import subprocess +import sys +import time + +c = linuxcnc.command() +e = linuxcnc.error_channel() +s = linuxcnc.stat() +l = linuxcnc_util.LinuxCNC(command=c, status=s, error=e) + + +def fail(msg): + print("ERROR: " + msg) + sys.exit(1) + + +def check(what, got, expected): + print("%s = %.6f (expecting %.6f)" % (what, got, expected)) + if math.fabs(got - expected) > 1e-6: + fail("%s = %f, expected %f" % (what, got, expected)) + + +def wait_for(predicate, what, timeout=10): + start = time.time() + while not predicate(): + if time.time() - start > timeout: + fail("timeout waiting for " + what) + time.sleep(0.01) + s.poll() + + +def wait_error(text, timeout=10): + start = time.time() + while time.time() - start < timeout: + err = e.poll() + if err is None: + time.sleep(0.01) + continue + print("(error channel: %s)" % (err[1],)) + if text in err[1]: + return + fail("no error containing '%s'" % text) + + +def tools(): + s.poll() + return {t.id: t for t in s.tool_table[1:] if t.id > 0} + + +def table(): + with open("tool.tbl", newline="") as f: + return f.read() + + +def saved(): + """The table file's lines, spaces between words normalized.""" + return [" ".join(line.split()) for line in table().split("\n")] + + +def start(): + l.wait_for_linuxcnc_startup() + c.state(linuxcnc.STATE_ESTOP_RESET) + c.state(linuxcnc.STATE_ON) + mdi_mode() + + +def mdi_mode(): + c.mode(linuxcnc.MODE_MDI) + c.wait_complete() + + +def mdi(cmd): + c.mdi(cmd) + c.wait_complete() + + +def spindle_tool_is(toolno): + """Status, pocket 0 and the iocontrol pin all show the tool.""" + s.poll() + return (s.tool_in_spindle == toolno and s.tool_table[0].id == toolno + and hal.get_value("iocontrol.0.tool-number") == toolno) + + +def load_table_file(name): + """Load a named table file; only linuxcncrsh's command takes a name.""" + ini = sys.argv[sys.argv.index("-ini") + 1] + with socket.socket() as probe: + probe.bind(("127.0.0.1", 0)) + port = probe.getsockname()[1] + rsh = subprocess.Popen(["linuxcncrsh", "-p", str(port), "--", "-ini", ini]) + try: + start_time = time.time() + while True: + try: + conn = socket.create_connection(("127.0.0.1", port), timeout=10) + break + except OSError: + if time.time() - start_time > 10: + fail("linuxcncrsh did not start") + time.sleep(0.05) + with conn: + for line in ("hello EMC test 1.0", "set enable EMCTOO", + "set wait_mode done", "set load_tool_table " + name, + "get wait_mode"): + conn.sendall((line + "\r\n").encode()) + # the reply to the last command: the load before it has finished + reply = b"" + while b"WAIT_MODE DONE" not in reply: + data = conn.recv(4096) + if not data: + fail("linuxcncrsh closed the connection: %r" % reply) + reply += data + print("(linuxcncrsh: %r)" % reply) + finally: + rsh.terminate() + rsh.wait() diff --git a/linuxcnc-tests/tool-table-load/crlf-ui.py b/linuxcnc-tests/tool-table-load/crlf-ui.py new file mode 100755 index 00000000..f2c80115 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/crlf-ui.py @@ -0,0 +1,27 @@ +#!/usr/bin/env python3 +"""A table with CRLF line ends, blank lines (CR included) and a +comment-only line loads whole, and saving it works.""" + +from common import * + +start() +loaded = tools() +print("loaded: %s" % sorted(loaded)) +if sorted(loaded) != [1, 2, 3]: + fail("tools %s loaded, expected 1, 2 and 3" % sorted(loaded)) +check("T2 zoffset", loaded[2].zoffset, 2.0) +check("T3 zoffset", loaded[3].zoffset, 3.0) +for toolno, comment in ((1, "first"), (3, "third")): + got = s.toolinfo(toolno)["comment"] + if got != comment: + fail("T%d comment %r, expected %r" % (toolno, got, comment)) + +mdi("g10 l1 p2 z5") +wait_for(lambda: "T2 P2 Z+5.000000" in saved(), "the saved edit") +print(table()) +if "\r" in table(): + fail("carriage return saved") +if "T1 P1 Z+1.000000 ;first" not in saved() or "T3 P3 Z+3.000000 ;third" not in saved(): + fail("tools lost from the saved table") +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/external-edit-ui.py b/linuxcnc-tests/tool-table-load/external-edit-ui.py new file mode 100755 index 00000000..ce064c08 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/external-edit-ui.py @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +"""A table file that no longer holds what was loaded or last saved has +changes the table in memory lacks: a save is refused until it is reloaded. +The comparison is of the contents, so an edit is found even when size and +timestamp are the same, and a mere touch or chmod refuses nothing.""" + +from common import * + +import os + + +def refused(edit_line, zoffset): + before = table() + mdi("g10 l1 p%d z%s" % edit_line) + if table() != before: + fail("the edited table file was replaced:\n" + table()) + check("T%d zoffset after the refused save" % edit_line[0], + tools()[edit_line[0]].zoffset, zoffset) + mdi_mode() + + +def reload_table(): + c.load_tool_table() + c.wait_complete() + mdi_mode() + + +start() +print("*** saves follow each other: a save does not look like an edit") +mdi("g10 l1 p1 z5") +wait_for(lambda: "T1 P1 Z+5.000000" in saved(), "the first save") +mdi("g10 l1 p1 z6") +wait_for(lambda: "T1 P1 Z+6.000000" in saved(), "the second save") + +print("*** a file replaced by an editor is not saved over") +with open("tool.tbl.new", "w") as f: + f.write("T1 P1 Z+6.000000\nT2 P2 Z+2.000000\nT3 P3 Z+3.000000\n") +os.rename("tool.tbl.new", "tool.tbl") +refused((1, 7), 6.0) +if 3 in tools(): + fail("T3 loaded without a reload") + +print("*** reloaded, it is used and saved") +reload_table() +wait_for(lambda: 3 in tools(), "T3 after the reload") +mdi("g10 l1 p3 z4") +wait_for(lambda: "T3 P3 Z+4.000000" in saved(), "the saved edit") + +print("*** an edit in place with the same size and time is found") +info = os.stat("tool.tbl") +edited = table().replace("Z+2.000000", "Z+2.500000") +with open("tool.tbl", "w") as f: + f.write(edited) +os.utime("tool.tbl", ns=(info.st_atime_ns, info.st_mtime_ns)) +refused((1, 8), 6.0) +reload_table() +check("T2 zoffset after the reload", tools()[2].zoffset, 2.5) + +print("*** a new time or mode alone does not stop saving, and the mode is kept") +os.utime("tool.tbl", (1000000000, 1000000000)) +os.chmod("tool.tbl", 0o640) +mdi("g10 l1 p1 z9") +wait_for(lambda: "T1 P1 Z+9.000000" in saved(), "the save after touch and chmod") +if os.stat("tool.tbl").st_mode & 0o777 != 0o640: + fail("file mode %o" % (os.stat("tool.tbl").st_mode & 0o777)) + +print("*** a deleted file holds nothing to lose: a save creates it again") +os.unlink("tool.tbl") +mdi("g10 l1 p1 z10") +wait_for(lambda: os.path.exists("tool.tbl") and "T1 P1 Z+10.000000" in saved(), + "the recreated file") +print(table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/garbage-ui.py b/linuxcnc-tests/tool-table-load/garbage-ui.py new file mode 100755 index 00000000..d1323f5d --- /dev/null +++ b/linuxcnc-tests/tool-table-load/garbage-ui.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""A table file with a line that is not a tool line does not load: the +operator is told at startup and the machine has no tools. A table loaded +later lifts the block on saving; a reload of the file that fails keeps the +table in memory but again keeps the file from being saved over. The block +after a failed startup is exercised by random-start-ui.py: without a tool +in the table, no save can be attempted here.""" + +from common import * + +start() +wait_error("can't load tool table") +if tools(): + fail("tools %s loaded from a table that did not load" % sorted(tools())) + +print("*** with the line fixed and the table reloaded, saving works") +with open("tool.tbl", "w") as f: + f.write("T1 P1 Z+1.000000\nT2 P2 Z+2.000000\n") +c.load_tool_table() +c.wait_complete() +wait_for(lambda: sorted(tools()) == [1, 2], "T1 and T2 after the reload") +mdi_mode() +mdi("g10 l1 p1 z5") +wait_for(lambda: "T1 P1 Z+5.000000" in saved(), "the saved edit") + +print("*** a reload that fails keeps the table, and the file is not saved over") +# A refused load changes nothing else either: it does not abort the machine, +# so a running spindle keeps running. +mdi("m3 s100") +edited = "T1 P1 Z+5.000000\nT2 P2 Z+2.000000\nT4 P4 Z+4.000000\nnot a tool line\n" +with open("tool.tbl", "w") as f: + f.write(edited) +c.load_tool_table() +c.wait_complete() +wait_error("can't load tool table") +time.sleep(0.2) +s.poll() +if hal.get_value("spindle.0.speed-out") <= 0 or s.task_state != linuxcnc.STATE_ON: + fail("the refused table load stopped the machine") +mdi("m5") +mdi_mode() +mdi("g10 l1 p2 z7") +if table() != edited: + fail("the table file was rewritten:\n" + table()) +check("T2 zoffset after the refused save", tools()[2].zoffset, 2.0) +if 4 in tools(): + fail("T4 loaded from a table that did not load") + +print("*** fixed and reloaded again, saving works") +with open("tool.tbl", "w") as f: + f.write(edited.replace("not a tool line\n", "")) +c.load_tool_table() +c.wait_complete() +wait_for(lambda: 4 in tools(), "T4 after the reload") +mdi_mode() +mdi("g10 l1 p2 z7") +wait_for(lambda: "T2 P2 Z+7.000000" in saved(), "the saved edit") +print(table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/missing-ui.py b/linuxcnc-tests/tool-table-load/missing-ui.py new file mode 100755 index 00000000..0f442902 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/missing-ui.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 +"""With no table file at startup a save creates one, but a file that appeared +in the meantime is someone's work and is not replaced until it is loaded.""" + +from common import * + +import os + +made = "T3 P0 Z+3.000000\nT4 P1 Z+4.000000\n" + + +def write_made(): + with open("tool.tbl", "w") as f: + f.write(made) + + +start() +wait_error("can't load tool table") + +print("*** a file made after startup is not saved over") +write_made() +mdi("m61 q0") +wait_error("not saved after the tool change") +if table() != made: + fail("the new table file was replaced:\n" + table()) + +print("*** with the file gone again, a save creates it") +os.unlink("tool.tbl") +mdi_mode() +mdi("m61 q0") +wait_for(lambda: os.path.exists("tool.tbl"), "the created table file") +first = os.stat("tool.tbl").st_ino + +print("*** the file a save made does not stop the next save") +mdi("m61 q0") +wait_for(lambda: os.stat("tool.tbl").st_ino != first, "the second save") + +print("*** a file made now is kept until it is loaded, then used") +write_made() +mdi("m61 q0") +wait_error("not saved after the tool change") +if table() != made: + fail("the new table file was replaced:\n" + table()) +c.load_tool_table() +c.wait_complete() +wait_for(lambda: spindle_tool_is(3), "T3 from the loaded file") +mdi_mode() +mdi("m61 q4") +wait_for(lambda: "T4 P0 Z+4.000000" in saved(), "the saved tool change") +print(table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/other-table-ui.py b/linuxcnc-tests/tool-table-load/other-table-ui.py new file mode 100755 index 00000000..af9ba050 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/other-table-ui.py @@ -0,0 +1,33 @@ +#!/usr/bin/env python3 +"""The configured table file did not load. Loading another file gives the +machine tools, but says nothing about the configured file: it is still not +saved over until it has been corrected and loaded itself.""" + +from common import * + +start() +wait_error("can't load tool table") +before = table() + +print("*** another table loads, the configured file stays protected") +load_table_file("other.tbl") +wait_for(lambda: sorted(tools()) == [8, 9], "T8 and T9 from the other file") +mdi_mode() +mdi("g10 l1 p8 z3") +if table() != before: + fail("the protected table file was rewritten:\n" + table()) +check("T8 zoffset after the refused save", tools()[8].zoffset, 8.0) + +print("*** corrected and loaded, the configured file is saved again") +mdi_mode() +with open("tool.tbl", "w") as f: + f.write("T1 P1 Z+1.000000\nT2 P2 Z+2.000000\n") +c.load_tool_table() +c.wait_complete() +wait_for(lambda: sorted(tools()) == [1, 2], "T1 and T2 after the reload") +mdi_mode() +mdi("g10 l1 p1 z5") +wait_for(lambda: "T1 P1 Z+5.000000" in saved(), "the saved edit") +print(table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/random-start-ui.py b/linuxcnc-tests/tool-table-load/random-start-ui.py new file mode 100755 index 00000000..3b860d3f --- /dev/null +++ b/linuxcnc-tests/tool-table-load/random-start-ui.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""A random changer whose table did not load at startup: a tool change saves +the table, and that save must not replace the file the operator still has +to correct. Once corrected and reloaded, the file says which tool is in the +spindle: status and the HAL pin follow it, and tool changes save again.""" + +from common import * + +start() +wait_error("can't load tool table") +before = table() +if not spindle_tool_is(0): + fail("a spindle tool before any table loaded: T%d" % s.tool_in_spindle) + +print("*** M61 cannot save over the file that did not load") +mdi("m61 q0") +wait_error("not saved after the tool change") +if table() != before: + fail("the table file was rewritten:\n" + table()) + +print("*** the corrected table says T7 is in the spindle") +with open("tool.tbl", "w") as f: + f.write("T7 P0 Z+7.000000\nT2 P1 Z+2.000000\n") +c.load_tool_table() +c.wait_complete() +wait_for(lambda: spindle_tool_is(7), "T7 in status, pocket 0 and the HAL pin") + +print("*** tool changes save again") +mdi_mode() +mdi("m61 q2") +wait_for(lambda: spindle_tool_is(2), "T2 in the spindle") +wait_for(lambda: "T2 P0 Z+2.000000" in saved() and "T7 P1 Z+7.000000" in saved(), + "the saved tool change") +print(table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/reload-ui.py b/linuxcnc-tests/tool-table-load/reload-ui.py new file mode 100755 index 00000000..5e073f58 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/reload-ui.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Reload accepts what startup accepts for a nonrandom changer, where P is +only a label. A reload refused for a file that still matches the table in +memory tells the operator and does not stop saves.""" + +from common import * + +start() +duplicate = "T5 P6" in table() +if duplicate: + print("*** a refused reload of the unchanged file does not stop saves") + c.load_tool_table() + c.wait_complete() + wait_error("can't load tool table") +else: + print("*** a pocket label above the changer limit reloads") + wait_for(lambda: sorted(tools()) == [1, 99999], "T1 and T99999") + c.load_tool_table() + c.wait_complete() + +mdi_mode() +mdi("g10 l1 p1 z5") +wait_for(lambda: "T1 P1 Z+5.000000" in saved(), "the saved edit") +print(table()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/symlink-ui.py b/linuxcnc-tests/tool-table-load/symlink-ui.py new file mode 100755 index 00000000..2e03fa77 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/symlink-ui.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""tool.tbl is a link to a link to the real table in another directory. +Saving writes the real file and leaves every link in place, also when the +real file is missing.""" + +from common import * + +import os + +REAL = "linked/real.tbl" + + +def check_layout(): + if os.readlink("tool.tbl") != "linked/alias.tbl": + fail("tool.tbl is no longer the link it was") + if os.readlink("linked/alias.tbl") != "real.tbl": + fail("linked/alias.tbl is no longer the link it was") + if os.path.islink(REAL) or not os.path.isfile(REAL): + fail("the real table is not a regular file") + left = [n for d in (".", "linked") for n in os.listdir(d) if ".tmp." in n] + if left: + fail("temporary files left: %s" % left) + + +def real(): + with open(REAL) as f: + return " ".join(f.read().split()) + + +start() +print("*** a save goes to the real file through the links") +mdi("g10 l1 p1 z5") +wait_for(lambda: "T1 P1 Z+5.000000" in real(), "the saved edit") +check_layout() +if os.stat(REAL).st_mode & 0o777 != 0o640: + fail("file mode %o" % (os.stat(REAL).st_mode & 0o777)) + +print("*** the link still names the table: reload and save again") +c.load_tool_table() +c.wait_complete() +mdi_mode() +check("T1 zoffset after the reload", tools()[1].zoffset, 5.0) +mdi("g10 l1 p2 z7") +wait_for(lambda: "T2 P2 Z+7.000000" in real(), "the second save") +check_layout() + +print("*** with the real file gone, a save creates it behind the links") +os.unlink(REAL) +mdi("g10 l1 p1 z9") +wait_for(lambda: os.path.exists(REAL) and "T1 P1 Z+9.000000" in real(), + "the recreated file") +check_layout() +print(real()) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-table-load/test.sh b/linuxcnc-tests/tool-table-load/test.sh new file mode 100755 index 00000000..c7295bc8 --- /dev/null +++ b/linuxcnc-tests/tool-table-load/test.sh @@ -0,0 +1,64 @@ +#!/bin/bash +set -e + +# run 1: a table with CRLF line ends, blank lines and a comment-only line +# loads whole +printf 'T1 P1 Z+1.000000 ;first\r\n\r\n \r\n ;only a comment\r\nT2 P2 Z+2.000000 \r\nT3 P3 Z+3.000000 ;third\r\n' > tool.tbl +rm -f sim.var +../tool-wear-common/make-ini.sh run.ini ui=./crlf-ui.py +linuxcnc -r run.ini + +# run 2: a table with a line that is not a tool line does not load, and is +# not saved over until a table loads +printf 'T1 P1 Z+1.000000\nnot a tool line\nT2 P2 Z+2.000000\n' > tool.tbl +rm -f sim.var +../tool-wear-common/make-ini.sh run.ini ui=./garbage-ui.py +linuxcnc -r run.ini + +# run 3: a nonrandom pocket number is only a label, so a table that loads at +# startup also reloads, and saving keeps working +printf 'T1 P1 Z+1.000000\nT99999 P99999 Z+2.000000\n' > tool.tbl +rm -f sim.var +../tool-wear-common/make-ini.sh run.ini ui=./reload-ui.py +linuxcnc -r run.ini + +# run 4: a reload refused for a file that matches the table in use reports +# the refusal and does not stop saves +printf 'T1 P1 Z+1.000000\nT5 P5 Z+5.000000\nT5 P6 Z+6.000000\n' > tool.tbl +rm -f sim.var +linuxcnc -r run.ini + +# the remaining runs choose their user interface and changer type +run_ui() { + rm -f sim.var + ../tool-wear-common/make-ini.sh run.ini "ui=./$1" "random=$2" + linuxcnc -r run.ini +} + +# run 5: a random changer whose table did not load at startup: a tool change +# does not save over the file, and the reload takes the spindle tool from it +printf 'T1 P1 Z+1.000000\nnot a tool line\n' > tool.tbl +run_ui random-start-ui.py 1 + +# run 6: a table file made while the machine runs is not saved over +rm -f tool.tbl +run_ui missing-ui.py 1 + +# run 7: nor is one changed or replaced since it was loaded +printf 'T1 P1 Z+1.000000\nT2 P2 Z+2.000000\n' > tool.tbl +run_ui external-edit-ui.py 0 + +# run 8: loading another file does not lift the protection of this one +printf 'T1 P1 Z+1.000000\nnot a tool line\n' > tool.tbl +printf 'T8 P8 Z+8.000000\nT9 P9 Z+9.000000\n' > other.tbl +run_ui other-table-ui.py 0 + +# run 9: saving through a symbolic link keeps the link +rm -rf tool.tbl linked +mkdir linked +printf 'T1 P1 Z+1.000000\nT2 P2 Z+2.000000\n' > linked/real.tbl +chmod 640 linked/real.tbl +ln -s real.tbl linked/alias.tbl +ln -s linked/alias.tbl tool.tbl +run_ui symlink-ui.py 0 +rm -rf tool.tbl linked diff --git a/linuxcnc-tests/tool-wear-abort/.gitignore b/linuxcnc-tests/tool-wear-abort/.gitignore new file mode 100644 index 00000000..09798bf4 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/.gitignore @@ -0,0 +1,4 @@ +sim.var +sim.var.bak +tool.tbl +lathe.ini diff --git a/linuxcnc-tests/tool-wear-abort/change-move.ngc b/linuxcnc-tests/tool-wear-abort/change-move.ngc new file mode 100644 index 00000000..df79eee2 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/change-move.ngc @@ -0,0 +1,5 @@ +; T2 M6, then a move; the test holds the change handshake open. +G21 G90 +T2 M6 +G0 X0 Z0 +M2 diff --git a/linuxcnc-tests/tool-wear-abort/change-then-end.ngc b/linuxcnc-tests/tool-wear-abort/change-then-end.ngc new file mode 100644 index 00000000..e02acfd4 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/change-then-end.ngc @@ -0,0 +1,3 @@ +G21 G90 +T2 M6 +M2 diff --git a/linuxcnc-tests/tool-wear-abort/checkresult b/linuxcnc-tests/tool-wear-abort/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/tool-wear-abort/core_sim_handshake.hal b/linuxcnc-tests/tool-wear-abort/core_sim_handshake.hal new file mode 100644 index 00000000..b1fdce42 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/core_sim_handshake.hal @@ -0,0 +1,18 @@ +# lib/hallib/core_sim.hal without the tool-change loopback: test-ui.py +# completes (or withholds) the prepare and change handshakes. +loadrt [KINS]KINEMATICS +loadrt [EMCMOT]EMCMOT base_period_nsec=[EMCMOT]BASE_PERIOD servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS +addf motion-command-handler servo-thread +addf motion-controller servo-thread + +net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb +net Ypos joint.1.motor-pos-cmd => joint.1.motor-pos-fb +net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb + +net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in + +net tool-prepare <= iocontrol.0.tool-prepare +net tool-prepared => iocontrol.0.tool-prepared +net tool-change <= iocontrol.0.tool-change +net tool-changed => iocontrol.0.tool-changed +net tool-number <= iocontrol.0.tool-number diff --git a/linuxcnc-tests/tool-wear-abort/interp-error-m6.ngc b/linuxcnc-tests/tool-wear-abort/interp-error-m6.ngc new file mode 100644 index 00000000..ac36eff1 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/interp-error-m6.ngc @@ -0,0 +1,7 @@ +; The M6 block queues the change and its offset, then fails on G1 with no +; feed rate; the queued commands are discarded by the error path. +G21 G90 G94 +F0 +G0 X1 +T2 M6 G1 X10 +M2 diff --git a/linuxcnc-tests/tool-wear-abort/move-origin.ngc b/linuxcnc-tests/tool-wear-abort/move-origin.ngc new file mode 100644 index 00000000..1d668475 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/move-origin.ngc @@ -0,0 +1,5 @@ +; run in AUTO right after the failed program, without a mode switch +G21 G90 +(debug,applied #5081 #5083) +G0 X0 Z0 +M2 diff --git a/linuxcnc-tests/tool-wear-abort/postgui.hal b/linuxcnc-tests/tool-wear-abort/postgui.hal new file mode 100644 index 00000000..114712da --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/postgui.hal @@ -0,0 +1,5 @@ +net tool-prepare => python-ui.tool-prepare +net tool-prepared <= python-ui.tool-prepared +net tool-change => python-ui.tool-change +net tool-changed <= python-ui.tool-changed +net tool-number => python-ui.tool-number diff --git a/linuxcnc-tests/tool-wear-abort/readahead-g43.ngc b/linuxcnc-tests/tool-wear-abort/readahead-g43.ngc new file mode 100644 index 00000000..b0ab68ca --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/readahead-g43.ngc @@ -0,0 +1,6 @@ +; The same for a plain G43 H2: upstream's read-ahead case. +G21 G90 +G1 X100 F60 +G43 H2 +G0 X0 Z0 +M2 diff --git a/linuxcnc-tests/tool-wear-abort/readahead-m61.ngc b/linuxcnc-tests/tool-wear-abort/readahead-m61.ngc new file mode 100644 index 00000000..e9fa7e5a --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/readahead-m61.ngc @@ -0,0 +1,7 @@ +; M61 Q2 (and its automatic offset) is interpreted while the slow move +; runs; the test aborts before the move ends, so neither executes. +G21 G90 +G1 X100 F60 +M61 Q2 +G0 X0 Z0 +M2 diff --git a/linuxcnc-tests/tool-wear-abort/test-ui.py b/linuxcnc-tests/tool-wear-abort/test-ui.py new file mode 100755 index 00000000..be0836e2 --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/test-ui.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +"""Abort or E-stop with an automatic tool offset interpreted but not executed. + +Built-in M6 and M61 queue their geometry-plus-wear offset behind the tool +change. When the change (or the move ahead of it) is aborted, the spindle +keeps the old tool, and so must every copy of the applied offset: canon's, +the interpreter's, #5081-#5089 and motion's. The check that matters is where +the next move goes: G0 X0 Z0 must land on the loaded tool's geometry plus +wear in machine coordinates. +""" + +import linuxcnc +import hal + +import math +import os +import sys +import time + +sys.stdout = os.fdopen(sys.stdout.fileno(), 'w') + +EPS = 1e-6 +HERE = os.path.dirname(os.path.abspath(__file__)) + +# geometry plus wear (X, Z) per tool; T0 is the empty spindle +APPLIED = {0: (0.0, 0.0), 1: (5.2, 9.9), 2: (-2.8, 20.15)} +POCKET = {1: 1, 2: 2} + + +def fail(msg): + print("ERROR: " + msg) + os.system("halcmd show pin python-ui") + sys.exit(1) + + +failures = [] + + +def check(what, got, expected): + """Record a mismatch and carry on, so one run shows every copy of the + offset that went wrong; the test fails at the end.""" + print("%s = %.6f (expecting %.6f)" % (what, got, expected)) + if math.fabs(got - expected) > EPS: + print("MISMATCH: %s = %f, expected %f" % (what, got, expected)) + failures.append(what) + + +def wait_for(predicate, what, timeout=10): + start = time.time() + while not predicate(): + if time.time() - start > timeout: + fail("timeout waiting for " + what) + time.sleep(0.01) + s.poll() + + +def wait_pin(name, value, timeout=5): + start = time.time() + while h[name] != value: + if time.time() - start > timeout: + fail("pin %s did not reach %s" % (name, value)) + time.sleep(0.01) + + +def wait_done(what, timeout=5): + start = time.time() + while time.time() - start < timeout: + s.poll() + if s.state == linuxcnc.RCS_DONE and \ + s.interp_state == linuxcnc.INTERP_IDLE: + return + time.sleep(0.01) + fail("not idle after %s" % what) + + +def prepare_handshake(): + wait_pin('tool-prepare', 1) + h['tool-prepared'] = 1 + wait_pin('tool-prepare', 0) + h['tool-prepared'] = 0 + + +def change_handshake(): + wait_pin('tool-change', 1) + h['tool-changed'] = 1 + wait_pin('tool-change', 0) + h['tool-changed'] = 0 + + +def mdi(cmd): + print("mdi: " + cmd) + c.mode(linuxcnc.MODE_MDI) + c.wait_complete() + c.mdi(cmd) + if c.wait_complete(30) == -1: + fail("timeout running '%s'" % cmd) + s.poll() + + +def param(n): + c.mode(linuxcnc.MODE_MDI) + c.wait_complete() + c.mdi("(debug,#%d)" % n) + c.wait_complete() + start = time.time() + while time.time() - start < 10: + err = e.poll() + if err is None: + time.sleep(0.01) + continue + kind, text = err + if kind == linuxcnc.OPERATOR_DISPLAY: + return float(text) + print(text) + fail("no value for #%d" % n) + + +def drain_errors(): + while True: + err = e.poll() + if err is None: + return + print("(error channel: %s)" % (err[1],)) + + +def check_loaded(toolno, what): + """The spindle holds toolno and the next move uses its offset.""" + check_applied(toolno, toolno, what) + + +def check_applied(toolno, offset_of, what): + """The spindle holds toolno, and motion, canon, the interpreter and + #5081-#5089 all have tool offset_of's geometry plus wear, so the next + move lands there.""" + print("*** after %s: T%d loaded, T%d's offset applied" + % (what, toolno, offset_of)) + s.poll() + check("tool_in_spindle", s.tool_in_spindle, toolno) + ax, az = APPLIED[offset_of] + check("stat.tool_offset X", s.tool_offset[0], ax) + check("stat.tool_offset Z", s.tool_offset[2], az) + check("#5081 applied X", param(5081), ax) + check("#5083 applied Z", param(5083), az) + mdi("g0 x0 z0") + s.poll() + check("machine X after G0 X0 Z0", s.position[0], ax) + check("machine Z after G0 X0 Z0", s.position[2], az) + + +def rebaseline(): + """Put T1 back with every copy of its offset, whatever the previous + scenario left behind, so each scenario is checked on its own.""" + mdi("m61 q1") + mdi("g43") + + +def load_tool(toolno): + c.mode(linuxcnc.MODE_MDI) + c.wait_complete() + c.mdi("t%d m6" % toolno) + prepare_handshake() + change_handshake() + if c.wait_complete(10) == -1: + fail("t%d m6 did not complete" % toolno) + check_loaded(toolno, "t%d m6" % toolno) + + +def machine_on(): + c.state(linuxcnc.STATE_ESTOP_RESET) + c.state(linuxcnc.STATE_ON) + c.mode(linuxcnc.MODE_MDI) + c.wait_complete() + + +def run_and_abort(program, abort_at_line): + """Run program in AUTO and abort once it has read abort_at_line, while + the slow move ahead of it is still running.""" + print("*** running %s, aborting after line %d is read" % (program, abort_at_line)) + c.mode(linuxcnc.MODE_AUTO) + c.wait_complete() + c.program_open(os.path.join(HERE, program)) + c.auto(linuxcnc.AUTO_RUN, 0) + start = time.time() + while True: + s.poll() + if s.read_line >= abort_at_line and s.current_vel > 0: + break + if time.time() - start > 10: + fail("%s never got to line %d while moving" % (program, abort_at_line)) + time.sleep(0.01) + time.sleep(0.2) + c.abort() + wait_done("abort of " + program) + drain_errors() + + +h = hal.component("python-ui") +h.newpin("tool-number", hal.Type.SINT, hal.Dir.IN) +h.newpin("tool-prepare", hal.Type.BOOL, hal.Dir.IN) +h.newpin("tool-prepared", hal.Type.BOOL, hal.Dir.OUT) +h.newpin("tool-change", hal.Type.BOOL, hal.Dir.IN) +h.newpin("tool-changed", hal.Type.BOOL, hal.Dir.OUT) +h.ready() +os.system("halcmd source ./postgui.hal") + +c = linuxcnc.command() +s = linuxcnc.stat() +e = linuxcnc.error_channel() + +machine_on() + +load_tool(1) + +print("*** abort while the PREPARE handshake for T2 is pending") +c.mdi("t2 m6") +wait_pin('tool-prepare', 1) +c.abort() +wait_pin('tool-prepare', 0) +wait_done("abort during prepare") +drain_errors() +check_loaded(1, "abort during prepare") + +rebaseline() +print("*** abort while the CHANGE handshake for T2 is pending") +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() +c.mdi("t2 m6") +prepare_handshake() +wait_pin('tool-change', 1) +c.abort() +wait_pin('tool-change', 0) +wait_done("abort during change") +drain_errors() +check_loaded(1, "abort during change") + +rebaseline() +print("*** E-stop while the CHANGE handshake for T2 is pending") +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() +c.mdi("t2 m6") +prepare_handshake() +wait_pin('tool-change', 1) +c.state(linuxcnc.STATE_ESTOP) +wait_pin('tool-change', 0) +wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP and + s.state == linuxcnc.RCS_DONE, "E-stop") +drain_errors() +machine_on() +check_loaded(1, "E-stop during change") + +rebaseline() +print("*** machine off while the CHANGE handshake for T2 is pending") +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() +c.mdi("t2 m6") +prepare_handshake() +wait_pin('tool-change', 1) +c.state(linuxcnc.STATE_OFF) +wait_pin('tool-change', 0) +# status reports a machine that is off as STATE_ESTOP_RESET +wait_for(lambda: s.task_state != linuxcnc.STATE_ON and + s.state == linuxcnc.RCS_DONE, "machine off") +drain_errors() +machine_on() +check_loaded(1, "machine off during change") + +rebaseline() +run_and_abort("readahead-m61.ngc", 5) +# M61 Q2 and its offset take effect together, after the move: the abort +# during the move discards both. +check_loaded(1, "abort with M61 Q2 read ahead") + +rebaseline() +run_and_abort("readahead-g43.ngc", 5) +check_loaded(1, "abort with G43 H2 read ahead") + +rebaseline() +def hold_change_then_abort(hold, what): + """Run change-move.ngc, hold the program (hold()) while the change + handshake is pending, complete the change, then abort: the change + completed, so T2 and its offset are both in effect.""" + print("*** %s at the change handshake, change completed, then abort" % what) + c.mode(linuxcnc.MODE_AUTO) + c.wait_complete() + c.program_open(os.path.join(HERE, "change-move.ngc")) + c.auto(linuxcnc.AUTO_RUN, 0) + prepare_handshake() + wait_pin('tool-change', 1) + hold() + change_handshake() + wait_for(lambda: s.tool_in_spindle == 2, "T2 in the spindle") + c.abort() + wait_done("abort after a held change") + drain_errors() + check_loaded(2, "%s, change completed, abort" % what) + + +def pause(): + c.auto(linuxcnc.AUTO_PAUSE) + wait_for(lambda: s.task_paused, "pause") + + +def program_stop(): + c.program_stop() + wait_for(lambda: s.stop_state != linuxcnc.STOP_IDLE, "Stop") + + +rebaseline() +hold_change_then_abort(pause, "pause") + +rebaseline() +hold_change_then_abort(program_stop, "resumable Stop") + +rebaseline() +print("*** an interpreter error on the M6 line after the change was queued") +c.mode(linuxcnc.MODE_AUTO) +c.wait_complete() +c.program_open(os.path.join(HERE, "interp-error-m6.ngc")) +c.auto(linuxcnc.AUTO_RUN, 0) +wait_done("interp-error-m6.ngc") +drain_errors() +# the next program in AUTO, before any mode switch (which would resync) +c.program_open(os.path.join(HERE, "move-origin.ngc")) +c.auto(linuxcnc.AUTO_RUN, 0) +reported = None +start = time.time() +while reported is None and time.time() - start < 10: + err = e.poll() + if err is None: + time.sleep(0.01) + elif err[0] == linuxcnc.OPERATOR_DISPLAY and err[1].startswith("applied"): + reported = [float(v) for v in err[1].split()[1:]] + else: + print(err[1]) +wait_done("move-origin.ngc") +if reported is None: + fail("move-origin.ngc reported nothing") +s.poll() +check("#5081 in the next AUTO program", reported[0], APPLIED[1][0]) +check("#5083 in the next AUTO program", reported[1], APPLIED[1][1]) +check("machine X after its G0 X0 Z0", s.position[0], APPLIED[1][0]) +check("machine Z after its G0 X0 Z0", s.position[2], APPLIED[1][1]) +check_loaded(1, "interpreter error on the M6 line") + +rebaseline() +print("*** a completed change at program end") +c.mode(linuxcnc.MODE_AUTO) +c.wait_complete() +c.program_open(os.path.join(HERE, "change-then-end.ngc")) +c.auto(linuxcnc.AUTO_RUN, 0) +prepare_handshake() +change_handshake() +wait_done("change-then-end.ngc", timeout=10) +check_loaded(2, "T2 M6 then M2") + +if failures: + fail("%d mismatches" % len(failures)) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-wear-abort/test.sh b/linuxcnc-tests/tool-wear-abort/test.sh new file mode 100755 index 00000000..c7ee908a --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/test.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +cp -f tool.tbl.original tool.tbl +rm -f sim.var + +../tool-wear-common/make-ini.sh lathe.ini halfile=core_sim_handshake.hal +exec linuxcnc -r lathe.ini diff --git a/linuxcnc-tests/tool-wear-abort/tool.tbl.original b/linuxcnc-tests/tool-wear-abort/tool.tbl.original new file mode 100644 index 00000000..1026231c --- /dev/null +++ b/linuxcnc-tests/tool-wear-abort/tool.tbl.original @@ -0,0 +1,2 @@ +T1 P1 X+5.000000 Z+10.000000 WX+0.200000 WZ-0.100000 Q3 ;front tool +T2 P2 X-2.500000 Z+20.000000 WX-0.300000 WZ+0.150000 Q2 ;back tool diff --git a/linuxcnc-tests/tool-wear-common/lathe.ini.in b/linuxcnc-tests/tool-wear-common/lathe.ini.in new file mode 100644 index 00000000..b4d12ae9 --- /dev/null +++ b/linuxcnc-tests/tool-wear-common/lathe.ini.in @@ -0,0 +1,84 @@ +# A metric lathe shared by the tool wear and tool table tests. +# make-ini.sh writes each test's copy. + +[EMC] +VERSION = 1.1 +DEBUG = 0 + +[DISPLAY] +DISPLAY = ./test-ui.py +LATHE = 1 + +[RS274NGC] +PARAMETER_FILE = sim.var + +[EMCMOT] +EMCMOT = motmod +COMM_TIMEOUT = 4.0 +BASE_PERIOD = 0 +SERVO_PERIOD = 1000000 + +[TASK] +TASK = milltask +CYCLE_TIME = 0.001 + +[HAL] +HALFILE = LIB:core_sim.hal + +[TRAJ] +NO_FORCE_HOMING = 1 +COORDINATES = X Z +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 30 +MAX_LINEAR_VELOCITY = 100 + +[EMCIO] +TOOL_TABLE = tool.tbl +RANDOM_TOOLCHANGER = 0 + +[KINS] +KINEMATICS = trivkins +JOINTS = 3 + +[AXIS_X] +MIN_LIMIT = -300.0 +MAX_LIMIT = 300.0 +MAX_VELOCITY = 100 +MAX_ACCELERATION = 1000.0 + +[JOINT_0] +TYPE = LINEAR +HOME = 0.0 +MAX_VELOCITY = 100 +MAX_ACCELERATION = 1000.0 +MIN_LIMIT = -300.0 +MAX_LIMIT = 300.0 +FERROR = 1.0 +MIN_FERROR = 0.25 +HOME_SEQUENCE = 0 + +[AXIS_Z] +MIN_LIMIT = -300.0 +MAX_LIMIT = 300.0 +MAX_VELOCITY = 100 +MAX_ACCELERATION = 1000.0 + +[JOINT_1] +# Y, not used on the lathe +TYPE = LINEAR +HOME = 0.0 +MAX_VELOCITY = 100 +MAX_ACCELERATION = 1000.0 +HOME_SEQUENCE = 0 + +[JOINT_2] +TYPE = LINEAR +HOME = 0.0 +MAX_VELOCITY = 100 +MAX_ACCELERATION = 1000.0 +MIN_LIMIT = -300.0 +MAX_LIMIT = 300.0 +FERROR = 1.0 +MIN_FERROR = 0.25 +HOME_SEQUENCE = 0 diff --git a/linuxcnc-tests/tool-wear-common/make-ini.sh b/linuxcnc-tests/tool-wear-common/make-ini.sh new file mode 100755 index 00000000..2e1b1f2f --- /dev/null +++ b/linuxcnc-tests/tool-wear-common/make-ini.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# Usage: make-ini.sh OUTPUT [ui=PROGRAM] [random=0|1] [halfile=FILE] +set -e +output=$1 +shift +ui=./test-ui.py random=0 halfile=LIB:core_sim.hal +for setting in "$@"; do + case "$setting" in + ui=*) ui=${setting#ui=} ;; + random=*) random=${setting#random=} ;; + halfile=*) halfile=${setting#halfile=} ;; + *) echo "make-ini.sh: unknown setting $setting" >&2; exit 2 ;; + esac +done +sed -e "s#^DISPLAY = ./test-ui.py\$#DISPLAY = $ui#" \ + -e "s#^RANDOM_TOOLCHANGER = 0\$#RANDOM_TOOLCHANGER = $random#" \ + -e "s#^HALFILE = LIB:core_sim.hal\$#HALFILE = $halfile#" \ + "$(dirname "$0")/lathe.ini.in" > "$output" diff --git a/linuxcnc-tests/tool-wear-restart/.gitignore b/linuxcnc-tests/tool-wear-restart/.gitignore new file mode 100644 index 00000000..99ef76e2 --- /dev/null +++ b/linuxcnc-tests/tool-wear-restart/.gitignore @@ -0,0 +1,5 @@ +sim.var +sim.var.bak +tool.tbl +run1.ini +run2.ini diff --git a/linuxcnc-tests/tool-wear-restart/checkresult b/linuxcnc-tests/tool-wear-restart/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/tool-wear-restart/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/tool-wear-restart/common.py b/linuxcnc-tests/tool-wear-restart/common.py new file mode 100644 index 00000000..ed5a426e --- /dev/null +++ b/linuxcnc-tests/tool-wear-restart/common.py @@ -0,0 +1,72 @@ +# shared by run1.py and run2.py +import linuxcnc +import linuxcnc_util + +import math +import sys +import time + +c = linuxcnc.command() +e = linuxcnc.error_channel() +s = linuxcnc.stat() +l = linuxcnc_util.LinuxCNC(command=c, status=s, error=e) + + +def fail(msg): + print("ERROR: " + msg) + sys.exit(1) + + +def check(what, got, expected): + print("%s = %.6f (expecting %.6f)" % (what, got, expected)) + if math.fabs(got - expected) > 1e-6: + fail("%s = %f, expected %f" % (what, got, expected)) + + +def start(): + l.wait_for_linuxcnc_startup() + c.state(linuxcnc.STATE_ESTOP_RESET) + c.state(linuxcnc.STATE_ON) + c.mode(linuxcnc.MODE_MDI) + c.wait_complete() + + +def mdi(cmd): + print("mdi: " + cmd) + c.mdi(cmd) + if c.wait_complete(10) == -1: + fail("timeout running '%s'" % cmd) + s.poll() + + +def param(n): + c.mdi("(debug,#%d)" % n) + c.wait_complete() + start_time = time.time() + while time.time() - start_time < 10: + err = e.poll() + if err is None: + time.sleep(0.01) + continue + if err[0] == linuxcnc.OPERATOR_DISPLAY: + return float(err[1]) + print(err[1]) + fail("no value for #%d" % n) + + +def check_state(toolno, stored, wear, applied): + s.poll() + check("tool_in_spindle", s.tool_in_spindle, toolno) + check("#5400 tool", param(5400), toolno) + check("#5401 stored geometry X", param(5401), stored[0]) + check("#5403 stored geometry Z", param(5403), stored[1]) + check("#5430 stored wear X", param(5430), wear[0]) + check("#5432 stored wear Z", param(5432), wear[1]) + check("#5081 applied X", param(5081), applied[0]) + check("#5083 applied Z", param(5083), applied[1]) + s.poll() + check("stat.tool_offset X", s.tool_offset[0], applied[0]) + check("stat.tool_offset Z", s.tool_offset[2], applied[1]) + mdi("g0 x0 z0") + check("machine X after G0 X0 Z0", s.position[0], applied[0]) + check("machine Z after G0 X0 Z0", s.position[2], applied[1]) diff --git a/linuxcnc-tests/tool-wear-restart/run1.py b/linuxcnc-tests/tool-wear-restart/run1.py new file mode 100755 index 00000000..35238107 --- /dev/null +++ b/linuxcnc-tests/tool-wear-restart/run1.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 +from common import * + +start() +mdi("t1 m6") +l.wait_for_tool_in_spindle(1) +mdi("g10 l3 p1 x0.3") +check_state(1, (5.0, 10.0), (0.3, -0.1), (5.2, 9.9)) +print("*** run 1 done, T1 in the spindle") +sys.exit(0) diff --git a/linuxcnc-tests/tool-wear-restart/run2.py b/linuxcnc-tests/tool-wear-restart/run2.py new file mode 100755 index 00000000..5feff1ad --- /dev/null +++ b/linuxcnc-tests/tool-wear-restart/run2.py @@ -0,0 +1,18 @@ +#!/usr/bin/env python3 +from common import * + +start() +print("*** after the restart: T1 loaded, its stored values back, no offset") +check_state(1, (5.0, 10.0), (0.3, -0.1), (0.0, 0.0)) +print("*** G43 applies T1's geometry plus wear") +mdi("g43") +check_state(1, (5.0, 10.0), (0.3, -0.1), (5.3, 9.9)) +print("*** M6 to T2 and back applies each tool's geometry plus wear") +mdi("t2 m6") +l.wait_for_tool_in_spindle(2) +check_state(2, (-2.5, 20.0), (-0.3, 0.15), (-2.8, 20.15)) +mdi("t1 m6") +l.wait_for_tool_in_spindle(1) +check_state(1, (5.0, 10.0), (0.3, -0.1), (5.3, 9.9)) +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-wear-restart/test.sh b/linuxcnc-tests/tool-wear-restart/test.sh new file mode 100755 index 00000000..72a85fdb --- /dev/null +++ b/linuxcnc-tests/tool-wear-restart/test.sh @@ -0,0 +1,14 @@ +#!/bin/bash +set -e +cp -f tool.tbl.original tool.tbl +rm -f sim.var + +# run 1: load T1, change its wear, shut down with it in the spindle +../tool-wear-common/make-ini.sh run1.ini ui=./run1.py random=1 +linuxcnc -r run1.ini +cat tool.tbl + +# run 2: T1 is still in the spindle with its stored wear, but no offset is +# applied until G43, M6 or M61 +../tool-wear-common/make-ini.sh run2.ini ui=./run2.py random=1 +linuxcnc -r run2.ini diff --git a/linuxcnc-tests/tool-wear-restart/tool.tbl.original b/linuxcnc-tests/tool-wear-restart/tool.tbl.original new file mode 100644 index 00000000..1026231c --- /dev/null +++ b/linuxcnc-tests/tool-wear-restart/tool.tbl.original @@ -0,0 +1,2 @@ +T1 P1 X+5.000000 Z+10.000000 WX+0.200000 WZ-0.100000 Q3 ;front tool +T2 P2 X-2.500000 Z+20.000000 WX-0.300000 WZ+0.150000 Q2 ;back tool diff --git a/linuxcnc-tests/tool-wear-task/.gitignore b/linuxcnc-tests/tool-wear-task/.gitignore new file mode 100644 index 00000000..09798bf4 --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/.gitignore @@ -0,0 +1,4 @@ +sim.var +sim.var.bak +tool.tbl +lathe.ini diff --git a/linuxcnc-tests/tool-wear-task/checkresult b/linuxcnc-tests/tool-wear-task/checkresult new file mode 100755 index 00000000..24dc9aa5 --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value diff --git a/linuxcnc-tests/tool-wear-task/remap.py b/linuxcnc-tests/tool-wear-task/remap.py new file mode 100644 index 00000000..05e1a699 --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/remap.py @@ -0,0 +1,15 @@ +import emccanon +from interpreter import INTERP_OK + + +def out_of_range_tools(self, **words): + """Report what emccanon.GET_EXTERNAL_TOOL_TABLE gives for indexes + outside the table: an empty entry, wear included.""" + for idx in (-1, 100000): + t = emccanon.GET_EXTERNAL_TOOL_TABLE(idx) + w = t.wear_offset + emccanon.MESSAGE("out-of-range %d: toolno %d wear %r" + % (idx, t.toolno, + [w.tran.x, w.tran.y, w.tran.z, w.a, w.b, w.c, + w.u, w.v, w.w])) + return INTERP_OK diff --git a/linuxcnc-tests/tool-wear-task/test-ui.py b/linuxcnc-tests/tool-wear-task/test-ui.py new file mode 100755 index 00000000..a6a6fd6b --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/test-ui.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""Native tool wear through task, on a metric lathe. + +The tool table gives a front tool (T1) and a back tool (T2) X and Z wear. +Built-in M6 and M61 apply geometry plus wear; G10 L3 edits stored wear +without touching the applied offset until G43; the table file keeps the +W* words and reads back the same. Checked from both sides: interpreter +parameters (#5401-#5409 stored geometry, #5430-#5438 stored wear, +#5081-#5089 applied offset) and the Python status (tool_table, toolinfo, +tool_offset). +""" + +import linuxcnc +import linuxcnc_util + +import math +import os +import sys +import time + +sys.stdout = os.fdopen(sys.stdout.fileno(), 'w') + +c = linuxcnc.command() +e = linuxcnc.error_channel() +s = linuxcnc.stat() +l = linuxcnc_util.LinuxCNC(command=c, status=s, error=e) + +TOOL_TABLE = "tool.tbl" +EPS = 1e-6 + + +def fail(msg): + print("ERROR: " + msg) + sys.exit(1) + + +def check(what, got, expected): + print("%s = %.6f (expecting %.6f)" % (what, got, expected)) + if math.fabs(got - expected) > EPS: + fail("%s = %f, expected %f" % (what, got, expected)) + + +def mdi(cmd): + print("mdi: " + cmd) + c.mdi(cmd) + if c.wait_complete(10) == -1: + fail("timeout running '%s'" % cmd) + # The status the checks below read must be from after the command. + s.poll() + + +def param(n): + c.mdi("(debug,#%d)" % n) + c.wait_complete() + start = time.time() + while time.time() - start < 10: + err = e.poll() + if err is None: + time.sleep(0.01) + continue + kind, text = err + if kind == linuxcnc.OPERATOR_DISPLAY: + return float(text) + print(text) + fail("no value for #%d" % n) + + +def check_params(stored_x, stored_z, wear_x, wear_z, applied_x, applied_z): + check("#5401 stored geometry X", param(5401), stored_x) + check("#5403 stored geometry Z", param(5403), stored_z) + check("#5430 stored wear X", param(5430), wear_x) + check("#5432 stored wear Z", param(5432), wear_z) + check("#5081 applied X", param(5081), applied_x) + check("#5083 applied Z", param(5083), applied_z) + s.poll() + check("stat.tool_offset X", s.tool_offset[0], applied_x) + check("stat.tool_offset Z", s.tool_offset[2], applied_z) + + +def reload_table(): + """Reload the table file and wait until task has done it.""" + c.load_tool_table() + c.wait_complete(10) + start = time.time() + while True: + s.poll() + if s.state == linuxcnc.RCS_DONE and s.exec_state == linuxcnc.EXEC_DONE: + return + if time.time() - start > 10: + fail("tool table reload did not complete") + time.sleep(0.01) + + +def machine_at(x, z, machine_x, machine_z): + """G0 to program X, Z and check where the machine was commanded.""" + mdi("g0 x%s z%s" % (x, z)) + s.poll() + check("machine X after G0 X%s" % x, s.position[0], machine_x) + check("machine Z after G0 Z%s" % z, s.position[2], machine_z) + + +def check_tool(toolno, x, z, wx, wz): + s.poll() + # index 0 is the spindle mirror of the loaded tool + entry = [t for t in s.tool_table[1:] if t.id == toolno] + if len(entry) != 1: + fail("tool %d not in stat.tool_table" % toolno) + t = entry[0] + check("stat.tool_table T%d xoffset" % toolno, t.xoffset, x) + check("stat.tool_table T%d zoffset" % toolno, t.zoffset, z) + check("stat.tool_table T%d wxoffset" % toolno, t.wxoffset, wx) + check("stat.tool_table T%d wzoffset" % toolno, t.wzoffset, wz) + info = s.toolinfo(toolno) + check("stat.toolinfo(%d) wxoffset" % toolno, info["wxoffset"], wx) + check("stat.toolinfo(%d) wzoffset" % toolno, info["wzoffset"], wz) + + +def table_line(toolno): + with open(TOOL_TABLE) as f: + for line in f: + if line.split() and line.split()[0] == "T%d" % toolno: + return line.strip() + fail("T%d missing from %s" % (toolno, TOOL_TABLE)) + + +def check_table_words(toolno, **words): + """The tool's line in the table file, as numbers: a word the file + leaves out (zero values may be omitted) counts as zero.""" + line = table_line(toolno) + print("%s: %s" % (TOOL_TABLE, line)) + values = {} + for token in line.split(";")[0].split()[2:]: + letters = token.rstrip("+-.0123456789") + values[letters] = float(token[len(letters):]) + for word, expected in words.items(): + check("%s T%d %s" % (TOOL_TABLE, toolno, word), values.get(word, 0.0), + expected) + + +l.wait_for_linuxcnc_startup() +c.state(linuxcnc.STATE_ESTOP_RESET) +c.state(linuxcnc.STATE_ON) +c.mode(linuxcnc.MODE_MDI) +c.wait_complete() + +print("*** the table as loaded") +check_tool(1, 5.0, 10.0, 0.2, -0.1) +check_tool(2, -2.5, 20.0, -0.3, 0.15) + +print("*** T1 M6 applies T1's geometry plus wear (front tool)") +mdi("t1 m6") +l.wait_for_tool_in_spindle(1) +check_params(5.0, 10.0, 0.2, -0.1, 5.2, 9.9) +check("stat.tool_table[0] wxoffset", s.tool_table[0].wxoffset, 0.2) +check("stat.tool_table[0] wzoffset", s.tool_table[0].wzoffset, -0.1) +machine_at(0, 0, 5.2, 9.9) + +print("*** G10 L3 edits stored wear; the applied offset waits for G43") +mdi("g10 l3 p1 x0.3 z-0.05") +check_params(5.0, 10.0, 0.3, -0.05, 5.2, 9.9) +check_tool(1, 5.0, 10.0, 0.3, -0.05) +check_table_words(1, X=5.0, Z=10.0, WX=0.3, WZ=-0.05) + +mdi("g43") +check_params(5.0, 10.0, 0.3, -0.05, 5.3, 9.95) + +print("*** G10 L3 keeps the axes it is not given") +mdi("g10 l3 p1 z0") +check_tool(1, 5.0, 10.0, 0.3, 0.0) +mdi("g43") +check_params(5.0, 10.0, 0.3, 0.0, 5.3, 10.0) + +print("*** G7: G10 L3 X is a diameter") +mdi("g7") +mdi("g10 l3 p2 x0.4") +mdi("g8") +check_tool(2, -2.5, 20.0, 0.2, 0.15) + +print("*** M61 Q2 applies T2's geometry plus wear (back tool)") +mdi("m61 q2") +l.wait_for_tool_in_spindle(2) +check_params(-2.5, 20.0, 0.2, 0.15, -2.3, 20.15) +machine_at(0, 0, -2.3, 20.15) + +print("*** G43 H1 applies T1's geometry plus wear with T2 loaded") +mdi("g43 h1") +check_params(-2.5, 20.0, 0.2, 0.15, 5.3, 10.0) + +print("*** G49 cancels the applied offset, stored values stay") +mdi("g49") +check_params(-2.5, 20.0, 0.2, 0.15, 0.0, 0.0) + +print("*** a G49 in the M6 block wins") +mdi("t1 m6 g49") +l.wait_for_tool_in_spindle(1) +check_params(5.0, 10.0, 0.3, 0.0, 0.0, 0.0) + +print("*** an explicit offset in the change block wins") +mdi("t2 m6 g43 h1") +l.wait_for_tool_in_spindle(2) +check_params(-2.5, 20.0, 0.2, 0.15, 5.3, 10.0) +machine_at(0, 0, 5.3, 10.0) +mdi("m61 q1 g49") +l.wait_for_tool_in_spindle(1) +check_params(5.0, 10.0, 0.3, 0.0, 0.0, 0.0) +mdi("g43") +mdi("m61 q0") +l.wait_for_tool_in_spindle(0) +check_params(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) +mdi("t1 m6 g49") +l.wait_for_tool_in_spindle(1) + +print("*** T0 M6 clears everything") +mdi("t0 m6") +l.wait_for_tool_in_spindle(0) +check_params(0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + +print("*** the table file round-trips the W* words") +check_table_words(1, X=5.0, Z=10.0, WX=0.3, WZ=0.0) +check_table_words(2, X=-2.5, Z=20.0, WX=0.2, WZ=0.15, Q=2) +reload_table() +check_tool(1, 5.0, 10.0, 0.3, 0.0) +check_tool(2, -2.5, 20.0, 0.2, 0.15) +mdi("t2 m6") +l.wait_for_tool_in_spindle(2) +check_params(-2.5, 20.0, 0.2, 0.15, -2.3, 20.15) + +print("*** an inch program on the metric lathe") +# offsets and #5081-#5089 stay in machine units (mm); positions and +# G10 L3 values are inches +mdi("g20") +mdi("t1 m6") +l.wait_for_tool_in_spindle(1) +check_params(5.0, 10.0, 0.3, 0.0, 5.3, 10.0) +machine_at(1, 1, 25.4 + 5.3, 25.4 + 10.0) +mdi("g10 l3 p1 x0.01 z-0.002") +check_tool(1, 5.0, 10.0, 0.254, -0.0508) +check_table_words(1, X=5.0, Z=10.0, WX=0.254, WZ=-0.0508) +mdi("g43") +check_params(5.0, 10.0, 0.254, -0.0508, 5.254, 9.9492) +machine_at(1, 1, 25.4 + 5.254, 25.4 + 9.9492) +mdi("g21") +mdi("g10 l3 p1 x0.3 z0") +mdi("t2 m6") +l.wait_for_tool_in_spindle(2) +check_params(-2.5, 20.0, 0.2, 0.15, -2.3, 20.15) + +print("*** a tool line too long to write is refused, the file kept") +before = table_line(1) +# each %+f of 1e100 is over 100 characters: D, X and Z fit in a line, +# adding WX and WZ does not +mdi("#1 = [10 ** 100]") +mdi("g10 l1 p1 x#1 z#1 r#1") +long_line = table_line(1) +print("%s: T1 line is %d characters" % (TOOL_TABLE, len(long_line))) +if long_line == before or len(long_line) > 510: + fail("expected a long but valid T1 line, got %d characters" % len(long_line)) +c.mdi("g10 l3 p1 x#1 z#1") +c.wait_complete(10) +s.poll() +if table_line(1) != long_line: + fail("T1 line changed although it no longer fits: %s" % table_line(1)) +print("%s: T1 line unchanged" % TOOL_TABLE) +# what could not be stored is not kept in memory either +s.poll() +t1 = [t for t in s.tool_table[1:] if t.id == 1][0] +check("stat.tool_table T1 wxoffset after the refused save", t1.wxoffset, 0.3) +check("stat.tool_table T1 wzoffset after the refused save", t1.wzoffset, 0.0) +check("stat.toolinfo(1) wxoffset after the refused save", + s.toolinfo(1)["wxoffset"], 0.3) +check_table_words(2, X=-2.5, Z=20.0, WX=0.2, WZ=0.15, Q=2) +mdi("g10 l1 p1 x5 z10 r0.4") +mdi("g10 l3 p1 x0.3 z0") +check_table_words(1, X=5.0, Z=10.0, WX=0.3, WZ=0.0, D=0.8) +reload_table() +check_tool(1, 5.0, 10.0, 0.3, 0.0) + +print("*** tool entries out of range are empty, wear included") +mdi("m7") +expected = "toolno -1 wear %r" % ([0.0] * 9,) +seen = 0 +start = time.time() +while seen < 2 and time.time() - start < 10: + err = e.poll() + if err is None: + time.sleep(0.01) + continue + print(err[1]) + if err[1].startswith("out-of-range"): + seen += 1 + if not err[1].endswith(expected): + fail("out-of-range tool entry is not empty: %s" % err[1]) +if seen != 2: + fail("no out-of-range report from M7") + +print("*** all checks passed") +sys.exit(0) diff --git a/linuxcnc-tests/tool-wear-task/test.sh b/linuxcnc-tests/tool-wear-task/test.sh new file mode 100755 index 00000000..f5f4988a --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/test.sh @@ -0,0 +1,10 @@ +#!/bin/bash + +cp -f tool.tbl.original tool.tbl +rm -f sim.var + +../tool-wear-common/make-ini.sh lathe.ini +# M7 reads tool entries out of range through emccanon (remap.py) +sed -i '/^\[RS274NGC\]$/a REMAP = M7 modalgroup=8 python=out_of_range_tools' lathe.ini +printf '\n[PYTHON]\nPATH_PREPEND = .\nTOPLEVEL = toplevel.py\n' >> lathe.ini +exec linuxcnc -r lathe.ini diff --git a/linuxcnc-tests/tool-wear-task/tool.tbl.original b/linuxcnc-tests/tool-wear-task/tool.tbl.original new file mode 100644 index 00000000..feb7fa0d --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/tool.tbl.original @@ -0,0 +1,2 @@ +T1 P1 X+5.000000 Z+10.000000 WX+0.200000 WZ-0.100000 D+0.800000 I+80.000000 J+10.000000 Q3 ;front tool +T2 P2 X-2.500000 Z+20.000000 WX-0.300000 WZ+0.150000 D+0.400000 I+100.000000 J+30.000000 Q2 ;back tool diff --git a/linuxcnc-tests/tool-wear-task/toplevel.py b/linuxcnc-tests/tool-wear-task/toplevel.py new file mode 100644 index 00000000..0dc38fa2 --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/toplevel.py @@ -0,0 +1 @@ +import remap diff --git a/native/server/CMakeLists.txt b/native/server/CMakeLists.txt index 86ed9b62..dc23dd08 100644 --- a/native/server/CMakeLists.txt +++ b/native/server/CMakeLists.txt @@ -113,7 +113,7 @@ if(LINUXCNC_GRPC_ENABLE_NML AND src/gcode/parser.cc src/gcode/canon_preview.cc src/gcode/python_modules.cc - "${LINUXCNC_ROOT}/src/emc/rs274ngc/recordingcanon.cc") + src/gcode/recording_canon.cc) target_compile_definitions(linuxcnc-grpc-domain PUBLIC LINUXCNC_GRPC_HAS_RS274=1) set(LINUXCNC_GRPC_HAS_RS274 TRUE) target_compile_definitions(linuxcnc-grpc-domain PRIVATE ULAPI) @@ -146,7 +146,7 @@ if(LINUXCNC_GRPC_ENABLE_NML AND endif() endif() -if(LINUXCNC_GRPC_ENABLE_NML AND EXISTS "${LINUXCNC_ROOT}/src/hal/hal_priv.h") +if(LINUXCNC_GRPC_ENABLE_NML AND EXISTS "${LINUXCNC_ROOT}/src/hal/hal.h") find_library(LINUXCNC_HAL_LIBRARY NAMES linuxcnchal PATHS "${LINUXCNC_ROOT}/lib" NO_DEFAULT_PATH) if(LINUXCNC_HAL_LIBRARY) target_sources(linuxcnc-grpc-domain PRIVATE @@ -497,6 +497,25 @@ if(LINUXCNC_GRPC_BUILD_TESTS) "$") endif() + if(LINUXCNC_GRPC_HAS_HAL) + add_executable(linuxcnc-grpc-hal-value-codec-tests + tests/hal_value_codec_tests.cc) + target_compile_features(linuxcnc-grpc-hal-value-codec-tests PRIVATE cxx_std_20) + target_link_libraries(linuxcnc-grpc-hal-value-codec-tests PRIVATE + linuxcnc-grpc-domain) + target_compile_definitions(linuxcnc-grpc-hal-value-codec-tests PRIVATE ULAPI) + target_include_directories(linuxcnc-grpc-hal-value-codec-tests PRIVATE + "${CMAKE_CURRENT_SOURCE_DIR}/src" + "${LINUXCNC_ROOT}/include" + "${LINUXCNC_ROOT}/src" + "${LINUXCNC_ROOT}/src/hal" + "${LINUXCNC_ROOT}/src/rtapi") + target_compile_options(linuxcnc-grpc-hal-value-codec-tests PRIVATE + -Wall -Wextra -Wpedantic) + add_test(NAME linuxcnc-grpc-hal-value-codec-tests + COMMAND linuxcnc-grpc-hal-value-codec-tests) + endif() + if(LINUXCNC_GRPC_HAS_SCOPE) add_executable(linuxcnc-grpc-scope-controller-contract-tests tests/scope_controller_contract_tests.cc) diff --git a/native/server/GCODE_PARSER_INTEGRATION.md b/native/server/GCODE_PARSER_INTEGRATION.md index 62734059..980f76c1 100644 --- a/native/server/GCODE_PARSER_INTEGRATION.md +++ b/native/server/GCODE_PARSER_INTEGRATION.md @@ -7,8 +7,8 @@ and gRPC. Add these sources to the daemon's native target: native/server/src/gcode/parser.cc native/server/src/gcode/canon_preview.cc native/server/src/gcode/python_modules.cc -/src/emc/rs274ngc/recordingcanon.cc -/src/emc/rs274ngc/recordingcanon.hh +native/server/src/gcode/recording_canon.cc +native/server/src/gcode/recording_canon.hpp native/server/include/linuxcnc_grpc/gcode/parser.hpp native/server/include/linuxcnc_grpc/gcode/canon_preview.hpp native/server/include/linuxcnc_grpc/gcode/operation_types.hpp @@ -41,8 +41,8 @@ Add the Python development include directory reported by `emccanon` built-ins for remap support. Python is not part of the preview backend. -LinuxCNC's `recordingcanon.cc` is a separate link-selected implementation of -the global CANON API, like `gcodemodule.cc` (Axis) and `saicanon.cc` +`recording_canon.cc` is a separate link-selected implementation of LinuxCNC's +global CANON API, like `gcodemodule.cc` (Axis) and `saicanon.cc` (standalone interpretation). A parse-scoped `recording::Session` owns a queue of transport-neutral events. The daemon drains that queue only after an interpreter step and translates the events into its native operation model. diff --git a/native/server/include/linuxcnc_grpc/command_coordinator.hpp b/native/server/include/linuxcnc_grpc/command_coordinator.hpp index 9a3dc4bf..a43e4934 100644 --- a/native/server/include/linuxcnc_grpc/command_coordinator.hpp +++ b/native/server/include/linuxcnc_grpc/command_coordinator.hpp @@ -29,6 +29,16 @@ enum class CommandState { enum class CommandPriority { Normal, Safety, + // Safety, and also cancels every normal-priority command still queued when + // it is submitted. For commands after which earlier work must not run. + Interrupt, +}; + +// Whether a normal-priority command waits while the normal queue is held. +// Safety-priority commands never wait for a hold. +enum class CommandHoldPolicy { + Wait, + Bypass, }; enum class CommandSubmitStatus { @@ -58,6 +68,11 @@ struct CommandContext { std::function defer_completion; std::function mark_completed; std::function mark_failed; + // Stops later normal-priority commands from starting until the returned + // callable runs or the limit passes, whichever is first. The callable may run + // on any thread, more than once, and after a newer hold replaced this one. + std::function(std::chrono::milliseconds)> + hold_normal_commands; }; // A command is deliberately a native callable. The gRPC layer translates a @@ -65,6 +80,9 @@ struct CommandContext { // protobuf and can be exercised without LinuxCNC or a network connection. using CommandAction = std::function; using ContextCommandAction = std::function; +// Runs instead of the action when an Interrupt command cancels a queued +// command, so the command can release what it reserved when submitted. +using CommandCancelHandler = std::function; class CommandTicket { public: @@ -126,7 +144,11 @@ class CommandCoordinator { CommandSubmission submit_with_context(ContextCommandAction action); CommandSubmission submit_with_context( ContextCommandAction action, const std::stop_token& stop_token, - CommandPriority priority = CommandPriority::Normal); + CommandPriority priority = CommandPriority::Normal, + CommandHoldPolicy hold_policy = CommandHoldPolicy::Wait, + CommandCancelHandler on_cancelled = {}); + // Stops the worker after it drains both queues. A hold does not delay this: + // nothing resolves a hold once the service stops polling LinuxCNC. void shutdown(); std::size_t queued() const; @@ -136,9 +158,18 @@ class CommandCoordinator { CommandAction action; ContextCommandAction context_action; std::shared_ptr state; + bool bypass_hold = false; + CommandCancelHandler on_cancelled; }; void run(); + // Queues `item`, cancelling queued normal commands first for an Interrupt. + CommandSubmitStatus enqueue(Item item, CommandPriority priority); + static void cancel(Item& item); + // Moves the next runnable command into `item`. Requires mutex_. + bool take_next(Item* item); + std::function hold_normal_commands(std::chrono::milliseconds limit); + void release_hold(std::uint64_t generation); static void transition(const std::shared_ptr& state, CommandState result, std::string error = {}, std::uint64_t accepted_sequence = 0); @@ -150,6 +181,9 @@ class CommandCoordinator { std::deque queue_; std::deque safety_queue_; std::uint64_t next_sequence_ = 1; + bool hold_active_ = false; + std::uint64_t hold_generation_ = 0; + std::chrono::steady_clock::time_point hold_deadline_{}; bool stopping_ = false; std::thread worker_; }; diff --git a/native/server/include/linuxcnc_grpc/hal/adapter.hpp b/native/server/include/linuxcnc_grpc/hal/adapter.hpp index 4fc087bd..0963ff37 100644 --- a/native/server/include/linuxcnc_grpc/hal/adapter.hpp +++ b/native/server/include/linuxcnc_grpc/hal/adapter.hpp @@ -13,6 +13,10 @@ namespace linuxcnc::server { +// The six wire types. LinuxCNC HAL (2.10+) stores integers in 64 bits only, +// so items read from HAL are always Bit, Float, S64 or U64. S32 and U32 are +// accepted as values written to S64 and U64 items, and as the declared types +// of items of owned components (see LinuxCncHalComponent). enum class HalAdapterType { Bit, Float, S32, U32, S64, U64 }; using HalAdapterValue = std::variant; @@ -107,6 +111,12 @@ class HalAdapterError final : public std::runtime_error { * Owns one server-retained remote HAL proxy. Its lifetime is independent of * any individual RPC stream; hal_exit() runs only when the proxy is destroyed * or the daemon shuts down. + * + * Items keep their declared type for read() and write(). An item declared + * S32 or U32 is a 64-bit HAL item (listed as S64/U64); LinuxCncHalAdapter + * refuses writes from outside that do not fit the declared range, and read() + * clamps a value outside it (which only a linked 64-bit writer pin can still + * produce) to the nearest 32-bit limit. */ class LinuxCncHalComponent final { public: @@ -139,8 +149,20 @@ class LinuxCncHalComponent final { /** * Transport-neutral LinuxCNC HAL adapter. It owns a small ready observer - * component to attach to HAL and serializes shared-memory list/value access - * under HAL's mutex. It intentionally exposes no signal link/unlink methods. + * component to attach to HAL and uses only HAL's public query API. Each call + * (topology(), read_many(), write_many(), ...) runs under one hold of HAL's + * mutex, so it observes and modifies a consistent HAL state. It intentionally + * exposes no signal link/unlink methods. + * + * write() and write_many() refuse (return false / apply nothing) a value that + * would reach an S32/U32 item of an owned component outside its declared + * range, written to the item directly or to a signal it is linked to, exactly + * like a mistyped write. + * + * Thread "running" is derived from each thread's threadbeat pin, because HAL + * no longer publishes its global flag. It can lag a start or stop by up to + * twice the thread period plus 20 ms. When earlier topology() calls give no + * evidence, topology() watches the beats for at most 100 ms. */ class LinuxCncHalAdapter final { public: diff --git a/native/server/include/linuxcnc_grpc/linuxcnc/command_completion_tracker.hpp b/native/server/include/linuxcnc_grpc/linuxcnc/command_completion_tracker.hpp index bdc918e8..d36e85ce 100644 --- a/native/server/include/linuxcnc_grpc/linuxcnc/command_completion_tracker.hpp +++ b/native/server/include/linuxcnc_grpc/linuxcnc/command_completion_tracker.hpp @@ -7,6 +7,7 @@ #include #include #include +#include #include namespace linuxcnc::server { @@ -27,6 +28,15 @@ struct NmlErrorEvent { std::uint32_t command_sequence = 0; }; +enum class NmlCompletionRule { + // A later echoed serial counts as completion. Used for commands task does + // not queue behind other work. + EchoAdvance, + // The result is only meaningful while task still echoes this serial. A later + // serial means the result was overwritten, so the outcome is unknown. + ExactEcho, +}; + // The command-relevant part of one LinuxCNC status read. struct NmlCommandEcho { enum class State { Other, Done, Error }; @@ -46,8 +56,9 @@ struct NmlCommandEcho { // A command is rejected when an error stamped with its serial was read, even // if the status has already moved on to a later command, or when the status // echoes its serial with an error. Its failure message is the text of its -// stamped errors. It completes when the status echoes it as done or has moved -// past it without either. +// stamped errors. It completes when the status echoes it as done, or, under +// NmlCompletionRule::EchoAdvance, has moved past it without either. Under +// ExactEcho a status that moved past it leaves its outcome unknown. class NmlCommandCompletionTracker { public: using Completion = std::function; @@ -63,7 +74,12 @@ class NmlCommandCompletionTracker { explicit NmlCommandCompletionTracker(std::chrono::milliseconds timeout); - void track(std::int32_t serial, Completion completed, Failure failed); + void track(std::int32_t serial, Completion completed, Failure failed) { + track(serial, NmlCompletionRule::EchoAdvance, std::move(completed), + std::move(failed)); + } + void track(std::int32_t serial, NmlCompletionRule rule, Completion completed, + Failure failed); void channel_failed(); // Records an error read from the error channel. command_serial is the // serial LinuxCNC stamped on it, or zero. @@ -71,10 +87,13 @@ class NmlCommandCompletionTracker { void observe(const NmlCommandEcho& echo); void tick(); bool fresh() const; + // Whether a written command is still waiting for LinuxCNC to finish it. + bool has_pending() const; private: struct Pending { std::int32_t serial; + NmlCompletionRule rule; std::chrono::steady_clock::time_point deadline; std::uint64_t after_observation; Completion completed; @@ -87,7 +106,14 @@ class NmlCommandCompletionTracker { std::chrono::steady_clock::time_point read_at; }; - enum class Resolution { Pending, Completed, Rejected, TimedOut, Unavailable }; + enum class Resolution { + Pending, + Completed, + Rejected, + Superseded, + TimedOut, + Unavailable + }; struct Ready { Pending pending; diff --git a/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp b/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp index cfaac9fb..56c698f8 100644 --- a/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp +++ b/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp @@ -19,6 +19,19 @@ namespace linuxcnc::server { // LinuxCNC's EMC_TASK_PLAN_OPEN::file is a LINELEN-sized C string. inline constexpr std::size_t kNmlProgramPathCapacity = 255; +// Longest time later normal commands wait for a task-queued command when no +// command completion timeout is configured. A configured timeout replaces it. +inline constexpr std::chrono::seconds kNmlTaskQueuedHoldLimit{30}; + +namespace detail { +// LinuxCNC's RCS_STATUS and EMC_TASK_STATE values; nml_adapter.cc checks them +// against the LinuxCNC headers. +inline constexpr std::int32_t kNmlRcsStatusDone = 1; +inline constexpr std::int32_t kNmlRcsStatusError = 3; +inline constexpr std::int32_t kNmlTaskStateEstop = 1; +inline constexpr std::int32_t kNmlTaskStateOff = 3; +} // namespace detail + enum class NmlCommandKind { SetTaskMode, SetTaskState, @@ -131,6 +144,7 @@ struct NmlTaskStatus { bool task_paused = false; double delay_left = 0.0; std::int32_t queued_mdi_commands = 0; + std::int32_t hold_wait = 0; }; struct NmlJointStatus { @@ -258,6 +272,106 @@ struct NmlCommand { std::function on_failed; }; +namespace detail { +struct NmlCommandRouting { + CommandPriority priority = CommandPriority::Normal; + CommandHoldPolicy hold_policy = CommandHoldPolicy::Wait; + // LinuxCNC reports this command's result some cycles after reading it, and + // only until it reads another command. + bool task_queued = false; +}; + +// Later commands wait for a task-queued command because task reports one +// result, for the command it read last. Safety commands go first regardless. +// Abort, E-stop and machine off also cancel every command still queued here, +// so work requested before them never reaches LinuxCNC after them. +// Resume, Step and SpindleOff keep their queue position but pass a hold: task +// admits them during an availability operation, and a queued command cannot +// finish while the program is paused until Resume or Step is delivered. +inline NmlCommandRouting nml_command_routing(const NmlCommand& command) { + NmlCommandRouting routing; + switch (command.kind) { + case NmlCommandKind::StopProgram: + case NmlCommandKind::Pause: + routing.priority = CommandPriority::Safety; + break; + case NmlCommandKind::AbortTask: + routing.priority = CommandPriority::Interrupt; + break; + case NmlCommandKind::SetTaskState: + if (command.integer == kNmlTaskStateEstop || + command.integer == kNmlTaskStateOff) + routing.priority = CommandPriority::Interrupt; + break; + case NmlCommandKind::Resume: + case NmlCommandKind::Step: + case NmlCommandKind::SpindleOff: + routing.hold_policy = CommandHoldPolicy::Bypass; + break; + case NmlCommandKind::LoadToolTable: + case NmlCommandKind::SetTool: + case NmlCommandKind::DeleteTool: + case NmlCommandKind::SetJointAvailability: + case NmlCommandKind::SetSpindleAvailability: + routing.task_queued = true; + break; + default: + break; + } + return routing; +} + +// Finishes a command already written to LinuxCNC: defers its ticket to the +// tracker and, for a task-queued command, holds later normal commands until +// the ticket resolves. Must run inside the command's coordinator action. +inline void track_written_command(NmlCommandCompletionTracker* tracker, + CommandContext& context, int serial, + bool task_queued, + std::chrono::milliseconds completion_timeout, + std::function on_completed, + std::function on_failed) { + context.mark_accepted(static_cast(serial)); + context.defer_completion(); + std::function release_hold = [] {}; + if (task_queued) { + release_hold = context.hold_normal_commands( + completion_timeout > std::chrono::milliseconds::zero() + ? completion_timeout + : std::chrono::milliseconds(kNmlTaskQueuedHoldLimit)); + } + tracker->track( + serial, + task_queued ? NmlCompletionRule::ExactEcho + : NmlCompletionRule::EchoAdvance, + [completed = context.mark_completed, failed = context.mark_failed, + on_completed = std::move(on_completed), release_hold]() mutable { + try { + if (on_completed) on_completed(); + completed(); + } catch (const std::exception& error) { + failed(error.what()); + } catch (...) { + failed("command completion callback failed"); + } + release_hold(); + }, + [failed = context.mark_failed, on_failed = std::move(on_failed), + release_hold](std::string error) mutable { + try { + if (on_failed) on_failed(); + } catch (const std::exception& rollback_error) { + error += "; rollback failed: "; + error += rollback_error.what(); + } catch (...) { + error += "; rollback failed"; + } + failed(std::move(error)); + release_hold(); + }); +} + +} // namespace detail + struct NmlStatusSnapshot { std::int32_t echo_serial_number = 0; std::int32_t rcs_status = -1; diff --git a/native/server/src/command_coordinator.cc b/native/server/src/command_coordinator.cc index 002c3bc5..3a34f0f5 100644 --- a/native/server/src/command_coordinator.cc +++ b/native/server/src/command_coordinator.cc @@ -1,5 +1,6 @@ #include "linuxcnc_grpc/command_coordinator.hpp" +#include #include namespace linuxcnc::server { @@ -74,51 +75,75 @@ CommandCoordinator::~CommandCoordinator() { shutdown(); } CommandSubmission CommandCoordinator::submit(CommandAction action, CommandPriority priority) { if (!action) throw std::invalid_argument("command action must not be empty"); - auto state = std::make_shared(); - std::unique_lock lock(mutex_); - if (stopping_) return {CommandSubmitStatus::Stopped, {}}; - auto& queue = priority == CommandPriority::Safety ? safety_queue_ : queue_; - const auto capacity = - priority == CommandPriority::Safety ? safety_capacity_ : capacity_; - if (queue.size() >= capacity) return {CommandSubmitStatus::QueueFull, {}}; - const auto sequence = next_sequence_++; - state->result.sequence = sequence; - queue.push_back(Item{sequence, std::move(action), {}, state}); - lock.unlock(); - condition_.notify_one(); - return {CommandSubmitStatus::Submitted, CommandTicket(std::move(state))}; + const auto status = + enqueue(Item{0, std::move(action), {}, state, false, {}}, priority); + if (status != CommandSubmitStatus::Submitted) return {status, {}}; + return {status, CommandTicket(std::move(state))}; } CommandSubmission CommandCoordinator::submit_with_context( ContextCommandAction action) { - return submit_with_context(std::move(action), {}, CommandPriority::Normal); + return submit_with_context(std::move(action), {}, CommandPriority::Normal, + CommandHoldPolicy::Wait); } CommandSubmission CommandCoordinator::submit_with_context( ContextCommandAction action, const std::stop_token& stop_token, - CommandPriority priority) { + CommandPriority priority, CommandHoldPolicy hold_policy, + CommandCancelHandler on_cancelled) { if (!action) throw std::invalid_argument("command action must not be empty"); auto state = std::make_shared(); - std::unique_lock lock(mutex_); - if (stopping_) return {CommandSubmitStatus::Stopped, {}}; - auto& queue = priority == CommandPriority::Safety ? safety_queue_ : queue_; - const auto capacity = - priority == CommandPriority::Safety ? safety_capacity_ : capacity_; - if (queue.size() >= capacity) return {CommandSubmitStatus::QueueFull, {}}; - const auto sequence = next_sequence_++; - state->result.sequence = sequence; - queue.push_back( - Item{sequence, + const auto status = enqueue( + Item{0, {}, [action = std::move(action), stop_token](CommandContext& context) { context.stop_token = stop_token; action(context); }, - state}); - lock.unlock(); + state, + hold_policy == CommandHoldPolicy::Bypass, + std::move(on_cancelled)}, + priority); + if (status != CommandSubmitStatus::Submitted) return {status, {}}; + return {status, CommandTicket(std::move(state))}; +} + +CommandSubmitStatus CommandCoordinator::enqueue(Item item, + CommandPriority priority) { + std::deque cancelled; + { + std::lock_guard lock(mutex_); + if (stopping_) return CommandSubmitStatus::Stopped; + const bool safety = priority != CommandPriority::Normal; + auto& queue = safety ? safety_queue_ : queue_; + if (queue.size() >= (safety ? safety_capacity_ : capacity_)) + return CommandSubmitStatus::QueueFull; + // Under the same lock that queues the interrupt, so exactly the commands + // submitted before it are cancelled and later ones are kept. + if (priority == CommandPriority::Interrupt) cancelled.swap(queue_); + item.sequence = next_sequence_++; + item.state->result.sequence = item.sequence; + queue.push_back(std::move(item)); + } condition_.notify_one(); - return {CommandSubmitStatus::Submitted, CommandTicket(std::move(state))}; + for (auto& queued : cancelled) cancel(queued); + return CommandSubmitStatus::Submitted; +} + +void CommandCoordinator::cancel(Item& item) { + std::string error = + "cancelled before reaching LinuxCNC by a later abort, E-stop or " + "machine off"; + try { + if (item.on_cancelled) item.on_cancelled(); + } catch (const std::exception& cleanup_error) { + error += "; cleanup failed: "; + error += cleanup_error.what(); + } catch (...) { + error += "; cleanup failed"; + } + transition(item.state, CommandState::Failed, std::move(error)); } void CommandCoordinator::shutdown() { @@ -136,18 +161,54 @@ std::size_t CommandCoordinator::queued() const { return queue_.size() + safety_queue_.size(); } +bool CommandCoordinator::take_next(Item* item) { + if (hold_active_ && std::chrono::steady_clock::now() >= hold_deadline_) + hold_active_ = false; + if (!safety_queue_.empty()) { + *item = std::move(safety_queue_.front()); + safety_queue_.pop_front(); + return true; + } + auto next = queue_.begin(); + if (hold_active_ && !stopping_) { + next = std::find_if(queue_.begin(), queue_.end(), + [](const Item& queued) { return queued.bypass_hold; }); + } + if (next == queue_.end()) return false; + *item = std::move(*next); + queue_.erase(next); + return true; +} + +std::function CommandCoordinator::hold_normal_commands( + std::chrono::milliseconds limit) { + std::lock_guard lock(mutex_); + hold_active_ = true; + hold_deadline_ = std::chrono::steady_clock::now() + limit; + return [this, generation = ++hold_generation_] { release_hold(generation); }; +} + +void CommandCoordinator::release_hold(std::uint64_t generation) { + { + std::lock_guard lock(mutex_); + if (!hold_active_ || hold_generation_ != generation) return; + hold_active_ = false; + } + condition_.notify_all(); +} + void CommandCoordinator::run() { while (true) { Item item; { std::unique_lock lock(mutex_); - condition_.wait(lock, [this] { - return stopping_ || !safety_queue_.empty() || !queue_.empty(); - }); - if (queue_.empty() && safety_queue_.empty() && stopping_) return; - auto& next = safety_queue_.empty() ? queue_ : safety_queue_; - item = std::move(next.front()); - next.pop_front(); + while (!take_next(&item)) { + if (stopping_) return; + if (hold_active_) + condition_.wait_until(lock, hold_deadline_); + else + condition_.wait(lock); + } } const auto mark_accepted = @@ -167,6 +228,9 @@ void CommandCoordinator::run() { [state = item.state](std::string error) { transition(state, CommandState::Failed, std::move(error)); + }, + [this](std::chrono::milliseconds limit) { + return hold_normal_commands(limit); }}; item.context_action(context); if (!deferred) transition(item.state, CommandState::Completed); diff --git a/native/server/src/gcode/canon_preview.cc b/native/server/src/gcode/canon_preview.cc index 404a659d..f103e575 100644 --- a/native/server/src/gcode/canon_preview.cc +++ b/native/server/src/gcode/canon_preview.cc @@ -5,7 +5,7 @@ #include #include -#include "recordingcanon.hh" +#include "recording_canon.hpp" namespace linuxcnc::server::gcode { namespace { diff --git a/native/server/src/gcode/parser.cc b/native/server/src/gcode/parser.cc index a3c7f3bd..bc627914 100644 --- a/native/server/src/gcode/parser.cc +++ b/native/server/src/gcode/parser.cc @@ -6,13 +6,16 @@ #include #include #include +#include #include +#include +#include #include "interp_base.hh" #include "interp_return.hh" #include "linuxcnc_grpc/gcode/canon_preview.hpp" #include "linuxcnc_grpc/linuxcnc/active_ini.hpp" -#include "recordingcanon.hh" +#include "recording_canon.hpp" #include "rs274ngc_interp.hh" #include "tooldata.hh" @@ -27,9 +30,25 @@ bool result_ok(const int result) { struct IniPreviewState { CANON_UNITS units = CANON_UNITS_INCHES; + int axis_mask = 0x7; std::string startup_code; }; +// The axis mask exactly as task builds it (src/emc/ini/initraj.cc): every +// letter of XYZABCUVW named in [TRAJ]COORDINATES, in any case, and X, Y and Z +// when COORDINATES is missing. Other characters, such as spaces, are ignored. +int axis_mask_from_coordinates(const std::optional& coordinates) { + if (!coordinates) return 0x7; + constexpr std::string_view axes = "XYZABCUVW"; + int mask = 0; + for (const char character : *coordinates) { + const auto index = axes.find( + static_cast(std::toupper(static_cast(character)))); + if (index != std::string_view::npos) mask |= 1 << index; + } + return mask; +} + IniPreviewState load_preview_state(const std::string& path) { const ActiveIni ini(path); IniPreviewState state; @@ -50,6 +69,8 @@ IniPreviewState load_preview_state(const std::string& path) { else throw std::runtime_error("unsupported [TRAJ]LINEAR_UNITS: " + *units); } + state.axis_mask = + axis_mask_from_coordinates(ini.find_string("TRAJ", "COORDINATES")); if (const auto startup = ini.find_string("RS274NGC", "RS274NGC_STARTUP_CODE")) state.startup_code = *startup; return state; @@ -98,6 +119,7 @@ ParseResult SerializedRs274Parser::parse_file(const std::string& filepath, const auto preview_state = load_preview_state(options.ini_path); ::linuxcnc::recording::SessionConfig session_config; session_config.units = preview_state.units; + session_config.axis_mask = preview_state.axis_mask; session_config.tools.assign(CANON_POCKETS_MAX, tooldata_entry_init()); if (tool_mmap_user() == 0) { for (int pocket = 0; pocket < CANON_POCKETS_MAX; ++pocket) { diff --git a/native/server/src/gcode/recording_canon.cc b/native/server/src/gcode/recording_canon.cc new file mode 100644 index 00000000..f70f251f --- /dev/null +++ b/native/server/src/gcode/recording_canon.cc @@ -0,0 +1,619 @@ +#include "recording_canon.hpp" + +#include +#include +#include +#include + +namespace recording = linuxcnc::recording; + +// LinuxCNC requires these global names from every canon implementation. +// NOLINTNEXTLINE(bugprone-reserved-identifier) +int _task = 0; +// NOLINTNEXTLINE(bugprone-reserved-identifier) +char _parameter_file_name[PARAMETER_FILE_NAME_LENGTH]{}; +EmcPose tool_offset{}; +USER_DEFINED_FUNCTION_TYPE USER_DEFINED_FUNCTION[USER_DEFINED_FUNCTION_NUM]{}; + +namespace linuxcnc::recording { + +struct Session::Impl { + std::vector events; + EmcPose position{}; + EmcPose probe_position{}; + CANON_UNITS units = CANON_UNITS_INCHES; + int axis_mask = 0x7; + std::vector tools; + std::size_t max_events = 0; + std::size_t max_bytes = 0; + std::size_t recorded_bytes = 0; + std::size_t max_control_points = 0; + bool exceeded = false; + CANON_PLANE plane = CANON_PLANE::XY; + CANON_MOTION_MODE motion_mode = CANON_CONTINUOUS; + double motion_tolerance = 0.1; + double naivecam_tolerance = 0.1; + double feed_rate = 1.0; + double traverse_rate = 0.0; + double spindle_speed[EMCMOT_MAX_SPINDLES]{}; + CANON_DIRECTION spindle_direction[EMCMOT_MAX_SPINDLES]{}; + int selected_tool = 0; + int tool_slot = 0; + bool block_delete = false; + bool optional_stop = false; + bool flood = false; + bool mist = false; +}; + +namespace { + +thread_local Session::Impl* active_session = nullptr; + +Session::Impl& active() { + assert(active_session && "recording canon call without an active Session"); + return *active_session; +} + +template +std::size_t event_size(const T&) { + return sizeof(T); +} + +std::size_t event_size(const NurbsG5Feed& event) { + return sizeof(event) + + event.control_points.size() * sizeof(NURBS_CONTROL_POINT); +} + +std::size_t event_size(const NurbsG6Feed& event) { + return sizeof(event) + + event.control_points.size() * sizeof(NURBS_G6_CONTROL_POINT); +} + +template +void record(T&& event) { + auto& state = active(); + const auto bytes = event_size(event); + if (state.events.size() >= state.max_events || + bytes > + state.max_bytes - std::min(state.recorded_bytes, state.max_bytes)) { + state.exceeded = true; + return; + } + state.recorded_bytes += bytes; + state.events.emplace_back(std::forward(event)); +} + +EmcPose pose(double x, double y, double z, double a, double b, double c, + double u, double v, double w) { + EmcPose result{}; + result.tran.x = x; + result.tran.y = y; + result.tran.z = z; + result.a = a; + result.b = b; + result.c = c; + result.u = u; + result.v = v; + result.w = w; + return result; +} + +void scale_pose(EmcPose& value, double scale) { + value.tran.x *= scale; + value.tran.y *= scale; + value.tran.z *= scale; + value.u *= scale; + value.v *= scale; + value.w *= scale; +} + +double millimetres_per_unit(CANON_UNITS units) { + switch (units) { + case CANON_UNITS_INCHES: + return 25.4; + case CANON_UNITS_MM: + return 1.0; + case CANON_UNITS_CM: + return 10.0; + } + return 1.0; +} + +void set_plane_end(EmcPose& position, CANON_PLANE plane, double first, + double second, double axis) { + switch (plane) { + case CANON_PLANE::XY: + position.tran.x = first; + position.tran.y = second; + position.tran.z = axis; + break; + case CANON_PLANE::YZ: + position.tran.y = first; + position.tran.z = second; + position.tran.x = axis; + break; + case CANON_PLANE::XZ: + position.tran.z = first; + position.tran.x = second; + position.tran.y = axis; + break; + case CANON_PLANE::UV: + position.u = first; + position.v = second; + break; + case CANON_PLANE::VW: + position.v = first; + position.w = second; + break; + case CANON_PLANE::UW: + position.u = first; + position.w = second; + break; + } +} + +double orthogonal_axis(const EmcPose& position, CANON_PLANE plane) { + switch (plane) { + case CANON_PLANE::XY: + return position.tran.z; + case CANON_PLANE::YZ: + return position.tran.x; + case CANON_PLANE::XZ: + return position.tran.y; + default: + return 0.0; + } +} + +bool valid_spindle(int spindle) { + return spindle >= 0 && spindle < EMCMOT_MAX_SPINDLES; +} + +} // namespace + +Session::Session(SessionConfig config) : impl(std::make_unique()) { + assert(!active_session && "recording canon Sessions may not overlap"); + active_session = impl.get(); + impl->units = config.units; + impl->axis_mask = config.axis_mask; + impl->tools = std::move(config.tools); + impl->max_events = config.max_events; + impl->max_bytes = config.max_bytes; + impl->max_control_points = config.max_control_points; + tool_offset = {}; +} + +bool Session::limit_exceeded() const { return impl->exceeded; } + +Session::~Session() { + assert(active_session == impl.get()); + active_session = nullptr; +} + +std::vector Session::take_events() { + std::vector result; + result.swap(impl->events); + impl->recorded_bytes = 0; + return result; +} + +} // namespace linuxcnc::recording + +void INIT_CANON() {} + +void STRAIGHT_TRAVERSE(int line_number, double x, double y, double z, double a, + double b, double c, double u, double v, double w) { + auto& state = recording::active(); + state.position = recording::pose(x, y, z, a, b, c, u, v, w); + recording::record(recording::StraightTraverse{line_number, state.position}); +} + +void STRAIGHT_FEED(int line_number, double x, double y, double z, double a, + double b, double c, double u, double v, double w) { + auto& state = recording::active(); + state.position = recording::pose(x, y, z, a, b, c, u, v, w); + recording::record(recording::StraightFeed{line_number, state.position}); +} + +void ARC_FEED(int line_number, double first_end, double second_end, + double first_axis, double second_axis, int rotation, + double axis_end_point, double a, double b, double c, double u, + double v, double w) { + auto& state = recording::active(); + recording::record(recording::ArcFeed{ + line_number, first_end, second_end, first_axis, second_axis, rotation, + axis_end_point, a, b, c, u, v, w, state.plane}); + recording::set_plane_end(state.position, state.plane, first_end, second_end, + axis_end_point); + state.position.a = a; + state.position.b = b; + state.position.c = c; + state.position.u = u; + state.position.v = v; + state.position.w = w; +} + +void STRAIGHT_PROBE(int line_number, double x, double y, double z, double a, + double b, double c, double u, double v, double w, + unsigned char probe_type) { + auto& state = recording::active(); + state.probe_position = recording::pose(x, y, z, a, b, c, u, v, w); + state.position = state.probe_position; + recording::record( + recording::StraightProbe{line_number, state.position, probe_type}); +} + +void RIGID_TAP(int line_number, double x, double y, double z, double scale) { + auto& state = recording::active(); + recording::record(recording::RigidTap{line_number, x, y, z, scale}); + state.position.tran.x = x; + state.position.tran.y = y; +} + +void DWELL(double seconds) { recording::record(recording::Dwell{seconds}); } + +void NURBS_G5_FEED(int line_number, + const std::vector& control_points, + unsigned int order, CANON_PLANE plane) { + auto& state = recording::active(); + if (control_points.size() > state.max_control_points) { + state.exceeded = true; + return; + } + recording::record( + recording::NurbsG5Feed{line_number, control_points, order, plane}); + if (!control_points.empty()) { + const auto& last = control_points.back(); + recording::set_plane_end(state.position, plane, last.NURBS_X, last.NURBS_Y, + recording::orthogonal_axis(state.position, plane)); + } +} + +void NURBS_G6_FEED(int line_number, + const std::vector& control_points, + unsigned int order, double feed_rate, int l_option, + CANON_PLANE plane) { + auto& state = recording::active(); + if (control_points.size() > state.max_control_points) { + state.exceeded = true; + return; + } + recording::record(recording::NurbsG6Feed{line_number, control_points, order, + feed_rate, l_option, plane}); + if (control_points.size() > order) { + const auto& last = control_points.back(); + recording::set_plane_end(state.position, plane, last.NURBS_X, last.NURBS_Y, + recording::orthogonal_axis(state.position, plane)); + } +} + +void USE_LENGTH_UNITS(CANON_UNITS units) { + auto& state = recording::active(); + if (state.units != units) { + const double scale = recording::millimetres_per_unit(state.units) / + recording::millimetres_per_unit(units); + recording::scale_pose(state.position, scale); + recording::scale_pose(state.probe_position, scale); + recording::scale_pose(tool_offset, scale); + state.units = units; + } + recording::record(recording::LengthUnits{units}); +} + +void SELECT_PLANE(CANON_PLANE plane) { + auto& state = recording::active(); + state.plane = plane; + recording::record(recording::Plane{plane}); +} + +void SET_G5X_OFFSET(int index, double x, double y, double z, double a, double b, + double c, double u, double v, double w) { + recording::record( + recording::G5xOffset{index, recording::pose(x, y, z, a, b, c, u, v, w)}); +} + +void SET_G92_OFFSET(double x, double y, double z, double a, double b, double c, + double u, double v, double w) { + recording::record( + recording::G92Offset{recording::pose(x, y, z, a, b, c, u, v, w)}); +} + +void SET_XY_ROTATION(double degrees) { + recording::record(recording::XyRotation{degrees}); +} + +void HOME_CYCLE() {} +void HOME_CYCLE_JOINT(int) {} + +void CANON_UPDATE_END_POINT(double x, double y, double z, double a, double b, + double c, double u, double v, double w) { + recording::active().position = recording::pose(x, y, z, a, b, c, u, v, w); +} + +void SET_FEED_RATE(double rate) { + auto& state = recording::active(); + state.feed_rate = rate; + recording::record(recording::FeedRate{rate}); +} + +void SET_TRAVERSE_RATE(double rate) { + recording::active().traverse_rate = rate; +} +void SET_FEED_REFERENCE(CANON_FEED_REFERENCE) {} +void SET_FEED_MODE(int, int) {} + +void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode, double tolerance, int, + double) { + auto& state = recording::active(); + state.motion_mode = mode; + state.motion_tolerance = tolerance; +} + +void SET_NAIVECAM_TOLERANCE(double tolerance) { + recording::active().naivecam_tolerance = tolerance; +} + +void SET_CUTTER_RADIUS_COMPENSATION(double) {} +void START_CUTTER_RADIUS_COMPENSATION(int side) { + recording::record( + recording::CutterCompensation{static_cast(side)}); +} + +void STOP_CUTTER_RADIUS_COMPENSATION() { + recording::record(recording::CutterCompensation{CANON_SIDE_OFF}); +} +void START_SPEED_FEED_SYNCH(int, double, bool) {} +void STOP_SPEED_FEED_SYNCH() {} +void STOP() {} + +void SET_SPINDLE_MODE(int, double) {} +void SPINDLE_RETRACT_TRAVERSE() {} +void SPINDLE_RETRACT() {} +void LOCK_SPINDLE_Z() {} +void USE_SPINDLE_FORCE() {} +void USE_NO_SPINDLE_FORCE() {} +void ORIENT_SPINDLE(int, double, int) {} +void WAIT_SPINDLE_ORIENT_COMPLETE(int, double) {} + +void START_SPINDLE_CLOCKWISE(int spindle, int) { + if (recording::valid_spindle(spindle)) + recording::active().spindle_direction[spindle] = CANON_CLOCKWISE; +} + +void START_SPINDLE_COUNTERCLOCKWISE(int spindle, int) { + if (recording::valid_spindle(spindle)) + recording::active().spindle_direction[spindle] = CANON_COUNTERCLOCKWISE; +} + +void SET_SPINDLE_SPEED(int spindle, double speed) { + if (recording::valid_spindle(spindle)) + recording::active().spindle_speed[spindle] = speed; +} + +void STOP_SPINDLE_TURNING(int spindle, int) { + if (recording::valid_spindle(spindle)) + recording::active().spindle_direction[spindle] = CANON_STOPPED; +} + +void SET_JOINT_AVAILABILITY(int /*joint*/, int /*available*/) {} +void SET_SPINDLE_AVAILABILITY(int /*spindle*/, int /*available*/) {} + +void USE_TOOL_LENGTH_OFFSET(const EmcPose& offset) { + tool_offset = offset; + recording::record(recording::ToolOffset{offset}); +} + +void SET_TOOL_TABLE_ENTRY(int, int, const EmcPose&, const EmcPose&, double, + double, double, int) {} + +void SELECT_TOOL(int tool) { recording::active().selected_tool = tool; } + +void CHANGE_TOOL() { + auto& state = recording::active(); + state.tool_slot = state.selected_tool; + recording::record(recording::ToolChange{state.selected_tool}); +} + +void CHANGE_TOOL_NUMBER(int number) { + auto& state = recording::active(); + state.tool_slot = number; + recording::record(recording::ToolChange{number}); +} + +void RELOAD_TOOLDATA() {} +void CLAMP_AXIS(CANON_AXIS) {} +void UNCLAMP_AXIS(CANON_AXIS) {} +void COMMENT(const char*) {} +void MESSAGE(char*) {} +void LOG(char*) {} +void LOGOPEN(char*) {} +void LOGAPPEND(char*) {} +void LOGCLOSE() {} +void DISABLE_ADAPTIVE_FEED() {} +void ENABLE_ADAPTIVE_FEED() {} +void DISABLE_FEED_OVERRIDE() {} +void ENABLE_FEED_OVERRIDE() {} +void DISABLE_SPEED_OVERRIDE(int) {} +void ENABLE_SPEED_OVERRIDE(int) {} +void LOCK_SPEED_OVERRIDE(int) {} +void DISABLE_FEED_HOLD() {} +void ENABLE_FEED_HOLD() {} +void FLOOD_OFF() { recording::active().flood = false; } +void FLOOD_ON() { recording::active().flood = true; } +void MIST_OFF() { recording::active().mist = false; } +void MIST_ON() { recording::active().mist = true; } +void PALLET_SHUTTLE() {} +void TURN_PROBE_OFF() {} +void TURN_PROBE_ON() {} +void NURB_KNOT_VECTOR() {} +void NURB_CONTROL_POINT(int, double, double, double, double) {} +void NURB_FEED(double, double) {} + +void SET_BLOCK_DELETE(bool enabled) { + recording::active().block_delete = enabled; +} +bool GET_BLOCK_DELETE() { return recording::active().block_delete; } +void OPTIONAL_PROGRAM_STOP() {} +void SET_OPTIONAL_PROGRAM_STOP(bool enabled) { + recording::active().optional_stop = enabled; +} +bool GET_OPTIONAL_PROGRAM_STOP() { return recording::active().optional_stop; } +void PROGRAM_END() {} +void PROGRAM_STOP() {} +void SET_MOTION_OUTPUT_BIT(int) {} +void CLEAR_MOTION_OUTPUT_BIT(int) {} +void SET_AUX_OUTPUT_BIT(int) {} +void CLEAR_AUX_OUTPUT_BIT(int) {} +void SET_MOTION_OUTPUT_VALUE(int, double) {} +void SET_AUX_OUTPUT_VALUE(int, double) {} +int WAIT(int, int, int, double) { return 0; } +int UNLOCK_ROTARY(int, int) { return 0; } +int LOCK_ROTARY(int, int) { return 0; } + +double GET_EXTERNAL_ANGLE_UNIT_FACTOR() { return 1.0; } +double GET_EXTERNAL_LENGTH_UNIT_FACTOR() { return 1.0; } +double GET_EXTERNAL_LENGTH_UNITS() { + return 1.0 / recording::millimetres_per_unit(recording::active().units); +} +double GET_EXTERNAL_ANGLE_UNITS() { return 1.0; } +CANON_UNITS GET_EXTERNAL_LENGTH_UNIT_TYPE() { + return recording::active().units; +} +double GET_EXTERNAL_AXIS_MAX_VELOCITY(int) { return 0.0; } +double GET_EXTERNAL_SPINDLE_MAX_VELOCITY(int) { return 0.0; } +double GET_EXTERNAL_FEED_RATE() { return recording::active().feed_rate; } +double GET_EXTERNAL_TRAVERSE_RATE() { + return recording::active().traverse_rate; +} +int GET_EXTERNAL_FLOOD() { return recording::active().flood; } +int GET_EXTERNAL_MIST() { return recording::active().mist; } +CANON_MOTION_MODE GET_EXTERNAL_MOTION_CONTROL_MODE() { + return recording::active().motion_mode; +} +int GET_EXTERNAL_KINS_TYPE() { return 0; } +int GET_EXTERNAL_KINS_TYPE_FLAGS(int) { return -1; } +double GET_EXTERNAL_MOTION_CONTROL_TOLERANCE() { + return recording::active().motion_tolerance; +} +double GET_EXTERNAL_MOTION_CONTROL_NAIVECAM_TOLERANCE() { + return recording::active().naivecam_tolerance; +} +double GET_EXTERNAL_ORIGIN_X() { return 0.0; } +double GET_EXTERNAL_ORIGIN_Y() { return 0.0; } +double GET_EXTERNAL_ORIGIN_Z() { return 0.0; } +double GET_EXTERNAL_ORIGIN_A() { return 0.0; } +double GET_EXTERNAL_ORIGIN_B() { return 0.0; } +double GET_EXTERNAL_ORIGIN_C() { return 0.0; } + +void GET_EXTERNAL_PARAMETER_FILE_NAME(char* name, int max_size) { + if (!name || max_size <= 0) return; + std::strncpy(name, _parameter_file_name, max_size - 1); + name[max_size - 1] = '\0'; +} + +void SET_PARAMETER_FILE_NAME(const char* name) { + if (!name) return; + std::strncpy(_parameter_file_name, name, PARAMETER_FILE_NAME_LENGTH - 1); + _parameter_file_name[PARAMETER_FILE_NAME_LENGTH - 1] = '\0'; +} + +CANON_PLANE GET_EXTERNAL_PLANE() { return recording::active().plane; } +#define RECORDING_POSITION_GETTER(axis, member) \ + double GET_EXTERNAL_POSITION_##axis() { \ + return recording::active().position.member; \ + } +RECORDING_POSITION_GETTER(X, tran.x) +RECORDING_POSITION_GETTER(Y, tran.y) +RECORDING_POSITION_GETTER(Z, tran.z) +RECORDING_POSITION_GETTER(A, a) +RECORDING_POSITION_GETTER(B, b) +RECORDING_POSITION_GETTER(C, c) +RECORDING_POSITION_GETTER(U, u) +RECORDING_POSITION_GETTER(V, v) +RECORDING_POSITION_GETTER(W, w) +#undef RECORDING_POSITION_GETTER + +#define RECORDING_PROBE_GETTER(axis, member) \ + double GET_EXTERNAL_PROBE_POSITION_##axis() { \ + return recording::active().probe_position.member; \ + } +RECORDING_PROBE_GETTER(X, tran.x) +RECORDING_PROBE_GETTER(Y, tran.y) +RECORDING_PROBE_GETTER(Z, tran.z) +RECORDING_PROBE_GETTER(A, a) +RECORDING_PROBE_GETTER(B, b) +RECORDING_PROBE_GETTER(C, c) +RECORDING_PROBE_GETTER(U, u) +RECORDING_PROBE_GETTER(V, v) +RECORDING_PROBE_GETTER(W, w) +#undef RECORDING_PROBE_GETTER + +double GET_EXTERNAL_PROBE_VALUE() { return 0.0; } +int GET_EXTERNAL_PROBE_TRIPPED_VALUE() { return 0; } +int GET_EXTERNAL_QUEUE_EMPTY() { return 1; } +double GET_EXTERNAL_SPEED(int spindle) { + return recording::valid_spindle(spindle) + ? recording::active().spindle_speed[spindle] + : 0.0; +} +CANON_DIRECTION GET_EXTERNAL_SPINDLE(int spindle) { + return recording::valid_spindle(spindle) + ? recording::active().spindle_direction[spindle] + : CANON_STOPPED; +} + +double GET_EXTERNAL_TOOL_LENGTH_XOFFSET() { return tool_offset.tran.x; } +double GET_EXTERNAL_TOOL_LENGTH_YOFFSET() { return tool_offset.tran.y; } +double GET_EXTERNAL_TOOL_LENGTH_ZOFFSET() { return tool_offset.tran.z; } +double GET_EXTERNAL_TOOL_LENGTH_AOFFSET() { return tool_offset.a; } +double GET_EXTERNAL_TOOL_LENGTH_BOFFSET() { return tool_offset.b; } +double GET_EXTERNAL_TOOL_LENGTH_COFFSET() { return tool_offset.c; } +double GET_EXTERNAL_TOOL_LENGTH_UOFFSET() { return tool_offset.u; } +double GET_EXTERNAL_TOOL_LENGTH_VOFFSET() { return tool_offset.v; } +double GET_EXTERNAL_TOOL_LENGTH_WOFFSET() { return tool_offset.w; } +int GET_EXTERNAL_TOOL_SLOT() { return recording::active().tool_slot; } +int GET_EXTERNAL_SELECTED_TOOL_SLOT() { + return recording::active().selected_tool; +} + +CANON_TOOL_TABLE GET_EXTERNAL_TOOL_TABLE(int pocket) { + auto& state = recording::active(); + if (pocket >= 0 && static_cast(pocket) < state.tools.size()) + return state.tools[pocket]; + CANON_TOOL_TABLE result{}; + result.pocketno = -1; + result.toolno = -1; + return result; +} + +int GET_EXTERNAL_TC_FAULT() { return 0; } +int GET_EXTERNAL_TC_REASON() { return 0; } +int GET_EXTERNAL_FEED_OVERRIDE_ENABLE() { return 1; } +int GET_EXTERNAL_SPINDLE_OVERRIDE_ENABLE(int) { return 1; } +int GET_EXTERNAL_ADAPTIVE_FEED_ENABLE() { return 0; } +int GET_EXTERNAL_FEED_HOLD_ENABLE() { return 1; } +int GET_EXTERNAL_DIGITAL_INPUT(int, int default_value) { return default_value; } +double GET_EXTERNAL_ANALOG_INPUT(int, double default_value) { + return default_value; +} +int GET_EXTERNAL_AXIS_MASK() { return recording::active().axis_mask; } + +int USER_DEFINED_FUNCTION_ADD(USER_DEFINED_FUNCTION_TYPE function, int index) { + if (index < 0 || index >= USER_DEFINED_FUNCTION_NUM) return -1; + USER_DEFINED_FUNCTION[index] = function; + return 0; +} + +void FINISH() {} +void START_G76_PASS() {} +void FINISH_G76_APPROACH() {} +void START_G76_CUT() {} +void START_G76_CLEARANCE() {} +void FINISH_G76_PASS(int) {} +void ON_RESET() {} +void CANON_ERROR(const char*, ...) {} +int GET_EXTERNAL_OFFSET_APPLIED() { return 0; } +EmcPose GET_EXTERNAL_OFFSETS() { return {}; } +void UPDATE_TAG(const StateTag&) {} +void SELECT_KINS_TYPE(int) {} +void INTERP_ABORT(int, const char*) {} diff --git a/native/server/src/gcode/recording_canon.hpp b/native/server/src/gcode/recording_canon.hpp new file mode 100644 index 00000000..6d50b898 --- /dev/null +++ b/native/server/src/gcode/recording_canon.hpp @@ -0,0 +1,152 @@ +// LinuxCNC CANON implementation that records a preview event stream. + +#ifndef LINUXCNC_GRPC_GCODE_RECORDING_CANON_HPP +#define LINUXCNC_GRPC_GCODE_RECORDING_CANON_HPP + +#include +#include +#include + +#include "canon.hh" + +namespace linuxcnc::recording { + +struct SessionConfig { + CANON_UNITS units = CANON_UNITS_INCHES; + // Configured axes, bit 0 = X through bit 8 = W, as task derives them from + // [TRAJ]COORDINATES. The interpreter rejects words for any other axis. + int axis_mask = 0x7; + std::vector tools; + std::size_t max_events = 100000; + std::size_t max_bytes = std::size_t{8} * 1024U * 1024U; + std::size_t max_control_points = 10000; +}; + +struct StraightTraverse { + int line_number; + EmcPose end; +}; + +struct StraightFeed { + int line_number; + EmcPose end; +}; + +struct ArcFeed { + int line_number; + double first_end; + double second_end; + double first_axis; + double second_axis; + int rotation; + double axis_end_point; + double a; + double b; + double c; + double u; + double v; + double w; + CANON_PLANE plane; +}; + +struct StraightProbe { + int line_number; + EmcPose end; + unsigned char probe_type; +}; + +struct RigidTap { + int line_number; + double x; + double y; + double z; + double scale; +}; + +struct Dwell { + double seconds; +}; + +struct NurbsG5Feed { + int line_number; + std::vector control_points; + unsigned int order; + CANON_PLANE plane; +}; + +struct NurbsG6Feed { + int line_number; + std::vector control_points; + unsigned int order; + double feed_rate; + int l_option; + CANON_PLANE plane; +}; + +struct LengthUnits { + CANON_UNITS units; +}; + +struct Plane { + CANON_PLANE plane; +}; + +struct G5xOffset { + int index; + EmcPose offset; +}; + +struct G92Offset { + EmcPose offset; +}; + +struct XyRotation { + double degrees; +}; + +struct FeedRate { + double rate; +}; + +struct CutterCompensation { + CANON_SIDE side; +}; + +struct ToolOffset { + EmcPose offset; +}; + +struct ToolChange { + int tool_number; +}; + +using Event = + std::variant; + +// A Session selects this canon implementation for one interpreter run and +// owns the resulting event stream. Canon calls without an active Session are +// programming errors; this keeps the invariant in one place instead of adding +// a nullable callback check to every motion function. +class Session { + public: + struct Impl; + + explicit Session(SessionConfig config = {}); + ~Session(); + + Session(const Session&) = delete; + Session& operator=(const Session&) = delete; + + std::vector take_events(); + bool limit_exceeded() const; + + private: + std::unique_ptr impl; +}; + +} // namespace linuxcnc::recording + +#endif // LINUXCNC_GRPC_GCODE_RECORDING_CANON_HPP diff --git a/native/server/src/hal/adapter.cc b/native/server/src/hal/adapter.cc index ade506de..f35a4ed2 100644 --- a/native/server/src/hal/adapter.cc +++ b/native/server/src/hal/adapter.cc @@ -6,90 +6,110 @@ #include #include -#include -// halpr_find_* and the linked-list roots are intentionally private LinuxCNC -// APIs. This adapter is the one narrow native boundary that needs them to -// reproduce halcmd/_hal topology semantics without adding a Node binding layer. -// daemon. +// All HAL access goes through LinuxCNC's public API: the query API +// (hal_list_*, hal_get_*, hal_set_*, hal_comp_by_name) for inspecting and +// writing items by name, and the typed getters/setters for the pins and +// parameters of components this adapter owns. +#include #include +#include #include #include #include #include +#include +#include #include -#include "hal_priv.h" +#include "hal/narrow_item_registry.hpp" +#include "hal/query.hpp" +#include "hal/value_codec.hpp" namespace linuxcnc::server { namespace { -class HalMutex final { - public: - HalMutex() { - if (!hal_data) throw HalAdapterError("HAL is not initialized", -ENODEV); - rtapi_mutex_get(&hal_data->mutex); - } - ~HalMutex() { rtapi_mutex_give(&hal_data->mutex); } - HalMutex(const HalMutex&) = delete; - HalMutex& operator=(const HalMutex&) = delete; -}; +// Thread "running" detection (see LinuxCncHalAdapter::Impl::threads_running). +// A running thread advances its threadbeat pin once per period; a beat that +// stays put for twice the period plus this slack means threads are stopped. +// The slack absorbs wake-up latency, which is large without a realtime +// kernel. +constexpr auto kThreadBeatSlack = std::chrono::milliseconds(20); +// Longest time topology() waits for a beat when earlier observations cannot +// decide, and the interval between reads while it waits. +constexpr auto kThreadBeatMaxWait = std::chrono::milliseconds(100); +constexpr auto kThreadBeatPollInterval = std::chrono::milliseconds(1); + +[[noreturn]] void throw_hal_error(const std::string& operation, int code) { + // The query API reports -EFAULT only when HAL shared memory is not mapped. + if (code == -EFAULT) throw HalAdapterError("HAL is not initialized", -ENODEV); + throw HalAdapterError(operation + " failed", code); +} + +int checked(int result, const char* operation) { + if (result < 0) throw_hal_error(operation, result); + return result; +} + +// Runs `fn` while holding HAL's mutex, so all queries it makes observe one +// consistent HAL state, as the previous direct shared-memory walk did. +template +void run_locked(Fn&& fn) { + checked(hal_query::with_lock(std::forward(fn)), "HAL lock"); +} hal_type_t native_type(HalAdapterType type) { switch (type) { case HalAdapterType::Bit: - return HAL_BIT; + return HAL_BOOL; case HalAdapterType::Float: - return HAL_FLOAT; + return HAL_REAL; case HalAdapterType::S32: - return HAL_S32; - case HalAdapterType::U32: - return HAL_U32; case HalAdapterType::S64: - return HAL_S64; + return HAL_SINT; + case HalAdapterType::U32: case HalAdapterType::U64: - return HAL_U64; + return HAL_UINT; } return HAL_TYPE_UNSPECIFIED; } +// HAL integers are 64-bit only, so HAL items are always reported as S64/U64. std::optional adapter_type(hal_type_t type) { switch (type) { - case HAL_BIT: + case HAL_BOOL: return HalAdapterType::Bit; - case HAL_FLOAT: + case HAL_REAL: return HalAdapterType::Float; - case HAL_S32: - return HalAdapterType::S32; - case HAL_U32: - return HalAdapterType::U32; - case HAL_S64: + case HAL_SINT: return HalAdapterType::S64; - case HAL_U64: + case HAL_UINT: return HalAdapterType::U64; default: + // HAL_PORT is an implementation-specific internal type; it is not part + // of the scalar values exposed by the gRPC HAL oneof. return std::nullopt; } } -HalAdapterPinDirection pin_direction(hal_pin_dir_t direction) { +HalAdapterPinDirection pin_direction(hal_pdir_t direction) { if (direction == HAL_OUT) return HalAdapterPinDirection::Out; if (direction == HAL_IO) return HalAdapterPinDirection::Io; return HalAdapterPinDirection::In; } -HalAdapterParamDirection param_direction(hal_param_dir_t direction) { +HalAdapterParamDirection param_direction(hal_pdir_t direction) { return direction == HAL_RW ? HalAdapterParamDirection::ReadWrite : HalAdapterParamDirection::ReadOnly; } -HalAdapterComponentKind component_kind(component_type_t type) { +HalAdapterComponentKind component_kind(hal_comp_type_t type) { switch (type) { - case COMPONENT_TYPE_USER: + case HAL_COMP_TYPE_USER: return HalAdapterComponentKind::User; - case COMPONENT_TYPE_REALTIME: + case HAL_COMP_TYPE_REALTIME: return HalAdapterComponentKind::Realtime; - case COMPONENT_TYPE_OTHER: + case HAL_COMP_TYPE_OTHER: return HalAdapterComponentKind::Other; default: return HalAdapterComponentKind::Unknown; @@ -114,131 +134,285 @@ bool same_type(HalAdapterType type, const HalAdapterValue& value) { return false; } -HalAdapterValue read_value(HalAdapterType type, const void* pointer) { - if (!pointer) throw HalAdapterError("HAL item has no data pointer", -EFAULT); +std::int32_t clamp_s32(rtapi_sint value) { + return static_cast( + std::clamp(value, std::numeric_limits::min(), + std::numeric_limits::max())); +} + +HalAdapterValue from_hal(hal_type_t type, const hal_query_value_u& value) { + switch (type) { + case HAL_BOOL: + return static_cast(value.b); + case HAL_REAL: + return static_cast(value.r); + case HAL_SINT: + return static_cast(value.s); + case HAL_UINT: + return static_cast(value.u); + default: + throw HalAdapterError("Unsupported HAL scalar type", -EINVAL); + } +} + +using hal_codec::read_owned; +using hal_codec::to_hal; + +// Looks up a pin (HAL_QTYPE_PIN) or parameter (HAL_QTYPE_PARAM) by name. +// The returned query's strings are valid only while HAL's mutex is held. +std::optional find_pp(const std::string& name, hal_qtype_t qtype) { + if (name.empty() || name.size() > HAL_NAME_LEN) return std::nullopt; + hal_query_t query{}; + query.name = name.c_str(); + query.qtype = qtype; + const int result = hal_get_p(&query, nullptr, nullptr); + if (result == -ENOENT) return std::nullopt; + checked(result, "hal_get_p"); + return query; +} + +std::optional find_signal(const std::string& name) { + if (name.empty() || name.size() > HAL_NAME_LEN) return std::nullopt; + hal_query_t query{}; + query.name = name.c_str(); + const int result = hal_get_s(&query, nullptr, nullptr); + if (result == -ENOENT) return std::nullopt; + checked(result, "hal_get_s"); + return query; +} + +// Reads a signed statistics item such as .time (pin) or +// .tmax (parameter). HAL writes them with 32-bit setters. +std::optional statistic_value(const std::string& name, + hal_qtype_t qtype) { + const auto query = find_pp(name, qtype); + if (!query || query->pp.type != HAL_SINT) return std::nullopt; + return clamp_s32(query->pp.value.s); +} + +std::optional statistic_flag(const std::string& name, hal_qtype_t qtype) { + const auto query = find_pp(name, qtype); + if (!query || query->pp.type != HAL_BOOL) return std::nullopt; + return static_cast(query->pp.value.b); +} + +hal_qtype_t pp_qtype(HalAdapterItemKind kind) { + return kind == HalAdapterItemKind::Param ? HAL_QTYPE_PARAM : HAL_QTYPE_PIN; +} + +// Must run under run_locked(). +std::optional read_unlocked( + const HalAdapterReference& reference) { + hal_type_t type = HAL_TYPE_UNINITIALIZED; + hal_query_value_u value{}; + if (reference.kind == HalAdapterItemKind::Signal) { + const auto query = find_signal(reference.name); + if (!query) return std::nullopt; + type = query->sig.type; + value = query->sig.value; + } else { + const auto query = find_pp(reference.name, pp_qtype(reference.kind)); + if (!query) return std::nullopt; + type = query->pp.type; + value = query->pp.value; + } + if (!adapter_type(type)) return std::nullopt; + return from_hal(type, value); +} + +struct PreparedWrite { + const HalAdapterReference* reference = nullptr; + hal_type_t type = HAL_TYPE_UNINITIALIZED; + hal_query_value_u value{}; +}; + +// Checks that `reference` exists and accepts `value` from outside HAL. Must +// run under run_locked() together with apply_unlocked(). The rules are those +// of the previous direct implementation: unlinked non-output pins, HAL_RW +// parameters and signals without a writer pin. In addition, the value must +// fit the declared range of an owned S32/U32 item it reaches: the item itself, +// or for a signal, every owned narrow pin linked to it. +std::optional prepare_unlocked( + const HalAdapterReference& reference, const HalAdapterValue& value, + const NarrowItemRegistry& narrow) { + PreparedWrite prepared; + prepared.reference = &reference; + int owner_id = 0; + std::optional alias; + try { + if (reference.kind == HalAdapterItemKind::Signal) { + const auto query = find_signal(reference.name); + if (!query || query->sig.writers > 0) return std::nullopt; + prepared.type = query->sig.type; + } else { + const auto query = find_pp(reference.name, pp_qtype(reference.kind)); + if (!query) return std::nullopt; + if (reference.kind == HalAdapterItemKind::Pin && + (query->pp.dir == HAL_OUT || query->pp.signal != nullptr)) + return std::nullopt; + if (reference.kind == HalAdapterItemKind::Param && + query->pp.dir != HAL_RW) + return std::nullopt; + prepared.type = query->pp.type; + owner_id = query->pp.comp_id; + if (query->pp.alias) alias = query->pp.alias; + } + } catch (const HalAdapterError& error) { + // An item without a data target (-EIO) is not writable, as before. + if (error.code() == -EIO) return std::nullopt; + throw; + } + const auto converted = to_hal(prepared.type, value); + if (!converted) return std::nullopt; + prepared.value = *converted; + if (narrow.empty()) return prepared; + if (reference.kind != HalAdapterItemKind::Signal) { + if (!narrow.accepts(reference.kind == HalAdapterItemKind::Pin, + reference.name.c_str(), + alias ? alias->c_str() : nullptr, owner_id, + prepared.type, prepared.value)) + return std::nullopt; + return prepared; + } + bool accepted = true; + checked( + hal_query::list_signal_pins( + reference.name.c_str(), + [&](hal_query_t& query) { + if (narrow.accepts(true, query.name, query.pp.alias, + query.pp.comp_id, prepared.type, prepared.value)) + return 0; + accepted = false; + return hal_query::kStop; + }), + "hal_list_p_s"); + if (!accepted) return std::nullopt; + return prepared; +} + +bool apply_unlocked(const PreparedWrite& prepared) { + const auto& reference = *prepared.reference; + hal_query_t query{}; + query.name = reference.name.c_str(); + int result = 0; + if (reference.kind == HalAdapterItemKind::Signal) { + query.sig.type = prepared.type; + query.sig.value = prepared.value; + result = hal_set_s(&query, nullptr, nullptr); + } else { + query.qtype = pp_qtype(reference.kind); + query.pp.type = prepared.type; + query.pp.value = prepared.value; + result = hal_set_p(&query, nullptr, nullptr); + } + if (result == -EFAULT) throw_hal_error("HAL write", result); + return result == 0; +} + +HalAdapterValue read_back_unlocked(const HalAdapterReference& reference) { + auto value = read_unlocked(reference); + if (!value) + throw HalAdapterError("HAL item '" + reference.name + "' vanished", + -ENOENT); + return *value; +} + +std::string full_name(const std::string& prefix, const std::string& suffix) { + if (suffix.empty()) return {}; + auto result = prefix.empty() ? suffix : prefix + "." + suffix; + if (result.size() > HAL_NAME_LEN) return {}; + return result; +} + +int create_pin(int component_id, hal_pdir_t direction, HalAdapterType type, + hal_refs_u* ref, const char* name) { switch (type) { case HalAdapterType::Bit: - return *static_cast(pointer); + return hal_pin_new_bool(component_id, direction, &ref->b, false, "%s", + name); case HalAdapterType::Float: - return static_cast(*static_cast(pointer)); + return hal_pin_new_real(component_id, direction, &ref->r, 0.0, "%s", + name); case HalAdapterType::S32: - return static_cast(*static_cast(pointer)); + return hal_pin_new_si32(component_id, direction, &ref->s, 0, "%s", name); case HalAdapterType::U32: - return static_cast( - *static_cast(pointer)); + return hal_pin_new_ui32(component_id, direction, &ref->u, 0, "%s", name); case HalAdapterType::S64: - return static_cast(*static_cast(pointer)); + return hal_pin_new_sint(component_id, direction, &ref->s, 0, "%s", name); case HalAdapterType::U64: - return static_cast( - *static_cast(pointer)); + return hal_pin_new_uint(component_id, direction, &ref->u, 0, "%s", name); } - throw HalAdapterError("Unsupported HAL scalar type", -EINVAL); + return -EINVAL; } -bool write_value(HalAdapterType type, void* pointer, - const HalAdapterValue& value) { - if (!pointer || !same_type(type, value)) return false; +int create_param(int component_id, hal_pdir_t direction, HalAdapterType type, + hal_refs_u* ref, const char* name) { switch (type) { case HalAdapterType::Bit: - *static_cast(pointer) = std::get(value); - break; + return hal_param_new_bool(component_id, direction, &ref->b, false, "%s", + name); case HalAdapterType::Float: - *static_cast(pointer) = std::get(value); - break; + return hal_param_new_real(component_id, direction, &ref->r, 0.0, "%s", + name); case HalAdapterType::S32: - *static_cast(pointer) = std::get(value); - break; + return hal_param_new_si32(component_id, direction, &ref->s, 0, "%s", + name); case HalAdapterType::U32: - *static_cast(pointer) = std::get(value); - break; + return hal_param_new_ui32(component_id, direction, &ref->u, 0, "%s", + name); case HalAdapterType::S64: - *static_cast(pointer) = std::get(value); - break; + return hal_param_new_sint(component_id, direction, &ref->s, 0, "%s", + name); case HalAdapterType::U64: - *static_cast(pointer) = std::get(value); - break; + return hal_param_new_uint(component_id, direction, &ref->u, 0, "%s", + name); } - return true; + return -EINVAL; } -void* pin_data(hal_pin_t* pin) { - if (!pin) return nullptr; - if (pin->signal) { - auto* signal = static_cast(SHMPTR(pin->signal)); - return signal ? reinterpret_cast(SHMPTR(signal->data_ptr)) : nullptr; - } - return &pin->dummysig; -} - -std::optional runtime_pin_value(const char* owner_name) { - if (!owner_name) return std::nullopt; - const std::string pin_name = std::string(owner_name) + ".time"; - if (pin_name.size() > HAL_NAME_LEN) return std::nullopt; - auto* pin = halpr_find_pin_by_name(pin_name.c_str()); - if (!pin || pin->type != HAL_S32) return std::nullopt; - const auto* data = static_cast(pin_data(pin)); - if (!data) return std::nullopt; - return static_cast(*data); -} - -struct ResolvedItem { - HalAdapterType type = HalAdapterType::Bit; - void* data = nullptr; - hal_pin_t* pin = nullptr; - hal_param_t* param = nullptr; - hal_sig_t* signal = nullptr; -}; - -std::optional resolve_unlocked( - const HalAdapterReference& reference) { - ResolvedItem resolved; - if (reference.name.empty()) return std::nullopt; - switch (reference.kind) { - case HalAdapterItemKind::Pin: { - resolved.pin = halpr_find_pin_by_name(reference.name.c_str()); - if (!resolved.pin) return std::nullopt; - resolved.data = pin_data(resolved.pin); - break; - } - case HalAdapterItemKind::Param: { - resolved.param = halpr_find_param_by_name(reference.name.c_str()); - if (!resolved.param) return std::nullopt; - resolved.data = reinterpret_cast(SHMPTR(resolved.param->data_ptr)); - break; - } - case HalAdapterItemKind::Signal: { - resolved.signal = halpr_find_sig_by_name(reference.name.c_str()); - if (!resolved.signal) return std::nullopt; - resolved.data = - reinterpret_cast(SHMPTR(resolved.signal->data_ptr)); - break; - } +bool write_owned(HalAdapterType type, const hal_refs_u& ref, + const HalAdapterValue& value) { + if (!same_type(type, value)) return false; + switch (type) { + case HalAdapterType::Bit: + if (!ref.b) return false; + hal_set_bool(ref.b, std::get(value)); + return true; + case HalAdapterType::Float: + if (!ref.r) return false; + hal_set_real(ref.r, std::get(value)); + return true; + case HalAdapterType::S32: + if (!ref.s) return false; + hal_set_si32(ref.s, std::get(value)); + return true; + case HalAdapterType::U32: + if (!ref.u) return false; + hal_set_ui32(ref.u, std::get(value)); + return true; + case HalAdapterType::S64: + if (!ref.s) return false; + hal_set_sint(ref.s, std::get(value)); + return true; + case HalAdapterType::U64: + if (!ref.u) return false; + hal_set_uint(ref.u, std::get(value)); + return true; } - hal_type_t type = resolved.pin ? resolved.pin->type - : resolved.param ? resolved.param->type - : resolved.signal->type; - const auto converted = adapter_type(type); - if (!converted) return std::nullopt; - resolved.type = *converted; - return resolved; -} - -std::string full_name(const std::string& prefix, const std::string& suffix) { - if (suffix.empty()) return {}; - auto result = prefix.empty() ? suffix : prefix + "." + suffix; - if (result.size() > HAL_NAME_LEN) return {}; - return result; + return false; } +// Holds the pin and parameter handles of owned components. HAL requires the +// handle storage to come from hal_malloc(), which cannot be freed, so slots +// are recycled across components. class HalAllocationSlab final { public: explicit HalAllocationSlab(std::size_t capacity) : capacity_(capacity) { - static_assert(sizeof(hal_data_u) >= sizeof(void*)); - const auto bytes = static_cast(capacity * sizeof(hal_data_u)); - slots_ = static_cast(hal_malloc(bytes)); + const auto bytes = static_cast(capacity * sizeof(hal_refs_u)); + slots_ = static_cast(hal_malloc(bytes)); if (!slots_) throw HalAdapterError("HAL dynamic item slab allocation failed", -EBUSY); - std::memset(slots_, 0, capacity * sizeof(hal_data_u)); + std::memset(slots_, 0, capacity * sizeof(hal_refs_u)); free_.reserve(capacity); for (std::size_t index = capacity; index > 0; --index) free_.push_back(index - 1); @@ -249,22 +423,22 @@ class HalAllocationSlab final { if (free_.empty()) return std::nullopt; const auto index = free_.back(); free_.pop_back(); - std::memset(slots_ + index, 0, sizeof(hal_data_u)); + std::memset(slots_ + index, 0, sizeof(hal_refs_u)); return index; } void release(std::size_t index) { std::lock_guard lock(mutex_); if (index >= capacity_) return; - std::memset(slots_ + index, 0, sizeof(hal_data_u)); + std::memset(slots_ + index, 0, sizeof(hal_refs_u)); free_.push_back(index); } - void* data(std::size_t index) { return slots_ + index; } + hal_refs_u* data(std::size_t index) { return slots_ + index; } private: const std::size_t capacity_; - hal_data_u* slots_ = nullptr; + hal_refs_u* slots_ = nullptr; std::mutex mutex_; std::vector free_; }; @@ -282,9 +456,8 @@ struct LinuxCncHalComponent::Impl { std::string full_name; HalAdapterType type = HalAdapterType::Bit; bool pin = false; - hal_pin_dir_t pin_direction = HAL_DIR_UNSPECIFIED; - hal_param_dir_t param_direction = HAL_RO; - void* data_location = nullptr; + hal_pdir_t direction = HAL_DIR_UNSPECIFIED; + hal_refs_u* ref = nullptr; std::size_t slab_slot = 0; }; @@ -293,27 +466,179 @@ struct LinuxCncHalComponent::Impl { std::string prefix; bool ready = false; std::shared_ptr slab; + std::shared_ptr narrow; std::map items; void close() { + const int id_before_exit = id; if (id > 0) { hal_exit(id); id = 0; } - if (slab) { - for (const auto& [suffix, item] : items) { - (void)suffix; - slab->release(item.slab_slot); - } + for (const auto& [suffix, item] : items) { + (void)suffix; + if (slab) slab->release(item.slab_slot); + if (narrow && NarrowItemRegistry::is_narrow(item.type)) + narrow->remove(item.pin, item.full_name, id_before_exit); } items.clear(); } + + bool add(const std::string& suffix, HalAdapterType type, bool pin, + hal_pdir_t direction) { + if (id <= 0 || ready || suffix.empty() || items.find(suffix) != items.end()) + return false; + const auto full = full_name(prefix, suffix); + if (full.empty()) return false; + const auto slot = slab->acquire(); + if (!slot) + throw HalAdapterError("global HAL dynamic item quota reached", -EBUSY); + auto [it, inserted] = items.emplace( + suffix, + Item{suffix, full, type, pin, direction, slab->data(*slot), *slot}); + if (!inserted) { + slab->release(*slot); + return false; + } + const auto& item = it->second; + // Registered before HAL creates the item, so no write can reach it + // unchecked. + const bool narrow_item = narrow && NarrowItemRegistry::is_narrow(type) && + narrow->add(pin, item.full_name, id, type); + const int result = + pin ? create_pin(id, direction, type, item.ref, item.full_name.c_str()) + : create_param(id, direction, type, item.ref, + item.full_name.c_str()); + if (result != 0) { + if (narrow_item) narrow->remove(pin, full, id); + items.erase(it); + slab->release(*slot); + throw HalAdapterError(std::string(pin ? "hal_pin_new" : "hal_param_new") + + " failed for '" + full + "'", + result); + } + return true; + } }; +// Reads .threadbeat, which HAL increments once per cycle while +// threads run. +std::optional read_thread_beat(const std::string& thread) { + const auto beat = find_pp(thread + ".threadbeat", HAL_QTYPE_PIN); + if (!beat || beat->pp.type != HAL_SINT) return std::nullopt; + return beat->pp.value.s; +} + struct LinuxCncHalAdapter::Impl { + using Clock = std::chrono::steady_clock; + + struct BeatState { + rtapi_sint beat = 0; + Clock::time_point since; // first read that returned `beat` + Clock::time_point read_at; // latest read + }; + int component_id = 0; std::string component_name; std::shared_ptr slab; + std::shared_ptr narrow = + std::make_shared(); + std::mutex beat_mutex; + std::unordered_map beats; + std::optional last_running; + + // HAL no longer exposes its global "threads running" flag through the + // public API; hal_start_threads()/hal_stop_threads() change nothing else + // a process can observe except each thread's .threadbeat pin, + // which advances once per period only while threads run. + // + // `observed` holds the beats read in topology() at `read_at`. Compared + // with the previous topology() call, a beat that changed within twice its + // period plus kThreadBeatSlack proves threads are running, and a beat that + // has stayed put for at least that long proves they are stopped. Without + // such evidence (first call, a new thread, or a change seen only after a + // longer gap) the beats are re-read every kThreadBeatPollInterval until + // one moves (running) or twice the shortest period plus the slack has + // passed (stopped). That wait is bounded by kThreadBeatMaxWait; when it + // cannot decide (every thread period above about 40 ms) the previous + // answer is kept, or, on the first call, a non-zero beat counts as + // running. + // + // Cost: none when topology() is called again within the window; about one + // period when threads run; twice the shortest period plus the slack (22 ms + // with a 1 ms thread) on the first call while threads are stopped. + bool threads_running(const std::vector& threads, + const std::vector>& observed, + Clock::time_point read_at) { + std::lock_guard lock(beat_mutex); + std::unordered_map next; + bool running = false; + bool stopped = false; + bool any_beat = false; + bool nonzero_beat = false; + auto shortest_window = Clock::duration::max(); + for (std::size_t index = 0; index < threads.size(); ++index) { + const auto& reading = observed[index]; + if (!reading) continue; + const auto& thread = threads[index]; + const auto beat = *reading; + const auto window = std::chrono::duration_cast( + std::chrono::nanoseconds(thread.period_ns) * 2) + + kThreadBeatSlack; + any_beat = true; + nonzero_beat = nonzero_beat || beat != 0; + shortest_window = std::min(shortest_window, window); + BeatState state{beat, read_at, read_at}; + if (const auto found = beats.find(thread.name); found != beats.end()) { + const auto& previous = found->second; + if (previous.beat != beat) { + if (read_at - previous.read_at <= window) running = true; + } else { + state.since = previous.since; + if (read_at - previous.since >= window) stopped = true; + } + } + next.emplace(thread.name, state); + } + beats = std::move(next); + if (!any_beat) { + last_running = false; + return false; + } + if (!running && !stopped) { + const auto decided = probe_beats(read_at, shortest_window); + running = decided.value_or(last_running.value_or(nonzero_beat)); + } + last_running = running; + return running; + } + + // Re-reads the beats recorded in `beats` until one changes (true), until + // `window` has passed since `read_at` without a change (false), or for at + // most kThreadBeatMaxWait (nullopt). Called with beat_mutex held and HAL's + // mutex not held. + std::optional probe_beats(Clock::time_point read_at, + Clock::duration window) { + const auto give_up = Clock::now() + kThreadBeatMaxWait; + const auto decide_stopped = read_at + window; + while (true) { + const auto wake = std::min( + {Clock::now() + kThreadBeatPollInterval, decide_stopped, give_up}); + std::this_thread::sleep_until(wake); + const auto now = Clock::now(); + for (auto& [name, state] : beats) { + const auto beat = read_thread_beat(name); + if (!beat) continue; + if (*beat != state.beat) { + state = BeatState{*beat, now, now}; + return true; + } + state.read_at = now; + } + if (now >= decide_stopped) return false; + if (now >= give_up) return std::nullopt; + } + } }; LinuxCncHalComponent::LinuxCncHalComponent(std::unique_ptr impl) @@ -351,75 +676,20 @@ bool LinuxCncHalComponent::ready() const noexcept { bool LinuxCncHalComponent::add_pin(const std::string& suffix, HalAdapterType type, HalAdapterPinDirection direction) { - if (!impl_ || impl_->id <= 0 || impl_->ready || suffix.empty() || - impl_->items.find(suffix) != impl_->items.end()) - return false; - const auto full = full_name(impl_->prefix, suffix); - if (full.empty()) return false; - const auto slot = impl_->slab->acquire(); - if (!slot) - throw HalAdapterError("global HAL dynamic item quota reached", -EBUSY); - auto item = Impl::Item{suffix, - full, - type, - true, - HAL_DIR_UNSPECIFIED, - HAL_RO, - impl_->slab->data(*slot), - *slot}; - item.pin_direction = direction == HalAdapterPinDirection::Out ? HAL_OUT - : direction == HalAdapterPinDirection::Io ? HAL_IO - : HAL_IN; - auto [it, inserted] = impl_->items.emplace(suffix, std::move(item)); - if (!inserted) { - impl_->slab->release(*slot); - return false; - } - const int result = hal_pin_new( - it->second.full_name.c_str(), native_type(type), it->second.pin_direction, - static_cast(it->second.data_location), impl_->id); - if (result != 0) { - impl_->items.erase(it); - impl_->slab->release(*slot); - throw HalAdapterError("hal_pin_new failed for '" + full + "'", result); - } - return true; + if (!impl_) return false; + const hal_pdir_t native = direction == HalAdapterPinDirection::Out ? HAL_OUT + : direction == HalAdapterPinDirection::Io ? HAL_IO + : HAL_IN; + return impl_->add(suffix, type, true, native); } bool LinuxCncHalComponent::add_param(const std::string& suffix, HalAdapterType type, HalAdapterParamDirection direction) { - if (!impl_ || impl_->id <= 0 || impl_->ready || suffix.empty() || - impl_->items.find(suffix) != impl_->items.end()) - return false; - const auto full = full_name(impl_->prefix, suffix); - if (full.empty()) return false; - const auto slot = impl_->slab->acquire(); - if (!slot) - throw HalAdapterError("global HAL dynamic item quota reached", -EBUSY); - auto item = Impl::Item{ - suffix, - full, - type, - false, - HAL_DIR_UNSPECIFIED, - direction == HalAdapterParamDirection::ReadWrite ? HAL_RW : HAL_RO, - impl_->slab->data(*slot), - *slot}; - auto [it, inserted] = impl_->items.emplace(suffix, std::move(item)); - if (!inserted) { - impl_->slab->release(*slot); - return false; - } - const int result = hal_param_new( - it->second.full_name.c_str(), native_type(type), - it->second.param_direction, it->second.data_location, impl_->id); - if (result != 0) { - impl_->items.erase(it); - impl_->slab->release(*slot); - throw HalAdapterError("hal_param_new failed for '" + full + "'", result); - } - return true; + if (!impl_) return false; + return impl_->add( + suffix, type, false, + direction == HalAdapterParamDirection::ReadWrite ? HAL_RW : HAL_RO); } void LinuxCncHalComponent::set_ready() { @@ -442,31 +712,18 @@ std::optional LinuxCncHalComponent::read( const std::string& suffix) const { if (!impl_) return std::nullopt; const auto found = impl_->items.find(suffix); - if (found == impl_->items.end()) return std::nullopt; - const auto& item = found->second; - void* data = - item.pin ? item.data_location && *static_cast(item.data_location) - ? *static_cast(item.data_location) - : nullptr - : item.data_location; - if (!data) return std::nullopt; - return read_value(item.type, data); + if (found == impl_->items.end() || !found->second.ref) return std::nullopt; + return read_owned(found->second.type, *found->second.ref); } bool LinuxCncHalComponent::write(const std::string& suffix, HalAdapterValue value) { if (!impl_) return false; const auto found = impl_->items.find(suffix); - if (found == impl_->items.end() || !same_type(found->second.type, value)) - return false; - auto& item = found->second; - if (item.pin && item.pin_direction == HAL_IN) return false; - void* data = - item.pin ? item.data_location && *static_cast(item.data_location) - ? *static_cast(item.data_location) - : nullptr - : item.data_location; - return write_value(item.type, data, value); + if (found == impl_->items.end() || !found->second.ref) return false; + const auto& item = found->second; + if (item.pin && item.direction == HAL_IN) return false; + return write_owned(item.type, *item.ref, value); } LinuxCncHalAdapter::LinuxCncHalAdapter(std::string component_name, @@ -477,7 +734,7 @@ LinuxCncHalAdapter::LinuxCncHalAdapter(std::string component_name, if (dynamic_item_capacity == 0 || dynamic_item_capacity > static_cast(std::numeric_limits::max()) / - sizeof(hal_data_u)) + sizeof(hal_refs_u)) throw HalAdapterError("invalid HAL dynamic item capacity", -EINVAL); impl_->component_name = std::move(component_name); impl_->component_id = hal_init(impl_->component_name.c_str()); @@ -519,195 +776,200 @@ int LinuxCncHalAdapter::component_id() const noexcept { } HalAdapterTopology LinuxCncHalAdapter::topology() const { - HalMutex lock; HalAdapterTopology result; - for (SHMFIELD(hal_comp_t) next = hal_data->comp_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* component = static_cast(SHMPTR(next)); - HalAdapterComponentInfo info; - info.id = component->comp_id; - info.name = component->name; - info.kind = component_kind(component->type); - info.ready = component->ready != 0; - if (component->pid > 0) info.pid = component->pid; - result.components.push_back(std::move(info)); - } - for (SHMFIELD(hal_funct_t) next = hal_data->funct_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* function = static_cast(SHMPTR(next)); - auto* owner = static_cast(SHMPTR(function->owner_ptr)); - HalAdapterFunctionInfo info; - info.name = function->name; - if (owner) { - info.owner_id = owner->comp_id; - info.owner_name = owner->name; - } - info.uses_fp = function->uses_fp != 0; - info.reentrant = function->reentrant != 0; - info.users = function->users; - info.max_runtime = function->maxtime; - info.max_runtime_increased = function->maxtime_increased != 0; - // hal_funct_t::runtime is a process-local pointer written by the - // realtime component. Resolve the exported .time HAL pin - // instead of dereferencing that pointer in this daemon process. - info.runtime = runtime_pin_value(function->name); - result.functions.push_back(std::move(info)); - } - for (SHMFIELD(hal_thread_t) next = hal_data->thread_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* thread = static_cast(SHMPTR(next)); - HalAdapterThreadInfo info; - info.name = thread->name; - info.period_ns = thread->period; - info.priority = thread->priority; - info.uses_fp = thread->uses_fp != 0; - info.running = hal_data->threads_running != 0; - info.max_runtime = thread->maxtime; - // hal_thread_t::runtime has the same process-local pointer semantics as - // hal_funct_t::runtime. The shared .time pin is the safe view. - info.runtime = runtime_pin_value(thread->name); - auto* root = &thread->funct_list; - for (auto* entry = list_next(root); entry != root; - entry = list_next(entry)) { - auto* function_entry = reinterpret_cast(entry); - auto* function = - static_cast(SHMPTR(function_entry->funct_ptr)); - if (function) info.functions.emplace_back(function->name); + std::vector> thread_beats; + std::chrono::steady_clock::time_point beats_read_at; + run_locked([&] { + checked(hal_query::list_components([&](hal_query_t& query) { + HalAdapterComponentInfo info; + info.id = query.comp.comp_id; + info.name = query.name; + info.kind = component_kind(query.comp.type); + info.ready = query.comp.ready; + if (query.comp.pid > 0) info.pid = query.comp.pid; + result.components.push_back(std::move(info)); + }), + "hal_list_comp"); + + checked(hal_query::list_functions([&](hal_query_t& query) { + HalAdapterFunctionInfo info; + info.name = query.name; + info.owner_id = query.funct.comp_id; + if (query.funct.comp) info.owner_name = query.funct.comp; + // HAL no longer tracks a per-function floating-point flag; all + // functions may use floating point. + info.uses_fp = true; + info.reentrant = query.funct.reentrant; + info.users = query.funct.users; + result.functions.push_back(std::move(info)); + }), + "hal_list_funct"); + for (auto& function : result.functions) { + // HAL publishes the execution statistics as items owned by the + // function's component: .time (pin), .tmax and + // .tmax-increased (parameters). + function.runtime = + statistic_value(function.name + ".time", HAL_QTYPE_PIN); + function.max_runtime = + statistic_value(function.name + ".tmax", HAL_QTYPE_PARAM).value_or(0); + function.max_runtime_increased = + statistic_flag(function.name + ".tmax-increased", HAL_QTYPE_PARAM) + .value_or(false); } - result.threads.push_back(std::move(info)); - } - for (SHMFIELD(hal_pin_t) next = hal_data->pin_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* pin = static_cast(SHMPTR(next)); - HalAdapterPinInfo info; - info.name = pin->name; - const auto converted = adapter_type(pin->type); - // HAL_PORT is an implementation-specific internal type; it is not part - // of the six scalar values exposed by the gRPC HAL oneof. - if (!converted) continue; - info.type = *converted; - info.direction = pin_direction(pin->dir); - auto* owner = static_cast(SHMPTR(pin->owner_ptr)); - if (owner) info.owner_id = owner->comp_id; - if (pin->signal) { - auto* signal = static_cast(SHMPTR(pin->signal)); - if (signal) info.signal_name = signal->name; + + checked(hal_query::list_threads( + true, + [&](hal_query_t& query) { + if (query.qtype == HAL_QTYPE_THREAD) { + HalAdapterThreadInfo info; + info.name = query.name; + info.period_ns = query.thread.period; + info.priority = query.thread.priority; + info.uses_fp = true; + result.threads.push_back(std::move(info)); + } else if (query.qtype == HAL_QTYPE_THREAD_FUNCT && + !query.thread.is_init && query.thread.funct && + !result.threads.empty()) { + // One-shot init functions are not part of the cyclic + // function list reported here. + result.threads.back().functions.emplace_back( + query.thread.funct); + } + }), + "hal_list_thread"); + thread_beats.reserve(result.threads.size()); + for (auto& thread : result.threads) { + thread.runtime = statistic_value(thread.name + ".time", HAL_QTYPE_PIN); + thread.max_runtime = + statistic_value(thread.name + ".tmax", HAL_QTYPE_PARAM).value_or(0); + thread_beats.push_back(read_thread_beat(thread.name)); } - info.value = read_value(info.type, pin_data(pin)); - result.pins.push_back(std::move(info)); - } - for (SHMFIELD(hal_param_t) next = hal_data->param_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* parameter = static_cast(SHMPTR(next)); - HalAdapterParamInfo info; - info.name = parameter->name; - const auto converted = adapter_type(parameter->type); - if (!converted) continue; - info.type = *converted; - info.direction = param_direction(parameter->dir); - auto* owner = static_cast(SHMPTR(parameter->owner_ptr)); - if (owner) info.owner_id = owner->comp_id; - info.value = read_value( - info.type, reinterpret_cast(SHMPTR(parameter->data_ptr))); - result.params.push_back(std::move(info)); - } - for (SHMFIELD(hal_sig_t) next = hal_data->sig_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* signal = static_cast(SHMPTR(next)); - HalAdapterSignalInfo info; - info.name = signal->name; - const auto converted = adapter_type(signal->type); - if (!converted) continue; - info.type = *converted; - info.value = read_value( - info.type, reinterpret_cast(SHMPTR(signal->data_ptr))); - info.readers = signal->readers; - info.writers = signal->writers; - info.bidirs = signal->bidirs; - for (auto* pin = halpr_find_pin_by_sig(signal, nullptr); pin; - pin = halpr_find_pin_by_sig(signal, pin)) { - if (pin->dir == HAL_OUT || pin->dir == HAL_IO) { - info.driver = pin->name; - break; - } + beats_read_at = std::chrono::steady_clock::now(); + + checked(hal_query::list_pins_params( + HAL_QTYPE_PIN, + [&](hal_query_t& query) { + const auto converted = adapter_type(query.pp.type); + if (!converted) return; + HalAdapterPinInfo info; + info.name = query.name; + info.type = *converted; + info.direction = pin_direction(query.pp.dir); + info.owner_id = query.pp.comp_id; + if (query.pp.signal) info.signal_name = query.pp.signal; + info.value = from_hal(query.pp.type, query.pp.value); + result.pins.push_back(std::move(info)); + }), + "hal_list_p"); + + checked(hal_query::list_pins_params( + HAL_QTYPE_PARAM, + [&](hal_query_t& query) { + const auto converted = adapter_type(query.pp.type); + if (!converted) return; + HalAdapterParamInfo info; + info.name = query.name; + info.type = *converted; + info.direction = param_direction(query.pp.dir); + info.owner_id = query.pp.comp_id; + info.value = from_hal(query.pp.type, query.pp.value); + result.params.push_back(std::move(info)); + }), + "hal_list_p"); + + checked(hal_query::list_signals([&](hal_query_t& query) { + const auto converted = adapter_type(query.sig.type); + if (!converted) return; + HalAdapterSignalInfo info; + info.name = query.name; + info.type = *converted; + info.value = from_hal(query.sig.type, query.sig.value); + info.readers = query.sig.readers; + info.writers = query.sig.writers; + info.bidirs = query.sig.bidirs; + result.signals.push_back(std::move(info)); + }), + "hal_list_s"); + for (auto& signal : result.signals) { + checked(hal_query::list_signal_pins(signal.name.c_str(), + [&](hal_query_t& query) { + if (query.pp.dir != HAL_OUT && + query.pp.dir != HAL_IO) + return 0; + signal.driver = query.name; + return hal_query::kStop; + }), + "hal_list_p_s"); } - result.signals.push_back(std::move(info)); - } + }); + const bool running = + impl_->threads_running(result.threads, thread_beats, beats_read_at); + for (auto& thread : result.threads) thread.running = running; return result; } std::optional LinuxCncHalAdapter::read( const HalAdapterReference& reference) const { - HalMutex lock; - const auto item = resolve_unlocked(reference); - if (!item) return std::nullopt; - return read_value(item->type, item->data); + std::optional result; + run_locked([&] { result = read_unlocked(reference); }); + return result; } std::vector> LinuxCncHalAdapter::read_many( const std::vector& references, const std::stop_token& stop_token) const { - HalMutex lock; std::vector> result; result.reserve(references.size()); - for (const auto& reference : references) { - if (stop_token.stop_requested()) - throw HalAdapterError("HAL read cancelled", -ECANCELED); - const auto item = resolve_unlocked(reference); - result.push_back(item ? std::optional( - read_value(item->type, item->data)) - : std::nullopt); - } + run_locked([&] { + for (const auto& reference : references) { + if (stop_token.stop_requested()) + throw HalAdapterError("HAL read cancelled", -ECANCELED); + result.push_back(read_unlocked(reference)); + } + }); return result; } bool LinuxCncHalAdapter::write(const HalAdapterReference& reference, HalAdapterValue value, HalAdapterValue* written) { - HalMutex lock; - const auto item = resolve_unlocked(reference); - if (!item || !same_type(item->type, value)) return false; - if (item->param && item->param->dir != HAL_RW) return false; - if (item->pin && (item->pin->dir == HAL_OUT || item->pin->signal)) - return false; - if (item->signal && item->signal->writers > 0) return false; - if (!write_value(item->type, item->data, value)) return false; - if (written) *written = read_value(item->type, item->data); - return true; + bool applied = false; + run_locked([&] { + const auto prepared = prepare_unlocked(reference, value, *impl_->narrow); + if (!prepared || !apply_unlocked(*prepared)) return; + if (written) *written = read_back_unlocked(reference); + applied = true; + }); + return applied; } std::size_t LinuxCncHalAdapter::write_many( const std::vector>& updates, std::vector* written, const std::stop_token& stop_token) { - HalMutex lock; - std::vector resolved; - resolved.reserve(updates.size()); - for (const auto& [reference, value] : updates) { + std::size_t applied = 0; + run_locked([&] { + std::vector prepared; + prepared.reserve(updates.size()); + for (const auto& [reference, value] : updates) { + if (stop_token.stop_requested()) + throw HalAdapterError("HAL write cancelled", -ECANCELED); + auto item = prepare_unlocked(reference, value, *impl_->narrow); + if (!item) return; + prepared.push_back(*item); + } + if (written) { + written->clear(); + written->reserve(updates.size()); + } if (stop_token.stop_requested()) throw HalAdapterError("HAL write cancelled", -ECANCELED); - const auto item = resolve_unlocked(reference); - if (!item || !item->data || !same_type(item->type, value)) return 0; - if (item->param && item->param->dir != HAL_RW) return 0; - if (item->pin && (item->pin->dir == HAL_OUT || item->pin->signal)) return 0; - if (item->signal && item->signal->writers > 0) return 0; - resolved.push_back(*item); - } - if (written) { - written->clear(); - written->reserve(updates.size()); - } - if (stop_token.stop_requested()) - throw HalAdapterError("HAL write cancelled", -ECANCELED); - for (std::size_t index = 0; index < updates.size(); ++index) { - const auto& value = updates[index].second; - if (!write_value(resolved[index].type, resolved[index].data, value)) - return index; - if (written) { - written->push_back( - read_value(resolved[index].type, resolved[index].data)); + for (const auto& item : prepared) { + if (!apply_unlocked(item)) return; + if (written) written->push_back(read_back_unlocked(*item.reference)); + ++applied; } - } - return updates.size(); + }); + return applied; } bool LinuxCncHalAdapter::create_signal(const std::string& name, @@ -720,24 +982,34 @@ bool LinuxCncHalAdapter::create_signal(const std::string& name, } bool LinuxCncHalAdapter::pin_has_writer(const std::string& name) const { - HalMutex lock; - auto* pin = halpr_find_pin_by_name(name.c_str()); - if (!pin) + bool found = false; + bool has_writer = false; + run_locked([&] { + const auto pin = find_pp(name, HAL_QTYPE_PIN); + if (!pin) return; + found = true; + if (!pin->pp.signal) return; + const auto signal = find_signal(pin->pp.signal); + has_writer = signal && signal->sig.writers > 0; + }); + if (!found) throw HalAdapterError("HAL pin '" + name + "' was not found", -ENOENT); - if (!pin->signal) return false; - auto* signal = static_cast(SHMPTR(pin->signal)); - return signal && signal->writers > 0; + return has_writer; } bool LinuxCncHalAdapter::component_exists(const std::string& name) const { - HalMutex lock; - return halpr_find_comp_by_name(name.c_str()) != nullptr; + const int result = hal_comp_by_name(name.c_str(), nullptr); + if (result == -ENOENT) return false; + checked(result, "hal_comp_by_name"); + return true; } bool LinuxCncHalAdapter::component_ready(const std::string& name) const { - HalMutex lock; - auto* component = halpr_find_comp_by_name(name.c_str()); - return component && component->ready != 0; + hal_query_t query{}; + const int result = hal_comp_by_name(name.c_str(), &query); + if (result == -ENOENT) return false; + checked(result, "hal_comp_by_name"); + return query.comp.ready; } int LinuxCncHalAdapter::message_level() const { return rtapi_get_msg_level(); } @@ -755,6 +1027,7 @@ std::unique_ptr LinuxCncHalAdapter::open_component( component_impl->name = name; component_impl->prefix = prefix.empty() ? name : prefix; component_impl->slab = impl_->slab; + component_impl->narrow = impl_->narrow; if (component_impl->prefix.size() > HAL_NAME_LEN) throw HalAdapterError("invalid client HAL component prefix", -EINVAL); component_impl->id = hal_init(component_impl->name.c_str()); diff --git a/native/server/src/hal/narrow_item_registry.hpp b/native/server/src/hal/narrow_item_registry.hpp new file mode 100644 index 00000000..35abebbd --- /dev/null +++ b/native/server/src/hal/narrow_item_registry.hpp @@ -0,0 +1,79 @@ +#pragma once + +#ifndef ULAPI +#define ULAPI +#endif + +#include + +#include +#include +#include +#include + +#include "hal/value_codec.hpp" +#include "linuxcnc_grpc/hal/adapter.hpp" + +namespace linuxcnc::server { + +// The pins and parameters of owned components declared S32 or U32. HAL +// stores them in 64 bits and lists them as S64/U64, but their owner reads them +// clamped to 32 bits (read_owned()). Writes from outside are therefore checked +// against the declared range, so that a value is never acknowledged to the +// writer and then seen differently by the owner. Entries are keyed by the +// name the item was created with (HAL keeps it as the alias's old name when +// the item is renamed by an alias) and matched against the owning component +// id, so a foreign item that reuses a name is never mistaken for an owned one. +class NarrowItemRegistry final { + public: + // Returns false, registering nothing, when the name is already registered; + // HAL then refuses to create the item because the name is taken. + bool add(bool pin, const std::string& name, int component_id, + HalAdapterType declared) { + std::lock_guard lock(mutex_); + return items_.try_emplace({pin, name}, Entry{component_id, declared}) + .second; + } + + void remove(bool pin, const std::string& name, int component_id) { + std::lock_guard lock(mutex_); + const auto found = items_.find({pin, name}); + if (found != items_.end() && found->second.component_id == component_id) + items_.erase(found); + } + + bool empty() const { + std::lock_guard lock(mutex_); + return items_.empty(); + } + + // Whether a write of `value` (HAL type `type`) to the item named `name` + // (with old name `alias` when aliased, else null) reaches its owner + // unchanged; true for every item that is not an owned narrow item. + bool accepts(bool pin, const char* name, const char* alias, int component_id, + hal_type_t type, const hal_query_value_u& value) const { + std::lock_guard lock(mutex_); + for (const char* candidate : {name, alias}) { + if (!candidate) continue; + const auto found = items_.find({pin, candidate}); + if (found != items_.end() && found->second.component_id == component_id && + !hal_codec::fits_declared(found->second.declared, type, value)) + return false; + } + return true; + } + + static bool is_narrow(HalAdapterType type) { + return type == HalAdapterType::S32 || type == HalAdapterType::U32; + } + + private: + struct Entry { + int component_id = 0; + HalAdapterType declared = HalAdapterType::S32; + }; + mutable std::mutex mutex_; + std::map, Entry> items_; +}; + +} // namespace linuxcnc::server diff --git a/native/server/src/hal/query.hpp b/native/server/src/hal/query.hpp new file mode 100644 index 00000000..1c01373f --- /dev/null +++ b/native/server/src/hal/query.hpp @@ -0,0 +1,141 @@ +#pragma once + +// C++ wrappers around LinuxCNC's public HAL query API (hal_list_*, hal_get_*, +// hal_set_*), shared by the HAL adapter and the scope controller. +// +// Every query function holds HAL's mutex while it runs its callback. That +// mutex is recursive per OS thread, so queries issued from inside a callback +// (or inside with_lock()) see the same locked HAL state. Callbacks run inside +// C code: an exception must not unwind through it, because that would leave +// HAL locked for every process. The wrappers catch any exception thrown by a +// callable, stop the iteration and rethrow it after HAL has released the +// mutex. +// +// Strings in hal_query_t (name, comp, signal, ...) point into HAL shared +// memory and stay valid only while the mutex is held. Copy them inside the +// callable or inside with_lock(). + +#ifndef ULAPI +#error "hal/query.hpp requires ULAPI" +#endif + +#include + +#include +#include +#include +#include + +namespace linuxcnc::server::hal_query { + +// Returned by a callable to stop an iteration early without an error. +inline constexpr int kStop = 1; + +namespace detail { + +template +struct Context { + Fn* fn = nullptr; + std::exception_ptr error; +}; + +template +int trampoline(hal_query_t* query, void* arg) noexcept { + auto* context = static_cast*>(arg); + try { + if constexpr (std::is_void_v>) { + std::invoke(*context->fn, *query); + return 0; + } else { + return std::invoke(*context->fn, *query); + } + } catch (...) { + context->error = std::current_exception(); + return kStop; + } +} + +template +int invoke(Api api, hal_query_t* query, Fn& fn) { + Context context{&fn, nullptr}; + const int result = api(query, &trampoline, &context); + if (context.error) std::rethrow_exception(context.error); + return result; +} + +} // namespace detail + +// A callable takes `hal_query_t&` and returns void (continue) or int: zero to +// continue, kStop (positive) to stop, a negative errno to stop with an error. +// Each wrapper returns the HAL function's result: zero after a complete +// iteration, the callable's non-zero value, or a negative HAL error such as +// -EFAULT when HAL is not mapped. + +// Pins and/or parameters; `filter` is HAL_QTYPE_ANY, HAL_QTYPE_PIN or +// HAL_QTYPE_PARAM. +template +int list_pins_params(hal_qtype_t filter, Fn&& fn) { + hal_query_t query{}; + query.qtype = filter; + return detail::invoke(&hal_list_p, &query, fn); +} + +// Pins linked to the named signal, in HAL's list order. -ENOENT if the +// signal does not exist. +template +int list_signal_pins(const char* signal, Fn&& fn) { + hal_query_t query{}; + query.name = signal; + return detail::invoke(&hal_list_p_s, &query, fn); +} + +template +int list_signals(Fn&& fn) { + hal_query_t query{}; + return detail::invoke(&hal_list_s, &query, fn); +} + +template +int list_components(Fn&& fn) { + hal_query_t query{}; + return detail::invoke(&hal_list_comp, &query, fn); +} + +template +int list_functions(Fn&& fn) { + hal_query_t query{}; + return detail::invoke(&hal_list_funct, &query, fn); +} + +// Threads; with `with_functions` the callable is also invoked once per +// attached function (query.qtype == HAL_QTYPE_THREAD_FUNCT) after its thread. +template +int list_threads(bool with_functions, Fn&& fn) { + hal_query_t query{}; + query.qtype = with_functions ? HAL_QTYPE_THREAD_FUNCT : HAL_QTYPE_THREAD; + return detail::invoke(&hal_list_thread, &query, fn); +} + +// Runs `fn()` once while holding HAL's mutex, so that several queries made +// inside it observe one consistent HAL state. Exceptions from `fn` are +// rethrown after the mutex is released. +// +// The public API has no plain lock call; this borrows the mutex of +// hal_list_comp() and stops at the first component. It therefore requires at +// least one HAL component to exist, which holds for any caller that has +// called hal_init(). Returns 0 on success, -ENODEV when no component exists, +// or a negative HAL error. +template +int with_lock(Fn&& fn) { + bool ran = false; + auto once = [&](hal_query_t&) { + ran = true; + std::invoke(fn); + return kStop; + }; + const int result = list_components(once); + if (result < 0) return result; + return ran ? 0 : -ENODEV; +} + +} // namespace linuxcnc::server::hal_query diff --git a/native/server/src/hal/value_codec.hpp b/native/server/src/hal/value_codec.hpp new file mode 100644 index 00000000..22010a4e --- /dev/null +++ b/native/server/src/hal/value_codec.hpp @@ -0,0 +1,121 @@ +#pragma once + +// Conversion between the adapter's typed values and HAL's 64-bit storage. +// Kept separate from adapter.cc so a unit test can check it without a running +// HAL. +// +// LinuxCNC HAL (2.10+) stores integers as 64-bit HAL_SINT/HAL_UINT only. +// Items of owned components may still be declared S32 or U32: they are 64-bit +// HAL items whose owner reads them clamped to the 32-bit range. A value +// written from outside must therefore fit the declared range (fits_declared), +// or the owner would silently see a different value than the writer was told +// it wrote. + +#ifndef ULAPI +#error "hal/value_codec.hpp requires ULAPI" +#endif + +#include + +#include +#include +#include +#include +#include + +#include "linuxcnc_grpc/hal/adapter.hpp" + +namespace linuxcnc::server::hal_codec { + +static_assert(sizeof(rtapi_sint) == 8 && std::is_signed_v); +static_assert(sizeof(rtapi_uint) == 8 && std::is_unsigned_v); + +// Converts a client value for an item of HAL type `type`. Integer values must +// match the item's signedness; 32-bit values are widened to HAL's 64-bit +// storage, which cannot go out of range. Cross-signedness writes are refused, +// as mismatched types were before. +inline std::optional to_hal(hal_type_t type, + const HalAdapterValue& value) { + hal_query_value_u result{}; + switch (type) { + case HAL_BOOL: + if (const auto* typed = std::get_if(&value)) { + result.b = *typed; + return result; + } + break; + case HAL_REAL: + if (const auto* typed = std::get_if(&value)) { + result.r = *typed; + return result; + } + break; + case HAL_SINT: + if (const auto* typed = std::get_if(&value)) { + result.s = *typed; + return result; + } + if (const auto* typed = std::get_if(&value)) { + result.s = *typed; + return result; + } + break; + case HAL_UINT: + if (const auto* typed = std::get_if(&value)) { + result.u = *typed; + return result; + } + if (const auto* typed = std::get_if(&value)) { + result.u = *typed; + return result; + } + break; + default: + break; + } + return std::nullopt; +} + +// Whether `value`, stored in a HAL item of type `type`, reaches an owner that +// declared the item `declared` unchanged. Only S32 and U32 declarations +// narrow; every value fits the other types. +inline bool fits_declared(HalAdapterType declared, hal_type_t type, + const hal_query_value_u& value) { + if (declared == HalAdapterType::S32 && type == HAL_SINT) + return value.s >= std::numeric_limits::min() && + value.s <= std::numeric_limits::max(); + if (declared == HalAdapterType::U32 && type == HAL_UINT) + return value.u <= std::numeric_limits::max(); + return true; +} + +// Reads an owned item through its handle. Items declared with a 32-bit type +// keep that type for their owner; HAL stores 64 bits, so a value outside the +// 32-bit range (which only a linked 64-bit writer pin can still produce) is +// clamped. +inline std::optional read_owned(HalAdapterType type, + const hal_refs_u& ref) { + switch (type) { + case HalAdapterType::Bit: + if (!ref.b) return std::nullopt; + return static_cast(hal_get_bool(ref.b)); + case HalAdapterType::Float: + if (!ref.r) return std::nullopt; + return static_cast(hal_get_real(ref.r)); + case HalAdapterType::S32: + if (!ref.s) return std::nullopt; + return static_cast(hal_get_si32_clamped(ref.s)); + case HalAdapterType::U32: + if (!ref.u) return std::nullopt; + return static_cast(hal_get_ui32_clamped(ref.u)); + case HalAdapterType::S64: + if (!ref.s) return std::nullopt; + return static_cast(hal_get_sint(ref.s)); + case HalAdapterType::U64: + if (!ref.u) return std::nullopt; + return static_cast(hal_get_uint(ref.u)); + } + return std::nullopt; +} + +} // namespace linuxcnc::server::hal_codec diff --git a/native/server/src/linuxcnc/command_completion_tracker.cc b/native/server/src/linuxcnc/command_completion_tracker.cc index e594036a..e2cb94e7 100644 --- a/native/server/src/linuxcnc/command_completion_tracker.cc +++ b/native/server/src/linuxcnc/command_completion_tracker.cc @@ -10,13 +10,17 @@ NmlCommandCompletionTracker::NmlCommandCompletionTracker( : timeout_(timeout) {} void NmlCommandCompletionTracker::track(std::int32_t serial, + NmlCompletionRule rule, Completion completed, Failure failed) { const auto now = std::chrono::steady_clock::now(); Pending pending{serial, + rule, timeout_ == std::chrono::milliseconds::zero() ? std::chrono::steady_clock::time_point::max() : now + timeout_, - 0, std::move(completed), std::move(failed)}; + 0, + std::move(completed), + std::move(failed)}; { std::lock_guard lock(mutex_); if (channel_healthy_) { @@ -75,6 +79,11 @@ void NmlCommandCompletionTracker::tick() { for (const auto& item : ready) finish(item); } +bool NmlCommandCompletionTracker::has_pending() const { + std::lock_guard lock(mutex_); + return !pending_.empty(); +} + bool NmlCommandCompletionTracker::fresh() const { std::lock_guard lock(mutex_); return channel_healthy_ && have_snapshot_ && @@ -99,7 +108,11 @@ NmlCommandCompletionTracker::Resolution NmlCommandCompletionTracker::resolve( *reason += error.message; } if (stamped) return Resolution::Rejected; - if (latest_.serial != pending.serial) return Resolution::Completed; + if (latest_.serial != pending.serial) { + return pending.rule == NmlCompletionRule::ExactEcho + ? Resolution::Superseded + : Resolution::Completed; + } if (latest_.state == NmlCommandEcho::State::Done) return Resolution::Completed; if (latest_.state == NmlCommandEcho::State::Error) @@ -151,6 +164,11 @@ void NmlCommandCompletionTracker::finish(const Ready& ready) { ready.pending.failed(ready.reason.empty() ? kRejectedMessage : ready.reason); break; + case Resolution::Superseded: + ready.pending.failed( + "LinuxCNC moved on to a later command before reporting this " + "command's result; its outcome is unknown"); + break; case Resolution::TimedOut: ready.pending.failed("timed out waiting for LinuxCNC command completion"); break; diff --git a/native/server/src/linuxcnc/nml_adapter.cc b/native/server/src/linuxcnc/nml_adapter.cc index 62f6ec33..35c00ac2 100644 --- a/native/server/src/linuxcnc/nml_adapter.cc +++ b/native/server/src/linuxcnc/nml_adapter.cc @@ -11,6 +11,8 @@ #include #include +#include "linuxcnc_grpc/linuxcnc/command_completion_tracker.hpp" + #ifdef LINUXCNC_GRPC_HAS_NML #include "cms.hh" #include "emc.hh" @@ -25,6 +27,14 @@ static_assert(linuxcnc::server::NmlAdapter::kDigitalOutputLimit == EMCMOT_MAX_DIO); static_assert(linuxcnc::server::NmlAdapter::kAnalogOutputLimit == EMCMOT_MAX_AIO); +static_assert(linuxcnc::server::detail::kNmlRcsStatusDone == + static_cast(RCS_STATUS::DONE)); +static_assert(linuxcnc::server::detail::kNmlRcsStatusError == + static_cast(RCS_STATUS::ERROR)); +static_assert(linuxcnc::server::detail::kNmlTaskStateEstop == + static_cast(EMC_TASK_STATE::ESTOP)); +static_assert(linuxcnc::server::detail::kNmlTaskStateOff == + static_cast(EMC_TASK_STATE::OFF)); #endif namespace linuxcnc::server { @@ -390,6 +400,7 @@ NmlStatusPoll NmlAdapter::poll_status(NmlStatusSnapshot* snapshot) { task.task_paused = status->task.task_paused; task.delay_left = status->task.delayLeft; task.queued_mdi_commands = status->task.queuedMDIcommands; + task.hold_wait = static_cast(status->task.holdWait); auto& motion = snapshot->motion_stat; const auto& source_traj = status->motion.traj; @@ -537,12 +548,14 @@ CommandSubmission NmlAdapter::submit( // NOLINTNEXTLINE(performance-unnecessary-value-param): see above. std::stop_token stop_token) { #ifdef LINUXCNC_GRPC_HAS_NML - const bool safety_command = command.kind == NmlCommandKind::StopProgram || - command.kind == NmlCommandKind::Pause || - command.kind == NmlCommandKind::AbortTask; + const auto routing = detail::nml_command_routing(command); + const bool safety_command = routing.priority != CommandPriority::Normal; + // A command cancelled by a later Interrupt never runs its action, so undo + // what was reserved for it here instead. + auto on_cancelled = command.on_failed; return impl_->commands.submit_with_context( - [this, command = std::move(command), - safety_command](CommandContext& context) mutable { + [this, command = std::move(command), safety_command, + routing](CommandContext& context) mutable { const auto rollback = [&command] { if (command.on_failed) command.on_failed(); }; @@ -573,6 +586,14 @@ CommandSubmission NmlAdapter::submit( message = std::make_unique(); break; case NmlCommandKind::ResetInterpreter: + // LinuxCNC refuses a reset unless the machine is idle. Commands + // this server wrote earlier may not have reached task yet, so + // refuse here too rather than let task judge a stale state. + // Checked after every earlier command was written. + if (impl_->completions.has_pending()) + throw std::runtime_error( + "interpreter reset refused: earlier commands are still " + "in progress; wait for them or abort first"); message = std::make_unique(); break; case NmlCommandKind::ProgramOpen: { @@ -926,41 +947,17 @@ CommandSubmission NmlAdapter::submit( } } const int serial = command_message->serial_number; - context.mark_accepted(static_cast(serial)); - context.defer_completion(); - impl_->completions.track( - serial, - [completed = context.mark_completed, failed = context.mark_failed, - on_completed = std::move(command.on_completed)]() mutable { - try { - if (on_completed) on_completed(); - completed(); - } catch (const std::exception& error) { - failed(error.what()); - } catch (...) { - failed("command completion callback failed"); - } - }, - [failed = context.mark_failed, - on_failed = - std::move(command.on_failed)](std::string error) mutable { - try { - if (on_failed) on_failed(); - } catch (const std::exception& rollback_error) { - error += "; rollback failed: "; - error += rollback_error.what(); - } catch (...) { - error += "; rollback failed"; - } - failed(std::move(error)); - }); + detail::track_written_command( + &impl_->completions, context, serial, routing.task_queued, + impl_->command_completion_timeout, + std::move(command.on_completed), std::move(command.on_failed)); } catch (...) { rollback(); throw; } }, - stop_token, - safety_command ? CommandPriority::Safety : CommandPriority::Normal); + stop_token, routing.priority, routing.hold_policy, + std::move(on_cancelled)); #else (void)command; (void)stop_token; diff --git a/native/server/src/machine/grpc/status_codec.cc b/native/server/src/machine/grpc/status_codec.cc index 018e67bd..868b2d99 100644 --- a/native/server/src/machine/grpc/status_codec.cc +++ b/native/server/src/machine/grpc/status_codec.cc @@ -108,6 +108,7 @@ void fill_status(const NmlStatusSnapshot& source, LinuxCNCStat* target) { task->set_task_paused(task_source.task_paused); task->set_delay_left(task_source.delay_left); task->set_queued_mdi_commands(task_source.queued_mdi_commands); + task->set_hold_wait(static_cast(task_source.hold_wait)); const auto& motion_source = source.motion_stat; auto* trajectory = target->mutable_motion()->mutable_traj(); @@ -278,6 +279,7 @@ bool copy_task_delta(const TaskStat& previous, const TaskStat& current, COPY_TASK_SCALAR(task_paused) COPY_TASK_SCALAR(delay_left) COPY_TASK_SCALAR(queued_mdi_commands) + COPY_TASK_SCALAR(hold_wait) #undef COPY_TASK_SCALAR #define COPY_TASK_MESSAGE(name) \ diff --git a/native/server/src/scope/controller.cc b/native/server/src/scope/controller.cc index cd728cfc..1abc25a5 100644 --- a/native/server/src/scope/controller.cc +++ b/native/server/src/scope/controller.cc @@ -6,15 +6,16 @@ #include #include -#include #include "config.h" +#include "hal/query.hpp" #include "scope/delta_count.hpp" +#include "scope/sample_codec.hpp" #include "scope/shm_abi.h" -// Scope source lookup and thread attachment use the same private HAL lists as -// halcmd. This is the native-only implementation seam; no transport -// abstraction layer crosses it. +// Scope source lookup and thread attachment use LinuxCNC's public HAL query +// API, as halscope does. This is the native-only implementation seam; no +// transport abstraction layer crosses it. #include #include #include @@ -22,32 +23,38 @@ #include #include #include -#include #include #include -#include #include +#include #include #include -#include "hal_priv.h" - extern char** environ; namespace linuxcnc::server { namespace { -class HalMutex final { - public: - HalMutex() { - if (!hal_data) - throw ScopeControllerError("HAL is not initialized", -ENODEV); - rtapi_mutex_get(&hal_data->mutex); - } - ~HalMutex() { rtapi_mutex_give(&hal_data->mutex); } - HalMutex(const HalMutex&) = delete; - HalMutex& operator=(const HalMutex&) = delete; -}; +constexpr const char* kSampleFunction = "scope.sample"; + +[[noreturn]] void throw_hal_error(const char* operation, int code) { + // The query API reports -EFAULT only when HAL shared memory is not mapped. + if (code == -EFAULT) + throw ScopeControllerError("HAL is not initialized", -ENODEV); + throw ScopeControllerError(std::string(operation) + " failed", code); +} + +int checked(int result, const char* operation) { + if (result < 0) throw_hal_error(operation, result); + return result; +} + +// Runs `fn` while holding HAL's mutex, so all queries it makes observe one +// consistent HAL state. +template +void run_locked(Fn&& fn) { + checked(hal_query::with_lock(std::forward(fn)), "HAL lock"); +} ScopeState scope_state(linuxcnc_scope_state_t state) { switch (state) { @@ -82,75 +89,108 @@ bool starts_with(const char* value, std::string_view prefix) { } bool has_scope_controller_owner() { - if (!hal_data) return false; - HalMutex lock; - for (SHMFIELD(hal_comp_t) next = hal_data->comp_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* component = static_cast(SHMPTR(next)); - if (!component) continue; - if (std::strcmp(component->name, "halscope") == 0) return true; - if (starts_with(component->name, "linuxcnc-grpc-scope") && - process_is_live(component->pid)) - return true; - } - return false; -} - -void* resolve_scope_source_unlocked(const ScopeSource& source, - hal_type_t* type) { - if (!type) return nullptr; - *type = HAL_TYPE_UNSPECIFIED; - if (source.name.empty()) return nullptr; + // Like the previous implementation, the check needs this process to have + // HAL mapped already; before that there is nothing to inspect. + if (!hal_is_init()) return false; + bool found = false; + checked(hal_query::list_components([&](hal_query_t& query) { + if (!query.name) return 0; + if (std::strcmp(query.name, "halscope") == 0 || + (starts_with(query.name, "linuxcnc-grpc-scope") && + process_is_live(query.comp.pid))) { + found = true; + return hal_query::kStop; + } + return 0; + }), + "hal_list_comp"); + return found; +} + +struct ResolvedSource { + rtapi_intptr_t offset = 0; + hal_type_t type = HAL_TYPE_UNSPECIFIED; +}; + +// Resolves a channel source to the offset of its value in HAL shared memory, +// the form scope_rt maps back with hal_reference_map(). A pin linked to a +// signal resolves to the signal's value; an unlinked pin to its own value. +// Returns nullopt when the item does not exist or has no value. +std::optional resolve_scope_source(const ScopeSource& source) { + if (source.name.empty() || source.name.size() > HAL_NAME_LEN) + return std::nullopt; + hal_query_t query{}; + query.name = source.name.c_str(); + int result = 0; switch (source.kind) { - case ScopeSourceKind::Param: { - auto* parameter = halpr_find_param_by_name(source.name.c_str()); - if (!parameter) return nullptr; - *type = parameter->type; - return reinterpret_cast(SHMPTR(parameter->data_ptr)); - } - case ScopeSourceKind::Pin: { - auto* pin = halpr_find_pin_by_name(source.name.c_str()); - if (!pin) return nullptr; - *type = pin->type; - if (pin->signal) { - auto* signal = static_cast(SHMPTR(pin->signal)); - return signal ? reinterpret_cast(SHMPTR(signal->data_ptr)) - : nullptr; - } - return &pin->dummysig; - } - case ScopeSourceKind::Signal: { - auto* signal = halpr_find_sig_by_name(source.name.c_str()); - if (!signal) return nullptr; - *type = signal->type; - return reinterpret_cast(SHMPTR(signal->data_ptr)); - } - } - return nullptr; -} - -std::string find_scope_thread_unlocked() { - auto* scope_function = halpr_find_funct_by_name("scope.sample"); - if (!scope_function) return {}; - for (SHMFIELD(hal_thread_t) next = hal_data->thread_list_ptr; next; - next = SHMPTR(next)->next_ptr) { - auto* thread = static_cast(SHMPTR(next)); - if (!thread) continue; - auto* root = &thread->funct_list; - for (auto* entry = list_next(root); entry != root; - entry = list_next(entry)) { - auto* function_entry = reinterpret_cast(entry); - auto* function = - static_cast(SHMPTR(function_entry->funct_ptr)); - if (function == scope_function) return thread->name; - } - } - return {}; + case ScopeSourceKind::Param: + query.qtype = HAL_QTYPE_PARAM; + result = hal_getref_p(&query); + break; + case ScopeSourceKind::Pin: + query.qtype = HAL_QTYPE_PIN; + result = hal_getref_p(&query); + break; + case ScopeSourceKind::Signal: + result = hal_getref_s(&query); + break; + default: + return std::nullopt; + } + // -ENOENT: no such item; -EIO: the item has no data target. + if (result == -ENOENT || result == -EIO) return std::nullopt; + checked(result, source.kind == ScopeSourceKind::Signal ? "hal_getref_s" + : "hal_getref_p"); + const bool signal = source.kind == ScopeSourceKind::Signal; + const hal_refs_u ref = signal ? query.sig.ref : query.pp.ref; + ResolvedSource resolved; + resolved.type = signal ? query.sig.type : query.pp.type; + // HAL fills the reference through its hal_sint_t member. + resolved.offset = hal_reference_unmap(static_cast(ref.s)); + if (resolved.offset <= 0) return std::nullopt; + return resolved; +} + +// Name of the thread that runs scope.sample cyclically, or empty. +std::string find_scope_thread() { + std::string thread; + checked(hal_query::list_threads( + true, + [&](hal_query_t& query) { + if (query.qtype != HAL_QTYPE_THREAD_FUNCT || + query.thread.is_init || !query.thread.funct || + std::strcmp(query.thread.funct, kSampleFunction) != 0) + return 0; + thread = query.name; + return hal_query::kStop; + }), + "hal_list_thread"); + return thread; +} + +// Period of the named thread in nanoseconds, or nullopt if it does not exist. +std::optional thread_period(const char* name) { + std::optional period; + checked(hal_query::list_threads(false, + [&](hal_query_t& query) { + if (std::strcmp(query.name, name) != 0) + return 0; + period = query.thread.period; + return hal_query::kStop; + }), + "hal_list_thread"); + return period; } bool scope_rt_loaded() { - HalMutex lock; - return halpr_find_funct_by_name("scope.sample") != nullptr; + bool found = false; + checked(hal_query::list_functions([&](hal_query_t& query) { + if (std::strcmp(query.name, kSampleFunction) != 0) return 0; + found = true; + return hal_query::kStop; + }), + "hal_list_funct"); + return found; } int load_scope_rt(std::size_t requested_samples) { @@ -174,75 +214,16 @@ int load_scope_rt(std::size_t requested_samples) { return scope_rt_loaded() ? 0 : -ENODEV; } -int source_length(hal_type_t type) { - switch (type) { - case HAL_BIT: - return 1; - case HAL_FLOAT: - return sizeof(hal_float_t); - case HAL_S32: - return sizeof(hal_s32_t); - case HAL_U32: - return sizeof(hal_u32_t); - default: - return 0; - } -} - -double sample_value(const linuxcnc_scope_data_t& value, hal_type_t type) { - switch (type) { - case HAL_BIT: - return value.d_u8 ? 1.0 : 0.0; - case HAL_FLOAT: - return value.d_real; - case HAL_S32: - return value.d_s32; - case HAL_U32: - return value.d_u32; - default: - return 0.0; - } -} - std::int64_t sample_period_ns_unlocked( const linuxcnc_scope_shm_control_t& control) { - if (!control.thread_name[0] || !hal_data) return 0; - HalMutex lock; - auto* thread = halpr_find_thread_by_name(control.thread_name); - if (!thread || control.mult <= 0) return 0; - return static_cast(thread->period) * control.mult; -} - -void set_trigger_level(linuxcnc_scope_shm_control_t* control, hal_type_t type, - double value) { - switch (type) { - case HAL_BIT: - control->trig_level.d_u8 = value != 0.0; - break; - case HAL_S32: - control->trig_level.d_s32 = static_cast(value); - break; - case HAL_U32: - control->trig_level.d_u32 = static_cast(value); - break; - default: - control->trig_level.d_real = value; - break; - } -} - -void validate_trigger_level(hal_type_t type, double value) { - if (type == HAL_S32 && - (!std::isfinite(value) || - value < static_cast(std::numeric_limits::lowest()) || - value > static_cast(std::numeric_limits::max()))) { - throw ScopeControllerError("S32 trigger level is out of range", -ERANGE); - } - if (type == HAL_U32 && - (!std::isfinite(value) || value < 0.0 || - value > static_cast(std::numeric_limits::max()))) { - throw ScopeControllerError("U32 trigger level is out of range", -ERANGE); - } + if (!control.thread_name[0] || !hal_is_init()) return 0; + // thread_name lives in shared memory; copy it with a bounded length. + const std::string name( + control.thread_name, + strnlen(control.thread_name, sizeof(control.thread_name))); + const auto period = thread_period(name.c_str()); + if (!period || control.mult <= 0) return 0; + return static_cast(*period) * control.mult; } } // namespace @@ -445,7 +426,7 @@ ScopeCapture copy_capture_unlocked(const LinuxCncScopeControllerState& impl, int cell = start + sample * control.sample_len + packed_channel; cell %= control.buf_len; values[static_cast(sample)] = - sample_value(impl.buffer[cell], control.data_type[channel]); + scope_codec::decode(impl.buffer[cell], control.data_type[channel]); } ++packed_channel; } @@ -521,7 +502,7 @@ std::optional copy_delta_unlocked( int cell = start + (first + sample) * sample_length + packed_channel; cell %= buffer_length; values[static_cast(sample)] = - sample_value(impl.buffer[cell], control.data_type[channel]); + scope_codec::decode(impl.buffer[cell], control.data_type[channel]); } ++packed_channel; } @@ -603,7 +584,7 @@ void teardown(LinuxCncScopeControllerState& impl) noexcept { if (impl.control->state != LINUXCNC_SCOPE_IDLE) { const std::string thread = impl.control->thread_name; if (!thread.empty()) - hal_del_funct_from_thread("scope.sample", thread.c_str()); + hal_del_funct_from_thread(kSampleFunction, thread.c_str()); impl.control->curr = 0; impl.control->start = 0; impl.control->samples = 0; @@ -651,47 +632,56 @@ LinuxCncScopeController::LinuxCncScopeController( throw ScopeControllerError("hal_init failed for scope controller", impl_->component_id); } - if (const int loaded = load_scope_rt(requested_samples); loaded != 0) { - teardown(*impl_); - throw ScopeControllerError("unable to load LinuxCNC scope_rt", loaded); - } - impl_->shared_memory_id = - rtapi_shmem_new(LINUXCNC_SCOPE_SHM_KEY, impl_->component_id, - sizeof(linuxcnc_scope_shm_control_t)); - if (impl_->shared_memory_id < 0) { - const int error = impl_->shared_memory_id; - teardown(*impl_); - throw ScopeControllerError("scope_rt shared memory is unavailable", error); - } - void* base = nullptr; - const int result = rtapi_shmem_getptr(impl_->shared_memory_id, &base); - if (result < 0 || !base) { - teardown(*impl_); - throw ScopeControllerError("unable to map scope_rt shared memory", result); - } - impl_->control = static_cast(base); - const auto header = (sizeof(linuxcnc_scope_shm_control_t) + 3UL) & ~3UL; - if (impl_->control->shm_size < header || impl_->control->buf_len <= 0 || - impl_->control->shm_size < - header + static_cast(impl_->control->buf_len) * - sizeof(linuxcnc_scope_data_t)) { - teardown(*impl_); - throw ScopeControllerError( - "invalid or incompatible scope_rt shared-memory ABI", -EPROTO); - } - impl_->buffer = reinterpret_cast( - static_cast(base) + header); - if (!impl_->control->thread_name[0]) { - HalMutex lock; - const auto thread = find_scope_thread_unlocked(); - if (!thread.empty()) { - std::strncpy(impl_->control->thread_name, thread.c_str(), HAL_NAME_LEN); - impl_->control->thread_name[HAL_NAME_LEN] = '\0'; + // Every failure from here on must release the HAL component, the shared + // memory mapping and, if attached, scope.sample. + try { + if (const int loaded = load_scope_rt(requested_samples); loaded != 0) { + throw ScopeControllerError("unable to load LinuxCNC scope_rt", loaded); } - } - if (const int ready = hal_ready(impl_->component_id); ready != 0) { + impl_->shared_memory_id = + rtapi_shmem_new(LINUXCNC_SCOPE_SHM_KEY, impl_->component_id, + sizeof(linuxcnc_scope_shm_control_t)); + if (impl_->shared_memory_id < 0) { + const int error = impl_->shared_memory_id; + throw ScopeControllerError("scope_rt shared memory is unavailable", + error); + } + void* base = nullptr; + const int result = rtapi_shmem_getptr(impl_->shared_memory_id, &base); + if (result < 0 || !base) { + throw ScopeControllerError("unable to map scope_rt shared memory", + result); + } + impl_->control = static_cast(base); + // scope_rt sets buf_len = (shm_size - header) / sizeof(sample), with the + // header rounded up to 8 bytes. A module built with another control-block + // layout yields a different buffer length for the same segment size. + constexpr auto header = LINUXCNC_SCOPE_BUFFER_OFFSET; + const auto shm_size = impl_->control->shm_size; + const auto buffer_length = impl_->control->buf_len; + if (shm_size < header || buffer_length <= 0 || + (shm_size - header) / sizeof(linuxcnc_scope_data_t) != + static_cast(buffer_length)) { + // Keep teardown from writing control fields into a foreign layout. + impl_->control = nullptr; + throw ScopeControllerError( + "invalid or incompatible scope_rt shared-memory ABI", -EPROTO); + } + impl_->buffer = reinterpret_cast( + static_cast(base) + header); + if (!impl_->control->thread_name[0]) { + const auto thread = find_scope_thread(); + if (!thread.empty()) { + std::strncpy(impl_->control->thread_name, thread.c_str(), HAL_NAME_LEN); + impl_->control->thread_name[HAL_NAME_LEN] = '\0'; + } + } + if (const int ready = hal_ready(impl_->component_id); ready != 0) { + throw ScopeControllerError("unable to ready scope controller", ready); + } + } catch (...) { teardown(*impl_); - throw ScopeControllerError("unable to ready scope controller", ready); + throw; } start_polling(); } @@ -750,32 +740,30 @@ void LinuxCncScopeController::configure(const std::string& owner, -EINVAL); } - std::array offsets{}; + std::array offsets{}; std::array types{}; std::array lengths{}; types.fill(HAL_TYPE_UNSPECIFIED); long period = 0; std::string attached_thread; - { - HalMutex hal_lock; - auto* thread = halpr_find_thread_by_name(config.thread_name.c_str()); - if (thread) period = thread->period; + run_locked([&] { + period = thread_period(config.thread_name.c_str()).value_or(0); for (std::size_t index = 0; index < kScopeChannelCount; ++index) { const auto& channel = config.channels[index]; if (!channel.enabled) continue; - hal_type_t type = HAL_TYPE_UNSPECIFIED; - void* data = resolve_scope_source_unlocked(channel.source, &type); - const int length = source_length(type); - if (!data || length == 0) { + const auto source = resolve_scope_source(channel.source); + if (!source || !scope_codec::sampleable(source->type)) { throw ScopeControllerError("invalid or unsupported scope source", -EINVAL); } - offsets[index] = hal_shmoff(data); - types[index] = type; - lengths[index] = static_cast(length); + offsets[index] = source->offset; + types[index] = source->type; + // scope_rt samples every type into one full cell; any non-zero length + // enables the channel. halscope uses the same value. + lengths[index] = static_cast(sizeof(linuxcnc_scope_data_t)); } - attached_thread = find_scope_thread_unlocked(); - } + attached_thread = find_scope_thread(); + }); if (period <= 0) throw ScopeControllerError("scope thread is unavailable", -ENOENT); const auto max_multiplier = @@ -792,8 +780,8 @@ void LinuxCncScopeController::configure(const std::string& owner, const auto trigger_type = config.trigger_channel > 0 ? types[static_cast(config.trigger_channel - 1)] - : HAL_FLOAT; - validate_trigger_level(trigger_type, config.trigger_level); + : HAL_REAL; + scope_codec::validate_trigger_level(trigger_type, config.trigger_level); if (impl_->control->state != LINUXCNC_SCOPE_IDLE) { impl_->control->state = LINUXCNC_SCOPE_RESET; @@ -803,7 +791,7 @@ void LinuxCncScopeController::configure(const std::string& owner, } if (impl_->control->state != LINUXCNC_SCOPE_IDLE) { if (!attached_thread.empty()) - hal_del_funct_from_thread("scope.sample", attached_thread.c_str()); + hal_del_funct_from_thread(kSampleFunction, attached_thread.c_str()); impl_->control->curr = 0; impl_->control->start = 0; impl_->control->samples = 0; @@ -814,7 +802,7 @@ void LinuxCncScopeController::configure(const std::string& owner, } if (attached_thread != config.thread_name) { if (!attached_thread.empty()) { - if (const int result = hal_del_funct_from_thread("scope.sample", + if (const int result = hal_del_funct_from_thread(kSampleFunction, attached_thread.c_str()); result != 0) { throw ScopeControllerError( @@ -822,7 +810,7 @@ void LinuxCncScopeController::configure(const std::string& owner, } } if (const int result = hal_add_funct_to_thread( - "scope.sample", config.thread_name.c_str(), -1); + kSampleFunction, config.thread_name.c_str(), -1); result != 0) { throw ScopeControllerError("unable to link scope.sample to scope thread", result); @@ -842,7 +830,8 @@ void LinuxCncScopeController::configure(const std::string& owner, config.pre_trigger, 0, std::max(0, impl_->control->rec_len - 1)); impl_->control->mult = config.multiplier; impl_->control->trig_chan = config.trigger_channel; - set_trigger_level(impl_->control, trigger_type, config.trigger_level); + scope_codec::encode_trigger_level(&impl_->control->trig_level, trigger_type, + config.trigger_level); impl_->control->trig_edge = config.rising ? 1 : 0; impl_->control->auto_trig = config.automatic ? 1 : 0; for (std::size_t index = 0; index < kScopeChannelCount; ++index) { diff --git a/native/server/src/scope/sample_codec.hpp b/native/server/src/scope/sample_codec.hpp new file mode 100644 index 00000000..fad3fa29 --- /dev/null +++ b/native/server/src/scope/sample_codec.hpp @@ -0,0 +1,111 @@ +#pragma once + +// Conversion between scope_rt's per-sample cells and the controller's +// double-valued channels. Kept separate from controller.cc so the contract +// test can check it against upstream's scope_data_t. +// +// LinuxCNC 2.10's scope_rt records one 8-byte cell per channel and sample, +// writing only the union member that matches the channel's HAL type: +// +// HAL_BOOL rtapi_bool (1 byte; the other 7 bytes keep stale data) +// HAL_SINT rtapi_sint (int64_t) +// HAL_UINT rtapi_uint (uint64_t) +// HAL_REAL rtapi_real (double) +// +// Samples leave the controller as doubles. BOOL and REAL are exact. SINT and +// UINT are exact while their magnitude is at most 2^53; larger values are +// rounded to the nearest double (relative error below 2^-53), because the +// scope wire format carries only doubles. + +#ifndef ULAPI +#error "scope/sample_codec.hpp requires ULAPI" +#endif + +#include +#include +#include +#include +#include + +#include "linuxcnc_grpc/scope/controller.hpp" +#include "scope/shm_abi.h" + +namespace linuxcnc::server::scope_codec { + +static_assert(sizeof(linuxcnc_scope_data_t) == 8); +static_assert(sizeof(rtapi_sint) == 8 && std::is_signed_v); +static_assert(sizeof(rtapi_uint) == 8 && std::is_unsigned_v); +static_assert(sizeof(rtapi_real) == 8); + +// Whether scope_rt can sample a HAL item of this type. +constexpr bool sampleable(hal_type_t type) { + return type == HAL_BOOL || type == HAL_REAL || type == HAL_SINT || + type == HAL_UINT; +} + +namespace detail { +template +T load(const linuxcnc_scope_data_t& cell) { + // The cell lives in memory written by another process; copy its bytes + // rather than read a union member that may not be the one last written. + T value; + std::memcpy(&value, &cell, sizeof(T)); + return value; +} +} // namespace detail + +inline double decode(const linuxcnc_scope_data_t& cell, hal_type_t type) { + switch (type) { + case HAL_BOOL: + // Only the first byte is written for a bool channel. + return detail::load(cell) != 0 ? 1.0 : 0.0; + case HAL_REAL: + return detail::load(cell); + case HAL_SINT: + return static_cast(detail::load(cell)); + case HAL_UINT: + return static_cast(detail::load(cell)); + default: + return 0.0; + } +} + +// 2^63 and 2^64: the first doubles outside the int64_t and uint64_t ranges. +inline constexpr double kSintLimit = 9223372036854775808.0; +inline constexpr double kUintLimit = 18446744073709551616.0; + +// Throws when `level` cannot be stored as a trigger level for `type`. +inline void validate_trigger_level(hal_type_t type, double level) { + if (type == HAL_SINT && + (!std::isfinite(level) || level < -kSintLimit || level >= kSintLimit)) { + throw ScopeControllerError("S64 trigger level is out of range", -ERANGE); + } + if (type == HAL_UINT && + (!std::isfinite(level) || level < 0.0 || level >= kUintLimit)) { + throw ScopeControllerError("U64 trigger level is out of range", -ERANGE); + } +} + +// Stores a validated trigger level. Integer levels are truncated toward +// zero; scope_rt triggers when the sampled value is greater than the level. +// Bool channels trigger on the value itself and ignore the level. +inline void encode_trigger_level(linuxcnc_scope_data_t* cell, hal_type_t type, + double level) { + *cell = linuxcnc_scope_data_t{}; + switch (type) { + case HAL_BOOL: + cell->b = level != 0.0; + break; + case HAL_SINT: + cell->s = static_cast(level); + break; + case HAL_UINT: + cell->u = static_cast(level); + break; + default: + cell->r = level; + break; + } +} + +} // namespace linuxcnc::server::scope_codec diff --git a/native/server/src/scope/shm_abi.h b/native/server/src/scope/shm_abi.h index bbcd371c..5bdcb413 100644 --- a/native/server/src/scope/shm_abi.h +++ b/native/server/src/scope/shm_abi.h @@ -1,8 +1,9 @@ /* - * LinuxCNC scope_rt shared-memory ABI, pinned to the repository's baseline. - * Derived from src/hal/utils/scope_shm.h. This header is deliberately kept - * on the native implementation side; transport-facing code sees only the - * types in scope_controller.hpp. + * LinuxCNC scope_rt shared-memory ABI, pinned to the repository's baseline + * (LinuxCNC 2.10, src/hal/utils/scope_shm.h). This header is deliberately + * kept on the native implementation side; transport-facing code sees only + * the types in scope_controller.hpp. The scope controller contract test + * checks it against upstream's header. */ #pragma once @@ -22,12 +23,13 @@ enum linuxcnc_scope_state_t { LINUXCNC_SCOPE_RESET, }; +/* One sample of one channel. scope_rt stores the member that matches the + * channel's HAL type; the other bytes of the cell keep stale data. */ union linuxcnc_scope_data_t { - unsigned char d_u8; - rtapi_u32 d_u32; - rtapi_s32 d_s32; - real_t d_real; - ireal_t d_ireal; + rtapi_bool b; + rtapi_uint u; + rtapi_sint s; + rtapi_real r; }; struct linuxcnc_scope_shm_control_t { @@ -48,7 +50,15 @@ struct linuxcnc_scope_shm_control_t { int curr; int samples; linuxcnc_scope_state_t state; - int data_offset[LINUXCNC_SCOPE_CHANNELS]; + /* Offset of the channel's value in HAL shared memory, as produced by + * hal_reference_unmap() and consumed by scope_rt's hal_reference_map(). */ + rtapi_intptr_t data_offset[LINUXCNC_SCOPE_CHANNELS]; hal_type_t data_type[LINUXCNC_SCOPE_CHANNELS]; + /* Non-zero when the channel is sampled. */ char data_len[LINUXCNC_SCOPE_CHANNELS]; }; + +/* scope_rt places the sample buffer after the control block, rounded up to + * a multiple of 8 bytes. */ +#define LINUXCNC_SCOPE_BUFFER_OFFSET \ + ((sizeof(struct linuxcnc_scope_shm_control_t) + 7UL) & ~7UL) diff --git a/native/server/tests/fixtures/rotary_axis.ngc b/native/server/tests/fixtures/rotary_axis.ngc new file mode 100644 index 00000000..a5cbd8df --- /dev/null +++ b/native/server/tests/fixtures/rotary_axis.ngc @@ -0,0 +1,3 @@ +G21 +G0 X1 A90 U2 +M2 diff --git a/native/server/tests/gcode_parser_integration.cc b/native/server/tests/gcode_parser_integration.cc index 3e3072db..0e5edf06 100644 --- a/native/server/tests/gcode_parser_integration.cc +++ b/native/server/tests/gcode_parser_integration.cc @@ -19,6 +19,7 @@ using linuxcnc::server::gcode::G5xOffsetOp; using linuxcnc::server::gcode::G92OffsetOp; using linuxcnc::server::gcode::Operation; using linuxcnc::server::gcode::OperationBatch; +using linuxcnc::server::gcode::ParseError; using linuxcnc::server::gcode::ParseOptions; using linuxcnc::server::gcode::PlaneChangeOp; using linuxcnc::server::gcode::SerializedRs274Parser; @@ -41,11 +42,12 @@ bool nearly_equal(double actual, double expected) { } // namespace int main(int argc, char** argv) { - if (argc != 8) { + if (argc != 10) { std::cerr << "usage: gcode_parser_integration " " " " " - "\n"; + " " + "\n"; return 2; } @@ -229,6 +231,38 @@ int main(int argc, char** argv) { }); assert(default_inch_move != default_unit_operations.end()); + // The preview accepts exactly the axes [TRAJ]COORDINATES configures, as task + // does: an A and U move parses with X Y Z A U and is refused with X Y Z. + std::vector rotary_operations; + ParseOptions rotary_options; + rotary_options.ini_path = argv[8]; + rotary_options.on_batch = [&](OperationBatch&& batch) { + rotary_operations.insert(rotary_operations.end(), + std::make_move_iterator(batch.begin()), + std::make_move_iterator(batch.end())); + }; + parser.parse_file(argv[9], rotary_options); + const auto rotary_move = std::find_if( + rotary_operations.begin(), rotary_operations.end(), [](const auto& op) { + const auto* traverse = std::get_if(&op); + return traverse && nearly_equal(traverse->pos.x, 1.0) && + nearly_equal(traverse->pos.a, 90.0) && + nearly_equal(traverse->pos.u, 2.0); + }); + assert(rotary_move != rotary_operations.end()); + + bool unconfigured_axis_refused = false; + ParseOptions xyz_options; + xyz_options.ini_path = argv[1]; + try { + parser.parse_file(argv[9], xyz_options); + } catch (const ParseError& error) { + unconfigured_axis_refused = + std::string(error.what()).find("Bad character 'a'") != + std::string::npos; + } + assert(unconfigured_axis_refused); + // A callback can cancel after a bounded batch. Cancellation is observed // before the next rs274 read/execute step and never removes that batch. std::size_t cancelled_batches = 0; diff --git a/native/server/tests/grpc_live_hal.cc b/native/server/tests/grpc_live_hal.cc index 44ead4d6..739feafc 100644 --- a/native/server/tests/grpc_live_hal.cc +++ b/native/server/tests/grpc_live_hal.cc @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include @@ -16,6 +17,7 @@ #include #include #include +#include #include #include @@ -34,6 +36,165 @@ namespace beast = boost::beast; namespace websocket = beast::websocket; using tcp = asio::ip::tcp; +namespace { + +constexpr std::int64_t kBeyondS32 = 30000000000LL; + +linuxcnc::v1::HalScalar s64_value(std::int64_t value) { + linuxcnc::v1::HalScalar scalar; + scalar.set_type(linuxcnc::v1::HAL_TYPE_S64); + scalar.set_s64(value); + return scalar; +} + +grpc::StatusCode write_item(linuxcnc::v1::HalService::Stub* hal, + linuxcnc::v1::HalItemKind kind, + const std::string& name, std::int64_t value) { + linuxcnc::v1::HalWrite request; + auto* write = request.add_writes(); + write->mutable_item()->set_kind(kind); + write->mutable_item()->set_name(name); + *write->mutable_value() = s64_value(value); + linuxcnc::v1::HalWriteResponse response; + grpc::ClientContext context; + return hal->Write(&context, request, &response).error_code(); +} + +// A value within S32 is written and one beyond it is refused. +void require_narrow(linuxcnc::v1::HalService::Stub* hal, + linuxcnc::v1::HalItemKind kind, const std::string& name, + const char* description) { + live_require(write_item(hal, kind, name, 5) == grpc::StatusCode::OK, + description); + live_require(write_item(hal, kind, name, kBeyondS32) == + grpc::StatusCode::FAILED_PRECONDITION, + description); +} + +void run_halcmd(const char* halcmd, const std::string& arguments) { + const auto command = std::string(halcmd) + " " + arguments; + // NOLINTNEXTLINE(concurrency-mt-unsafe): nothing here changes the environment + live_require(std::system(command.c_str()) == 0, command.c_str()); +} + +class NarrowComponent { + public: + explicit NarrowComponent(linuxcnc::v1::HalService::Stub* hal) { + context_.set_deadline(std::chrono::system_clock::now() + + std::chrono::seconds(10)); + stream_ = hal->RunComponent(&context_); + linuxcnc::v1::HalComponentClientMessage open; + auto* create = open.mutable_create(); + create->set_name("grpc-live-narrow"); + create->set_prefix("grpc-live-narrow"); + for (const char* name : {"direct", "aliased", "linked"}) { + auto* pin = create->add_pins(); + pin->set_name(name); + pin->set_type(linuxcnc::v1::HAL_TYPE_S32); + pin->set_direction(linuxcnc::v1::HAL_PIN_DIRECTION_IN); + } + auto* parameter = create->add_parameters(); + parameter->set_name("limit"); + parameter->set_type(linuxcnc::v1::HAL_TYPE_S32); + parameter->set_direction(linuxcnc::v1::HAL_PARAM_DIRECTION_RW); + live_require(stream_->Write(open), "narrow component create is sent"); + linuxcnc::v1::HalComponentServerMessage message; + live_require(stream_->Read(&message) && message.has_attached(), + "narrow component attaches"); + generation_ = message.attached().generation(); + linuxcnc::v1::HalComponentClientMessage activate; + activate.mutable_activate()->set_generation(generation_); + auto* initial = activate.mutable_activate()->add_values(); + initial->mutable_item()->set_kind(linuxcnc::v1::HAL_ITEM_KIND_PARAM); + initial->mutable_item()->set_name("grpc-live-narrow.limit"); + initial->mutable_value()->set_type(linuxcnc::v1::HAL_TYPE_S32); + initial->mutable_value()->set_s32(0); + live_require(stream_->Write(activate), "narrow component activate is sent"); + live_require(stream_->Read(&message) && message.has_active(), + "narrow component activates"); + } + + void destroy() { + linuxcnc::v1::HalComponentClientMessage close; + close.mutable_close()->set_generation(generation_); + close.mutable_close()->set_mode( + linuxcnc::v1::HAL_COMPONENT_CLOSE_MODE_DESTROY); + live_require(stream_->Write(close), "narrow component close is sent"); + stream_->WritesDone(); + linuxcnc::v1::HalComponentServerMessage message; + bool closed = false; + while (!closed && stream_->Read(&message)) closed = message.has_closed(); + live_require(closed, "narrow component closes"); + live_require(stream_->Finish().ok(), "narrow component stream finishes"); + } + + private: + grpc::ClientContext context_; + std::unique_ptr< + grpc::ClientReaderWriter> + stream_; + std::uint64_t generation_ = 0; +}; + +// Covers every route by which a write reaches an owned S32 item, and that the +// check ends with the component. +void verify_narrow_write_paths(linuxcnc::v1::HalService::Stub* hal) { + constexpr auto kPin = linuxcnc::v1::HAL_ITEM_KIND_PIN; + constexpr auto kParam = linuxcnc::v1::HAL_ITEM_KIND_PARAM; + constexpr auto kSignalKind = linuxcnc::v1::HAL_ITEM_KIND_SIGNAL; + const std::string signal = "grpc-live-narrow-signal"; + + NarrowComponent component(hal); + require_narrow(hal, kPin, "grpc-live-narrow.direct", "direct pin write"); + require_narrow(hal, kParam, "grpc-live-narrow.limit", "parameter write"); + + linuxcnc::v1::CreateHalSignalRequest create_signal; + create_signal.set_name(signal); + create_signal.set_type(linuxcnc::v1::HAL_TYPE_S64); + linuxcnc::v1::CreateHalSignalResponse created_signal; + grpc::ClientContext create_signal_context; + live_require( + hal->CreateSignal(&create_signal_context, create_signal, &created_signal) + .ok(), + "the narrow test signal is created"); + live_require( + write_item(hal, kSignalKind, signal, kBeyondS32) == grpc::StatusCode::OK, + "an unlinked 64-bit signal takes a 64-bit value"); + live_require(write_item(hal, kSignalKind, signal, 0) == grpc::StatusCode::OK, + "the unlinked signal is reset"); + + // NOLINTNEXTLINE(concurrency-mt-unsafe): nothing here changes the environment + const char* halcmd = std::getenv("LINUXCNC_GRPC_LIVE_HALCMD"); + if (halcmd) { + run_halcmd(halcmd, "linkps grpc-live-narrow.linked " + signal); + require_narrow(hal, kSignalKind, signal, "write through a linked signal"); + run_halcmd(halcmd, + "alias pin grpc-live-narrow.aliased grpc-live-narrow-pin-alias"); + require_narrow(hal, kPin, "grpc-live-narrow-pin-alias", + "write to a pin through its alias"); + run_halcmd(halcmd, + "alias param grpc-live-narrow.limit grpc-live-narrow-par-alias"); + require_narrow(hal, kParam, "grpc-live-narrow-par-alias", + "write to a parameter through its alias"); + } else { + std::cout << "LINUXCNC_GRPC_LIVE_HALCMD is unset; skipping linked signal " + "and alias write checks\n"; + } + component.destroy(); + + // A stale registry entry would stop the new component's pins from being + // registered, leaving them unchecked. + NarrowComponent recreated(hal); + require_narrow(hal, kPin, "grpc-live-narrow.direct", + "direct pin write after re-creation"); + require_narrow(hal, kParam, "grpc-live-narrow.limit", + "parameter write after re-creation"); + recreated.destroy(); +} + +} // namespace + bool verify_hal_and_scope(const std::shared_ptr& channel, const std::string& telemetry_endpoint) { google::protobuf::Empty empty; @@ -207,6 +368,26 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, assert(create_signal_response.signal().type() == type); } + // HAL (2.10+) has 64-bit integer signals only: a signal requested as S32 or + // U32 is created as, and reported with, the 64-bit type of the same + // signedness. + for (const auto& [name, requested, reported] : + {std::tuple{"grpc-live-s32", linuxcnc::v1::HAL_TYPE_S32, + linuxcnc::v1::HAL_TYPE_S64}, + std::tuple{"grpc-live-u32", linuxcnc::v1::HAL_TYPE_U32, + linuxcnc::v1::HAL_TYPE_U64}}) { + linuxcnc::v1::CreateHalSignalRequest create_signal_request; + create_signal_request.set_name(name); + create_signal_request.set_type(requested); + linuxcnc::v1::CreateHalSignalResponse create_signal_response; + grpc::ClientContext create_signal_context; + const auto create_signal_status = hal->CreateSignal( + &create_signal_context, create_signal_request, &create_signal_response); + assert(create_signal_status.ok()); + assert(create_signal_response.signal().name() == name); + assert(create_signal_response.signal().type() == reported); + } + linuxcnc::v1::CreateHalSignalRequest conflicting_signal; conflicting_signal.set_name("grpc-live-s64"); conflicting_signal.set_type(linuxcnc::v1::HAL_TYPE_U64); @@ -292,6 +473,10 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, component_input->set_name("input"); component_input->set_type(linuxcnc::v1::HAL_TYPE_S32); component_input->set_direction(linuxcnc::v1::HAL_PIN_DIRECTION_IN); + auto* component_unsigned_input = component_create->add_pins(); + component_unsigned_input->set_name("unsigned-input"); + component_unsigned_input->set_type(linuxcnc::v1::HAL_TYPE_U32); + component_unsigned_input->set_direction(linuxcnc::v1::HAL_PIN_DIRECTION_IN); assert(component->Write(component_open)); linuxcnc::v1::HalComponentServerMessage component_response; assert(component->Read(&component_response)); @@ -384,6 +569,101 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, } assert(saw_input_delta); + // Items declared S32/U32 are 64-bit in HAL and topology reports them as + // S64/U64, but their owner reads them as 32-bit values. A write outside the + // declared range is refused like a mistyped write, instead of being + // acknowledged and then silently clamped for the owner. A batch containing + // such a write applies nothing. + const auto narrow_write = + [&](const std::vector>& + writes, + linuxcnc::v1::HalWriteResponse* response) { + linuxcnc::v1::HalWrite request; + for (const auto& [name, value] : writes) { + auto* write = request.add_writes(); + write->mutable_item()->set_kind(linuxcnc::v1::HAL_ITEM_KIND_PIN); + write->mutable_item()->set_name(name); + *write->mutable_value() = value; + } + grpc::ClientContext context; + return hal->Write(&context, request, response); + }; + const auto s64_scalar = [](std::int64_t value) { + linuxcnc::v1::HalScalar scalar; + scalar.set_type(linuxcnc::v1::HAL_TYPE_S64); + scalar.set_s64(value); + return scalar; + }; + const auto u64_scalar = [](std::uint64_t value) { + linuxcnc::v1::HalScalar scalar; + scalar.set_type(linuxcnc::v1::HAL_TYPE_U64); + scalar.set_u64(value); + return scalar; + }; + constexpr auto kS32Min = std::numeric_limits::min(); + constexpr auto kS32Max = std::numeric_limits::max(); + constexpr auto kU32Max = std::numeric_limits::max(); + const std::string signed_input = "grpc-live-component.input"; + const std::string unsigned_input = "grpc-live-component.unsigned-input"; + for (const auto& rejected : + {std::pair{signed_input, s64_scalar(30000000000LL)}, + std::pair{signed_input, s64_scalar(std::int64_t{kS32Max} + 1)}, + std::pair{signed_input, s64_scalar(std::int64_t{kS32Min} - 1)}, + std::pair{unsigned_input, u64_scalar(std::uint64_t{kU32Max} + 1)}}) { + linuxcnc::v1::HalWriteResponse response; + const auto status = narrow_write({rejected}, &response); + assert(status.error_code() == grpc::StatusCode::FAILED_PRECONDITION); + assert(response.values_size() == 0); + } + { + linuxcnc::v1::HalWriteResponse response; + const auto status = + narrow_write({{signed_input, s64_scalar(7)}, + {unsigned_input, u64_scalar(std::uint64_t{kU32Max} + 1)}}, + &response); + assert(status.error_code() == grpc::StatusCode::FAILED_PRECONDITION); + } + { + linuxcnc::v1::HalReadRequest request; + auto* read_item = request.add_items(); + read_item->set_kind(linuxcnc::v1::HAL_ITEM_KIND_PIN); + read_item->set_name(signed_input); + linuxcnc::v1::HalReadResponse response; + grpc::ClientContext context; + assert(hal->Read(&context, request, &response).ok()); + assert(response.values_size() == 1); + assert(response.values(0).value().type() == linuxcnc::v1::HAL_TYPE_S64); + assert(response.values(0).value().s64() == 55); + } + { + linuxcnc::v1::HalWriteResponse response; + const auto status = narrow_write({{signed_input, s64_scalar(kS32Min)}, + {unsigned_input, u64_scalar(kU32Max)}}, + &response); + assert(status.ok()); + assert(response.values_size() == 2); + assert(response.values(0).value().s64() == kS32Min); + assert(response.values(1).value().u64() == kU32Max); + } + bool saw_signed_limit = false; + bool saw_unsigned_limit = false; + while (component->Read(&component_response)) { + if (!component_response.has_delta()) continue; + for (const auto& value : component_response.delta().values()) { + if (value.item().name() == signed_input) { + assert(value.value().type() == linuxcnc::v1::HAL_TYPE_S32); + assert(value.value().s32() == kS32Min); + saw_signed_limit = true; + } else if (value.item().name() == unsigned_input) { + assert(value.value().type() == linuxcnc::v1::HAL_TYPE_U32); + assert(value.value().u32() == kU32Max); + saw_unsigned_limit = true; + } + } + if (saw_signed_limit && saw_unsigned_limit) break; + } + assert(saw_signed_limit && saw_unsigned_limit); + linuxcnc::v1::HalComponentClientMessage component_close; component_close.mutable_close()->set_generation(component_generation); component_close.mutable_close()->set_mode( @@ -407,6 +687,7 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, for (const auto& item : cleanup_topology.topology().pins()) { assert(item.name() != "grpc-live-component.value"); assert(item.name() != "grpc-live-component.input"); + assert(item.name() != "grpc-live-component.unsigned-input"); assert(item.name() != "grpc-live-component.online"); } @@ -572,6 +853,8 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, assert(timeout_destroy->Read(&component_response)); assert(timeout_destroy->Finish().ok()); + verify_narrow_write_paths(hal.get()); + // Scope controls use the shared gRPC control plane while capture data uses // the shared WebSocket telemetry listener. auto scope = linuxcnc::v1::ScopeService::NewStub(channel); @@ -583,16 +866,19 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, assert(scope_response.has_status()); assert(!scope_response.websocket_path().empty()); + // Sample one integer pin (HAL reports integers as S64/U64 only) and one + // bit/float pin, so both the 64-bit integer and the other sample paths run. + const linuxcnc::v1::HalPinInfo* scope_integer_pin = nullptr; const linuxcnc::v1::HalPinInfo* scope_pin = nullptr; for (const auto& candidate : topology.topology().pins()) { - if (candidate.type() == linuxcnc::v1::HAL_TYPE_BIT || - candidate.type() == linuxcnc::v1::HAL_TYPE_FLOAT || - candidate.type() == linuxcnc::v1::HAL_TYPE_S32 || - candidate.type() == linuxcnc::v1::HAL_TYPE_U32) { + if (!scope_integer_pin && (candidate.type() == linuxcnc::v1::HAL_TYPE_S64 || + candidate.type() == linuxcnc::v1::HAL_TYPE_U64)) + scope_integer_pin = &candidate; + if (!scope_pin && (candidate.type() == linuxcnc::v1::HAL_TYPE_BIT || + candidate.type() == linuxcnc::v1::HAL_TYPE_FLOAT)) scope_pin = &candidate; - break; - } } + assert(scope_integer_pin != nullptr); assert(scope_pin != nullptr); linuxcnc::v1::ScopeConfigure scope_configure; auto* acquisition = scope_configure.mutable_config(); @@ -603,7 +889,13 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, scope_channel->set_index(0); scope_channel->set_enabled(true); scope_channel->mutable_item()->set_kind(linuxcnc::v1::HAL_ITEM_KIND_PIN); - scope_channel->mutable_item()->set_name(scope_pin->name()); + scope_channel->mutable_item()->set_name(scope_integer_pin->name()); + auto* scope_second_channel = acquisition->add_channels(); + scope_second_channel->set_index(1); + scope_second_channel->set_enabled(true); + scope_second_channel->mutable_item()->set_kind( + linuxcnc::v1::HAL_ITEM_KIND_PIN); + scope_second_channel->mutable_item()->set_name(scope_pin->name()); grpc::ClientContext configure_context; assert(scope->Configure(&configure_context, scope_configure, &scope_response) .ok()); @@ -630,6 +922,12 @@ bool verify_hal_and_scope(const std::shared_ptr& channel, assert(scope_frame.ParseFromArray(scope_bytes.data(), static_cast(scope_bytes.size()))); assert(scope_frame.has_capture() || scope_frame.has_roll()); + const auto& scope_channels = scope_frame.has_capture() + ? scope_frame.capture().channels() + : scope_frame.roll().channels(); + assert(scope_channels.size() >= 2); + assert(scope_channels.Get(0).index() == 0 && scope_channels.Get(0).enabled()); + assert(scope_channels.Get(1).index() == 1 && scope_channels.Get(1).enabled()); grpc::ClientContext trigger_context; assert(scope->Trigger(&trigger_context, {}, &scope_response).ok()); diff --git a/native/server/tests/grpc_live_integration.cc b/native/server/tests/grpc_live_integration.cc index 2d932c91..3d295750 100644 --- a/native/server/tests/grpc_live_integration.cc +++ b/native/server/tests/grpc_live_integration.cc @@ -203,6 +203,8 @@ int main(int argc, char** argv) { dwell.join(); assert(dwell_status.ok()); + verify_interpreter_reset_requires_idle(machine.get()); + // Exercise one safe representative from the remaining command families. // The protobuf setters are the command catalog: this table deliberately // does not duplicate command-case numbers or names. @@ -384,6 +386,7 @@ int main(int argc, char** argv) { verify_command_error_attribution(machine.get()); verify_abort_handler_errors(machine.get()); + verify_task_queued_command_ordering(machine.get()); expect_command_error(machine.get(), ExecuteCommandRequest{}, grpc::StatusCode::INVALID_ARGUMENT); diff --git a/native/server/tests/grpc_live_support.cc b/native/server/tests/grpc_live_support.cc index 893a0b06..7cf4158a 100644 --- a/native/server/tests/grpc_live_support.cc +++ b/native/server/tests/grpc_live_support.cc @@ -461,6 +461,262 @@ void verify_abort_handler_errors(linuxcnc::v1::MachineService::Stub* machine) { (void)errors->Finish(); } +void live_require(bool condition, const char* description) { + if (condition) return; + std::cerr << "live check failed: " << description << "\n"; + std::abort(); +} + +namespace { + +bool tool_exists(linuxcnc::v1::MachineService::Stub* machine, int tool_no) { + const auto status = get_status_with_retry(machine); + for (const auto& tool : status.status().tool_table()) { + if (tool.tool_no() == tool_no) return true; + } + return false; +} + +void create_live_tool(linuxcnc::v1::MachineService::Stub* machine, int tool_no, + int pocket_no) { + ExecuteCommandRequest create; + auto* tool = create.mutable_set_tool()->mutable_tool(); + tool->set_tool_no(tool_no); + tool->set_pocket_no(pocket_no); + (void)execute_completed(machine, std::move(create)); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (!tool_exists(machine, tool_no) && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + live_require(tool_exists(machine, tool_no), "the live test tool is created"); +} + +// Issues a tool delete that LinuxCNC queues behind a running dwell, so that it +// is still unresolved when the caller sends its next command. +class QueuedToolDelete { + public: + QueuedToolDelete(linuxcnc::v1::MachineService::Stub* machine, int tool_no, + const std::function& before_delete = {}) { + ExecuteCommandRequest dwell; + dwell.mutable_mdi()->set_command("G4 P1"); + (void)execute_accepted(machine, std::move(dwell)); + if (before_delete) before_delete(); + worker_ = std::thread([this, machine, tool_no] { + ExecuteCommandRequest request; + request.set_wait_policy(linuxcnc::v1::WAIT_POLICY_COMPLETED); + request.mutable_delete_tool()->set_tool_no(tool_no); + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + + std::chrono::seconds(10)); + status_ = machine->ExecuteCommand(&context, request, &response_); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + } + + const ExecuteCommandResponse& wait() { + worker_.join(); + live_require(status_.ok(), "the queued tool delete RPC finishes"); + return response_; + } + + private: + std::thread worker_; + grpc::Status status_; + ExecuteCommandResponse response_; +}; + +} // namespace + +void verify_task_queued_command_ordering( + linuxcnc::v1::MachineService::Stub* machine) { + constexpr int kMissingTool = 9999; + constexpr int kLiveTool = 78; + constexpr int kLivePocket = 44; + + // The next command waits for the queued command, so a refusal is reported + // by the command that was refused. + { + QueuedToolDelete refused(machine, kMissingTool); + ExecuteCommandRequest next; + next.mutable_set_debug_level()->set_level(0); + const auto next_response = execute_completed(machine, std::move(next)); + live_require(next_response.status() == linuxcnc::v1::RCS_STATUS_DONE, + "the command after a refused command succeeds"); + const auto& response = refused.wait(); + live_require(response.status() == linuxcnc::v1::RCS_STATUS_ERROR, + "the refused tool delete reports its own failure"); + live_require(response.error().message() == "LinuxCNC rejected the command", + "the refusal comes from LinuxCNC's result for that command"); + } + + // Abort passes the hold. It discards the queued delete, which must not be + // reported as done, and cancels the MDI command held behind it, which must + // not run after the abort. + create_live_tool(machine, kLiveTool, kLivePocket); + { + QueuedToolDelete overtaken(machine, kLiveTool); + ExecuteCommandResponse held_response; + grpc::Status held_status; + std::thread held([&] { + ExecuteCommandRequest request; + request.set_wait_policy(linuxcnc::v1::WAIT_POLICY_COMPLETED); + request.mutable_mdi()->set_command("G4 P0.2"); + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + + std::chrono::seconds(10)); + held_status = machine->ExecuteCommand(&context, request, &held_response); + }); + std::this_thread::sleep_for(std::chrono::milliseconds(150)); + ExecuteCommandRequest abort; + abort.mutable_abort_task(); + const auto started = std::chrono::steady_clock::now(); + (void)execute_accepted(machine, std::move(abort)); + live_require(std::chrono::steady_clock::now() - started < + std::chrono::milliseconds(500), + "abort is not delayed by the queued command"); + const auto& response = overtaken.wait(); + live_require(response.status() == linuxcnc::v1::RCS_STATUS_ERROR, + "a delete discarded by abort is not reported as done"); + live_require(tool_exists(machine, kLiveTool), + "the discarded delete left the tool in place"); + held.join(); + live_require(held_status.ok(), "the held MDI command is answered"); + live_require( + held_response.status() == linuxcnc::v1::RCS_STATUS_ERROR && + held_response.error().message().find( + "cancelled before reaching LinuxCNC") != std::string::npos, + "abort cancels the command held behind the queued delete"); + } + + // E-stop passes the hold in the same way. + { + QueuedToolDelete overtaken(machine, kLiveTool); + ExecuteCommandRequest estop; + estop.mutable_set_state()->set_state(linuxcnc::v1::TASK_STATE_ESTOP); + const auto started = std::chrono::steady_clock::now(); + (void)execute_accepted(machine, std::move(estop)); + live_require(std::chrono::steady_clock::now() - started < + std::chrono::milliseconds(500), + "E-stop is not delayed by the queued command"); + const auto& response = overtaken.wait(); + live_require(response.status() == linuxcnc::v1::RCS_STATUS_ERROR, + "a delete discarded by E-stop is not reported as done"); + live_require(tool_exists(machine, kLiveTool), + "the delete discarded by E-stop left the tool in place"); + } + for (const auto state : + {linuxcnc::v1::TASK_STATE_ESTOP_RESET, linuxcnc::v1::TASK_STATE_ON}) { + ExecuteCommandRequest request; + request.mutable_set_state()->set_state(state); + (void)execute_completed(machine, std::move(request)); + } + ExecuteCommandRequest mdi_mode; + mdi_mode.mutable_set_task_mode()->set_mode(linuxcnc::v1::TASK_MODE_MDI); + (void)execute_completed(machine, std::move(mdi_mode)); + + // A command queued during a pause cannot finish until Resume, so Resume has + // to pass the hold. The delete stays queued in LinuxCNC and runs afterwards, + // but Resume replaced its result, so its outcome is reported as unknown. + { + QueuedToolDelete paused(machine, kLiveTool, [machine] { + ExecuteCommandRequest pause; + pause.mutable_pause_program(); + (void)execute_accepted(machine, std::move(pause)); + }); + ExecuteCommandRequest resume; + resume.mutable_resume_program(); + const auto started = std::chrono::steady_clock::now(); + (void)execute_accepted(machine, std::move(resume)); + live_require(std::chrono::steady_clock::now() - started < + std::chrono::milliseconds(500), + "Resume is not delayed by the queued command"); + const auto& response = paused.wait(); + live_require(response.status() == linuxcnc::v1::RCS_STATUS_ERROR, + "a delete overtaken by Resume is not reported as done"); + } + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (tool_exists(machine, kLiveTool) && + std::chrono::steady_clock::now() < deadline) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + live_require(!tool_exists(machine, kLiveTool), + "the delete still queued in LinuxCNC runs after Resume"); +} + +namespace { + +void expect_reset_refused(linuxcnc::v1::MachineService::Stub* machine, + const std::string& reason) { + ExecuteCommandRequest reset; + reset.set_wait_policy(linuxcnc::v1::WAIT_POLICY_COMPLETED); + reset.mutable_reset_interpreter(); + grpc::ClientContext context; + context.set_deadline(std::chrono::system_clock::now() + + std::chrono::seconds(5)); + ExecuteCommandResponse response; + live_require(machine->ExecuteCommand(&context, reset, &response).ok(), + "the refused reset is answered"); + live_require(response.status() == linuxcnc::v1::RCS_STATUS_ERROR, + "a reset of a busy machine is refused"); + live_require(response.error().message().find(reason) != std::string::npos, + "the refusal says why"); +} + +} // namespace + +void verify_interpreter_reset_requires_idle( + linuxcnc::v1::MachineService::Stub* machine) { + const auto mdi = [](const char* line) { + ExecuteCommandRequest request; + request.mutable_mdi()->set_command(line); + return request; + }; + const auto distance_mode = [](const GetStatusResponse& response) { + return response.status().task().active_g_codes().distance_mode(); + }; + const auto wait_for = [&](const char* description, auto&& condition) { + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (std::chrono::steady_clock::now() < deadline) { + if (condition(get_status_with_retry(machine))) return; + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + live_require(false, description); + }; + + (void)execute_completed(machine, mdi("G91")); + (void)execute_accepted(machine, mdi("G1 X5 F60")); + wait_for("the move starts", [](const GetStatusResponse& response) { + return response.status().motion().traj().current_velocity() > 0.0; + }); + + expect_reset_refused(machine, "refused"); + const auto refused = get_status_with_retry(machine); + live_require(refused.status().motion().traj().current_velocity() > 0.0, + "the move keeps running after the refusal"); + live_require(distance_mode(refused) == 910, "the refusal keeps the modes"); + + ExecuteCommandRequest abort; + abort.mutable_abort_task(); + (void)execute_completed(machine, std::move(abort)); + wait_for("the abort reaches idle", [](const GetStatusResponse& response) { + const auto& task = response.status().task(); + const auto& traj = response.status().motion().traj(); + return task.interp_state() == linuxcnc::v1::INTERP_STATE_IDLE && + task.exec_state() == linuxcnc::v1::EXEC_STATE_DONE && + traj.queue() == 0 && traj.in_position() && + traj.current_velocity() == 0.0; + }); + ExecuteCommandRequest reset; + reset.mutable_reset_interpreter(); + (void)execute_completed(machine, std::move(reset)); + wait_for("the reset restores the modes", + [&](const GetStatusResponse& s) { return distance_mode(s) == 900; }); +} + void verify_priority_admission(linuxcnc::v1::MachineService::Stub* machine) { constexpr int kSubmitters = 256; std::atomic ready{0}; diff --git a/native/server/tests/grpc_live_support.hpp b/native/server/tests/grpc_live_support.hpp index f6d464ee..14482800 100644 --- a/native/server/tests/grpc_live_support.hpp +++ b/native/server/tests/grpc_live_support.hpp @@ -45,7 +45,15 @@ void expect_command_error(linuxcnc::v1::MachineService::Stub* machine, void verify_command_error_attribution( linuxcnc::v1::MachineService::Stub* machine); void verify_abort_handler_errors(linuxcnc::v1::MachineService::Stub* machine); +// Unlike assert(), stays active when NDEBUG is defined. +void live_require(bool condition, const char* description); +// Requires MDI mode with the machine on, and leaves it that way. +void verify_task_queued_command_ordering( + linuxcnc::v1::MachineService::Stub* machine); void verify_priority_admission(linuxcnc::v1::MachineService::Stub* machine); +// Requires MDI mode with the machine on, and leaves it that way. +void verify_interpreter_reset_requires_idle( + linuxcnc::v1::MachineService::Stub* machine); std::string read_file(const std::string& path); linuxcnc::v1::UploadWorkspaceResponse upload_program( diff --git a/native/server/tests/hal_value_codec_tests.cc b/native/server/tests/hal_value_codec_tests.cc new file mode 100644 index 00000000..8632406b --- /dev/null +++ b/native/server/tests/hal_value_codec_tests.cc @@ -0,0 +1,288 @@ +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "../src/hal/narrow_item_registry.hpp" +#include "../src/hal/value_codec.hpp" +#include "linuxcnc_grpc/hal/adapter.hpp" + +using namespace linuxcnc::server; + +namespace { + +constexpr auto kS32Min = std::numeric_limits::min(); +constexpr auto kS32Max = std::numeric_limits::max(); +constexpr auto kU32Max = std::numeric_limits::max(); + +hal_query_value_u sint(rtapi_sint value) { + hal_query_value_u result{}; + result.s = value; + return result; +} + +hal_query_value_u uint(rtapi_uint value) { + hal_query_value_u result{}; + result.u = value; + return result; +} + +// to_hal() for a conversion that must succeed. +hal_query_value_u converted(hal_type_t type, const HalAdapterValue& value) { + const auto result = hal_codec::to_hal(type, value); + if (!result) std::abort(); + return *result; +} + +// The value of a read that must succeed with type T. +template +T owned(const std::optional& value) { + if (!value || !std::holds_alternative(*value)) std::abort(); + return std::get(*value); +} + +void check_to_hal() { + using hal_codec::to_hal; + // Exact types. + assert(converted(HAL_BOOL, HalAdapterValue{true}).b); + assert(converted(HAL_REAL, HalAdapterValue{2.5}).r == 2.5); + assert(converted(HAL_SINT, HalAdapterValue{std::int64_t{-30000000000}}).s == + -30000000000); + assert(converted(HAL_UINT, HalAdapterValue{std::uint64_t{30000000000}}).u == + 30000000000U); + + // 32-bit values widen to HAL's 64-bit storage, keeping their value. + assert(converted(HAL_SINT, HalAdapterValue{kS32Min}).s == kS32Min); + assert(converted(HAL_SINT, HalAdapterValue{std::int32_t{-1}}).s == -1); + assert(converted(HAL_UINT, HalAdapterValue{kU32Max}).u == kU32Max); + + // Signedness must match: no implicit reinterpretation. + assert(!to_hal(HAL_SINT, HalAdapterValue{std::uint64_t{1}})); + assert(!to_hal(HAL_SINT, HalAdapterValue{std::uint32_t{1}})); + assert(!to_hal(HAL_UINT, HalAdapterValue{std::int64_t{1}})); + assert(!to_hal(HAL_UINT, HalAdapterValue{std::int32_t{1}})); + + // Other mismatches. + assert(!to_hal(HAL_BOOL, HalAdapterValue{std::int64_t{1}})); + assert(!to_hal(HAL_REAL, HalAdapterValue{std::int64_t{1}})); + assert(!to_hal(HAL_SINT, HalAdapterValue{1.0})); + assert(!to_hal(HAL_UINT, HalAdapterValue{true})); + assert(!to_hal(HAL_PORT, HalAdapterValue{std::uint64_t{1}})); +} + +void check_fits_declared() { + using hal_codec::fits_declared; + const auto s32 = HalAdapterType::S32; + const auto u32 = HalAdapterType::U32; + assert(fits_declared(s32, HAL_SINT, sint(0))); + assert(fits_declared(s32, HAL_SINT, sint(kS32Min))); + assert(fits_declared(s32, HAL_SINT, sint(kS32Max))); + assert(!fits_declared(s32, HAL_SINT, sint(rtapi_sint{kS32Max} + 1))); + assert(!fits_declared(s32, HAL_SINT, sint(rtapi_sint{kS32Min} - 1))); + assert(!fits_declared(s32, HAL_SINT, sint(30000000000))); + assert(fits_declared(u32, HAL_UINT, uint(0))); + assert(fits_declared(u32, HAL_UINT, uint(kU32Max))); + assert(!fits_declared(u32, HAL_UINT, uint(rtapi_uint{kU32Max} + 1))); + assert(!fits_declared(u32, HAL_UINT, uint(30000000000U))); + + // 64-bit and non-integer declarations take every value. + assert(fits_declared(HalAdapterType::S64, HAL_SINT, + sint(std::numeric_limits::min()))); + assert(fits_declared(HalAdapterType::U64, HAL_UINT, + uint(std::numeric_limits::max()))); + assert(fits_declared(HalAdapterType::Bit, HAL_BOOL, hal_query_value_u{})); + assert(fits_declared(HalAdapterType::Float, HAL_REAL, hal_query_value_u{})); +} + +// read_owned() reads through HAL's inline accessors, which only dereference +// the handle; a local cell stands in for HAL shared memory. +union Cell { + rtapi_sint s; + rtapi_uint u; +}; + +std::optional read_sint(HalAdapterType type, + rtapi_sint stored) { + Cell cell{}; + cell.s = stored; + hal_refs_u ref{}; + // NOLINTNEXTLINE(bugprone-casting-through-void) + ref.s = static_cast(static_cast(&cell)); + return hal_codec::read_owned(type, ref); +} + +std::optional read_uint(HalAdapterType type, + rtapi_uint stored) { + Cell cell{}; + cell.u = stored; + hal_refs_u ref{}; + // NOLINTNEXTLINE(bugprone-casting-through-void) + ref.u = static_cast(static_cast(&cell)); + return hal_codec::read_owned(type, ref); +} + +void check_read_owned() { + const auto s32 = HalAdapterType::S32; + const auto u32 = HalAdapterType::U32; + // In range: the declared 32-bit type with the exact value. + assert(owned(read_sint(s32, -55)) == -55); + assert(owned(read_sint(s32, kS32Min)) == kS32Min); + assert(owned(read_uint(u32, kU32Max)) == kU32Max); + // Out of range (only a linked 64-bit writer can still produce this): the + // owner sees the nearest 32-bit limit. + assert(owned(read_sint(s32, 30000000000)) == kS32Max); + assert(owned(read_sint(s32, -30000000000)) == kS32Min); + assert(owned(read_uint(u32, 30000000000U)) == kU32Max); + // 64-bit declarations are exact. + assert(owned(read_sint(HalAdapterType::S64, -30000000000)) == + -30000000000); + assert(owned(read_uint(HalAdapterType::U64, 30000000000U)) == + 30000000000U); + // A missing handle reads as nothing. + assert(!hal_codec::read_owned(s32, hal_refs_u{})); + assert(!hal_codec::read_owned(HalAdapterType::U64, hal_refs_u{})); +} + +// Unlike assert(), stays active when NDEBUG is defined. +void require(bool condition, const char* description) { + if (condition) return; + std::cerr << "narrow item registry check failed: " << description << "\n"; + std::abort(); +} + +constexpr int kOwner = 7; +constexpr int kOtherOwner = 8; +constexpr rtapi_sint kTooLarge = rtapi_sint{kS32Max} + 1; + +bool accepts_sint(const NarrowItemRegistry& registry, bool pin, + const char* name, const char* alias, int owner, + rtapi_sint value) { + return registry.accepts(pin, name, alias, owner, HAL_SINT, sint(value)); +} + +void check_narrow_registry_add_and_ranges() { + NarrowItemRegistry registry; + require(registry.empty(), "a new registry is empty"); + require(accepts_sint(registry, true, "c.in", nullptr, kOwner, kTooLarge), + "an unregistered item takes any value"); + + require(registry.add(true, "c.in", kOwner, HalAdapterType::S32), + "first registration succeeds"); + require(!registry.empty(), "a registered item makes the registry non-empty"); + require(accepts_sint(registry, true, "c.in", nullptr, kOwner, kS32Max), + "the S32 maximum fits"); + require(accepts_sint(registry, true, "c.in", nullptr, kOwner, kS32Min), + "the S32 minimum fits"); + require(!accepts_sint(registry, true, "c.in", nullptr, kOwner, kTooLarge), + "a value above the S32 range is refused"); + require(!accepts_sint(registry, true, "c.in", nullptr, kOwner, + rtapi_sint{kS32Min} - 1), + "a value below the S32 range is refused"); + + require(registry.add(true, "c.count", kOwner, HalAdapterType::U32), + "a second item registers"); + require(registry.accepts(true, "c.count", nullptr, kOwner, HAL_UINT, + uint(kU32Max)), + "the U32 maximum fits"); + require(!registry.accepts(true, "c.count", nullptr, kOwner, HAL_UINT, + uint(rtapi_uint{kU32Max} + 1)), + "a value above the U32 range is refused"); + + // Pins and parameters are separate HAL namespaces. + require(accepts_sint(registry, false, "c.in", nullptr, kOwner, kTooLarge), + "a parameter does not match a pin of the same name"); + require(registry.add(false, "c.in", kOwner, HalAdapterType::S32), + "a parameter may share a pin's name"); + require(!accepts_sint(registry, false, "c.in", nullptr, kOwner, kTooLarge), + "a registered parameter is range checked"); + + // The first registration stays when HAL would refuse the duplicate name. + require(!registry.add(true, "c.in", kOtherOwner, HalAdapterType::U32), + "a duplicate name is not registered"); + require(!accepts_sint(registry, true, "c.in", nullptr, kOwner, kTooLarge), + "a refused duplicate leaves the original entry"); + require(accepts_sint(registry, true, "c.in", nullptr, kOtherOwner, kTooLarge), + "a refused duplicate does not register its owner"); + + require(NarrowItemRegistry::is_narrow(HalAdapterType::S32) && + NarrowItemRegistry::is_narrow(HalAdapterType::U32), + "32-bit types are narrow"); + require(!NarrowItemRegistry::is_narrow(HalAdapterType::S64) && + !NarrowItemRegistry::is_narrow(HalAdapterType::U64) && + !NarrowItemRegistry::is_narrow(HalAdapterType::Bit) && + !NarrowItemRegistry::is_narrow(HalAdapterType::Float), + "other types are not narrow"); +} + +void check_narrow_registry_owner_mismatch() { + NarrowItemRegistry registry; + require(registry.add(true, "c.in", kOwner, HalAdapterType::S32), + "registration succeeds"); + // A foreign item that reuses the name is not the owned item. + require(accepts_sint(registry, true, "c.in", nullptr, kOtherOwner, kTooLarge), + "another component's item is not range checked"); + registry.remove(true, "c.in", kOtherOwner); + require(!registry.empty(), "removal by another owner removes nothing"); + require(!accepts_sint(registry, true, "c.in", nullptr, kOwner, kTooLarge), + "the entry survives removal by another owner"); + registry.remove(false, "c.in", kOwner); + require(!accepts_sint(registry, true, "c.in", nullptr, kOwner, kTooLarge), + "removing a parameter leaves the pin of the same name"); +} + +void check_narrow_registry_alias() { + NarrowItemRegistry registry; + require(registry.add(true, "c.in", kOwner, HalAdapterType::S32), + "registration succeeds"); + // HAL reports an aliased item under its alias, with the original name as + // the old name; the entry is keyed by the original name. + require(!accepts_sint(registry, true, "alias", "c.in", kOwner, kTooLarge), + "an aliased item is checked through its original name"); + require(accepts_sint(registry, true, "alias", "c.in", kOwner, kS32Max), + "an aliased item takes values in range"); + require(accepts_sint(registry, true, "alias", "c.in", kOtherOwner, kTooLarge), + "the alias candidate still requires the owner to match"); + require(accepts_sint(registry, true, "alias", "other", kOwner, kTooLarge), + "an unrelated original name is not checked"); +} + +void check_narrow_registry_remove_and_recreate() { + NarrowItemRegistry registry; + require(registry.add(true, "c.in", kOwner, HalAdapterType::S32), + "registration succeeds"); + registry.remove(true, "c.in", kOwner); + require(registry.empty(), "removing the last entry empties the registry"); + require(accepts_sint(registry, true, "c.in", nullptr, kOwner, kTooLarge), + "a removed item is no longer checked"); + + // A component re-created under the same name gets a new id and may declare + // a different type; the check must follow the new declaration. + require(registry.add(true, "c.in", kOtherOwner, HalAdapterType::U32), + "the name registers again after removal"); + require(accepts_sint(registry, true, "c.in", nullptr, kOwner, kTooLarge), + "the old owner no longer matches"); + require(!registry.accepts(true, "c.in", nullptr, kOtherOwner, HAL_UINT, + uint(rtapi_uint{kU32Max} + 1)), + "the new declaration is enforced"); + require(registry.accepts(true, "c.in", nullptr, kOtherOwner, HAL_UINT, + uint(kU32Max)), + "the new declaration's range applies"); +} + +} // namespace + +int main() { + check_to_hal(); + check_fits_declared(); + check_read_owned(); + check_narrow_registry_add_and_ranges(); + check_narrow_registry_owner_mismatch(); + check_narrow_registry_alias(); + check_narrow_registry_remove_and_recreate(); + return 0; +} diff --git a/native/server/tests/machine_status_codec_tests.cc b/native/server/tests/machine_status_codec_tests.cc index a77ba5da..e1a0dd74 100644 --- a/native/server/tests/machine_status_codec_tests.cc +++ b/native/server/tests/machine_status_codec_tests.cc @@ -68,6 +68,7 @@ void delta_preserves_wire_changes() { auto changed = status_sample(); changed.echo_serial_number = 18; changed.task_stat.optional_stop_state = true; + changed.task_stat.hold_wait = linuxcnc::v1::HOLD_WAIT_EXECUTOR; changed.motion_stat.traj.actual_position.values[0] = 15.0; changed.motion_stat.joints[0].homed = false; changed.motion_stat.digital_input = {1, 0}; @@ -80,6 +81,7 @@ void delta_preserves_wire_changes() { assert(delta->sequence() == 23); assert(delta->echo_serial_number() == 18); assert(delta->task().optional_stop_state()); + assert(delta->task().hold_wait() == linuxcnc::v1::HOLD_WAIT_EXECUTOR); assert(!delta->task().has_mode()); assert(delta->motion().traj().actual_position().values(0) == 15.0); assert(!delta->motion().traj().has_linear_units()); diff --git a/native/server/tests/native_edge_tests.cc b/native/server/tests/native_edge_tests.cc index 05e50d90..0557be0c 100644 --- a/native/server/tests/native_edge_tests.cc +++ b/native/server/tests/native_edge_tests.cc @@ -11,8 +11,11 @@ #include #include #include +#include #include #include +#include +#include #include #include #include @@ -23,7 +26,9 @@ #include "linuxcnc_grpc/command_coordinator.hpp" #include "linuxcnc_grpc/gcode/canon_preview.hpp" #include "linuxcnc_grpc/hal/value_telemetry.hpp" +#include "linuxcnc_grpc/linuxcnc/command_completion_tracker.hpp" #include "linuxcnc_grpc/linuxcnc/command_validation.hpp" +#include "linuxcnc_grpc/linuxcnc/nml_adapter.hpp" #include "linuxcnc_grpc/position/history.hpp" #include "linuxcnc_grpc/program/workspace.hpp" #include "linuxcnc_grpc/program/workspace_archive.hpp" @@ -246,6 +251,505 @@ void deferred_command_completion_test() { coordinator.shutdown(); } +// Unlike assert(), stays active when NDEBUG is defined. +void require(bool condition, const char* description) { + if (condition) return; + std::cerr << "command hold check failed: " << description << "\n"; + std::abort(); +} + +constexpr auto kSettle = std::chrono::milliseconds(40); +constexpr auto kPatience = std::chrono::seconds(5); + +// The order in which commands reached the simulated LinuxCNC channel. +class WriteLog { + public: + void add(int serial) { + { + std::lock_guard lock(mutex_); + writes_.push_back(serial); + } + condition_.notify_all(); + } + + bool wait_for(int serial) { + std::unique_lock lock(mutex_); + return condition_.wait_for(lock, kPatience, [&] { + return std::find(writes_.begin(), writes_.end(), serial) != writes_.end(); + }); + } + + std::vector writes() const { + std::lock_guard lock(mutex_); + return writes_; + } + + private: + mutable std::mutex mutex_; + std::condition_variable condition_; + std::vector writes_; +}; + +CommandResult finished(const CommandTicket& ticket, const char* description) { + CommandResult result; + require(ticket.wait_for(kPatience, &result), description); + return result; +} + +// Starts a hold from inside a command and returns its release callable. +std::function start_hold(CommandCoordinator& coordinator, + std::chrono::milliseconds limit) { + std::function release; + const auto ticket = + submitted(coordinator.submit_with_context([&](CommandContext& context) { + release = context.hold_normal_commands(limit); + })); + (void)finished(ticket, "the holding command finishes"); + return release; +} + +CommandTicket logged(CommandCoordinator& coordinator, WriteLog& log, int serial, + CommandPriority priority = CommandPriority::Normal, + CommandHoldPolicy policy = CommandHoldPolicy::Wait) { + return submitted(coordinator.submit_with_context( + [&log, serial](CommandContext&) { log.add(serial); }, {}, priority, + policy)); +} + +void command_hold_keeps_later_commands_in_order_test() { + CommandCoordinator coordinator(4); + WriteLog log; + const auto release = start_hold(coordinator, std::chrono::seconds(30)); + const auto first = logged(coordinator, log, 1); + const auto second = logged(coordinator, log, 2); + std::this_thread::sleep_for(kSettle); + require(log.writes().empty(), "held commands do not start"); + require(coordinator.queued() == 2, "held commands stay queued"); + release(); + (void)finished(first, "first held command runs after release"); + (void)finished(second, "second held command runs after release"); + require(log.writes() == std::vector({1, 2}), + "held commands keep their order"); + release(); // A repeated release is harmless. + coordinator.shutdown(); +} + +void command_hold_bypass_test() { + CommandCoordinator coordinator(4, 2); + WriteLog log; + const auto release = start_hold(coordinator, std::chrono::seconds(30)); + const auto held = logged(coordinator, log, 1); + const auto safety = logged(coordinator, log, 2, CommandPriority::Safety); + (void)finished(safety, "a safety command passes a hold"); + const auto bypass = logged(coordinator, log, 3, CommandPriority::Normal, + CommandHoldPolicy::Bypass); + (void)finished(bypass, "a bypassing command passes a hold"); + std::this_thread::sleep_for(kSettle); + require(log.writes() == std::vector({2, 3}), + "ordinary commands stay held while others pass"); + release(); + (void)finished(held, "the held command runs after release"); + require(log.writes() == std::vector({2, 3, 1}), + "the held command runs last"); + coordinator.shutdown(); +} + +void command_hold_bypass_keeps_order_without_hold_test() { + CommandCoordinator coordinator(4); + WriteLog log; + Gate blocker; + const auto busy = submitted(coordinator.submit([&] { + blocker.arrive(); + blocker.wait_until_open(); + })); + blocker.wait_for_arrival(); + const auto first = logged(coordinator, log, 1); + const auto second = logged(coordinator, log, 2, CommandPriority::Normal, + CommandHoldPolicy::Bypass); + blocker.open(); + (void)finished(busy, "the blocking command finishes"); + (void)finished(first, "the first command runs"); + (void)finished(second, "the second command runs"); + require(log.writes() == std::vector({1, 2}), + "bypass does not reorder commands when nothing is held"); + coordinator.shutdown(); +} + +void command_hold_expiry_test() { + CommandCoordinator coordinator(4); + WriteLog log; + const auto started = std::chrono::steady_clock::now(); + const auto expired = start_hold(coordinator, kSettle); + const auto after_expiry = logged(coordinator, log, 1); + (void)finished(after_expiry, "a hold ends at its limit without a release"); + require(std::chrono::steady_clock::now() - started >= kSettle, + "a hold lasts until its limit"); + + // A late release of the expired hold must not end a newer hold. + const auto release = start_hold(coordinator, std::chrono::seconds(30)); + expired(); + const auto held = logged(coordinator, log, 2); + std::this_thread::sleep_for(kSettle); + require(log.writes() == std::vector({1}), + "a stale release leaves the newer hold in place"); + release(); + (void)finished(held, "the current release ends the hold"); + coordinator.shutdown(); +} + +void command_hold_shutdown_test() { + CommandCoordinator coordinator(4); + WriteLog log; + const auto release = start_hold(coordinator, std::chrono::minutes(10)); + const auto held = logged(coordinator, log, 1); + const auto started = std::chrono::steady_clock::now(); + coordinator.shutdown(); + require(std::chrono::steady_clock::now() - started < kPatience, + "shutdown does not wait for a hold"); + require(log.writes() == std::vector({1}), + "shutdown drains held commands"); + (void)finished(held, "a drained command finishes"); + release(); +} + +CommandTicket cancellable(CommandCoordinator& coordinator, WriteLog& log, + int serial, std::atomic& cancelled, + CommandHoldPolicy policy = CommandHoldPolicy::Wait) { + return submitted(coordinator.submit_with_context( + [&log, serial](CommandContext&) { log.add(serial); }, {}, + CommandPriority::Normal, policy, [&cancelled] { ++cancelled; })); +} + +void require_cancelled(const CommandTicket& ticket, const char* description) { + const auto result = finished(ticket, description); + require(result.state == CommandState::Failed && + result.error.find("cancelled before reaching LinuxCNC") != + std::string::npos, + description); +} + +void interrupt_cancels_held_commands_test() { + CommandCoordinator coordinator(8, 4); + WriteLog log; + std::atomic cancelled{0}; + const auto release = start_hold(coordinator, std::chrono::seconds(30)); + const auto held = cancellable(coordinator, log, 1, cancelled); + const auto bypass = + cancellable(coordinator, log, 2, cancelled, CommandHoldPolicy::Bypass); + (void)finished(bypass, "the bypassing command passes the hold"); + + // Pause and Stop keep earlier work queued. + const auto pause = logged(coordinator, log, 3, CommandPriority::Safety); + (void)finished(pause, "the safety command runs"); + require(coordinator.queued() == 1, "a safety command keeps held work"); + + const auto later_bypass = + cancellable(coordinator, log, 4, cancelled, CommandHoldPolicy::Bypass); + (void)finished(later_bypass, "the second bypassing command runs"); + const auto second_held = cancellable(coordinator, log, 5, cancelled); + const auto abort = logged(coordinator, log, 6, CommandPriority::Interrupt); + (void)finished(abort, "the interrupt runs"); + require_cancelled(held, "a command held before the interrupt is cancelled"); + require_cancelled(second_held, + "every command held before the interrupt is cancelled"); + require(cancelled == 2, "each cancelled command releases what it reserved"); + + const auto after = logged(coordinator, log, 7); + std::this_thread::sleep_for(kSettle); + require(coordinator.queued() == 1, + "a command submitted after the interrupt is kept"); + release(); + (void)finished(after, "the later command runs once the hold ends"); + require(log.writes() == std::vector({2, 3, 4, 6, 7}), + "cancelled commands never run"); + coordinator.shutdown(); +} + +void interrupt_cancels_queued_commands_without_hold_test() { + CommandCoordinator coordinator(8, 4); + WriteLog log; + std::atomic cancelled{0}; + Gate blocker; + const auto busy = submitted(coordinator.submit([&] { + blocker.arrive(); + blocker.wait_until_open(); + })); + blocker.wait_for_arrival(); + const auto queued = cancellable(coordinator, log, 1, cancelled); + const auto estop = logged(coordinator, log, 2, CommandPriority::Interrupt); + require_cancelled(queued, "a queued command is cancelled at once"); + blocker.open(); + require(finished(busy, "the running command finishes").state == + CommandState::Completed, + "the command already running is not cancelled"); + (void)finished(estop, "the interrupt runs"); + require(log.writes() == std::vector({2}), "only the interrupt runs"); + require(cancelled == 1, "the cancel handler runs once"); + coordinator.shutdown(); +} + +void nml_command_routing_test() { + const auto routed = [](NmlCommandKind kind, std::int32_t integer = 0) { + NmlCommand command; + command.kind = kind; + command.integer = integer; + return detail::nml_command_routing(command); + }; + for (const auto kind : + {NmlCommandKind::LoadToolTable, NmlCommandKind::SetTool, + NmlCommandKind::DeleteTool, NmlCommandKind::SetJointAvailability, + NmlCommandKind::SetSpindleAvailability}) { + const auto routing = routed(kind); + require(routing.task_queued, "task-queued commands start a hold"); + require(routing.priority == CommandPriority::Normal && + routing.hold_policy == CommandHoldPolicy::Wait, + "task-queued commands wait for an earlier hold"); + } + for (const auto kind : {NmlCommandKind::Pause, NmlCommandKind::StopProgram}) { + const auto routing = routed(kind); + require(routing.priority == CommandPriority::Safety, + "Pause and Stop are safety commands that keep queued work"); + require(!routing.task_queued, "stops do not start a hold"); + } + const auto abort = routed(NmlCommandKind::AbortTask); + require(abort.priority == CommandPriority::Interrupt && !abort.task_queued, + "Abort cancels queued work"); + for (const auto state : + {detail::kNmlTaskStateEstop, detail::kNmlTaskStateOff}) { + require(routed(NmlCommandKind::SetTaskState, state).priority == + CommandPriority::Interrupt, + "E-stop and machine off cancel queued work"); + } + for (const auto state : {2, 4}) { + const auto routing = routed(NmlCommandKind::SetTaskState, state); + require(routing.priority == CommandPriority::Normal && + routing.hold_policy == CommandHoldPolicy::Wait, + "E-stop reset and machine on wait for a hold"); + } + for (const auto kind : {NmlCommandKind::Resume, NmlCommandKind::Step, + NmlCommandKind::SpindleOff}) { + const auto routing = routed(kind); + require(routing.priority == CommandPriority::Normal && + routing.hold_policy == CommandHoldPolicy::Bypass, + "commands needed to finish held work pass a hold"); + } + const auto ordinary = routed(NmlCommandKind::SetFeedRate); + require(ordinary.priority == CommandPriority::Normal && + ordinary.hold_policy == CommandHoldPolicy::Wait && + !ordinary.task_queued, + "ordinary commands wait and do not hold"); +} + +NmlCommandEcho task_status(int echo, std::int32_t rcs_status) { + NmlCommandEcho status; + status.serial = echo; + if (rcs_status == detail::kNmlRcsStatusDone) + status.state = NmlCommandEcho::State::Done; + else if (rcs_status == detail::kNmlRcsStatusError) + status.state = NmlCommandEcho::State::Error; + return status; +} + +constexpr std::int32_t kRcsExec = 2; + +// A command coordinator and completion tracker around a simulated channel. +class TrackedCommands { + public: + explicit TrackedCommands(std::chrono::milliseconds timeout = {}) + : timeout(timeout), tracker(timeout) { + tracker.observe(task_status(0, detail::kNmlRcsStatusDone)); + } + + CommandTicket write(int serial, bool task_queued, + CommandPriority priority = CommandPriority::Normal) { + return submitted(coordinator.submit_with_context( + [this, serial, task_queued](CommandContext& context) { + detail::track_written_command( + &tracker, context, serial, task_queued, timeout, + [this] { ++completed_callbacks; }, + [this] { ++failed_callbacks; }); + // Logged once tracked, so a status the test publishes after seeing + // this entry counts as newer than the write. + log.add(serial); + }, + {}, priority)); + } + + std::chrono::milliseconds timeout; + NmlCommandCompletionTracker tracker; + WriteLog log; + std::atomic completed_callbacks{0}; + std::atomic failed_callbacks{0}; + CommandCoordinator coordinator{8}; +}; + +void queued_command_failure_attribution_test() { + TrackedCommands commands; + const auto queued = commands.write(10, true); + const auto next = commands.write(11, false); + require(commands.log.wait_for(10), "the queued command is written"); + + commands.tracker.observe(task_status(9, detail::kNmlRcsStatusDone)); + commands.tracker.observe(task_status(10, kRcsExec)); + std::this_thread::sleep_for(kSettle); + require(commands.log.writes() == std::vector({10}), + "the next command waits for the queued command's result"); + + commands.tracker.observe(task_status(10, detail::kNmlRcsStatusError)); + const auto failed = finished(queued, "the queued command resolves"); + require(failed.state == CommandState::Failed, + "the failure belongs to the queued command"); + require(failed.error == "LinuxCNC rejected the command", + "the queued command reports the rejection"); + require(commands.failed_callbacks == 1, "the failure callback runs"); + require(commands.log.wait_for(11), "the next command follows the result"); + + commands.tracker.observe(task_status(11, detail::kNmlRcsStatusDone)); + require(finished(next, "the next command resolves").state == + CommandState::Completed, + "the next command does not inherit the failure"); + require(commands.completed_callbacks == 1, "only the next command completed"); +} + +void queued_command_success_releases_hold_test() { + TrackedCommands commands; + const auto queued = commands.write(10, true); + const auto next = commands.write(11, true); + require(commands.log.wait_for(10), "the first queued command is written"); + commands.tracker.observe(task_status(10, detail::kNmlRcsStatusDone)); + require(finished(queued, "the first command resolves").state == + CommandState::Completed, + "the first queued command completes"); + require(commands.log.wait_for(11), "the second queued command follows"); + commands.tracker.observe(task_status(11, detail::kNmlRcsStatusDone)); + require(finished(next, "the second command resolves").state == + CommandState::Completed, + "the second queued command completes"); +} + +void queued_command_superseded_by_safety_test() { + TrackedCommands commands; + const auto queued = commands.write(10, true); + require(commands.log.wait_for(10), "the queued command is written"); + const auto held = commands.write(12, false); + const auto abort = commands.write(11, false, CommandPriority::Safety); + require(commands.log.wait_for(11), "the safety command passes the hold"); + std::this_thread::sleep_for(kSettle); + require(commands.log.writes() == std::vector({10, 11}), + "the normal command stays held behind the queued command"); + + commands.tracker.observe(task_status(11, detail::kNmlRcsStatusDone)); + const auto superseded = finished(queued, "the overtaken command resolves"); + require(superseded.state == CommandState::Failed, + "an overtaken queued command is not reported complete"); + require(superseded.error.find("outcome is unknown") != std::string::npos, + "the error says the outcome is unknown"); + require(commands.completed_callbacks == 1, + "only the safety command completed"); + require(finished(abort, "the safety command resolves").state == + CommandState::Completed, + "the safety command completes"); + require(commands.log.wait_for(12), "the hold ends with the queued command"); + commands.tracker.observe(task_status(12, detail::kNmlRcsStatusDone)); + (void)finished(held, "the held command resolves"); +} + +void queued_command_abort_cancels_held_commands_test() { + TrackedCommands commands; + const auto queued = commands.write(10, true); + require(commands.log.wait_for(10), "the queued command is written"); + const auto held = commands.write(12, false); + const auto abort = commands.write(11, false, CommandPriority::Interrupt); + require(commands.log.wait_for(11), "the abort passes the hold"); + require_cancelled(held, "the command held behind the queued one is dropped"); + + commands.tracker.observe(task_status(11, detail::kNmlRcsStatusDone)); + require(finished(queued, "the overtaken command resolves").state == + CommandState::Failed, + "the overtaken queued command is not reported complete"); + require( + finished(abort, "the abort resolves").state == CommandState::Completed, + "the abort completes"); + std::this_thread::sleep_for(kSettle); + require(commands.log.writes() == std::vector({10, 11}), + "the held command never reaches LinuxCNC"); +} + +void immediate_command_completes_on_later_echo_test() { + TrackedCommands commands; + const auto immediate = commands.write(10, false); + const auto next = commands.write(11, false); + require(commands.log.wait_for(11), "immediate commands do not hold"); + commands.tracker.observe(task_status(11, detail::kNmlRcsStatusDone)); + require(finished(immediate, "the first command resolves").state == + CommandState::Completed, + "a later echo completes an immediate command"); + require(finished(next, "the second command resolves").state == + CommandState::Completed, + "the echoed command completes"); +} + +void queued_command_timeout_releases_hold_test() { + TrackedCommands commands(std::chrono::milliseconds(60)); + const auto queued = commands.write(10, true); + const auto next = commands.write(11, false); + require(commands.log.wait_for(10), "the queued command is written"); + commands.tracker.observe(task_status(10, kRcsExec)); + std::this_thread::sleep_for(std::chrono::milliseconds(80)); + commands.tracker.tick(); + const auto timed_out = finished(queued, "the queued command times out"); + require(timed_out.state == CommandState::Failed, "a timeout is a failure"); + require(timed_out.error.find("timed out") != std::string::npos, + "the error reports the timeout"); + require(commands.log.wait_for(11), "a timeout releases the hold"); + commands.tracker.observe(task_status(11, detail::kNmlRcsStatusDone)); + (void)finished(next, "the next command resolves"); +} + +void queued_command_hold_outlives_silent_status_test() { + // With no status at all nothing resolves the command, so the hold's own + // limit is what lets later commands continue. + TrackedCommands commands(std::chrono::milliseconds(60)); + const auto queued = commands.write(10, true); + const auto next = commands.write(11, false); + require(commands.log.wait_for(10), "the queued command is written"); + require(commands.log.wait_for(11), "the hold limit releases later commands"); + commands.tracker.observe(task_status(11, detail::kNmlRcsStatusDone)); + require(finished(queued, "the expired command resolves").state == + CommandState::Failed, + "a command overtaken after expiry is not reported complete"); + (void)finished(next, "the next command resolves"); +} + +void queued_command_channel_failure_releases_hold_test() { + TrackedCommands commands; + const auto queued = commands.write(10, true); + const auto next = commands.write(11, false); + require(commands.log.wait_for(10), "the queued command is written"); + commands.tracker.channel_failed(); + require(finished(queued, "the queued command resolves").state == + CommandState::Failed, + "losing the status channel fails the queued command"); + require(commands.log.wait_for(11), "losing the channel releases the hold"); + require( + finished(next, "the next command resolves").state == CommandState::Failed, + "the next command also reports the lost channel"); +} + +void interpreter_reset_pending_test() { + TrackedCommands commands; + commands.tracker.observe(task_status(0, detail::kNmlRcsStatusDone)); + require(!commands.tracker.has_pending(), "nothing is pending at first"); + const auto written = commands.write(10, false); + require(commands.log.wait_for(10), "the command is written"); + require(commands.tracker.has_pending(), + "a written command is pending until LinuxCNC finishes it"); + commands.tracker.observe(task_status(10, detail::kNmlRcsStatusDone)); + (void)finished(written, "the written command resolves"); + require(!commands.tracker.has_pending(), + "nothing is pending once the command resolved"); +} + void command_validation_test() { NmlStatusSnapshot configuration; configuration.motion_stat.traj.joints = 3; @@ -930,6 +1434,23 @@ int main() { command_failure_wait_test(); command_priority_and_reserved_capacity_test(); deferred_command_completion_test(); + command_hold_keeps_later_commands_in_order_test(); + command_hold_bypass_test(); + command_hold_bypass_keeps_order_without_hold_test(); + command_hold_expiry_test(); + command_hold_shutdown_test(); + interrupt_cancels_held_commands_test(); + interrupt_cancels_queued_commands_without_hold_test(); + nml_command_routing_test(); + queued_command_failure_attribution_test(); + queued_command_success_releases_hold_test(); + queued_command_superseded_by_safety_test(); + queued_command_abort_cancels_held_commands_test(); + immediate_command_completes_on_later_echo_test(); + queued_command_timeout_releases_hold_test(); + queued_command_hold_outlives_silent_status_test(); + queued_command_channel_failure_releases_hold_test(); + interpreter_reset_pending_test(); command_validation_test(); nml_serial_wrap_test(); position_cursor_generation_and_replacement_test(); diff --git a/native/server/tests/run_gcode_parser_integration.sh b/native/server/tests/run_gcode_parser_integration.sh index 2c26f587..561b4d66 100755 --- a/native/server/tests/run_gcode_parser_integration.sh +++ b/native/server/tests/run_gcode_parser_integration.sh @@ -17,6 +17,7 @@ operations_program="$fixture_dir/preview_operations.ngc" cutter_compensation_program="$fixture_dir/cutter_compensation.ngc" python_remap_program="$fixture_dir/python_remap.ngc" modal_free_metric_program="$fixture_dir/modal_free_metric.ngc" +rotary_axis_program="$fixture_dir/rotary_axis.ngc" parameter_file="$fixture_dir/sim_mm.var" tool_table="$fixture_dir/sim_mm.tbl" workdir=$(mktemp -d "${TMPDIR:-/tmp}/linuxcnc-gcode-parser.XXXXXX") @@ -30,6 +31,10 @@ printf '#INCLUDE included.ini\n' >"$workdir/machine.ini" sed -e '/^LINEAR_UNITS[[:space:]]*=/d' \ -e '/^RS274NGC_STARTUP_CODE[[:space:]]*=/d' \ "$ini" >"$workdir/missing-linear-units.ini" +# The same machine with an A and a U axis, in lower case to match task's +# case-insensitive reading of COORDINATES. +sed -e 's/^COORDINATES[[:space:]]*=.*/COORDINATES = x y z a u/' \ + "$ini" >"$workdir/xyzau.ini" cp "$parameter_file" "$workdir/sim_mm.var" cp "$tool_table" "$workdir/sim_mm.tbl" cp "$fixture_dir/remap.py" "$workdir/remap.py" @@ -39,4 +44,5 @@ cd "$workdir" EMC2_HOME="${EMC2_HOME:-}" "$binary" "$workdir/machine.ini" "$program" \ "$operations_program" "$cutter_compensation_program" \ "$python_remap_program" "$modal_free_metric_program" \ - "$workdir/missing-linear-units.ini" + "$workdir/missing-linear-units.ini" "$workdir/xyzau.ini" \ + "$rotary_axis_program" diff --git a/native/server/tests/run_grpc_live_integration.sh b/native/server/tests/run_grpc_live_integration.sh index 5e0c3295..12f8ba43 100755 --- a/native/server/tests/run_grpc_live_integration.sh +++ b/native/server/tests/run_grpc_live_integration.sh @@ -218,6 +218,10 @@ fi start_server "$root/server.log" +# Lets the HAL acceptance test link pins and create aliases, which the gRPC API +# does not offer. +export LINUXCNC_GRPC_LIVE_HALCMD="$linuxcnc_root/scripts/rip-environment halcmd" + if ! timeout 60s "$integration" "127.0.0.1:${grpc_port}" \ "$fixture_dir/simple_linear.ngc" "127.0.0.1:${telemetry_port}" \ --batch-size=8; then diff --git a/native/server/tests/scope_controller_contract_tests.cc b/native/server/tests/scope_controller_contract_tests.cc index b8dc5f9f..69de2f32 100644 --- a/native/server/tests/scope_controller_contract_tests.cc +++ b/native/server/tests/scope_controller_contract_tests.cc @@ -3,24 +3,124 @@ #include #include +#include #include #include +#include +#include +#include #include "../src/scope/delta_count.hpp" +#include "../src/scope/sample_codec.hpp" #include "../src/scope/shm_abi.h" #include "linuxcnc_grpc/scope/controller.hpp" using namespace linuxcnc::server; +namespace { + +// Copies a cell written through upstream's union into ours, as the +// controller sees scope_rt's buffer. +linuxcnc_scope_data_t as_cell(const scope_data_t& upstream) { + linuxcnc_scope_data_t cell; + std::memcpy(&cell, &upstream, sizeof(cell)); + return cell; +} + +int trigger_error(hal_type_t type, double level) { + try { + scope_codec::validate_trigger_level(type, level); + } catch (const ScopeControllerError& error) { + return error.code(); + } + return 0; +} + +void check_sample_codec() { + using scope_codec::decode; + + // scope_rt writes only the member matching the channel type; the rest of + // the cell keeps whatever an earlier sample left there. + scope_data_t upstream; + std::memset(&upstream, 0xA5, sizeof(upstream)); + upstream.b = true; + assert(decode(as_cell(upstream), HAL_BOOL) == 1.0); + upstream.b = false; + assert(decode(as_cell(upstream), HAL_BOOL) == 0.0); + + upstream.s = -5; + assert(decode(as_cell(upstream), HAL_SINT) == -5.0); + upstream.s = std::numeric_limits::min(); + assert(decode(as_cell(upstream), HAL_SINT) == -9223372036854775808.0); + upstream.s = (rtapi_sint{1} << 53) + 1; // not representable: rounds + assert(decode(as_cell(upstream), HAL_SINT) == 9007199254740992.0); + + upstream.u = (rtapi_uint{1} << 32) + 7; + assert(decode(as_cell(upstream), HAL_UINT) == 4294967303.0); + upstream.u = std::numeric_limits::max(); + assert(decode(as_cell(upstream), HAL_UINT) == 18446744073709551616.0); + + upstream.r = -1.25; + assert(decode(as_cell(upstream), HAL_REAL) == -1.25); + assert(decode(as_cell(upstream), HAL_PORT) == 0.0); + + assert(scope_codec::sampleable(HAL_BOOL)); + assert(scope_codec::sampleable(HAL_REAL)); + assert(scope_codec::sampleable(HAL_SINT)); + assert(scope_codec::sampleable(HAL_UINT)); + assert(!scope_codec::sampleable(HAL_PORT)); + assert(!scope_codec::sampleable(HAL_TYPE_UNSPECIFIED)); + + // Trigger levels are compared by scope_rt through upstream's union. + linuxcnc_scope_data_t level; + scope_data_t read_back; + scope_codec::encode_trigger_level(&level, HAL_SINT, -3.5e12); + std::memcpy(&read_back, &level, sizeof(level)); + assert(read_back.s == -3500000000000); + scope_codec::encode_trigger_level(&level, HAL_UINT, 6e9); + std::memcpy(&read_back, &level, sizeof(level)); + assert(read_back.u == 6000000000U); + scope_codec::encode_trigger_level(&level, HAL_REAL, 0.5); + std::memcpy(&read_back, &level, sizeof(level)); + assert(read_back.r == 0.5); + scope_codec::encode_trigger_level(&level, HAL_BOOL, 1.0); + std::memcpy(&read_back, &level, sizeof(level)); + assert(read_back.b); + + assert(trigger_error(HAL_SINT, -9223372036854775808.0) == 0); + assert(trigger_error(HAL_SINT, 9223372036854775808.0) == -ERANGE); + assert(trigger_error(HAL_SINT, -1e19) == -ERANGE); + assert(trigger_error(HAL_UINT, 18446744073709549568.0) == 0); + assert(trigger_error(HAL_UINT, 18446744073709551616.0) == -ERANGE); + assert(trigger_error(HAL_UINT, -1.0) == -ERANGE); + assert(trigger_error(HAL_SINT, std::numeric_limits::quiet_NaN()) == + -ERANGE); + assert(trigger_error(HAL_REAL, 1e300) == 0); +} + +} // namespace + int main() { + static_assert(sizeof(linuxcnc_scope_data_t) == sizeof(scope_data_t)); static_assert(sizeof(linuxcnc_scope_shm_control_t) == sizeof(scope_shm_control_t)); + static_assert(offsetof(linuxcnc_scope_shm_control_t, trig_level) == + offsetof(scope_shm_control_t, trig_level)); + static_assert(offsetof(linuxcnc_scope_shm_control_t, state) == + offsetof(scope_shm_control_t, state)); + static_assert( + std::is_same_v); static_assert(offsetof(linuxcnc_scope_shm_control_t, data_offset) == offsetof(scope_shm_control_t, data_offset)); static_assert(offsetof(linuxcnc_scope_shm_control_t, data_type) == offsetof(scope_shm_control_t, data_type)); static_assert(offsetof(linuxcnc_scope_shm_control_t, data_len) == offsetof(scope_shm_control_t, data_len)); + // scope_rt's header rounding: (sizeof(scope_shm_control_t) + 7) & ~7. + static_assert(LINUXCNC_SCOPE_BUFFER_OFFSET == + ((sizeof(scope_shm_control_t) + 7) & ~std::size_t{7})); + check_sample_codec(); // scope_rt first grows the record and then slides it; a snapshot pair can // straddle the moment it fills, and every sample on both sides counts. diff --git a/proto/linuxcnc/v1/machine.proto b/proto/linuxcnc/v1/machine.proto index b41b60d5..9481bda4 100644 --- a/proto/linuxcnc/v1/machine.proto +++ b/proto/linuxcnc/v1/machine.proto @@ -75,6 +75,23 @@ enum StopState { STOP_STATE_STARTING = 3; } +// While a Stop is STOPPING or the program is paused: the operation the hold +// waits for. An operation already handed to another subsystem runs to its +// end before the machine holds; Abort ends it. +enum HoldWait { + HOLD_WAIT_NONE = 0; + // A queued G28.2 homing cycle. + HOLD_WAIT_HOMING = 1; + // A tool change or other I/O controller command. + HOLD_WAIT_IO = 2; + // A user M100-M199 program. + HOLD_WAIT_SYSTEM_COMMAND = 3; + // A request started by an executor remap. + HOLD_WAIT_EXECUTOR = 4; + // A joint or spindle availability handshake waiting for its acknowledgment. + HOLD_WAIT_AVAILABILITY = 5; +} + enum TrajMode { TRAJ_MODE_UNSPECIFIED = 0; TRAJ_MODE_FREE = 1; @@ -201,6 +218,7 @@ message TaskStat { bool task_paused = 30; double delay_left = 31; int32 queued_mdi_commands = 32; + HoldWait hold_wait = 35; } message JointStat { @@ -379,6 +397,7 @@ message TaskStatDelta { optional bool task_paused = 30; optional double delay_left = 31; optional int32 queued_mdi_commands = 32; + optional HoldWait hold_wait = 35; } message TrajectoryStatDelta { @@ -495,8 +514,12 @@ message ExecuteCommandRequest { WaitPolicy wait_policy = 1; oneof command { SetTaskMode set_task_mode = 2; + // E-stop and machine off, like abort_task, cancel every command still + // waiting in this server's queue when they arrive. SetTaskState set_state = 3; EmptyCommand task_plan_synch = 4; + // Restores the interpreter's startup modes. Refused with an error response + // unless the machine is idle; abort and wait for it to stop first. EmptyCommand reset_interpreter = 5; ProgramOpen program_open = 6; EmptyCommand program_close = 7; @@ -507,6 +530,9 @@ message ExecuteCommandRequest { EmptyCommand reverse_program = 12; EmptyCommand forward_program = 13; EmptyCommand stop_program = 14; + // Goes ahead of queued commands and cancels them; each cancelled command + // is answered with an error and never reaches LinuxCNC. Commands sent + // after the abort are kept. EmptyCommand abort_task = 15; SetBool set_optional_stop = 16; SetBool set_block_delete = 17; diff --git a/skills/patch-linuxcnc/SKILL.md b/skills/patch-linuxcnc/SKILL.md index 81a54c19..bceb3a17 100644 --- a/skills/patch-linuxcnc/SKILL.md +++ b/skills/patch-linuxcnc/SKILL.md @@ -30,6 +30,12 @@ validation into the ordinary edit-build-test loop. backup, and deterministic-ID checks are guarantees, not optional ceremony. - LinuxCNC tests must work with its userspace simulator under ordinary POSIX scheduling. Do not require hard real-time privileges or timing. +- New tests for a patch go in this repository's `linuxcnc-tests/`, laid out + like LinuxCNC's `tests/`, not in the patch. Patches only change existing + upstream tests. Reach the LinuxCNC tree from a test through `$EMC2_HOME`. + Run the suite with `linuxcnc-tests/run.sh `, or one test with + `scripts/runtests ` from the + LinuxCNC checkout. ## Phase 1: fast development loop @@ -90,7 +96,7 @@ edits alone do not complete a patch fix: ./linuxcnc-patches/refresh.sh linuxcnc ``` - `refresh.sh` preserves established filenames by ordinal, creates names for + `refresh.sh` preserves established filenames by position, creates names for appended commits, uses normalized `git format-patch` output, replays the complete generated series before replacing files, compares the replayed tree, and normalizes the managed branch to deterministic replayed commit @@ -159,6 +165,13 @@ Common interpreter parameter blocks are: - G28 home: `#5161–#5169`. - G30 home: `#5181–#5189`. +## Patch numbering + +Patch numbers are permanent. Never renumber the series. When a patch is +removed, delete its file, leave the gap, and keep its inventory entry in +`linuxcnc-patches/README.md` with the heading struck through and a note saying +when and why it was removed. Never reuse a removed patch's number. + ## Baseline changes Changing `base-revision` requires rebasing the complete linear patch stack,