From ac193cbdaadd85322318ee022f72f89257404a2c Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 21:24:08 +0100 Subject: [PATCH 01/45] chore(linuxcnc): keep patch numbers permanent across removals Allow gaps in the patch sequence so a removed patch does not force the rest of the series to be renumbered. apply.sh and refresh.sh now require ascending four-digit numbers instead of contiguous ordinals, and refresh.sh numbers an appended patch after the highest existing one. Document the rule: numbers are never changed or reused, and a removed patch stays in the README inventory, struck through, with the reason. --- linuxcnc-patches/README.md | 16 +++++++++++---- linuxcnc-patches/apply.sh | 14 ++++++++----- linuxcnc-patches/refresh.sh | 13 ++++++++---- linuxcnc-patches/test-stack.sh | 37 ++++++++++++++++++++++++++++++++++ skills/patch-linuxcnc/SKILL.md | 9 ++++++++- 5 files changed, 75 insertions(+), 14 deletions(-) diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index f1eccf7..33773ed 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -74,15 +74,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 diff --git a/linuxcnc-patches/apply.sh b/linuxcnc-patches/apply.sh index be271f0..5a16966 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/refresh.sh b/linuxcnc-patches/refresh.sh index 9539b49..4f1f48a 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 152d465..b3f7054 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/skills/patch-linuxcnc/SKILL.md b/skills/patch-linuxcnc/SKILL.md index 81a54c1..5bcd963 100644 --- a/skills/patch-linuxcnc/SKILL.md +++ b/skills/patch-linuxcnc/SKILL.md @@ -90,7 +90,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 +159,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, From 68b22cb3cbd8ca7d310b5cda32a4bfd7cd6e9d4f Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 21:24:38 +0100 Subject: [PATCH 02/45] chore(linuxcnc): start moving the patch series to v2.10.0-pre2 Pin the base to the v2.10.0-pre2 tag and park every patch that still applies only to the previous base under pending-pre2/, where the tooling ignores it. Each patch returns to the series, with its number and filename unchanged, when its port is accepted. Remove three patches and strike them through in the inventory: - 0017 and 0018: runtime availability is being redesigned around upstream's new G28.2 and will return as a new patch. - 0022: upstream already defines HAL_NAME_LEN as 55. The series is empty until the first ports land, so the patch workflow cannot pass on this commit. --- ...ntime-joint-and-spindle-availability.patch | 4407 ----------------- .../0018-availability-mcodes.patch | 1296 ----- .../0022-hal-raise-HAL_NAME_LEN-to-55.patch | 54 - linuxcnc-patches/README.md | 33 +- linuxcnc-patches/base-revision | 2 +- .../0001-export-spindle-speed-feedback.patch | 0 ...nterpreter-coordinate-data-in-status.patch | 0 ...ve-g96-g97-across-task-mode-switches.patch | 0 .../0004-resumable-stop.patch | 0 .../0005-headless-build-option.patch | 0 ...dered-realtime-component-search-path.patch | 0 .../0007-native-automatic-tool-wear.patch | 0 .../0008-tapered-g76-drive-lines.patch | 0 ...reading-stop-clear-and-pass-stepping.patch | 0 ...-add-recording-canon-preview-backend.patch | 0 ...-single-step-during-active-execution.patch | 0 ...-own-transactional-tool-CRUD-in-task.patch | 0 ...4ngc-add-composable-executor-stdglue.patch | 0 ...-publish-modal-CSS-maximum-in-status.patch | 0 ...ngc-pass-spindle-selectors-to-remaps.patch | 0 ...0016-motion-joint-target-preparation.patch | 0 ...w-concurrent-individual-joint-homing.patch | 0 ...otion-add-native-lathe-power-jogging.patch | 0 ...-cross-compiling-external-components.patch | 0 ...pose-native-thread-period-statistics.patch | 0 25 files changed, 31 insertions(+), 5761 deletions(-) delete mode 100644 linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch delete mode 100644 linuxcnc-patches/0018-availability-mcodes.patch delete mode 100644 linuxcnc-patches/0022-hal-raise-HAL_NAME_LEN-to-55.patch rename linuxcnc-patches/{ => pending-pre2}/0001-export-spindle-speed-feedback.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0002-expose-interpreter-coordinate-data-in-status.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0003-preserve-g96-g97-across-task-mode-switches.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0004-resumable-stop.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0005-headless-build-option.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0006-ordered-realtime-component-search-path.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0007-native-automatic-tool-wear.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0008-tapered-g76-drive-lines.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0009-threading-stop-clear-and-pass-stepping.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0010-rs274-add-recording-canon-preview-backend.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0011-motion-arm-single-step-during-active-execution.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0012-emc-own-transactional-tool-CRUD-in-task.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0013-rs274ngc-add-composable-executor-stdglue.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0016-motion-joint-target-preparation.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0019-motion-allow-concurrent-individual-joint-homing.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0020-feat-motion-add-native-lathe-power-jogging.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0021-hal-support-cross-compiling-external-components.patch (100%) rename linuxcnc-patches/{ => pending-pre2}/0023-hal-expose-native-thread-period-statistics.patch (100%) diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch deleted file mode 100644 index aa640cd..0000000 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ /dev/null @@ -1,4407 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Dariusz Majnert -Date: Thu, 17 Sep 2026 18:00:42 +0200 -Subject: [PATCH] runtime-joint-and-spindle-availability - ---- - docs/src/config/ini-config.adoc | 31 + - docs/src/config/python-interface.adoc | 26 + - 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/mot_priv.h | 21 + - src/emc/motion/motion.c | 16 + - src/emc/motion/motion.h | 61 +- - src/emc/nml_intf/emc.cc | 29 + - src/emc/nml_intf/emc.hh | 11 + - 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/task.hh | 1 + - src/emc/task/taskintf.cc | 94 ++- - src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + - .../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 - -diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc -index de598c529d..cdb1333971 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 < - #include - - #include "nml_intf/emc.hh" -@@ -139,9 +140,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 -- int sequence = ini.findIntV("HOME_SEQUENCE", jointSection, 999); -+ auto configured_sequence = ini.findInt("HOME_SEQUENCE", jointSection); -+ int sequence = configured_sequence.value_or(999); - old_inihal_data.joint_home_sequence[joint] = sequence; - -+ bool availability_control = -+ ini.findBoolV("AVAILABILITY_CONTROL", jointSection, false); -+ if (availability_control && configured_sequence) { -+ rcs_print_error("%s: HOME_SEQUENCE cannot be used with " -+ "AVAILABILITY_CONTROL; the joint is referenced only " -+ "during individual acquisition\n", -+ jointSection.c_str()); -+ return -1; -+ } -+ double availability_timeout = -+ ini.findRealV("AVAILABILITY_TIMEOUT", jointSection, 5.0); -+ if (!std::isfinite(availability_timeout) || availability_timeout <= 0.0) { -+ rcs_print_error("%s: AVAILABILITY_TIMEOUT must be greater than zero\n", -+ jointSection.c_str()); -+ return -1; -+ } - 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) - ignore_limits, - is_shared, - sequence, -- volatile_home, -+ volatile_home && !availability_control, - locking_idxer, - abs_encoder)) { - print_dbg_config("emcJointSetHomingParams"); -@@ -187,10 +205,20 @@ static int loadJoint(int joint, const IniFile &ini) - } - } - -- // Activate joint. -+ if (0 != emcJointSetAvailabilityConfig(joint, availability_control, -+ availability_timeout, -+ volatile_home)) { -+ rcs_print_error("%s: availability configuration rejected " -+ "(extra joints are unsupported)\n", jointSection.c_str()); -+ print_dbg_config("emcJointSetAvailabilityConfig"); -+ return -1; -+ } -+ -+ // Activate uncontrolled joints. Controlled joints are activated only -+ // after their acquisition handshake and position validation or homing. - // Doing this last should prevent the motion controller to flag errors - // during configuration -- if (0 != emcJointActivate(joint)) { -+ if (!availability_control && 0 != emcJointActivate(joint)) { - print_dbg_config("emcJointActivate"); - return -1; - } -diff --git a/src/emc/ini/inispindle.cc b/src/emc/ini/inispindle.cc -index 7438ae02bc..ad815f8df0 100644 ---- a/src/emc/ini/inispindle.cc -+++ b/src/emc/ini/inispindle.cc -@@ -14,6 +14,7 @@ - * Last change: created 30/12/21 - ********************************************************************/ - -+#include - #include - - #include "nml_intf/emc.hh" -@@ -91,12 +92,40 @@ static int loadSpindle(int spindle, const IniFile &ini) - double home_angle = 0.0; - double increment = ini.findRealV("INCREMENT", spindleSection, 100.0); - -+ bool availability_control = -+ ini.findBoolV("AVAILABILITY_CONTROL", spindleSection, false); -+ bool initial_availability = true; -+ if (availability_control) { -+ auto configured_initial = -+ ini.findBool("INITIAL_AVAILABILITY", spindleSection); -+ if (!configured_initial) { -+ rcs_print_error("%s: INITIAL_AVAILABILITY is required when " -+ "AVAILABILITY_CONTROL is enabled\n", -+ spindleSection.c_str()); -+ return -1; -+ } -+ initial_availability = *configured_initial; -+ } -+ double availability_timeout = -+ ini.findRealV("AVAILABILITY_TIMEOUT", spindleSection, 5.0); -+ if (!std::isfinite(availability_timeout) || availability_timeout <= 0.0) { -+ rcs_print_error("%s: AVAILABILITY_TIMEOUT must be greater than zero\n", -+ spindleSection.c_str()); -+ return -1; -+ } -+ - if (0 != emcSpindleSetParams(spindle, fastest_pos, slowest_pos, - slowest_neg, fastest_neg, search_vel, - home_angle, home_sequence, increment)) { - rcs_print_error("emcSpindleSetParams: failed\n"); - return -1; - } -+ if (0 != emcSpindleSetAvailabilityConfig(spindle, availability_control, -+ initial_availability, -+ availability_timeout)) { -+ rcs_print_error("emcSpindleSetAvailabilityConfig: failed\n"); -+ return -1; -+ } - return 0; - } - -diff --git a/src/emc/ini/linuxcnc_check_ini.py b/src/emc/ini/linuxcnc_check_ini.py -index d780715b90..eba42b648d 100755 ---- a/src/emc/ini/linuxcnc_check_ini.py -+++ b/src/emc/ini/linuxcnc_check_ini.py -@@ -251,8 +251,10 @@ def check_bools(): - "HOME_INDEX_NO_ENCODER_RESET", - "HOME_IGNORE_LIMITS", - "HOME_IS_SHARED", -- "VOLATILE_HOME" -+ "VOLATILE_HOME", -+ "AVAILABILITY_CONTROL" - ] -+ BOOLSVARS = ["AVAILABILITY_CONTROL", "INITIAL_AVAILABILITY"] - for s, v in BOOLVARS: - check_bool(s, v) - for asect in list(filter(lambda s: s.startswith("AXIS_"), ini.getsections())): -@@ -261,6 +263,9 @@ def check_bools(): - for jsect in list(filter(lambda s: s.startswith("JOINT_"), ini.getsections())): - for v in BOOLJVARS: - check_bool(jsect, v) -+ for ssect in list(filter(lambda s: s.startswith("SPINDLE_"), ini.getsections())): -+ for v in BOOLSVARS: -+ check_bool(ssect, v) - - # - # 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 ---- 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[]) { - log_print("SET_SPINDLE_PARAMS, %.2e, %.2e, %.2e, %.2e\n", c->maxLimit, c->min_pos_speed, c->minLimit, c->max_neg_speed); - break; - -+ case EMCMOT_SET_JOINT_AVAILABILITY_CONFIG: -+ log_print("SET_JOINT_AVAILABILITY_CONFIG joint=%d, controlled=%d, timeout=%.6g, volatile_home=%d\n", -+ c->joint, c->availability_control, -+ c->availability_timeout, c->volatile_home); -+ break; -+ -+ case EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG: -+ log_print("SET_SPINDLE_AVAILABILITY_CONFIG spindle=%d, controlled=%d, initial_available=%d, timeout=%.6g\n", -+ c->spindle, c->availability_control, -+ c->initial_availability, c->availability_timeout); -+ break; -+ -+ case EMCMOT_SET_JOINT_AVAILABILITY: -+ log_print("SET_JOINT_AVAILABILITY joint=%d, available=%d\n", -+ c->joint, c->available); -+ break; -+ -+ case EMCMOT_SET_SPINDLE_AVAILABILITY: -+ log_print("SET_SPINDLE_AVAILABILITY spindle=%d, available=%d\n", -+ c->spindle, c->available); -+ break; -+ - case EMCMOT_SET_SPINDLESYNC: - 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 ---- 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 - } - if (!motion_teleop_flag) { - axis->teleop_tp.enable = 0; -- return; -+ continue; - } - if (!motion_enable_flag) { continue; } - if ( *(axis_data->ajog_enable) == 0 ) { continue; } -diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index c166af652b..a18acd066f 100644 ---- a/src/emc/motion/command.c -+++ b/src/emc/motion/command.c -@@ -80,6 +80,38 @@ extern int motion_num_spindles; - - static int rehomeAll; - -+int availability_transition_busy(void) -+{ -+ int n; -+ for (n = 0; n < ALL_JOINTS; n++) { -+ availability_state_t state = -+ emcmotStatus->joint_status[n].availability.state; -+ if (state == EMCMOT_AVAILABILITY_ENABLING || -+ state == EMCMOT_AVAILABILITY_HOMING || -+ state == EMCMOT_AVAILABILITY_DISABLING) return 1; -+ } -+ for (n = 0; n < emcmotConfig->numSpindles; n++) { -+ availability_state_t state = -+ emcmotStatus->spindle_status[n].availability.state; -+ if (state == EMCMOT_AVAILABILITY_ENABLING || -+ state == EMCMOT_AVAILABILITY_DISABLING) return 1; -+ } -+ return 0; -+} -+ -+STATIC int spindle_range_is_available(int first, int last) -+{ -+ int spindle; -+ for (spindle = first; spindle <= last; spindle++) { -+ availability_status_t *availability = -+ &emcmotStatus->spindle_status[spindle].availability; -+ if (availability->controlled && -+ availability->state != EMCMOT_AVAILABILITY_AVAILABLE) -+ return 0; -+ } -+ return 1; -+} -+ - /* 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) - return; - } - } -+ if (availability_transition_busy()) { -+ switch (emcmotCommand->command) { -+ case EMCMOT_JOG_CONT: -+ case EMCMOT_JOG_INCR: -+ case EMCMOT_JOG_ABS: -+ case EMCMOT_SET_LINE: -+ case EMCMOT_SET_CIRCLE: -+ case EMCMOT_PROBE: -+ case EMCMOT_RIGID_TAP: -+ case EMCMOT_JOINT_HOME: -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ return; -+ default: break; -+ } -+ } -+ /* tcSetupState inherits the planner's modal spindle dependency. */ -+ switch (emcmotCommand->command) { -+ case EMCMOT_SET_LINE: -+ case EMCMOT_SET_CIRCLE: -+ case EMCMOT_PROBE: -+ case EMCMOT_RIGID_TAP: { -+ int spindle = emcmotInternal->coord_tp.spindle.spindle_num; -+ if (emcmotInternal->coord_tp.synchronized != TC_SYNC_NONE && -+ (spindle < 0 || spindle >= emcmotConfig->numSpindles || -+ !spindle_range_is_available(spindle, spindle))) { -+ reportError(_("cannot admit motion synchronized to unavailable spindle %d"), spindle); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ SET_MOTION_ERROR_FLAG(1); -+ return; -+ } -+ break; -+ } -+ default: break; -+ } - switch (emcmotCommand->command) { - case EMCMOT_ABORT: - /* abort motion */ -@@ -503,6 +569,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) - } - } - } -+ emcmotInternal->availability_motion_error = 0; - 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) - /* abort one joint number or axis number */ - /* can happen at any time */ - rtapi_print_msg(RTAPI_MSG_DBG, "JOG_ABORT: %i", joint_num); -+ if (joint_num >= 0 && joint_num < ALL_JOINTS && -+ emcmotStatus->joint_status[joint_num].availability.controlled && -+ (emcmotStatus->joint_status[joint_num].availability.state == EMCMOT_AVAILABILITY_HOMING || -+ emcmotStatus->joint_status[joint_num].availability.state == EMCMOT_AVAILABILITY_ENABLING)) -+ break; /* Jog stops do not cancel acquisition or its homing. */ - 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) - break; - - case EMCMOT_COORD: -+ if (availability_transition_busy()) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - /* 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) - break; - - case EMCMOT_TELEOP: -+ if (availability_transition_busy()) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - rtapi_print_msg(RTAPI_MSG_DBG, "TELEOP"); - switch_to_teleop_mode(); - break; -@@ -679,10 +760,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); -- emcmot_config_change(); - if (joint == 0) { - break; - } -+ if (emcmotStatus->joint_status[joint_num].availability.controlled && -+ emcmotCommand->home_sequence != 999) { -+ reportError(_("availability-controlled joint %d cannot define HOME_SEQUENCE"), -+ joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; -+ break; -+ } -+ emcmot_config_change(); - update_joint_homing_params(joint_num, - emcmotCommand->offset, - emcmotCommand->home, -@@ -795,6 +883,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) - SET_JOINT_ERROR_FLAG(joint, 1); - break; - } -+ if (!GET_MOTION_TELEOP_FLAG() && -+ emcmotStatus->joint_status[joint_num].availability.controlled && -+ emcmotStatus->joint_status[joint_num].availability.state != -+ EMCMOT_AVAILABILITY_AVAILABLE) { -+ reportError(_("Can't jog unavailable joint %d."), joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - // cannot jog if jog-inhibit is TRUE - if (*(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) - SET_JOINT_ERROR_FLAG(joint, 1); - break; - } -+ if (!GET_MOTION_TELEOP_FLAG() && -+ emcmotStatus->joint_status[joint_num].availability.controlled && -+ emcmotStatus->joint_status[joint_num].availability.state != -+ EMCMOT_AVAILABILITY_AVAILABLE) { -+ reportError(_("Can't jog unavailable joint %d."), joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - // cannot jog if jog-inhibit is TRUE - if (*(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) - SET_JOINT_ERROR_FLAG(joint, 1); - break; - } -+ if (!GET_MOTION_TELEOP_FLAG() && -+ emcmotStatus->joint_status[joint_num].availability.controlled && -+ emcmotStatus->joint_status[joint_num].availability.state != -+ EMCMOT_AVAILABILITY_AVAILABLE) { -+ reportError(_("Can't jog unavailable joint %d."), joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - // cannot jog if jog-inhibit is TRUE - if (*(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) - break; - - case EMCMOT_SET_SPINDLESYNC: -+ if (emcmotCommand->spindlesync != 0.0 && -+ emcmotCommand->spindle >= 0 && -+ emcmotCommand->spindle < emcmotConfig->numSpindles && -+ emcmotStatus->spindle_status[emcmotCommand->spindle].availability.controlled && -+ emcmotStatus->spindle_status[emcmotCommand->spindle].availability.state != -+ EMCMOT_AVAILABILITY_AVAILABLE) { -+ reportError(_("cannot synchronize to unavailable spindle %d"), -+ emcmotCommand->spindle); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - tpSetSpindleSync(&emcmotInternal->coord_tp, emcmotCommand->spindle, emcmotCommand->spindlesync, emcmotCommand->flags); - break; - -@@ -1380,6 +1503,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; -+ availability_cancel(1); - if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { - emcmotInternal->teleoperating = 0; - emcmotInternal->coordinating = 0; -@@ -1392,10 +1516,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"); -+ /* Initial availability belongs to a disabled-to-enabled request. -+ * 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 ) { - reportError(_("can't enable motion, enable input is false")); - } else { -- emcmotInternal->enabling = 1; -+ emcmotInternal->enabling = 0; -+ emcmotInternal->availability_machine_on = 1; -+ emcmotInternal->availability_resource = 0; - if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { - emcmotInternal->teleoperating = 0; - emcmotInternal->coordinating = 0; -@@ -1412,6 +1542,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) - if (joint == 0) { - break; - } -+ /* Availability owns activation, including the temporary active -+ * phase needed to finish or cancel acquisition homing. */ -+ if (emcmotStatus->joint_status[joint_num].availability.controlled) { -+ reportError(_("joint %d activation is owned by availability"), joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - SET_JOINT_ACTIVE_FLAG(joint, 1); - break; - -@@ -1424,6 +1561,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) - if (joint == 0) { - break; - } -+ /* Availability owns activation, including the temporary active -+ * phase needed to finish or cancel acquisition homing. */ -+ if (emcmotStatus->joint_status[joint_num].availability.controlled) { -+ reportError(_("joint %d activation is owned by availability"), joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - SET_JOINT_ACTIVE_FLAG(joint, 0); - break; - -@@ -1435,6 +1579,13 @@ 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) { -+ 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) - if (!GET_MOTION_ENABLE_FLAG()) { - break; - } -- - // Negative joint_num specifies homeall - do_home_joint(joint_num); - break; -@@ -1468,6 +1618,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) - return; - } - -+ if (joint_num >= 0 && joint_num < ALL_JOINTS && -+ emcmotStatus->joint_status[joint_num].availability.controlled) { -+ reportError(_("availability-controlled joint %d can only be unhomed by release"), -+ joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ if (joint_num == -1) { -+ int n; -+ for (n = 0; n < ALL_JOINTS; n++) { -+ if (emcmotStatus->joint_status[n].availability.controlled) { -+ reportError(_("cannot unhome all joints while joint %d is availability-controlled"), -+ n); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ } -+ if (n < ALL_JOINTS) break; -+ } -+ - // 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) - - break; - -+ case EMCMOT_SET_JOINT_AVAILABILITY_CONFIG: { -+ availability_status_t *availability; -+ /* Homed extra joints have an external posthome command owner. There -+ * is no handoff protocol with that owner, so acquisition is unsupported. */ -+ if (emcmotCommand->availability_control && IS_EXTRA_JOINT(joint_num)) { -+ rtapi_print_msg(RTAPI_MSG_ERR, -+ "availability control is unsupported for extra joint %d\n", joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; -+ break; -+ } -+ if (joint_num < 0 || joint_num >= ALL_JOINTS) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; -+ break; -+ } -+ if (emcmotCommand->availability_control && -+ get_home_sequence(joint_num) != 999) { -+ rtapi_print_msg(RTAPI_MSG_ERR, -+ "availability-controlled joint %d cannot define HOME_SEQUENCE\n", -+ joint_num); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; -+ break; -+ } -+ availability = &emcmotStatus->joint_status[joint_num].availability; -+ availability->controlled = !!emcmotCommand->availability_control; -+ availability->initial_available = 0; -+ availability->volatile_home = !!emcmotCommand->volatile_home; -+ availability->timeout = emcmotCommand->availability_timeout; -+ availability->fault = EMCMOT_AVAILABILITY_FAULT_NONE; -+ availability->state = availability->controlled -+ ? EMCMOT_AVAILABILITY_DISABLED : EMCMOT_AVAILABILITY_AVAILABLE; -+ availability->target_available = !availability->controlled; -+ availability->phase = AVAIL_PHASE_IDLE; -+ availability->held_position = joints[joint_num].pos_cmd; -+ if (availability->controlled) { -+ SET_JOINT_ENABLE_FLAG(&joints[joint_num], 0); -+ SET_JOINT_ACTIVE_FLAG(&joints[joint_num], 0); -+ } -+ emcmot_config_change(); -+ break; -+ } -+ -+ case EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG: { -+ availability_status_t *availability; -+ if (emcmotCommand->spindle < 0 || -+ emcmotCommand->spindle >= emcmotConfig->numSpindles) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; -+ break; -+ } -+ availability = &emcmotStatus->spindle_status[emcmotCommand->spindle].availability; -+ availability->controlled = !!emcmotCommand->availability_control; -+ availability->initial_available = !!emcmotCommand->initial_availability; -+ availability->timeout = emcmotCommand->availability_timeout; -+ availability->fault = EMCMOT_AVAILABILITY_FAULT_NONE; -+ availability->state = availability->controlled -+ ? EMCMOT_AVAILABILITY_DISABLED : EMCMOT_AVAILABILITY_AVAILABLE; -+ availability->target_available = !availability->controlled; -+ availability->phase = AVAIL_PHASE_IDLE; -+ emcmot_config_change(); -+ break; -+ } -+ -+ case EMCMOT_SET_JOINT_AVAILABILITY: { -+ availability_status_t *availability; -+ if (joint_num < 0 || joint_num >= ALL_JOINTS) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; -+ break; -+ } -+ availability = &emcmotStatus->joint_status[joint_num].availability; -+ if (availability_transition_busy()) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ if (!availability->controlled || -+ (availability->state != EMCMOT_AVAILABILITY_DISABLED && -+ availability->state != EMCMOT_AVAILABILITY_AVAILABLE && -+ availability->state != EMCMOT_AVAILABILITY_FAULT)) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ if (emcmotCommand->available && -+ availability->state == EMCMOT_AVAILABILITY_AVAILABLE) break; -+ if (!emcmotCommand->available && -+ availability->state == EMCMOT_AVAILABILITY_DISABLED) break; -+ if (motion_joint_release_state(joint_num) == -+ MOTION_JOINT_RELEASE_BLOCKED) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ if (emcmotCommand->available && !get_homed(joint_num) && -+ *(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) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ availability_begin(availability, 1); -+ } else { -+ if (availability->state == EMCMOT_AVAILABILITY_AVAILABLE) -+ availability_begin_joint_release(joint_num); -+ else -+ availability_release_joint(joint_num, EMCMOT_AVAILABILITY_FAULT_NONE); -+ } -+ break; -+ } -+ -+ case EMCMOT_SET_SPINDLE_AVAILABILITY: { -+ spindle_status_t *spindle; -+ availability_status_t *availability; -+ spindle_num = emcmotCommand->spindle; -+ if (spindle_num < 0 || spindle_num >= emcmotConfig->numSpindles) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; -+ break; -+ } -+ spindle = &emcmotStatus->spindle_status[spindle_num]; -+ availability = &spindle->availability; -+ if (availability_transition_busy()) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ if (!availability->controlled || -+ (availability->state != EMCMOT_AVAILABILITY_DISABLED && -+ availability->state != EMCMOT_AVAILABILITY_AVAILABLE && -+ availability->state != EMCMOT_AVAILABILITY_FAULT)) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ if (emcmotCommand->available && -+ availability->state == EMCMOT_AVAILABILITY_AVAILABLE) break; -+ if (!emcmotCommand->available && -+ availability->state == EMCMOT_AVAILABILITY_DISABLED) break; -+ if (spindle->state || spindle->orient_state == EMCMOT_ORIENT_IN_PROGRESS || -+ (tpQueueDepth(&emcmotInternal->coord_tp) != 0 && -+ emcmotInternal->coord_tp.synchronized != TC_SYNC_NONE && -+ emcmotInternal->coord_tp.spindle.spindle_num == spindle_num)) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ if (emcmotCommand->available) { -+ if (!GET_MOTION_ENABLE_FLAG() || !*emcmot_hal_data->enable) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } -+ availability_begin(availability, 1); -+ } else { -+ availability_release_spindle(spindle_num, EMCMOT_AVAILABILITY_FAULT_NONE); -+ } -+ break; -+ } -+ - 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) - s0 = 0; - s1 = motion_num_spindles - 1; - } -+ if (!spindle_range_is_available(s0, s1)) { -+ reportError(_("cannot command an unavailable spindle")); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ 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) - s0 = 0; - s1 = motion_num_spindles - 1; - } -+ if (!spindle_range_is_available(s0, s1)) { -+ reportError(_("cannot orient an unavailable spindle")); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - for (n = s0; n<=s1; n++){ -- - 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) - s0 = 0; - s1 = motion_num_spindles - 1; - } -+ if (!spindle_range_is_available(s0, s1)) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - 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) - s0 = 0; - s1 = motion_num_spindles - 1; - } -+ if (!spindle_range_is_available(s0, s1)) { -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - 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) - s0 = 0; - s1 = motion_num_spindles - 1; - } -+ if (!spindle_range_is_available(s0, s1)) { -+ reportError(_("cannot release the brake of an unavailable spindle")); -+ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; -+ break; -+ } - for (n = s0; n<=s1; n++){ -- - emcmotStatus->spindle_status[n].brake = 0; - } - break; -diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 8ed2cb3882..722c58545d 100644 ---- a/src/emc/motion/control.c -+++ b/src/emc/motion/control.c -@@ -46,6 +46,9 @@ static int switchkins_type = 0; - /* kinematics flags */ - KINEMATICS_FORWARD_FLAGS fflags = 0; - KINEMATICS_INVERSE_FLAGS iflags = 0; -+/* Shared by release and the encoder handshake. */ -+static int old_motion_index[EMCMOT_MAX_SPINDLES] = {0}; -+static int old_hal_index[EMCMOT_MAX_SPINDLES] = {0}; - - /*! \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]; - emcmotStatus structure. - */ - static void process_inputs(void); -+static void process_availability(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) - read_homing_in_pins(ALL_JOINTS); - handle_kinematicsSwitch(); - process_inputs(); -+ process_availability(); - 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) { - handle_jjogwheels(); - } -- if (!emcmotStatus->on_soft_limit && !*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, -+ get_homing_is_active()); -+ int availability_homing = 0, homing_cleanup = 0; -+ for (int n = 0; n < ALL_JOINTS; n++) { -+ availability_status_t *a = &emcmotStatus->joint_status[n].availability; -+ availability_homing |= a->state == EMCMOT_AVAILABILITY_HOMING; -+ homing_cleanup |= a->phase == AVAIL_PHASE_CANCEL_HOME; - } -- 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(); - } - -@@ -440,8 +453,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)) { -+ SET_JOINT_PHL_FLAG(joint, 1); -+ } else { -+ SET_JOINT_PHL_FLAG(joint, 0); -+ } -+ if (*(joint_data->neg_lim_sw)) { -+ SET_JOINT_NHL_FLAG(joint, 1); -+ } else { -+ SET_JOINT_NHL_FLAG(joint, 0); -+ } -+ 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)) { -+ SET_JOINT_FAULT_FLAG(joint, 1); -+ } else { -+ SET_JOINT_FAULT_FLAG(joint, 0); -+ } - if (!GET_JOINT_ACTIVE_FLAG(joint)) { -- /* if joint is not active, skip it */ -+ /* Keep released motion state frozen. The raw HAL feedback pin remains -+ live for hardware diagnostics and acquisition validation. */ - continue; - } - /* copy data from HAL to joint structure */ -@@ -489,25 +523,7 @@ static void process_inputs(void) - SET_JOINT_FERROR_FLAG(joint, 0); - } - -- /* read limit switches */ -- if (*(joint_data->pos_lim_sw)) { -- SET_JOINT_PHL_FLAG(joint, 1); -- } else { -- SET_JOINT_PHL_FLAG(joint, 0); -- } -- if (*(joint_data->neg_lim_sw)) { -- SET_JOINT_NHL_FLAG(joint, 1); -- } else { -- SET_JOINT_NHL_FLAG(joint, 0); -- } -- 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)) { -- SET_JOINT_FAULT_FLAG(joint, 1); -- } else { -- SET_JOINT_FAULT_FLAG(joint, 0); -- } -+ - } - - // a fault was signalled during a spindle-orient in progress -@@ -551,6 +567,394 @@ static void process_inputs(void) - } - } - -+/* Availability owns requests and completion, not homing or planner state. */ -+static void availability_clear_pending(availability_status_t *a) -+{ -+ 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. */ -+ a->state = a->state == EMCMOT_AVAILABILITY_FAULT -+ ? EMCMOT_AVAILABILITY_DISABLING : EMCMOT_AVAILABILITY_ENABLING; -+} -+ -+void availability_release_joint(int n, availability_fault_t fault) -+{ -+ availability_status_t *a = &emcmotStatus->joint_status[n].availability; -+ if (!a->controlled) return; -+ if (a->state == EMCMOT_AVAILABILITY_AVAILABLE || -+ a->state == EMCMOT_AVAILABILITY_HOMING) -+ a->held_position = joints[n].pos_cmd; -+ availability_clear_pending(a); -+ a->phase = AVAIL_PHASE_CANCEL_HOME; -+ a->fault = fault; -+ a->state = EMCMOT_AVAILABILITY_DISABLING; -+ a->transition_started = etime(); -+ *emcmot_hal_data->joint[n].availability_request = 0; -+ motion_cancel_joint(n); -+} -+ -+void availability_begin_joint_release(int n) -+{ -+ availability_status_t *a = &emcmotStatus->joint_status[n].availability; -+ /* Release admission has already completed planning. Capture its logical -+ * endpoint while the servo-side settled check drains the final sample. */ -+ a->held_position = joints[n].coarse_pos; -+ a->target_available = 0; -+ a->phase = AVAIL_PHASE_WAIT_SETTLED; -+ a->fault = EMCMOT_AVAILABILITY_FAULT_NONE; -+ a->state = EMCMOT_AVAILABILITY_DISABLING; -+ a->transition_started = etime(); -+} -+ -+void availability_release_spindle(int n, availability_fault_t fault) -+{ -+ spindle_status_t *s = &emcmotStatus->spindle_status[n]; -+ availability_status_t *a = &s->availability; -+ if (!a->controlled) return; -+ availability_clear_pending(a); -+ a->fault = fault; -+ a->state = EMCMOT_AVAILABILITY_DISABLING; -+ a->transition_started = etime(); -+ *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; -+ 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; -+} -+ -+void availability_cancel(int all) -+{ -+ int n; -+ int initial = emcmotInternal->availability_machine_on; -+ emcmotInternal->availability_machine_on = 0; -+ emcmotInternal->availability_resource = 0; -+ if (initial || all) emcmotInternal->enabling = 0; -+ /* Revoke mode restoration as well as acquisition. */ -+ if (all || initial) { -+ emcmotInternal->coordinating = 0; -+ emcmotInternal->teleoperating = 0; -+ } -+ for (n = 0; n < ALL_JOINTS; n++) { -+ availability_status_t *a = &emcmotStatus->joint_status[n].availability; -+ if ((all || initial || a->state == EMCMOT_AVAILABILITY_ENABLING || -+ a->state == EMCMOT_AVAILABILITY_HOMING || a->target_available) && -+ (all || initial || a->state != EMCMOT_AVAILABILITY_AVAILABLE)) -+ availability_release_joint(n, a->fault); -+ } -+ for (n = 0; n < emcmotConfig->numSpindles; n++) { -+ availability_status_t *a = &emcmotStatus->spindle_status[n].availability; -+ if ((all || initial || a->state == EMCMOT_AVAILABILITY_ENABLING || -+ a->target_available) && -+ (all || initial || a->state != EMCMOT_AVAILABILITY_AVAILABLE)) -+ availability_release_spindle(n, a->fault); -+ } -+} -+ -+/* Disable through the normal motion fault path, including already buffered -+ * interpolation. No further interpolation may run in the failing cycle. */ -+static void availability_motion_fault(void) -+{ -+ tpAbort(&emcmotInternal->coord_tp); -+ axis_jog_abort_all(1); -+ emcmotInternal->availability_motion_error = 1; -+ SET_MOTION_ERROR_FLAG(1); -+ emcmotInternal->enabling = 0; -+ set_operating_mode(); -+} -+ -+static void set_joint_availability_fault(int n, availability_fault_t fault) -+{ -+ availability_release_joint(n, fault); -+ reportError(_("joint %d availability failed (%d)"), n, fault); -+ availability_motion_fault(); -+} -+ -+static void set_spindle_availability_fault(int n, availability_fault_t fault) -+{ -+ availability_release_spindle(n, fault); -+ reportError(_("spindle %d availability failed (%d)"), n, fault); -+ availability_motion_fault(); -+} -+ -+static bool validate_joint_position(int n) -+{ -+ 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 expected = a->held_position + joint->backlash_filt + joint->motor_offset; -+ double tolerance = joint->min_ferror; -+ return isfinite(feedback) && isfinite(expected) && isfinite(tolerance) && -+ tolerance >= 0.0 && fabs(feedback - expected) <= tolerance; -+} -+ -+/* The homing request owns this provisional joint-space synchronization. It -+ * gives the normal homing state machine a stationary start at the acquired -+ * hardware position; only successful homing makes the position valid. */ -+static bool availability_start_homing(int n) -+{ -+ emcmot_joint_t *joint = &joints[n]; -+ double motor = *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); -+ 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 = -+ joint->free_tp.last_pos_cmd = position; -+ joint->free_tp.curr_vel = joint->free_tp.curr_acc = -+ joint->free_tp.curr_jerk = 0.0; -+ joint->free_tp.enable = joint->free_tp.active = 0; -+ joint->vel_cmd = joint->acc_cmd = joint->jerk_cmd = 0.0; -+ joint->ferror = 0.0; -+ SET_JOINT_FERROR_FLAG(joint, 0); -+ SET_JOINT_ACTIVE_FLAG(joint, 1); -+ SET_JOINT_ENABLE_FLAG(joint, GET_MOTION_ENABLE_FLAG()); -+ return true; -+} -+ -+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) -+{ -+ availability_complete_joint(n); -+} -+ -+static void process_availability(void) -+{ -+ int n; -+ double now = etime(); -+ if (!*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; -+ if (!a->controlled) { -+ a->state = EMCMOT_AVAILABILITY_AVAILABLE; -+ } else switch (a->state) { -+ case EMCMOT_AVAILABILITY_DISABLED: -+ if (ack) set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_UNEXPECTED); -+ break; -+ case EMCMOT_AVAILABILITY_ENABLING: -+ if (ack && !*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; -+ a->state = EMCMOT_AVAILABILITY_HOMING; -+ a->phase = AVAIL_PHASE_WAIT_FREE; -+ } else { -+ if (!validate_joint_position(n)) { -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_POSITION_MISMATCH); -+ break; -+ } -+ SET_JOINT_ACTIVE_FLAG(&joints[n], 1); -+ SET_JOINT_ENABLE_FLAG(&joints[n], GET_MOTION_ENABLE_FLAG()); -+ availability_complete_joint(n); -+ } -+ } else if (now - a->transition_started >= a->timeout) -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACQUIRE_TIMEOUT); -+ break; -+ case EMCMOT_AVAILABILITY_HOMING: -+ if (!ack) { -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); -+ } else if (a->phase == AVAIL_PHASE_WAIT_FREE) { -+ 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); -+ } -+ break; -+ case EMCMOT_AVAILABILITY_AVAILABLE: -+ if (!get_homed(n)) -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_FAILED); -+ else if (!ack) -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); -+ break; -+ case EMCMOT_AVAILABILITY_DISABLING: -+ if (a->phase == AVAIL_PHASE_WAIT_SETTLED) { -+ if (!ack) { -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); -+ break; -+ } -+ if (motion_joint_release_state(n) != MOTION_JOINT_RELEASE_READY) { -+ if (now - a->transition_started >= a->timeout) -+ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_TRANSITION_ABORTED); -+ break; -+ } -+ /* Cubic points and commanded derivatives are drained. Finish -+ * the final sampled position at the commanded endpoint. */ -+ a->held_position = joints[n].coarse_pos; -+ joints[n].pos_cmd = a->held_position; -+ availability_release_joint(n, EMCMOT_AVAILABILITY_FAULT_NONE); -+ } -+ /* Leave the joint active until the homing engine consumes abort. */ -+ if (a->phase == AVAIL_PHASE_CANCEL_HOME) { -+ if (!get_home_is_idle(n)) break; -+ /* Cancellation may stop acquisition homing at a new -+ * unreferenced location. Keep that result internal while the -+ * joint remains unavailable. Volatile joints freeze the -+ * final commanded homing location before invalidating it. */ -+ if (a->volatile_home && GET_JOINT_ACTIVE_FLAG(&joints[n])) -+ a->held_position = joints[n].pos_cmd; -+ joints[n].pos_fb = a->held_position; -+ joints[n].motor_pos_fb = a->held_position + -+ joints[n].backlash_filt + joints[n].motor_offset; -+ joints[n].vel_cmd = joints[n].acc_cmd = joints[n].jerk_cmd = 0.0; -+ joints[n].free_tp.curr_vel = joints[n].free_tp.curr_acc = -+ joints[n].free_tp.curr_jerk = 0.0; -+ joints[n].free_tp.enable = joints[n].free_tp.active = 0; -+ SET_JOINT_INPOS_FLAG(&joints[n], 1); -+ if (a->volatile_home && GET_JOINT_ACTIVE_FLAG(&joints[n])) -+ set_unhomed(n, emcmotStatus->motion_state); -+ SET_JOINT_ACTIVE_FLAG(&joints[n], 0); -+ a->phase = AVAIL_PHASE_IDLE; -+ } -+ if (!ack) { -+ if (a->target_available) { -+ a->state = EMCMOT_AVAILABILITY_ENABLING; -+ a->transition_started = now; -+ } else a->state = a->fault ? EMCMOT_AVAILABILITY_FAULT : EMCMOT_AVAILABILITY_DISABLED; -+ } else if (now - a->transition_started >= a->timeout) { -+ availability_clear_pending(a); -+ if (!a->fault) a->fault = EMCMOT_AVAILABILITY_FAULT_RELEASE_TIMEOUT; -+ a->state = EMCMOT_AVAILABILITY_FAULT; -+ reportError(_("joint %d availability release timed out"), n); -+ availability_motion_fault(); -+ } -+ break; -+ case EMCMOT_AVAILABILITY_FAULT: break; -+ } -+ *hal->availability_request = a->controlled && a->target_available && -+ (a->state == EMCMOT_AVAILABILITY_ENABLING || -+ 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; -+ } -+ 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; -+ 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) { -+ set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_STALE_HIGH); -+ break; -+ } -+ if (ack) { a->state = EMCMOT_AVAILABILITY_AVAILABLE; a->phase = AVAIL_PHASE_IDLE; } -+ else if (now - a->transition_started >= a->timeout) -+ set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACQUIRE_TIMEOUT); -+ break; -+ case EMCMOT_AVAILABILITY_AVAILABLE: -+ if (!ack) set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); -+ break; -+ case EMCMOT_AVAILABILITY_DISABLING: -+ if (!ack) { -+ if (a->target_available) { -+ a->state = EMCMOT_AVAILABILITY_ENABLING; -+ a->transition_started = now; -+ } else a->state = a->fault ? EMCMOT_AVAILABILITY_FAULT : EMCMOT_AVAILABILITY_DISABLED; -+ } else if (now - a->transition_started >= a->timeout) { -+ availability_clear_pending(a); -+ if (!a->fault) a->fault = EMCMOT_AVAILABILITY_FAULT_RELEASE_TIMEOUT; -+ a->state = EMCMOT_AVAILABILITY_FAULT; -+ reportError(_("spindle %d availability release timed out"), n); -+ availability_motion_fault(); -+ } -+ break; -+ case EMCMOT_AVAILABILITY_HOMING: -+ set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_TRANSITION_ABORTED); -+ 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; -+ } -+ if (emcmotInternal->availability_machine_on) { -+ for (n = 0; n < ALL_JOINTS; n++) { -+ availability_status_t *a = &emcmotStatus->joint_status[n].availability; -+ if (a->controlled && a->fault) { availability_cancel(1); return; } -+ } -+ for (n = 0; n < emcmotConfig->numSpindles; n++) { -+ availability_status_t *a = &emcmotStatus->spindle_status[n].availability; -+ if (a->controlled && a->fault) { availability_cancel(1); return; } -+ } -+ while (emcmotInternal->availability_resource < emcmotConfig->numSpindles) { -+ n = emcmotInternal->availability_resource; -+ availability_status_t *a = &emcmotStatus->spindle_status[n].availability; -+ if (!a->controlled || !a->initial_available || a->state == EMCMOT_AVAILABILITY_AVAILABLE) { -+ emcmotInternal->availability_resource++; -+ continue; -+ } -+ if (a->state == EMCMOT_AVAILABILITY_DISABLED) availability_begin(a, 0); -+ break; -+ } -+ if (emcmotInternal->availability_resource == emcmotConfig->numSpindles) { -+ if (*emcmot_hal_data->enable) { -+ emcmotInternal->availability_machine_on = 0; -+ emcmotInternal->enabling = 1; -+ } else availability_cancel(1); -+ } -+ } -+} -+ - static void joint_jog_abort_all(bool immediate) - { - int jNum; -@@ -613,7 +1017,7 @@ static void do_forward_kins(void) - at the traj rate */ - - double joint_pos[EMCMOT_MAX_JOINTS] = {0,}; -- int joint_num, result; -+ int joint_num, result = 0; - emcmot_joint_t *joint; - - /* copy joint position feedback to local array */ -@@ -795,7 +1199,9 @@ static void check_for_faults(void) - } - /* check for spindle ampfifier errors */ - for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ -- if(emcmotStatus->spindle_status[spindle_num].fault && GET_MOTION_ENABLE_FLAG()){ -+ availability_status_t *a = &emcmotStatus->spindle_status[spindle_num].availability; -+ if (emcmotStatus->spindle_status[spindle_num].fault && GET_MOTION_ENABLE_FLAG() && -+ (!a->controlled || a->state == EMCMOT_AVAILABILITY_AVAILABLE)) { - reportError(_("spindle %d amplifier fault"), spindle_num); - emcmotInternal->enabling = 0; - } -@@ -867,6 +1273,7 @@ static void set_operating_mode(void) - - /* check for disabling */ - if (!emcmotInternal->enabling && GET_MOTION_ENABLE_FLAG()) { -+ availability_cancel(1); - /* 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) - } - } - SET_MOTION_ENABLE_FLAG(1); -- /* clear any outstanding motion errors when going into enabled state */ -- SET_MOTION_ERROR_FLAG(0); -+ /* Re-enable explicitly acknowledges the previous motion fault. */ -+ emcmotInternal->availability_motion_error = 0; -+ if (!emcmotInternal->availability_motion_error) { SET_MOTION_ERROR_FLAG(0); } - } - - /* check for entering teleop mode */ -@@ -950,7 +1358,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); -- SET_MOTION_ERROR_FLAG(0); -+ if (!emcmotInternal->availability_motion_error) { SET_MOTION_ERROR_FLAG(0); } - - kinematicsForward(positions, &emcmotStatus->carte_pos_cmd, &fflags, &iflags); - // entering teleop (INPOS), remove ext offsets -@@ -994,7 +1402,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) - } - 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) - /* point to joint data */ - joint_data = &(emcmot_hal_data->joint[joint_num]); - joint = &joints[joint_num]; -- if (!GET_JOINT_ACTIVE_FLAG(joint)) { -- /* if joint is not active, skip it */ -- continue; -- } -+ if (emcmotStatus->joint_status[joint_num].availability.controlled && -+ 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); -+ continue; -+ } -+ if (!GET_JOINT_ACTIVE_FLAG(joint)) { -+ /* if joint is not active, skip it */ -+ continue; -+ } - - // disallow accel bogus fractions - if ( (*(joint_data->jjog_accel_fraction) > 1) -@@ -1066,6 +1481,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; -+ if (availability_transition_busy()) continue; - /* initialization complete */ - if ( first_pass ) { - continue; -@@ -1197,6 +1613,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, - reportError(_("kinematicsInverse gave non-finite joint location on joint %d"), n); - return -1; - } -+ availability_status_t *a = &emcmotStatus->joint_status[n].availability; -+ if (a->controlled && a->state != EMCMOT_AVAILABILITY_AVAILABLE) { -+ /* Absolute tolerance in configured joint units (length or degrees). -+ * Never move the reference after accepting roundoff. */ -+ if (fabs(positions[n] - a->held_position) > 1e-9) { -+ reportError(_("motion would command unavailable joint %d"), n); -+ return -1; -+ } -+ positions[n] = a->held_position; -+ } - 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) - for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { - /* point to joint struct */ - joint = &joints[joint_num]; -- if (!GET_JOINT_ACTIVE_FLAG(joint)) { -+ if (!GET_JOINT_ACTIVE_FLAG(joint) || -+ (emcmotStatus->joint_status[joint_num].availability.controlled && -+ emcmotStatus->joint_status[joint_num].availability.state != EMCMOT_AVAILABILITY_AVAILABLE && -+ emcmotStatus->joint_status[joint_num].availability.state != EMCMOT_AVAILABILITY_HOMING)) { - /* if joint is not active, skip it */ - continue; - } -@@ -1430,8 +1859,7 @@ static void get_pos_cmds(long period) - result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, - positions, staged_cubics); - if (result != 0) { -- SET_MOTION_ERROR_FLAG(1); -- emcmotInternal->enabling = 0; -+ availability_motion_fault(); - break; - } - for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1492,8 +1920,7 @@ static void get_pos_cmds(long period) - result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, - positions, staged_cubics); - if (result != 0) { -- SET_MOTION_ERROR_FLAG(1); -- emcmotInternal->enabling = 0; -+ availability_motion_fault(); - break; - } - for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1504,6 +1931,8 @@ static void get_pos_cmds(long period) - &joint->vel_cmd, &joint->acc_cmd, &joint->jerk_cmd); - } - -+ SET_MOTION_INPOS_FLAG(!axis_jog_is_active()); -+ - - /* END OF OUTPUT KINS */ - -@@ -1520,10 +1949,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 */ -- emcmotStatus->carte_pos_cmd = emcmotStatus->carte_pos_fb; -+ emcmotStatus->carte_pos_cmd = emcmotStatus->carte_pos_fb; - for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { - /* point to joint struct */ - joint = &joints[joint_num]; -+ if (emcmotStatus->joint_status[joint_num].availability.controlled && -+ emcmotStatus->joint_status[joint_num].availability.state != EMCMOT_AVAILABILITY_AVAILABLE) -+ continue; - /* 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) - double inch_mult; - emcmot_joint_t *joint; - joint_hal_t *joint_data; -- static int old_motion_index[EMCMOT_MAX_SPINDLES] = {0}; -- 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) - - for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ - double speed; -+ int spindle_available = -+ emcmotStatus->spindle_status[spindle_num].availability.state == -+ EMCMOT_AVAILABILITY_AVAILABLE; - 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) - } - } - -+ 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; -+ } - *(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; -+ spindle_available && -+ 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) - - /* 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; -+ 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); -+ availability_status_t *availability = -+ &emcmotStatus->joint_status[joint_num].availability; -+ *(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; -diff --git a/src/emc/motion/mot_priv.h b/src/emc/motion/mot_priv.h -index 2050ad51a3..631c146ee2 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; -+ - } 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_bit_t *unlock; /* WPI: command that axis should unlock for rotation */ - hal_bit_t *is_unlocked; /* RPI: axis is currently unlocked */ - -@@ -356,4 +370,11 @@ typedef enum { - motion_joint_release_state_t motion_joint_release_state(int joint_num); - void motion_cancel_joint(int joint_num); - -+void availability_begin(availability_status_t *a, int runtime); -+void availability_begin_joint_release(int n); -+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); -+ - #endif /* MOT_PRIV_H */ -diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c -index 7f81108901..87f1a06205 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; - /* 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) - 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; -+ emcmotStatus->spindle_status[spindle_num].availability.state = EMCMOT_AVAILABILITY_AVAILABLE; -+ emcmotStatus->spindle_status[spindle_num].availability.timeout = 5.0; - } - - axis_init_all(); -@@ -936,6 +950,8 @@ static int init_comm_buffers(void) - joint->min_ferror = 0.01; - joint->max_ferror = 1.0; - joint->backlash = 0.0; -+ emcmotStatus->joint_status[joint_num].availability.state = EMCMOT_AVAILABILITY_AVAILABLE; -+ emcmotStatus->joint_status[joint_num].availability.timeout = 5.0; - - 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 ---- 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 */ - - EMCMOT_SET_SPINDLE_PARAMS, /* One command to set all spindle params */ -+ EMCMOT_SET_JOINT_AVAILABILITY_CONFIG, -+ EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG, -+ EMCMOT_SET_JOINT_AVAILABILITY, -+ EMCMOT_SET_SPINDLE_AVAILABILITY, - - } cmd_code_t; - -@@ -277,6 +281,10 @@ extern "C" { - struct state_tag_t tag; - int g76_pass_id; /* internal G76 pass ownership, zero otherwise */ - int g76_pass_clearance;/* 1: clearance retract, 2: approach endpoint */ -+ int availability_control; -+ int initial_availability; -+ int available; -+ double availability_timeout; - } 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.. - #define EMCMOT_JOINT_MIN_HARD_LIMIT_BIT 0x0020 - #define EMCMOT_JOINT_FERROR_BIT 0x0040 - #define EMCMOT_JOINT_FAULT_BIT 0x0080 -- - /*! \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.. - EMCMOT_ORIENT_FAULTED, - } orient_state_t; - -+ typedef enum { -+ EMCMOT_AVAILABILITY_DISABLED = 0, -+ EMCMOT_AVAILABILITY_ENABLING = 1, -+ EMCMOT_AVAILABILITY_HOMING = 2, -+ EMCMOT_AVAILABILITY_AVAILABLE = 3, -+ EMCMOT_AVAILABILITY_DISABLING = 4, -+ EMCMOT_AVAILABILITY_FAULT = 5, -+ } availability_state_t; -+ -+ typedef enum { -+ EMCMOT_AVAILABILITY_FAULT_NONE = 0, -+ EMCMOT_AVAILABILITY_FAULT_ACK_STALE_HIGH = 1, -+ EMCMOT_AVAILABILITY_FAULT_ACQUIRE_TIMEOUT = 2, -+ EMCMOT_AVAILABILITY_FAULT_RELEASE_TIMEOUT = 3, -+ EMCMOT_AVAILABILITY_FAULT_ACK_LOST = 4, -+ EMCMOT_AVAILABILITY_FAULT_ACK_UNEXPECTED = 5, -+ EMCMOT_AVAILABILITY_FAULT_HOME_FAILED = 6, -+ EMCMOT_AVAILABILITY_FAULT_HOME_ABORTED = 7, -+ EMCMOT_AVAILABILITY_FAULT_POSITION_MISMATCH = 8, -+ EMCMOT_AVAILABILITY_FAULT_TRANSITION_ABORTED = 9, -+ } availability_fault_t; -+ -+ typedef enum { -+ AVAIL_PHASE_IDLE, -+ AVAIL_PHASE_INITIAL_ACK, -+ AVAIL_PHASE_RUNTIME_ACK, -+ AVAIL_PHASE_WAIT_FREE, -+ AVAIL_PHASE_WAIT_HOME_START, -+ AVAIL_PHASE_WAIT_HOME_FINISH, -+ AVAIL_PHASE_WAIT_SETTLED, -+ AVAIL_PHASE_CANCEL_HOME, -+ } availability_phase_t; -+ -+ typedef struct { -+ int controlled; -+ int initial_available; -+ int volatile_home; -+ 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; -+ double transition_started; -+ } availability_status_t; -+ - /* 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.. - EMCMOT_JOINT_FLAG flag; /* see above for bit details */ - bool homed; - bool homing; -+ availability_status_t availability; - - 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.. - double home_search_vel; - int home_sequence; - double increment; -+ availability_status_t availability; - } spindle_status_t; - - typedef struct { -@@ -763,6 +819,9 @@ 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 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 ---- 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) - case EMC_JOINT_UNHOME_TYPE: - ((EMC_JOINT_UNHOME *) buffer)->update(cms); - break; -+ case EMC_JOINT_SET_AVAILABILITY_TYPE: -+ ((EMC_JOINT_SET_AVAILABILITY *) buffer)->update(cms); -+ break; - case EMC_JOG_CONT_TYPE: - ((EMC_JOG_CONT *) buffer)->update(cms); - break; -@@ -160,6 +163,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) - case EMC_SPINDLE_OFF_TYPE: - ((EMC_SPINDLE_OFF *) buffer)->update(cms); - break; -+ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: -+ ((EMC_SPINDLE_SET_AVAILABILITY *) buffer)->update(cms); -+ break; - case EMC_SPINDLE_ON_TYPE: - ((EMC_SPINDLE_ON *) buffer)->update(cms); - break; -@@ -375,6 +381,8 @@ const char *emc_symbol_lookup(uint32_t type) - return "EMC_JOINT_HOME"; - case EMC_JOINT_UNHOME_TYPE: - return "EMC_JOINT_UNHOME"; -+ case EMC_JOINT_SET_AVAILABILITY_TYPE: -+ return "EMC_JOINT_SET_AVAILABILITY"; - 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) - return "EMC_SPINDLE_INCREASE"; - case EMC_SPINDLE_OFF_TYPE: - return "EMC_SPINDLE_OFF"; -+ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: -+ return "EMC_SPINDLE_SET_AVAILABILITY"; - 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) - cms->update(_spindle); - } - -+void EMC_SPINDLE_SET_AVAILABILITY::update(CMS * cms) -+{ -+ EMC_SPINDLE_CMD_MSG::update(cms); -+ cms->update(spindle); -+ cms->update(available); -+} -+ - /* - * 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) - cms->update(spindle_override_enabled); - cms->update(at_speed); - cms->update(homed); -+ cms->update(available); -+ cms->update(availability_state); -+ cms->update(availability_fault); - } - - /* -@@ -1337,6 +1357,15 @@ void EMC_JOINT_STAT::update(CMS * cms) - cms->update(minHardLimit); - cms->update(maxHardLimit); - cms->update(overrideLimits); -+ cms->update(available); -+ cms->update(availability_state); -+ cms->update(availability_fault); -+} -+ -+void EMC_JOINT_SET_AVAILABILITY::update(CMS * cms) -+{ -+ EMC_JOINT_CMD_MSG::update(cms); -+ cms->update(available); - } - - /* -diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index 0dca92c7e0..32ca6fbaa0 100644 ---- a/src/emc/nml_intf/emc.hh -+++ b/src/emc/nml_intf/emc.hh -@@ -74,6 +74,7 @@ struct PM_CARTESIAN; - #define EMC_JOINT_SET_BACKLASH_TYPE ((NMLTYPE) 134) - #define EMC_JOINT_UNHOME_TYPE ((NMLTYPE) 135) - #define EMC_JOG_STOP_TYPE ((NMLTYPE) 136) -+#define EMC_JOINT_SET_AVAILABILITY_TYPE ((NMLTYPE) 137) - - #define EMC_JOINT_STAT_TYPE ((NMLTYPE) 198) - #define EMC_AXIS_STAT_TYPE ((NMLTYPE) 199) -@@ -180,6 +181,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) -+#define EMC_SPINDLE_SET_AVAILABILITY_TYPE ((NMLTYPE) 1319) - - #define EMC_SPINDLE_STAT_TYPE ((NMLTYPE) 1399) - -@@ -340,6 +342,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); - - - extern int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints); -+extern bool emcJointAvailabilityControlled(int index); -+extern int emcJointSetAvailabilityConfig(int joint, int controlled, -+ double timeout, int volatile_home); -+extern int emcJointSetAvailability(int joint, int available); - - extern int emcJointSetMaxJerk(int joint, double jerk); - -@@ -451,6 +457,11 @@ extern int emcSpindleBrakeRelease(int spindle); - extern int emcSpindleBrakeEngage(int spindle); - - extern int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles); -+extern bool emcSpindleAvailabilityControlled(int index); -+extern int emcSpindleSetAvailabilityConfig(int spindle, int controlled, -+ int initial_available, -+ double timeout); -+extern int emcSpindleSetAvailability(int spindle, int available); - - // 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 ---- 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 { - void update(CMS * cms); - }; - -+class EMC_JOINT_SET_AVAILABILITY:public EMC_JOINT_CMD_MSG { -+ public: -+ EMC_JOINT_SET_AVAILABILITY() -+ : EMC_JOINT_CMD_MSG(EMC_JOINT_SET_AVAILABILITY_TYPE, -+ sizeof(EMC_JOINT_SET_AVAILABILITY)), -+ available(0) -+ {}; -+ void update(CMS * cms); -+ int available; -+}; -+ - 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 { - 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 -+ int available; -+ int availability_state; -+ int availability_fault; - }; - - // declarations for EMC_TRAJ classes -@@ -1148,6 +1162,9 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { - bool spindle_override_enabled; - bool at_speed; - bool homed; -+ int available; -+ int availability_state; -+ int availability_fault; - }; - - 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 - }; - -+class EMC_SPINDLE_SET_AVAILABILITY:public EMC_SPINDLE_CMD_MSG { -+ public: -+ EMC_SPINDLE_SET_AVAILABILITY() -+ : EMC_SPINDLE_CMD_MSG(EMC_SPINDLE_SET_AVAILABILITY_TYPE, -+ sizeof(EMC_SPINDLE_SET_AVAILABILITY)), -+ spindle(0), available(0) -+ {}; -+ void update(CMS * cms); -+ int spindle; -+ int available; -+}; -+ - class EMC_SPINDLE_INCREASE:public EMC_SPINDLE_CMD_MSG { - public: - EMC_SPINDLE_INCREASE() -diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc -index 6d91ef1bd0..6215d7d68c 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() - maxSoftLimit(0), - minHardLimit(0), - maxHardLimit(0), -- overrideLimits(0) -+ overrideLimits(0), -+ available(1), -+ availability_state(3), -+ availability_fault(0) - { - } - -@@ -198,7 +201,10 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() - orient_fault(0), - spindle_override_enabled(OFF), - at_speed(OFF), -- homed(OFF) -+ homed(OFF), -+ available(1), -+ availability_state(3), -+ availability_fault(0) - { - } - -diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index e0fe4e3616..ac4a55781b 100644 ---- a/src/emc/task/emctask.cc -+++ b/src/emc/task/emctask.cc -@@ -234,6 +234,7 @@ void emcTaskQueueTaskPlanSynchCmd() - - int emcTaskAbort() - { -+ emcTaskCancelAvailability(); - emcMotionAbort(); - - // clear out the pending command -diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 59021c7dcb..1314163557 100644 ---- a/src/emc/task/emctaskmain.cc -+++ b/src/emc/task/emctaskmain.cc -@@ -169,6 +169,60 @@ volatile int done; - static int emctask_shutdown(void); - extern void backtrace(int signo); - int _task = 1; // control preview behaviour when remapping -+// Populated only after usrmotWriteEmcmotCommand confirms motion acceptance. -+// The ordinary executor wait and queued PLAN_SYNCH own completion. -+static struct { -+ bool active = false; -+ bool spindle = false; -+ int index = 0; -+ bool available = false; -+ bool cancelled = false; -+ bool failed = false; -+} availability_pending; -+ -+void emcTaskCancelAvailability() -+{ -+ auto &op = availability_pending; -+ if (!op.active) return; -+ op.cancelled = true; -+ op.failed |= emcStatus->motion.status == RCS_STATUS::ERROR || -+ emcStatus->io.status == RCS_STATUS::ERROR || -+ (op.spindle ? emcStatus->motion.spindle[op.index].availability_fault -+ : emcStatus->motion.joint[op.index].availability_fault); -+} -+ -+static bool availability_transition(int state) -+{ -+ return state == EMCMOT_AVAILABILITY_ENABLING || -+ state == EMCMOT_AVAILABILITY_HOMING || -+ state == EMCMOT_AVAILABILITY_DISABLING; -+} -+ -+// Check the particular accepted operation, never infer success from motion DONE. -+static EMC_TASK_EXEC availability_completion() -+{ -+ // Dispatch can run before this cycle's normal status update. A failed or -+ // stale read must not turn command acceptance into completion. -+ if (emcMotionUpdate(&emcStatus->motion) != 0) -+ return EMC_TASK_EXEC::WAITING_FOR_MOTION; -+ const auto &op = availability_pending; -+ int state = op.spindle ? emcStatus->motion.spindle[op.index].availability_state -+ : emcStatus->motion.joint[op.index].availability_state; -+ int fault = op.spindle ? emcStatus->motion.spindle[op.index].availability_fault -+ : emcStatus->motion.joint[op.index].availability_fault; -+ if (availability_transition(state)) return EMC_TASK_EXEC::WAITING_FOR_MOTION; -+ if (op.cancelled) { -+ availability_pending.failed |= fault != 0; -+ return EMC_TASK_EXEC::DONE; -+ } -+ if (fault || state != (op.available ? EMCMOT_AVAILABILITY_AVAILABLE -+ : EMCMOT_AVAILABILITY_DISABLED)) { -+ emcOperatorError(_("availability operation failed for %s %d"), -+ op.spindle ? "spindle" : "joint", op.index); -+ return EMC_TASK_EXEC::ERROR; -+ } -+ return EMC_TASK_EXEC::DONE; -+} - 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 - - int all_homed(void) { - for (int i = 0; i < emcStatus->motion.traj.joints; i++) { -- if(!emcStatus->motion.joint[i].homed) // XXX -- return 0; -+ const auto &joint = emcStatus->motion.joint[i]; -+ if (emcJointAvailabilityControlled(i)) { -+ if (joint.availability_fault) return 0; -+ if (joint.availability_state == EMCMOT_AVAILABILITY_DISABLED) continue; -+ if (joint.availability_state != EMCMOT_AVAILABILITY_AVAILABLE) return 0; -+ } -+ if (!joint.homed) return 0; - } - return 1; - } -@@ -836,6 +895,13 @@ static bool emcTaskArmSingleStep() - return true; - } - -+static void emcTaskPausedSingleStep() -+{ -+ if (!emcTaskArmSingleStep()) { -+ emcStatus->task.interpState = interpResumeState; -+ } -+} -+ - static void emcTaskStopClear() - { - bool was_active = emcStatus && -@@ -1029,6 +1095,31 @@ static int emcTaskPlan(void) - return emcTaskIssueCommand(emcCommand); - } - -+ if (type == EMC_JOINT_SET_AVAILABILITY_TYPE || -+ type == EMC_SPINDLE_SET_AVAILABILITY_TYPE) { -+ // External admission only: canonical commands use the ordered executor. -+ if (availability_pending.active || -+ emcStatus->task.interpState != EMC_TASK_INTERP::IDLE || -+ emcStatus->task.execState != EMC_TASK_EXEC::DONE || -+ emcStatus->task.task_paused || -+ emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE || -+ emcTaskCommand || interp_list.len() || mdi_execute_queue.len() || -+ mdi_execute_wait || mdi_execute_next || mdi_execute_level >= 0 || -+ emcTaskPlanIsWait() || -+ emcStatus->motion.status != RCS_STATUS::DONE || -+ emcStatus->io.status != RCS_STATUS::DONE) { -+ emcOperatorError(_("direct availability request requires idle task")); -+ return -1; -+ } -+ retval = emcTaskIssueCommand(emcCommand); -+ if (!retval) { -+ emcTaskPlanSetWait(); -+ emcTaskQueueTaskPlanSynchCmd(); -+ emcStatus->task.execState = EMC_TASK_EXEC::WAITING_FOR_MOTION; -+ } -+ return retval; -+ } -+ - 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) - return 0; - } - -+ if (availability_pending.active) { -+ // Do not interpret or admit motion across an availability transaction. -+ // Cleanup and resumable program controls retain their normal semantics. -+ switch (type) { -+ case EMC_TASK_ABORT_TYPE: -+ case EMC_TASK_PLAN_PAUSE_TYPE: -+ case EMC_TASK_PLAN_RESUME_TYPE: -+ case EMC_JOG_STOP_TYPE: -+ case EMC_SPINDLE_OFF_TYPE: -+ return emcTaskIssueCommand(emcCommand); -+ case EMC_TASK_SET_STATE_TYPE: -+ if (static_cast(emcCommand)->state == EMC_TASK_STATE::ON) -+ return -1; -+ return emcTaskIssueCommand(emcCommand); -+ case EMC_TASK_PLAN_STEP_TYPE: -+ if (emcStatus->task.mode != EMC_TASK_MODE::AUTO) return -1; -+ if (emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED) -+ emcTaskPausedSingleStep(); -+ else -+ emcTaskArmSingleStep(); -+ return 0; -+ case 0: -+ case EMC_NULL_TYPE: -+ return 0; -+ default: -+ emcOperatorError(_("command rejected during availability operation")); -+ return -1; -+ } -+ } -+ - // handle any new command - switch (emcStatus->task.state) { - case EMC_TASK_STATE::OFF: -@@ -1559,9 +1680,7 @@ static int emcTaskPlan(void) - break; - - case EMC_TASK_PLAN_STEP_TYPE: -- if (!emcTaskArmSingleStep()) { -- emcStatus->task.interpState = interpResumeState; -- } -+ emcTaskPausedSingleStep(); - break; - - // otherwise we can't handle it -@@ -1824,6 +1943,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: -+ case EMC_JOINT_SET_AVAILABILITY_TYPE: -+ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: - return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; - break; - -@@ -1993,6 +2114,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) - retval = emcJointUnhome(unhome_msg->joint); - break; - -+ case EMC_JOINT_SET_AVAILABILITY_TYPE: { -+ if (availability_pending.active) return -1; -+ auto *message = reinterpret_cast(cmd); -+ if (message->joint < 0 || message->joint >= emcStatus->motion.traj.joints || -+ !emcJointAvailabilityControlled(message->joint)) { -+ emcOperatorError(_("invalid or uncontrolled joint availability resource %d"), -+ message->joint); -+ retval = -1; -+ } else { -+ retval = emcJointSetAvailability(message->joint, message->available); -+ if (retval == 0) { -+ availability_pending = {true, false, message->joint, -+ !!message->available, false}; -+ } -+ } -+ break; -+ } -+ - 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); - break; - -+ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: { -+ if (availability_pending.active) return -1; -+ auto *message = reinterpret_cast(cmd); -+ if (message->spindle < 0 || -+ message->spindle >= emcStatus->motion.traj.spindles || -+ !emcSpindleAvailabilityControlled(message->spindle)) { -+ emcOperatorError(_("invalid or uncontrolled spindle availability resource %d"), -+ message->spindle); -+ retval = -1; -+ } else { -+ retval = emcSpindleSetAvailability(message->spindle, -+ message->available); -+ if (retval == 0) { -+ availability_pending = {true, true, message->spindle, -+ !!message->available, false}; -+ } -+ } -+ break; -+ } -+ - 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) - break; - - case EMC_TASK_PLAN_SYNCH_TYPE: -+ if (availability_pending.active && -+ availability_completion() != EMC_TASK_EXEC::DONE) return -1; - retval = emcTaskPlanSynch(); -+ availability_pending.active = false; -+ if (emcStatus->task.interpState == EMC_TASK_INTERP::IDLE) -+ emcTaskPlanClearWait(); - if (retval > INTERP_MIN_ERROR) { - retval = -1; - } -@@ -2887,6 +3051,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) - return EMC_TASK_EXEC::DONE; - break; - -+ case EMC_JOINT_SET_AVAILABILITY_TYPE: -+ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: -+ return EMC_TASK_EXEC::WAITING_FOR_MOTION; -+ break; -+ - 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) - int status; // status of child from EMC_SYSTEM_CMD - pid_t pid; // pid returned from waitpid() - -+ // Abort flushes the program and queues its normal synchronization command. -+ // Keep admission closed until the cancelled resource finishes RT cleanup. -+ if (availability_pending.active && availability_pending.cancelled && -+ emcStatus->task.execState == EMC_TASK_EXEC::DONE) -+ emcStatus->task.execState = EMC_TASK_EXEC::WAITING_FOR_MOTION; -+ - // first check for an abandoned system command and abort it - if (emcSystemCmdPid != 0 && - emcStatus->task.execState != -@@ -3067,11 +3242,32 @@ static int emcTaskExecute(void) - break; - - case EMC_TASK_EXEC::WAITING_FOR_MOTION: -+ if (availability_pending.active) { -+ auto completion = availability_completion(); -+ if (completion == EMC_TASK_EXEC::WAITING_FOR_MOTION) break; -+ if (availability_pending.cancelled) { -+ availability_pending.active = false; -+ emcStatus->task.execState = EMC_TASK_EXEC::DONE; -+ retval = availability_pending.failed ? -1 : 0; -+ break; -+ } -+ if (completion == EMC_TASK_EXEC::ERROR) { -+ emcStatus->task.execState = completion; -+ break; -+ } -+ } - STEPPING_CHECK(); - if (emcStatus->motion.status == RCS_STATUS::ERROR) { - // emcOperatorError(0, "error in motion controller"); - emcStatus->task.execState = EMC_TASK_EXEC::ERROR; - } else if (emcStatus->motion.status == RCS_STATUS::DONE) { -+ if (emcStatus->task.mode == EMC_TASK_MODE::AUTO && -+ emcStatus->task.interpState != EMC_TASK_INTERP::IDLE && -+ !no_force_homing && !all_homed()) { -+ emcOperatorError(_("Cannot continue AUTO with unhomed joints")); -+ emcStatus->task.execState = EMC_TASK_EXEC::ERROR; -+ break; -+ } - emcStatus->task.execState = EMC_TASK_EXEC::DONE; - emcTaskEager = 1; - } -diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh -index 79dbeb68bc..223886ebb2 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 emcTaskCancelAvailability(); - int emcTaskSetMode(EMC_TASK_MODE mode); - 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 ---- a/src/emc/task/taskintf.cc -+++ b/src/emc/task/taskintf.cc -@@ -990,6 +990,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 -+ stat[joint_num].availability_state = joint->availability.state; -+ stat[joint_num].availability_fault = joint->availability.fault; -+ stat[joint_num].available = -+ joint->availability.state == EMCMOT_AVAILABILITY_AVAILABLE; - // for - // all - -@@ -1015,6 +1019,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) - return 0; - } - -+bool emcJointAvailabilityControlled(int index) -+{ -+ return index >= 0 && index < EMCMOT_MAX_JOINTS && -+ emcmotStatus.joint_status[index].availability.controlled; -+} -+ -+int emcJointSetAvailabilityConfig(int joint, int controlled, double timeout, -+ int volatile_home) -+{ -+ if (joint < 0 || joint >= EMCMOT_MAX_JOINTS || timeout <= 0.0) return -1; -+ emcmotCommand.command = EMCMOT_SET_JOINT_AVAILABILITY_CONFIG; -+ emcmotCommand.joint = joint; -+ emcmotCommand.availability_control = controlled; -+ emcmotCommand.availability_timeout = timeout; -+ emcmotCommand.volatile_home = volatile_home; -+ return usrmotWriteEmcmotCommand(&emcmotCommand); -+} -+ -+int emcJointSetAvailability(int joint, int available) -+{ -+ if (joint < 0 || joint >= EMCMOT_MAX_JOINTS) return -1; -+ emcmotCommand.command = EMCMOT_SET_JOINT_AVAILABILITY; -+ emcmotCommand.joint = joint; -+ emcmotCommand.available = !!available; -+ return usrmotWriteEmcmotCommand(&emcmotCommand); -+} -+ - // EMC_TRAJ functions - - int emcTrajSetJoints(int joints) -@@ -1839,9 +1870,11 @@ int emcMotionInit() - - int emcMotionHalt() - { -- int r1, r2, r3, r4, r5; -+ int r1, r2, r3, r4, r5, r6; - int t; - -+ // Revoke acquisition and deferred homing before individual jog aborts. -+ r6 = emcTrajAbort(); - r1 = -1; - for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { - if (0 == emcJointHalt(t)) { -@@ -1854,7 +1887,7 @@ int emcMotionHalt() - r4 = emcPositionSave(); - r5 = ini_hal_exit(); - -- return (r1 == 0 && r2 == 0 && r3 == 0 && r4 == 0 && r5 == 0) ? 0 : -1; -+ return (r1 == 0 && r2 == 0 && r3 == 0 && r4 == 0 && r5 == 0 && r6 == 0) ? 0 : -1; - } - - int emcMotionAbort() -@@ -1864,6 +1897,8 @@ int emcMotionAbort() - int r3 = 0; - int t; - -+ // Revoke acquisition and deferred homing before individual jog aborts. -+ r2 = emcTrajAbort(); - r1 = -1; - for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { - if (0 == emcJogAbort(t)) { -@@ -1871,8 +1906,6 @@ int emcMotionAbort() - } - } - -- r2 = emcTrajAbort(); -- - return (r1 == 0 && r2 == 0 && r3 == 0) ? 0 : -1; - } - -@@ -2057,10 +2090,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; -+ stat[s].availability_state = emcmotStatus.spindle_status[s].availability.state; -+ stat[s].availability_fault = emcmotStatus.spindle_status[s].availability.fault; -+ stat[s].available = emcmotStatus.spindle_status[s].availability.state == -+ EMCMOT_AVAILABILITY_AVAILABLE; - } - return 0; - } - -+bool emcSpindleAvailabilityControlled(int index) -+{ -+ return index >= 0 && index < EMCMOT_MAX_SPINDLES && -+ emcmotStatus.spindle_status[index].availability.controlled; -+} -+ -+int emcSpindleSetAvailabilityConfig(int spindle, int controlled, -+ int initial_available, double timeout) -+{ -+ if (spindle < 0 || spindle >= EMCMOT_MAX_SPINDLES || timeout <= 0.0) -+ return -1; -+ emcmotCommand.command = EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG; -+ emcmotCommand.spindle = spindle; -+ emcmotCommand.availability_control = controlled; -+ emcmotCommand.initial_availability = initial_available; -+ emcmotCommand.availability_timeout = timeout; -+ return usrmotWriteEmcmotCommand(&emcmotCommand); -+} -+ -+int emcSpindleSetAvailability(int spindle, int available) -+{ -+ if (spindle < 0 || spindle >= EMCMOT_MAX_SPINDLES) return -1; -+ emcmotCommand.command = EMCMOT_SET_SPINDLE_AVAILABILITY; -+ emcmotCommand.spindle = spindle; -+ emcmotCommand.available = !!available; -+ return usrmotWriteEmcmotCommand(&emcmotCommand); -+} -+ - int emcMotionUpdate(EMC_MOTION_STAT * stat) - { - int r1, r2, r3, r4; -@@ -2133,6 +2198,18 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) - - // FIXME-AJ: joints not axes - for (joint = 0; joint < stat->traj.joints; joint++) { -+ availability_status_t *availability = -+ &emcmotStatus.joint_status[joint].availability; -+ // The realtime fault path raises MOTION_ERROR and inhibits outputs. -+ // Keep the resource fault latched in status, but do not re-abort task -+ // forever after Abort has acknowledged that motion error: idle recovery -+ // must be able to execute its ordered release/synchronization command. -+ if (availability->controlled && -+ (availability->state == EMCMOT_AVAILABILITY_ENABLING || -+ availability->state == EMCMOT_AVAILABILITY_HOMING || -+ availability->state == EMCMOT_AVAILABILITY_DISABLING)) { -+ exec = 1; -+ } - if (stat->joint[joint].status == RCS_STATUS::ERROR) { - error = 1; - break; -@@ -2142,6 +2219,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) - break; - } - } -+ for (int spindle = 0; spindle < stat->traj.spindles; spindle++) { -+ availability_status_t *availability = -+ &emcmotStatus.spindle_status[spindle].availability; -+ if (availability->controlled && -+ (availability->state == EMCMOT_AVAILABILITY_ENABLING || -+ availability->state == EMCMOT_AVAILABILITY_HOMING || -+ availability->state == EMCMOT_AVAILABILITY_DISABLING)) -+ exec = 1; -+ } - if (stat->traj.status == RCS_STATUS::ERROR) { - 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 ---- 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) { - F2("min_hard_limit", minHardLimit); - F2("max_hard_limit", maxHardLimit); - F2("override_limits", overrideLimits); -+ F(available); -+ F(availability_state); -+ F(availability_fault); - return res; - } - #undef F -@@ -1463,6 +1466,9 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { - F(homed); - F(orient_state); - F(orient_fault); -+ F(available); -+ F(availability_state); -+ F(availability_fault); - return res; - } - #undef F -@@ -2021,6 +2027,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { - return Py_None; - } - -+static PyObject *set_joint_availability(pyCommandChannel *s, PyObject *o) { -+ EMC_JOINT_SET_AVAILABILITY m; -+ if(!PyArg_ParseTuple(o, "ip", &m.joint, &m.available)) return NULL; -+ emcSendCommand(s, m); -+ Py_RETURN_NONE; -+} -+ -+static PyObject *set_spindle_availability(pyCommandChannel *s, PyObject *o) { -+ EMC_SPINDLE_SET_AVAILABILITY m; -+ if(!PyArg_ParseTuple(o, "ip", &m.spindle, &m.available)) return NULL; -+ emcSendCommand(s, m); -+ Py_RETURN_NONE; -+} -+ - // 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[] = { - "JOINT can be a valid joint number (0-9), or -1 to home all joints.\n" - }, - {"unhome", (PyCFunction)unhome, METH_VARARGS, NULL}, -+ {"set_joint_availability", (PyCFunction)set_joint_availability, -+ METH_VARARGS, "set_joint_availability(JOINT, AVAILABLE)"}, -+ {"set_spindle_availability", (PyCFunction)set_spindle_availability, -+ METH_VARARGS, "set_spindle_availability(SPINDLE, AVAILABLE)"}, - {"jog", (PyCFunction)jog, METH_VARARGS, - "jog(JOG_CONTINUOUS, joint_flag, index, speed)\n" - "jog(JOG_INCREMENT, joint_flag, index, speed, increment)\n" -diff --git a/tests/motion-logger/basic/expected.builtin-startup.in b/tests/motion-logger/basic/expected.builtin-startup.in -index d8bd807543..8ed60094c8 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 - 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 -@@ -28,6 +29,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 -@@ -38,6 +40,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 -@@ -48,6 +51,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 -@@ -58,6 +62,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 -@@ -68,6 +73,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 -@@ -78,6 +84,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 -@@ -88,6 +95,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 -@@ -98,6 +106,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 -@@ -154,6 +163,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 -@@ -170,11 +181,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 -@@ -191,7 +202,6 @@ JOG_ABORT joint=12 - JOG_ABORT joint=13 - JOG_ABORT joint=14 - JOG_ABORT joint=15 --ABORT - SPINDLE_OFF - - # -@@ -207,6 +217,7 @@ ENABLE - # - - COORD -+ABORT - JOG_ABORT joint=0 - JOG_ABORT joint=1 - JOG_ABORT joint=2 -@@ -223,4 +234,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 ---- 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 - SET_JOINT_VEL_LIMIT joint=0, vel=400 - 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 -@@ -28,6 +29,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 -+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=-40, max=0 -@@ -38,6 +40,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 -+SET_JOINT_AVAILABILITY_CONFIG joint=2, controlled=0, timeout=5, volatile_home=0 - 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 - 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 -+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 -@@ -74,11 +79,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 -@@ -95,10 +100,10 @@ JOG_ABORT joint=12 - JOG_ABORT joint=13 - JOG_ABORT joint=14 - JOG_ABORT joint=15 --ABORT - SPINDLE_OFF - ENABLE - COORD -+ABORT - JOG_ABORT joint=0 - JOG_ABORT joint=1 - JOG_ABORT joint=2 -@@ -115,7 +120,6 @@ JOG_ABORT joint=12 - JOG_ABORT joint=13 - JOG_ABORT joint=14 - JOG_ABORT joint=15 --ABORT - 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 - 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 ---- 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 - 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 -@@ -33,6 +34,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 -@@ -43,6 +45,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_AXIS_POSITION_LIMITS axis=0, min=-40, max=0 - -@@ -84,6 +87,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 -+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 -@@ -100,7 +105,6 @@ JOG_ABORT joint=12 - JOG_ABORT joint=13 - JOG_ABORT joint=14 - JOG_ABORT joint=15 --ABORT - SPINDLE_OFF - DISABLE - JOINT_UNHOME joint=-2 -@@ -121,6 +125,7 @@ FREE - # The test UI immediately sent an Abort. - # - -+ABORT - JOG_ABORT joint=0 - JOG_ABORT joint=1 - JOG_ABORT joint=2 -@@ -154,6 +159,6 @@ JOG_ABORT joint=12 - JOG_ABORT joint=13 - JOG_ABORT joint=14 - JOG_ABORT joint=15 --ABORT - SPINDLE_OFF -+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 deleted file mode 100644 index 7e8da6e..0000000 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ /dev/null @@ -1,1296 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Dariusz Majnert -Date: Thu, 17 Sep 2026 18:00:42 +0200 -Subject: [PATCH] availability-mcodes - ---- - 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 - -diff --git a/docs/src/gcode/m-code.adoc b/docs/src/gcode/m-code.adoc -index 1cb15521ad..0f3b65c8e4 100644 ---- a/docs/src/gcode/m-code.adoc -+++ b/docs/src/gcode/m-code.adoc -@@ -22,6 +22,7 @@ - |<> | Spindle Override Control - |<> | Adaptive Feed Control - |<> | Feed Stop Control -+|<> | Acquire or Release a Joint or Spindle Resource - |<> | 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. - * 'M53 P0' - disable the feed stop switch. The state of 'motion.feed-hold' - will have no effect on feed when M53 is not active. - -+[[mcode:m54-m55]] -+== M54, M55 Resource Availability -+ -+(((M54 Resource Acquire)))(((M55 Resource Release))) -+ -+`M54` acquires one availability-controlled physical resource and -+`M55` releases it. A `P` word selects a joint number and the -+standard `$` word selects a spindle number: -+ -+---- -+M54 P2 (acquire joint 2) -+M55 P2 (release joint 2) -+M54 $0 (acquire spindle 0) -+M55 $0 (release spindle 0) -+---- -+ -+Exactly one selector is required. Joint numbers must be nonnegative integers; -+spindle group selectors such as `$-1` are not supported. These commands are -+ordered barriers: subsequent G-code is not executed until the transition has -+completed or failed. LinuxCNC does not pair resources or roll back a preceding -+transition automatically. M54 and M55 must be the only command in their block; -+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. -+ -+The execution boundary is: finish preceding motion and IO, dispatch the runtime -+API request, wait for its shared completion boundary or failure, then continue. -+Held-position validation, homing whenever an acquired joint is unhomed, and normal -+task/interpreter synchronization are part of that runtime API completion for -+both NML/Python callers and M54. ACK alone does not permit continuation. -+Sequential M54/M55 blocks work in AUTO and MDI because each finishes before the -+next is interpreted. External direct requests require an idle task and cannot -+interrupt an in-program operation. Use Abort to cancel ACK wait or acquisition -+homing: it terminates the program and prevents subsequent blocks from executing, -+even if ACK arrives late. Ordinary M55/release does not cancel acquisition. -+Failure stops execution; subsequent blocks are not run. These M-codes use the same -+lifecycle as the NML/Python command API and provide no resource pairing or -+machine-specific switching sequence. -+ - [[mcode:m61]] - == M61 Set Current Tool - -diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index 5bb208e611..b2fd837823 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: - - M7 (activate coolant mist) - - M8 (activate coolant flood) - - M9 (deactivate coolant mist and flood) -+- M54, M55 (acquire and release joints or spindles) - - 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 - |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 | | --|50-59 | | | | |M54 |M55 |M56 |M57 |M58 |M59 -+|50-59 | | | | | | |M56 |M57 |M58 |M59 - |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 - - All M-codes from `M100` to `M199` are user-defined M-codes already, and should not be remapped. - -+M54 and M55 are built-in resource acquisition and release commands. They may -+still be overridden with REMAP for compatibility with existing configurations; -+a configured remap supplies its own argument and execution behavior. -+ - All M-codes from `M200` to `M999` are available for remapping. - - == 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 ---- 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 - speed, change to the speed given with this command. */ - - extern void STOP_SPINDLE_TURNING(int spindle); -+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 ---- 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*/) {} -+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*/) {} -diff --git a/src/emc/rs274ngc/interp_array.cc b/src/emc/rs274ngc/interp_array.cc -index ba393b5b9f..606365a3bd 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 - 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 -+ 9, 9, 9, 9, 9, 9, -1, -1, -1, -1, // 59 - 4, 6, 5, 5, 5, 5, 5, 5, 5, -1, // 69 - 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 ---- a/src/emc/rs274ngc/interp_check.cc -+++ b/src/emc/rs274ngc/interp_check.cc -@@ -17,6 +17,7 @@ - #include - #include - #include -+#include - #include - #include - #include "rs274ngc.hh" -@@ -175,6 +176,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 - { -+ if (((block->m_modes[9] == 54) || (block->m_modes[9] == 55)) && -+ !is_user_defined_m_code(block, &(_setup), 9)) { -+ CHKS((block->p_flag == block->dollar_flag), -+ _("M54/M55 requires exactly one P joint selector or $ spindle selector")); -+ CHKS((!block->is_standalone(1)), -+ _("M54/M55 must be the only command in its block")); -+ CHKS((block->p_flag && (!isfinite(block->p_number) || block->p_number < 0 || -+ floor(block->p_number) != block->p_number || block->p_number > INT_MAX)), -+ _("M54/M55 P selector must be a non-negative integer joint number")); -+ CHKS((block->dollar_flag && (block->dollar_value != block->dollar_number || -+ block->dollar_number < 0)), -+ _("M54/M55 $ selector must be a non-negative integer spindle number")); -+ } - - 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 - (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) && -- (block->m_modes[9] != 51) && (! block->s_flag)), -- _("$ (spindle selection) word with no M3, M4, M5, M19, M51, G33, G33.1, G76, G95, G96 or G97 to use it")); -+ (block->m_modes[9] != 51) && (block->m_modes[9] != 54) && -+ (block->m_modes[9] != 55) && (! block->s_flag)), -+ _("$ (spindle selection) word with no M3, M4, M5, M19, M51, M54, M55, G33, G33.1, G76, G95, G96 or G97 to use it")); - } - - 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) && - (motion != G_74) && (motion != G_84) && - (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) && -+ (block->m_modes[9] != 55) && (block->m_modes[5] != 62) && (block->m_modes[5] != 63) && - (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" -- " 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 ---- 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)){ - } - } - -+if (((block->m_modes[9] == 54) || (block->m_modes[9] == 55)) && ONCE_M(9)) { -+ const int available = block->m_modes[9] == 54; -+ FINISH(); -+ if (block->p_flag) -+ SET_JOINT_AVAILABILITY((int)block->p_number, available); -+ else -+ SET_SPINDLE_AVAILABILITY(block->dollar_number, available); -+ // execute_block reaches its normal end, then returns the queue barrier. -+ -+ } -+ - if (is_user_defined_m_code(block, settings, 10) && ONCE_M(10)) { - 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 ---- 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) - return (INTERP_EXECUTE_FINISH); - -+ if ((block->m_modes[9] == 54 || block->m_modes[9] == 55) && -+ !is_user_defined_m_code(block, settings, 9)) -+ return INTERP_EXECUTE_FINISH; -+ - // All changes to settings are complete - 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 ---- 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 - block->line_number = -1; - block->n_number = -1; - block->motion_to_be = -1; -+ block->item_count = 0; - block->m_count = 0; - 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 ---- a/src/emc/rs274ngc/interp_internal.hh -+++ b/src/emc/rs274ngc/interp_internal.hh -@@ -454,12 +454,19 @@ struct block_struct - int line_number{}; - int saved_line_number{}; // value of sequence_number when a remap was encountered - int motion_to_be{}; -+ int item_count{}; // non-comment block items, excluding the line number - int m_count{}; - int m_modes[11]{}; - int user_m{}; - int dollar_number{}; -+ double dollar_value{}; // unrounded selector for standalone resource validation - int g_modes[GM_MAX_MODAL_GROUPS]{}; - -+ bool is_standalone(int argument_items = 0) const -+ { -+ return item_count == argument_items + 1; -+ } -+ - bool a_flag{}; - 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 ---- a/src/emc/rs274ngc/interp_read.cc -+++ b/src/emc/rs274ngc/interp_read.cc -@@ -20,6 +20,7 @@ - #include - #include - #include -+#include - #include - #include - #include -@@ -406,7 +407,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)); -- block->dollar_number = value; -+ block->dollar_value = value; -+ /* Preserve existing truncation for representable legacy selectors, but -+ retain the original value so M54/M55 can require an exact integer. */ -+ block->dollar_number = isfinite(value) && value >= INT_MIN && value <= INT_MAX -+ ? static_cast(value) : -2; - block->dollar_flag = true; - return INTERP_OK; - } -@@ -870,7 +875,9 @@ int Interp::read_items(block_pointer block, //!< pointer to a block being f - } - - for (; counter < length;) { -+ const char item = line[counter]; - CHP(read_one_item(line, &counter, block, parameters)); -+ if (item != '(' && item != ';') block->item_count++; - } - return INTERP_OK; - } -diff --git a/src/emc/rs274ngc/interp_remap.cc b/src/emc/rs274ngc/interp_remap.cc -index b13bdc0a5e..a944478d8d 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) - m_code == 7 || - m_code == 8 || - m_code == 9 || -+ m_code == 54 || -+ m_code == 55 || - 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 ---- a/src/emc/sai/saicanon.cc -+++ b/src/emc/sai/saicanon.cc -@@ -491,6 +491,11 @@ void STOP_SPINDLE_TURNING(int spindle) - _sai._spindle_turning[spindle] = CANON_STOPPED; - } - -+void SET_JOINT_AVAILABILITY(int joint, int available) -+{ PRINT("SET_JOINT_AVAILABILITY(%d, %d)\n", joint, available); } -+void SET_SPINDLE_AVAILABILITY(int spindle, int available) -+{ PRINT("SET_SPINDLE_AVAILABILITY(%d, %d)\n", spindle, available); } -+ - void SPINDLE_RETRACT() - {PRINT("SPINDLE_RETRACT()\n");} - -diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc -index 9f36a8de8e..f61e55bcfa 100644 ---- a/src/emc/task/emccanon.cc -+++ b/src/emc/task/emccanon.cc -@@ -3091,6 +3091,24 @@ void STOP_SPINDLE_TURNING(int s) - canon.spindle[s].dir = 0; - } - -+void SET_JOINT_AVAILABILITY(int joint, int available) -+{ -+ auto message = std::make_unique(); -+ flush_segments(); -+ message->joint = joint; -+ message->available = !!available; -+ interp_list.append(std::move(message)); -+} -+ -+void SET_SPINDLE_AVAILABILITY(int spindle, int available) -+{ -+ auto message = std::make_unique(); -+ flush_segments(); -+ message->spindle = spindle; -+ message->available = !!available; -+ interp_list.append(std::move(message)); -+} -+ - 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/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 097bbf6..0000000 --- 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/README.md b/linuxcnc-patches/README.md index 33773ed..454595d 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -17,6 +17,20 @@ they are materialized into LinuxCNC as a linear Git history with exactly one commit per patch. Changing the baseline requires rebasing and validating the complete series. +## Migration to v2.10.0-pre2 (in progress) + +This branch moves the series from the previous base (`888cb941fbf23ee32fc8e15ca180997d99a39117`) to the +`v2.10.0-pre2` tag. + +- Patches in this directory have been ported and apply to the new base. +- Patches still waiting to be ported are kept unchanged under + [`pending-pre2/`](./pending-pre2). They apply only to the previous base and + the tooling ignores them. +- A patch leaves `pending-pre2/` when its port is accepted. It keeps its number + and filename. + +Remove this section and the directory once `pending-pre2/` is empty. + ## Continuous integration Changes under `linuxcnc-patches/` trigger the @@ -387,7 +401,12 @@ runtime feature. function with deterministic kinematics and the real cubic implementation. It covers late invalid targets, interpolation failure, and no partial commitment. -### 0017 — Runtime joint and spindle availability +### ~~0017 — Runtime joint and spindle availability~~ + +> **Removed** with the move to LinuxCNC v2.10.0-pre2. Upstream added `G28.2`, which homes joints from G-code. +> Runtime availability is being redesigned around it and will return as a new +> patch with a new number. +> The description below records what the patch did. Adds runtime acquisition and release of individual joints and spindles, allowing external hardware to hand physical resources to LinuxCNC and take them back. @@ -432,7 +451,12 @@ motion. Resources are managed independently, with no automatic pairing or switching sequence. Patch 0018 adds the M54/M55 G-code interface to these operations. -### 0018 — Standalone M54/M55 interface +### ~~0018 — Standalone M54/M55 interface~~ + +> **Removed** with the move to LinuxCNC v2.10.0-pre2. Upstream added `G28.2`, which homes joints from G-code. +> Runtime availability is being redesigned around it and will return as a new +> patch with a new number. +> The description below records what the patch did. Adds G-code commands for the runtime availability operations in patch 0017. `M54` acquires a joint or spindle, and `M55` releases it. Programs can explicitly @@ -523,7 +547,10 @@ 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 diff --git a/linuxcnc-patches/base-revision b/linuxcnc-patches/base-revision index 88ef55d..3700bac 100644 --- a/linuxcnc-patches/base-revision +++ b/linuxcnc-patches/base-revision @@ -1 +1 @@ -888cb941fbf23ee32fc8e15ca180997d99a39117 +49119ab84f260c208d598c8e0d7e3bcc9f37834c diff --git a/linuxcnc-patches/0001-export-spindle-speed-feedback.patch b/linuxcnc-patches/pending-pre2/0001-export-spindle-speed-feedback.patch similarity index 100% rename from linuxcnc-patches/0001-export-spindle-speed-feedback.patch rename to linuxcnc-patches/pending-pre2/0001-export-spindle-speed-feedback.patch diff --git a/linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch b/linuxcnc-patches/pending-pre2/0002-expose-interpreter-coordinate-data-in-status.patch similarity index 100% rename from linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch rename to linuxcnc-patches/pending-pre2/0002-expose-interpreter-coordinate-data-in-status.patch diff --git a/linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch b/linuxcnc-patches/pending-pre2/0003-preserve-g96-g97-across-task-mode-switches.patch similarity index 100% rename from linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch rename to linuxcnc-patches/pending-pre2/0003-preserve-g96-g97-across-task-mode-switches.patch diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/pending-pre2/0004-resumable-stop.patch similarity index 100% rename from linuxcnc-patches/0004-resumable-stop.patch rename to linuxcnc-patches/pending-pre2/0004-resumable-stop.patch diff --git a/linuxcnc-patches/0005-headless-build-option.patch b/linuxcnc-patches/pending-pre2/0005-headless-build-option.patch similarity index 100% rename from linuxcnc-patches/0005-headless-build-option.patch rename to linuxcnc-patches/pending-pre2/0005-headless-build-option.patch diff --git a/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch b/linuxcnc-patches/pending-pre2/0006-ordered-realtime-component-search-path.patch similarity index 100% rename from linuxcnc-patches/0006-ordered-realtime-component-search-path.patch rename to linuxcnc-patches/pending-pre2/0006-ordered-realtime-component-search-path.patch diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/pending-pre2/0007-native-automatic-tool-wear.patch similarity index 100% rename from linuxcnc-patches/0007-native-automatic-tool-wear.patch rename to linuxcnc-patches/pending-pre2/0007-native-automatic-tool-wear.patch diff --git a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch b/linuxcnc-patches/pending-pre2/0008-tapered-g76-drive-lines.patch similarity index 100% rename from linuxcnc-patches/0008-tapered-g76-drive-lines.patch rename to linuxcnc-patches/pending-pre2/0008-tapered-g76-drive-lines.patch diff --git a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch b/linuxcnc-patches/pending-pre2/0009-threading-stop-clear-and-pass-stepping.patch similarity index 100% rename from linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch rename to linuxcnc-patches/pending-pre2/0009-threading-stop-clear-and-pass-stepping.patch diff --git a/linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch b/linuxcnc-patches/pending-pre2/0010-rs274-add-recording-canon-preview-backend.patch similarity index 100% rename from linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch rename to linuxcnc-patches/pending-pre2/0010-rs274-add-recording-canon-preview-backend.patch diff --git a/linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch b/linuxcnc-patches/pending-pre2/0011-motion-arm-single-step-during-active-execution.patch similarity index 100% rename from linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch rename to linuxcnc-patches/pending-pre2/0011-motion-arm-single-step-during-active-execution.patch diff --git a/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch b/linuxcnc-patches/pending-pre2/0012-emc-own-transactional-tool-CRUD-in-task.patch similarity index 100% rename from linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch rename to linuxcnc-patches/pending-pre2/0012-emc-own-transactional-tool-CRUD-in-task.patch diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/pending-pre2/0013-rs274ngc-add-composable-executor-stdglue.patch similarity index 100% rename from linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch rename to linuxcnc-patches/pending-pre2/0013-rs274ngc-add-composable-executor-stdglue.patch diff --git a/linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch b/linuxcnc-patches/pending-pre2/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch similarity index 100% rename from linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch rename to linuxcnc-patches/pending-pre2/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch diff --git a/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch b/linuxcnc-patches/pending-pre2/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch similarity index 100% rename from linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch rename to linuxcnc-patches/pending-pre2/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch diff --git a/linuxcnc-patches/0016-motion-joint-target-preparation.patch b/linuxcnc-patches/pending-pre2/0016-motion-joint-target-preparation.patch similarity index 100% rename from linuxcnc-patches/0016-motion-joint-target-preparation.patch rename to linuxcnc-patches/pending-pre2/0016-motion-joint-target-preparation.patch diff --git a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch b/linuxcnc-patches/pending-pre2/0019-motion-allow-concurrent-individual-joint-homing.patch similarity index 100% rename from linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch rename to linuxcnc-patches/pending-pre2/0019-motion-allow-concurrent-individual-joint-homing.patch diff --git a/linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch b/linuxcnc-patches/pending-pre2/0020-feat-motion-add-native-lathe-power-jogging.patch similarity index 100% rename from linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch rename to linuxcnc-patches/pending-pre2/0020-feat-motion-add-native-lathe-power-jogging.patch diff --git a/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch b/linuxcnc-patches/pending-pre2/0021-hal-support-cross-compiling-external-components.patch similarity index 100% rename from linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch rename to linuxcnc-patches/pending-pre2/0021-hal-support-cross-compiling-external-components.patch diff --git a/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch b/linuxcnc-patches/pending-pre2/0023-hal-expose-native-thread-period-statistics.patch similarity index 100% rename from linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch rename to linuxcnc-patches/pending-pre2/0023-hal-expose-native-thread-period-statistics.patch From c1f845bbf766a7f2fa218ecbdbd878ebf519c5ed Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 21:50:11 +0100 Subject: [PATCH 03/45] feat(hal): add C++ wrappers for the HAL query API LinuxCNC 2.10 no longer exports HAL's private list walkers and shared-memory base; consumers inspect HAL through the public query API (hal_list_*, hal_get_*, hal_set_*), whose callbacks run while HAL's mutex is held. hal/query.hpp wraps those calls for C++ callables. It catches exceptions thrown by a callable, stops the iteration and rethrows after HAL has released its mutex, so an exception can never leave HAL locked. with_lock() holds the recursive, per-thread HAL mutex around several queries so they observe one consistent HAL state. The header is shared by the HAL adapter and the scope controller. --- native/server/src/hal/query.hpp | 141 ++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 native/server/src/hal/query.hpp diff --git a/native/server/src/hal/query.hpp b/native/server/src/hal/query.hpp new file mode 100644 index 0000000..1c01373 --- /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 From b69b6f0363b460f6f5b0af1147e1f324777c6fc4 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 21:50:11 +0100 Subject: [PATCH 04/45] refactor(hal): port the HAL adapter to the LinuxCNC 2.10 public API The adapter walked HAL shared memory through hal_priv.h (SHMPTR, halpr_find_*, hal_data lists and mutex) and created items with hal_pin_new/hal_param_new. LinuxCNC 2.10 removes all of that: pins and parameters are opaque 64-bit handles and HAL is inspected through the query API. - Listing, reads and writes use hal_list_*, hal_get_p/s and hal_set_p/s. Each adapter call holds HAL's mutex once, as before, so topology(), read_many() and write_many() still see and change a consistent state. Write rules are unchanged: unlinked non-output pins, HAL_RW parameters, signals without a writer. - HAL integers are 64-bit only. Items are reported as BIT, FLOAT, S64 or U64; S32 and U32 values are accepted as writes to S64 and U64 items, and CreateSignal with S32/U32 creates a 64-bit signal. - Owned remote-component items keep their declared type. A 32-bit item is created with hal_pin_new_si32/ui32 (64-bit storage) and its owner reads a value outside the 32-bit range clamped to the nearest limit. - Function and thread statistics come from the .time pin and the .tmax and .tmax-increased parameters. HAL dropped the floating-point flag, so uses_fp is always true. HAL no longer publishes whether threads run; it is derived from .threadbeat advancing between topology() calls. Thread function lists exclude init functions. - The CMake HAL gate checks for hal.h instead of hal_priv.h. --- native/server/CMakeLists.txt | 2 +- .../include/linuxcnc_grpc/hal/adapter.hpp | 18 +- native/server/src/hal/adapter.cc | 1009 ++++++++++------- 3 files changed, 636 insertions(+), 393 deletions(-) diff --git a/native/server/CMakeLists.txt b/native/server/CMakeLists.txt index 86ed9b6..462edc0 100644 --- a/native/server/CMakeLists.txt +++ b/native/server/CMakeLists.txt @@ -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 diff --git a/native/server/include/linuxcnc_grpc/hal/adapter.hpp b/native/server/include/linuxcnc_grpc/hal/adapter.hpp index 4fc087b..5573f27 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,10 @@ 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; read() clamps a value outside the 32-bit + * range to the nearest 32-bit limit. */ class LinuxCncHalComponent final { public: @@ -139,8 +147,14 @@ 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. + * + * Thread "running" is derived from each thread's threadbeat pin across + * topology() calls, because HAL no longer publishes its global flag; it can + * lag a start or stop by up to twice the thread period plus 250 ms. */ class LinuxCncHalAdapter final { public: diff --git a/native/server/src/hal/adapter.cc b/native/server/src/hal/adapter.cc index ade506d..032e4f2 100644 --- a/native/server/src/hal/adapter.cc +++ b/native/server/src/hal/adapter.cc @@ -6,90 +6,100 @@ #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 "hal_priv.h" +#include "hal/query.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; -}; +// A thread counts as running for this long beyond twice its period after its +// threadbeat pin was last seen to advance (see observe_thread_beats()). +constexpr auto kThreadRunningGrace = std::chrono::milliseconds(250); + +[[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,113 +124,201 @@ 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 HalAdapterType::Bit: - return *static_cast(pointer); - case HalAdapterType::Float: - return static_cast(*static_cast(pointer)); - case HalAdapterType::S32: - return static_cast(*static_cast(pointer)); - case HalAdapterType::U32: - return static_cast( - *static_cast(pointer)); - case HalAdapterType::S64: - return static_cast(*static_cast(pointer)); - case HalAdapterType::U64: - return static_cast( - *static_cast(pointer)); + 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); } - throw HalAdapterError("Unsupported HAL scalar type", -EINVAL); } -bool write_value(HalAdapterType type, void* pointer, - const HalAdapterValue& value) { - if (!pointer || !same_type(type, value)) return false; +// 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. +std::optional to_hal(hal_type_t type, + const HalAdapterValue& value) { + hal_query_value_u result{}; switch (type) { - case HalAdapterType::Bit: - *static_cast(pointer) = std::get(value); - break; - case HalAdapterType::Float: - *static_cast(pointer) = std::get(value); + case HAL_BOOL: + if (const auto* typed = std::get_if(&value)) { + result.b = *typed; + return result; + } break; - case HalAdapterType::S32: - *static_cast(pointer) = std::get(value); + case HAL_REAL: + if (const auto* typed = std::get_if(&value)) { + result.r = *typed; + return result; + } break; - case HalAdapterType::U32: - *static_cast(pointer) = std::get(value); + 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 HalAdapterType::S64: - *static_cast(pointer) = std::get(value); + 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; - case HalAdapterType::U64: - *static_cast(pointer) = std::get(value); + default: break; } - return true; + return std::nullopt; } -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; +// 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; } - 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; + 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{}; }; -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; +// 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. +std::optional prepare_unlocked( + const HalAdapterReference& reference, const HalAdapterValue& value) { + PreparedWrite prepared; + prepared.reference = &reference; + 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; } + } catch (const HalAdapterError& error) { + // An item without a data target (-EIO) is not writable, as before. + if (error.code() == -EIO) return std::nullopt; + throw; } - hal_type_t type = resolved.pin ? resolved.pin->type - : resolved.param ? resolved.param->type - : resolved.signal->type; - const auto converted = adapter_type(type); + const auto converted = to_hal(prepared.type, value); if (!converted) return std::nullopt; - resolved.type = *converted; - return resolved; + prepared.value = *converted; + 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) { @@ -230,15 +328,123 @@ std::string full_name(const std::string& prefix, const std::string& suffix) { 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 hal_pin_new_bool(component_id, direction, &ref->b, false, "%s", + name); + case HalAdapterType::Float: + return hal_pin_new_real(component_id, direction, &ref->r, 0.0, "%s", + name); + case HalAdapterType::S32: + return hal_pin_new_si32(component_id, direction, &ref->s, 0, "%s", name); + case HalAdapterType::U32: + return hal_pin_new_ui32(component_id, direction, &ref->u, 0, "%s", name); + case HalAdapterType::S64: + return hal_pin_new_sint(component_id, direction, &ref->s, 0, "%s", name); + case HalAdapterType::U64: + return hal_pin_new_uint(component_id, direction, &ref->u, 0, "%s", name); + } + return -EINVAL; +} + +int create_param(int component_id, hal_pdir_t direction, HalAdapterType type, + hal_refs_u* ref, const char* name) { + switch (type) { + case HalAdapterType::Bit: + return hal_param_new_bool(component_id, direction, &ref->b, false, "%s", + name); + case HalAdapterType::Float: + return hal_param_new_real(component_id, direction, &ref->r, 0.0, "%s", + name); + case HalAdapterType::S32: + return hal_param_new_si32(component_id, direction, &ref->s, 0, "%s", + name); + case HalAdapterType::U32: + return hal_param_new_ui32(component_id, direction, &ref->u, 0, "%s", + name); + case HalAdapterType::S64: + return hal_param_new_sint(component_id, direction, &ref->s, 0, "%s", + name); + case HalAdapterType::U64: + return hal_param_new_uint(component_id, direction, &ref->u, 0, "%s", + name); + } + return -EINVAL; +} + +// 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 (set from outside, or by a linked 64-bit writer) is clamped. +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; +} + +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; + } + 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 +455,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 +488,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; }; @@ -308,12 +513,88 @@ struct LinuxCncHalComponent::Impl { } 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; + 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) { + items.erase(it); + slab->release(*slot); + throw HalAdapterError(std::string(pin ? "hal_pin_new" : "hal_param_new") + + " failed for '" + full + "'", + result); + } + return true; + } }; struct LinuxCncHalAdapter::Impl { + struct BeatState { + rtapi_sint beat = 0; + std::optional last_change; + }; + int component_id = 0; std::string component_name; std::shared_ptr slab; + std::mutex beat_mutex; + std::unordered_map beats; + + // HAL no longer publishes its global "threads running" flag. Each thread's + // .threadbeat pin advances once per cycle only while threads run, + // so threads are reported as running when any beat advanced within twice + // its thread's period plus a grace interval since an earlier topology() + // call. A non-zero beat seen for the first time counts as an advance. + bool observe_thread_beats( + const std::vector& threads, + const std::vector>& thread_beats) { + const auto now = std::chrono::steady_clock::now(); + std::lock_guard lock(beat_mutex); + std::unordered_map next; + bool running = false; + for (std::size_t index = 0; index < threads.size(); ++index) { + const auto& observed = thread_beats[index]; + if (!observed) continue; + const auto& thread = threads[index]; + const auto beat = *observed; + BeatState state; + if (const auto found = beats.find(thread.name); found != beats.end()) { + state = found->second; + if (state.beat != beat) { + state.beat = beat; + state.last_change = now; + } + } else { + state.beat = beat; + if (beat != 0) state.last_change = now; + } + const auto window = + std::chrono::nanoseconds(thread.period_ns) * 2 + kThreadRunningGrace; + if (state.last_change && now - *state.last_change <= window) + running = true; + next.emplace(thread.name, state); + } + beats = std::move(next); + return running; + } }; LinuxCncHalComponent::LinuxCncHalComponent(std::unique_ptr impl) @@ -351,75 +632,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 +668,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 +690,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 +732,201 @@ 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; + std::vector> thread_beats; + 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); } - 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); - } - 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); + const auto beat = find_pp(thread.name + ".threadbeat", HAL_QTYPE_PIN); + thread_beats.push_back(beat && beat->pp.type == HAL_SINT + ? std::optional(beat->pp.value.s) + : std::nullopt); } - 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; - } + + 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_->observe_thread_beats(result.threads, thread_beats); + 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); + 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); + 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 +939,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(); } From 28bcf8a2e35de5c3b1c90d43b454add442c31c85 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 22:07:05 +0100 Subject: [PATCH 05/45] feat(linuxcnc): port patches 0001-0003 to v2.10.0-pre2 0001 and 0002 apply unchanged. 0003 now also keeps the interpreter's css_maximum (the G96 D limit upstream added for the G33/G76 pitch check) modal: it is initialized in Interp::init(), preserved across Interp::synch() and cleared by M2/M30, like the spindle mode. Canon keeps its own CSS limit across a mode switch, so resetting only the interpreter's copy made legal threading moves fail after any switch. The three patches build with -Werror on v2.10.0-pre2 and the upstream regression suite passes (324 of 324). --- .../0001-export-spindle-speed-feedback.patch | 20 ++++++------ ...nterpreter-coordinate-data-in-status.patch | 22 ++++++------- ...ve-g96-g97-across-task-mode-switches.patch | 32 +++++++++++++------ linuxcnc-patches/README.md | 5 +++ 4 files changed, 48 insertions(+), 31 deletions(-) rename linuxcnc-patches/{pending-pre2 => }/0001-export-spindle-speed-feedback.patch (84%) rename linuxcnc-patches/{pending-pre2 => }/0002-expose-interpreter-coordinate-data-in-status.patch (92%) rename linuxcnc-patches/{pending-pre2 => }/0003-preserve-g96-g97-across-task-mode-switches.patch (65%) diff --git a/linuxcnc-patches/pending-pre2/0001-export-spindle-speed-feedback.patch b/linuxcnc-patches/0001-export-spindle-speed-feedback.patch similarity index 84% rename from linuxcnc-patches/pending-pre2/0001-export-spindle-speed-feedback.patch rename to linuxcnc-patches/0001-export-spindle-speed-feedback.patch index 36c0659..6d01853 100644 --- a/linuxcnc-patches/pending-pre2/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/pending-pre2/0002-expose-interpreter-coordinate-data-in-status.patch b/linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch similarity index 92% rename from linuxcnc-patches/pending-pre2/0002-expose-interpreter-coordinate-data-in-status.patch rename to linuxcnc-patches/0002-expose-interpreter-coordinate-data-in-status.patch index 6e49fa6..59c632a 100644 --- a/linuxcnc-patches/pending-pre2/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/pending-pre2/0003-preserve-g96-g97-across-task-mode-switches.patch b/linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch similarity index 65% rename from linuxcnc-patches/pending-pre2/0003-preserve-g96-g97-across-task-mode-switches.patch rename to linuxcnc-patches/0003-preserve-g96-g97-across-task-mode-switches.patch index 336564c..eb3a6d2 100644 --- a/linuxcnc-patches/pending-pre2/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/README.md b/linuxcnc-patches/README.md index 454595d..6b03101 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -171,6 +171,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. From 1b60f067682a23bdd4b431f61876c185930e0fa3 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 22:03:08 +0100 Subject: [PATCH 06/45] refactor(scope): port the scope controller to the LinuxCNC 2.10 public API The controller found scope sources, threads and functions by walking HAL's private shared memory (hal_priv.h, SHMPTR, halpr_find_*, hal_data lists and mutex, hal_shmoff). LinuxCNC 2.10 removes all of that. Follow upstream's own halscope port (d88d10d, "hal: Update halmeter and halscope removing access to hal_priv.h"): - Sources resolve with hal_getref_p (HAL_QTYPE_PIN or HAL_QTYPE_PARAM) and hal_getref_s, and hal_reference_unmap() turns the returned reference into the offset scope_rt maps back with hal_reference_map(). A linked pin still samples its signal's value and an unlinked pin its own value; HAL now does that choice inside hal_getref_p. configure() resolves all channels, the thread period and the attached thread under one hold of HAL's mutex, as before. - scope.sample, its thread and thread periods come from hal_list_funct and hal_list_thread; the owner check uses hal_list_comp. - scope_rt's shared-memory layout changed: data_offset[] is rtapi_intptr_t, the sample union holds rtapi_bool/uint/sint/real, and the buffer starts at the control block rounded up to 8 bytes. shm_abi.h follows it. The compatibility check now requires buf_len to equal the buffer length implied by our layout instead of only fitting in the segment, so a module with a different control block is rejected in either direction. - scope_rt samples each type into a full 8-byte cell. BOOL and REAL decode exactly; SINT and UINT are 64-bit and decode to the channel's doubles, exactly up to 2^53 and rounded beyond. Trigger levels for SINT/UINT channels are validated against the 64-bit ranges ("S64"/"U64" errors). HAL_PORT items are rejected as before. - Every failure after hal_init in the constructor now tears down, including HAL query errors. The conversion and trigger-level code lives in scope/sample_codec.hpp so the contract test can check it against upstream's scope_data_t, together with the new layout. --- native/server/src/scope/controller.cc | 415 +++++++++--------- native/server/src/scope/sample_codec.hpp | 111 +++++ native/server/src/scope/shm_abi.h | 30 +- .../tests/scope_controller_contract_tests.cc | 100 +++++ 4 files changed, 433 insertions(+), 223 deletions(-) create mode 100644 native/server/src/scope/sample_codec.hpp diff --git a/native/server/src/scope/controller.cc b/native/server/src/scope/controller.cc index cd728cf..1abc25a 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 0000000..fad3fa2 --- /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 bbcd371..5bdcb41 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/scope_controller_contract_tests.cc b/native/server/tests/scope_controller_contract_tests.cc index b8dc5f9..69de2f3 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. From b461b59e2f791166255ac6267cfc2567e1ce1351 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 22:06:10 +0100 Subject: [PATCH 07/45] fix(hal): report stopped threads correctly on the first topology() call LinuxCNC 2.10 has no public equivalent of hal_data->threads_running: hal_start_threads() and hal_stop_threads() only flip that private flag, and the only effect a process can observe through the public API is each thread's .threadbeat pin advancing once per period while threads run. The adapter therefore keeps deriving "running" from the beats, but a fresh adapter counted any non-zero beat as running, so threads stopped before the process started were reported running until the next call. A beat that moved since a call long ago had the same problem. Decide only on evidence instead: - compared with the previous topology() call, a beat that changed within twice its thread period plus 20 ms means running, and a beat unchanged for at least that long means stopped; - otherwise re-read the beats every 1 ms, outside HAL's mutex, until one moves (running) or twice the shortest period plus 20 ms passes (stopped), for at most 100 ms. Only when no thread is faster than about 40 ms does that bound leave the question open; then the previous answer is kept, or on the first call a non-zero beat still counts as running. Measured in a non-realtime uspace container with a 1 ms thread: no extra wait when called again within the window, about 1 ms when threads run, and 22 ms on the first call while threads are stopped. --- .../include/linuxcnc_grpc/hal/adapter.hpp | 7 +- native/server/src/hal/adapter.cc | 142 +++++++++++++----- 2 files changed, 112 insertions(+), 37 deletions(-) diff --git a/native/server/include/linuxcnc_grpc/hal/adapter.hpp b/native/server/include/linuxcnc_grpc/hal/adapter.hpp index 5573f27..0385197 100644 --- a/native/server/include/linuxcnc_grpc/hal/adapter.hpp +++ b/native/server/include/linuxcnc_grpc/hal/adapter.hpp @@ -152,9 +152,10 @@ class LinuxCncHalComponent final { * mutex, so it observes and modifies a consistent HAL state. It intentionally * exposes no signal link/unlink methods. * - * Thread "running" is derived from each thread's threadbeat pin across - * topology() calls, because HAL no longer publishes its global flag; it can - * lag a start or stop by up to twice the thread period plus 250 ms. + * 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/src/hal/adapter.cc b/native/server/src/hal/adapter.cc index 032e4f2..4a0d360 100644 --- a/native/server/src/hal/adapter.cc +++ b/native/server/src/hal/adapter.cc @@ -18,6 +18,7 @@ #include #include #include +#include #include #include @@ -26,9 +27,16 @@ namespace linuxcnc::server { namespace { -// A thread counts as running for this long beyond twice its period after its -// threadbeat pin was last seen to advance (see observe_thread_beats()). -constexpr auto kThreadRunningGrace = std::chrono::milliseconds(250); +// 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. @@ -546,10 +554,21 @@ struct LinuxCncHalComponent::Impl { } }; +// 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; - std::optional last_change; + Clock::time_point since; // first read that returned `beat` + Clock::time_point read_at; // latest read }; int component_id = 0; @@ -557,44 +576,100 @@ struct LinuxCncHalAdapter::Impl { std::shared_ptr slab; std::mutex beat_mutex; std::unordered_map beats; - - // HAL no longer publishes its global "threads running" flag. Each thread's - // .threadbeat pin advances once per cycle only while threads run, - // so threads are reported as running when any beat advanced within twice - // its thread's period plus a grace interval since an earlier topology() - // call. A non-zero beat seen for the first time counts as an advance. - bool observe_thread_beats( - const std::vector& threads, - const std::vector>& thread_beats) { - const auto now = std::chrono::steady_clock::now(); + 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& observed = thread_beats[index]; - if (!observed) continue; + const auto& reading = observed[index]; + if (!reading) continue; const auto& thread = threads[index]; - const auto beat = *observed; - BeatState state; + 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()) { - state = found->second; - if (state.beat != beat) { - state.beat = beat; - state.last_change = now; + 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; } - } else { - state.beat = beat; - if (beat != 0) state.last_change = now; } - const auto window = - std::chrono::nanoseconds(thread.period_ns) * 2 + kThreadRunningGrace; - if (state.last_change && now - *state.last_change <= window) - running = 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) @@ -734,6 +809,7 @@ int LinuxCncHalAdapter::component_id() const noexcept { HalAdapterTopology LinuxCncHalAdapter::topology() const { HalAdapterTopology result; 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; @@ -797,11 +873,9 @@ HalAdapterTopology LinuxCncHalAdapter::topology() const { thread.runtime = statistic_value(thread.name + ".time", HAL_QTYPE_PIN); thread.max_runtime = statistic_value(thread.name + ".tmax", HAL_QTYPE_PARAM).value_or(0); - const auto beat = find_pp(thread.name + ".threadbeat", HAL_QTYPE_PIN); - thread_beats.push_back(beat && beat->pp.type == HAL_SINT - ? std::optional(beat->pp.value.s) - : std::nullopt); + thread_beats.push_back(read_thread_beat(thread.name)); } + beats_read_at = std::chrono::steady_clock::now(); checked(hal_query::list_pins_params( HAL_QTYPE_PIN, @@ -860,7 +934,7 @@ HalAdapterTopology LinuxCncHalAdapter::topology() const { } }); const bool running = - impl_->observe_thread_beats(result.threads, thread_beats); + impl_->threads_running(result.threads, thread_beats, beats_read_at); for (auto& thread : result.threads) thread.running = running; return result; } From 365e52eef5fd8553b23d98439003b3e690f6401c Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 11 Nov 2026 23:35:59 +0100 Subject: [PATCH 08/45] chore(linuxcnc): keep runtime availability in the pre2 series Restore patches 0017 and 0018 to the set waiting to be ported and drop their strike-through in the inventory. They were removed on the understanding that runtime availability would be redesigned around upstream's new G28.2; the intent is narrower: only the homing step of acquisition moves onto upstream's G28.2 homing machinery, and the rest of both patches is ported as it is. --- linuxcnc-patches/README.md | 14 +- ...ntime-joint-and-spindle-availability.patch | 4407 +++++++++++++++++ .../0018-availability-mcodes.patch | 1296 +++++ 3 files changed, 5705 insertions(+), 12 deletions(-) create mode 100644 linuxcnc-patches/pending-pre2/0017-runtime-joint-and-spindle-availability.patch create mode 100644 linuxcnc-patches/pending-pre2/0018-availability-mcodes.patch diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 6b03101..061be2b 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -406,12 +406,7 @@ runtime feature. function with deterministic kinematics and the real cubic implementation. It covers late invalid targets, interpolation failure, and no partial commitment. -### ~~0017 — Runtime joint and spindle availability~~ - -> **Removed** with the move to LinuxCNC v2.10.0-pre2. Upstream added `G28.2`, which homes joints from G-code. -> Runtime availability is being redesigned around it and will return as a new -> patch with a new number. -> The description below records what the patch did. +### 0017 — Runtime joint and spindle availability Adds runtime acquisition and release of individual joints and spindles, allowing external hardware to hand physical resources to LinuxCNC and take them back. @@ -456,12 +451,7 @@ motion. Resources are managed independently, with no automatic pairing or switching sequence. Patch 0018 adds the M54/M55 G-code interface to these operations. -### ~~0018 — Standalone M54/M55 interface~~ - -> **Removed** with the move to LinuxCNC v2.10.0-pre2. Upstream added `G28.2`, which homes joints from G-code. -> Runtime availability is being redesigned around it and will return as a new -> patch with a new number. -> The description below records what the patch did. +### 0018 — Standalone M54/M55 interface Adds G-code commands for the runtime availability operations in patch 0017. `M54` acquires a joint or spindle, and `M55` releases it. Programs can explicitly diff --git a/linuxcnc-patches/pending-pre2/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/pending-pre2/0017-runtime-joint-and-spindle-availability.patch new file mode 100644 index 0000000..aa640cd --- /dev/null +++ b/linuxcnc-patches/pending-pre2/0017-runtime-joint-and-spindle-availability.patch @@ -0,0 +1,4407 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Dariusz Majnert +Date: Thu, 17 Sep 2026 18:00:42 +0200 +Subject: [PATCH] runtime-joint-and-spindle-availability + +--- + docs/src/config/ini-config.adoc | 31 + + docs/src/config/python-interface.adoc | 26 + + 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/mot_priv.h | 21 + + src/emc/motion/motion.c | 16 + + src/emc/motion/motion.h | 61 +- + src/emc/nml_intf/emc.cc | 29 + + src/emc/nml_intf/emc.hh | 11 + + 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/task.hh | 1 + + src/emc/task/taskintf.cc | 94 ++- + src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + + .../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 + +diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc +index de598c529d..cdb1333971 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 < + #include + + #include "nml_intf/emc.hh" +@@ -139,9 +140,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 +- int sequence = ini.findIntV("HOME_SEQUENCE", jointSection, 999); ++ auto configured_sequence = ini.findInt("HOME_SEQUENCE", jointSection); ++ int sequence = configured_sequence.value_or(999); + old_inihal_data.joint_home_sequence[joint] = sequence; + ++ bool availability_control = ++ ini.findBoolV("AVAILABILITY_CONTROL", jointSection, false); ++ if (availability_control && configured_sequence) { ++ rcs_print_error("%s: HOME_SEQUENCE cannot be used with " ++ "AVAILABILITY_CONTROL; the joint is referenced only " ++ "during individual acquisition\n", ++ jointSection.c_str()); ++ return -1; ++ } ++ double availability_timeout = ++ ini.findRealV("AVAILABILITY_TIMEOUT", jointSection, 5.0); ++ if (!std::isfinite(availability_timeout) || availability_timeout <= 0.0) { ++ rcs_print_error("%s: AVAILABILITY_TIMEOUT must be greater than zero\n", ++ jointSection.c_str()); ++ return -1; ++ } + 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) + ignore_limits, + is_shared, + sequence, +- volatile_home, ++ volatile_home && !availability_control, + locking_idxer, + abs_encoder)) { + print_dbg_config("emcJointSetHomingParams"); +@@ -187,10 +205,20 @@ static int loadJoint(int joint, const IniFile &ini) + } + } + +- // Activate joint. ++ if (0 != emcJointSetAvailabilityConfig(joint, availability_control, ++ availability_timeout, ++ volatile_home)) { ++ rcs_print_error("%s: availability configuration rejected " ++ "(extra joints are unsupported)\n", jointSection.c_str()); ++ print_dbg_config("emcJointSetAvailabilityConfig"); ++ return -1; ++ } ++ ++ // Activate uncontrolled joints. Controlled joints are activated only ++ // after their acquisition handshake and position validation or homing. + // Doing this last should prevent the motion controller to flag errors + // during configuration +- if (0 != emcJointActivate(joint)) { ++ if (!availability_control && 0 != emcJointActivate(joint)) { + print_dbg_config("emcJointActivate"); + return -1; + } +diff --git a/src/emc/ini/inispindle.cc b/src/emc/ini/inispindle.cc +index 7438ae02bc..ad815f8df0 100644 +--- a/src/emc/ini/inispindle.cc ++++ b/src/emc/ini/inispindle.cc +@@ -14,6 +14,7 @@ + * Last change: created 30/12/21 + ********************************************************************/ + ++#include + #include + + #include "nml_intf/emc.hh" +@@ -91,12 +92,40 @@ static int loadSpindle(int spindle, const IniFile &ini) + double home_angle = 0.0; + double increment = ini.findRealV("INCREMENT", spindleSection, 100.0); + ++ bool availability_control = ++ ini.findBoolV("AVAILABILITY_CONTROL", spindleSection, false); ++ bool initial_availability = true; ++ if (availability_control) { ++ auto configured_initial = ++ ini.findBool("INITIAL_AVAILABILITY", spindleSection); ++ if (!configured_initial) { ++ rcs_print_error("%s: INITIAL_AVAILABILITY is required when " ++ "AVAILABILITY_CONTROL is enabled\n", ++ spindleSection.c_str()); ++ return -1; ++ } ++ initial_availability = *configured_initial; ++ } ++ double availability_timeout = ++ ini.findRealV("AVAILABILITY_TIMEOUT", spindleSection, 5.0); ++ if (!std::isfinite(availability_timeout) || availability_timeout <= 0.0) { ++ rcs_print_error("%s: AVAILABILITY_TIMEOUT must be greater than zero\n", ++ spindleSection.c_str()); ++ return -1; ++ } ++ + if (0 != emcSpindleSetParams(spindle, fastest_pos, slowest_pos, + slowest_neg, fastest_neg, search_vel, + home_angle, home_sequence, increment)) { + rcs_print_error("emcSpindleSetParams: failed\n"); + return -1; + } ++ if (0 != emcSpindleSetAvailabilityConfig(spindle, availability_control, ++ initial_availability, ++ availability_timeout)) { ++ rcs_print_error("emcSpindleSetAvailabilityConfig: failed\n"); ++ return -1; ++ } + return 0; + } + +diff --git a/src/emc/ini/linuxcnc_check_ini.py b/src/emc/ini/linuxcnc_check_ini.py +index d780715b90..eba42b648d 100755 +--- a/src/emc/ini/linuxcnc_check_ini.py ++++ b/src/emc/ini/linuxcnc_check_ini.py +@@ -251,8 +251,10 @@ def check_bools(): + "HOME_INDEX_NO_ENCODER_RESET", + "HOME_IGNORE_LIMITS", + "HOME_IS_SHARED", +- "VOLATILE_HOME" ++ "VOLATILE_HOME", ++ "AVAILABILITY_CONTROL" + ] ++ BOOLSVARS = ["AVAILABILITY_CONTROL", "INITIAL_AVAILABILITY"] + for s, v in BOOLVARS: + check_bool(s, v) + for asect in list(filter(lambda s: s.startswith("AXIS_"), ini.getsections())): +@@ -261,6 +263,9 @@ def check_bools(): + for jsect in list(filter(lambda s: s.startswith("JOINT_"), ini.getsections())): + for v in BOOLJVARS: + check_bool(jsect, v) ++ for ssect in list(filter(lambda s: s.startswith("SPINDLE_"), ini.getsections())): ++ for v in BOOLSVARS: ++ check_bool(ssect, v) + + # + # 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 +--- 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[]) { + log_print("SET_SPINDLE_PARAMS, %.2e, %.2e, %.2e, %.2e\n", c->maxLimit, c->min_pos_speed, c->minLimit, c->max_neg_speed); + break; + ++ case EMCMOT_SET_JOINT_AVAILABILITY_CONFIG: ++ log_print("SET_JOINT_AVAILABILITY_CONFIG joint=%d, controlled=%d, timeout=%.6g, volatile_home=%d\n", ++ c->joint, c->availability_control, ++ c->availability_timeout, c->volatile_home); ++ break; ++ ++ case EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG: ++ log_print("SET_SPINDLE_AVAILABILITY_CONFIG spindle=%d, controlled=%d, initial_available=%d, timeout=%.6g\n", ++ c->spindle, c->availability_control, ++ c->initial_availability, c->availability_timeout); ++ break; ++ ++ case EMCMOT_SET_JOINT_AVAILABILITY: ++ log_print("SET_JOINT_AVAILABILITY joint=%d, available=%d\n", ++ c->joint, c->available); ++ break; ++ ++ case EMCMOT_SET_SPINDLE_AVAILABILITY: ++ log_print("SET_SPINDLE_AVAILABILITY spindle=%d, available=%d\n", ++ c->spindle, c->available); ++ break; ++ + case EMCMOT_SET_SPINDLESYNC: + 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 +--- 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 + } + if (!motion_teleop_flag) { + axis->teleop_tp.enable = 0; +- return; ++ continue; + } + if (!motion_enable_flag) { continue; } + if ( *(axis_data->ajog_enable) == 0 ) { continue; } +diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c +index c166af652b..a18acd066f 100644 +--- a/src/emc/motion/command.c ++++ b/src/emc/motion/command.c +@@ -80,6 +80,38 @@ extern int motion_num_spindles; + + static int rehomeAll; + ++int availability_transition_busy(void) ++{ ++ int n; ++ for (n = 0; n < ALL_JOINTS; n++) { ++ availability_state_t state = ++ emcmotStatus->joint_status[n].availability.state; ++ if (state == EMCMOT_AVAILABILITY_ENABLING || ++ state == EMCMOT_AVAILABILITY_HOMING || ++ state == EMCMOT_AVAILABILITY_DISABLING) return 1; ++ } ++ for (n = 0; n < emcmotConfig->numSpindles; n++) { ++ availability_state_t state = ++ emcmotStatus->spindle_status[n].availability.state; ++ if (state == EMCMOT_AVAILABILITY_ENABLING || ++ state == EMCMOT_AVAILABILITY_DISABLING) return 1; ++ } ++ return 0; ++} ++ ++STATIC int spindle_range_is_available(int first, int last) ++{ ++ int spindle; ++ for (spindle = first; spindle <= last; spindle++) { ++ availability_status_t *availability = ++ &emcmotStatus->spindle_status[spindle].availability; ++ if (availability->controlled && ++ availability->state != EMCMOT_AVAILABILITY_AVAILABLE) ++ return 0; ++ } ++ return 1; ++} ++ + /* 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) + return; + } + } ++ if (availability_transition_busy()) { ++ switch (emcmotCommand->command) { ++ case EMCMOT_JOG_CONT: ++ case EMCMOT_JOG_INCR: ++ case EMCMOT_JOG_ABS: ++ case EMCMOT_SET_LINE: ++ case EMCMOT_SET_CIRCLE: ++ case EMCMOT_PROBE: ++ case EMCMOT_RIGID_TAP: ++ case EMCMOT_JOINT_HOME: ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ return; ++ default: break; ++ } ++ } ++ /* tcSetupState inherits the planner's modal spindle dependency. */ ++ switch (emcmotCommand->command) { ++ case EMCMOT_SET_LINE: ++ case EMCMOT_SET_CIRCLE: ++ case EMCMOT_PROBE: ++ case EMCMOT_RIGID_TAP: { ++ int spindle = emcmotInternal->coord_tp.spindle.spindle_num; ++ if (emcmotInternal->coord_tp.synchronized != TC_SYNC_NONE && ++ (spindle < 0 || spindle >= emcmotConfig->numSpindles || ++ !spindle_range_is_available(spindle, spindle))) { ++ reportError(_("cannot admit motion synchronized to unavailable spindle %d"), spindle); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ SET_MOTION_ERROR_FLAG(1); ++ return; ++ } ++ break; ++ } ++ default: break; ++ } + switch (emcmotCommand->command) { + case EMCMOT_ABORT: + /* abort motion */ +@@ -503,6 +569,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) + } + } + } ++ emcmotInternal->availability_motion_error = 0; + 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) + /* abort one joint number or axis number */ + /* can happen at any time */ + rtapi_print_msg(RTAPI_MSG_DBG, "JOG_ABORT: %i", joint_num); ++ if (joint_num >= 0 && joint_num < ALL_JOINTS && ++ emcmotStatus->joint_status[joint_num].availability.controlled && ++ (emcmotStatus->joint_status[joint_num].availability.state == EMCMOT_AVAILABILITY_HOMING || ++ emcmotStatus->joint_status[joint_num].availability.state == EMCMOT_AVAILABILITY_ENABLING)) ++ break; /* Jog stops do not cancel acquisition or its homing. */ + 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) + break; + + case EMCMOT_COORD: ++ if (availability_transition_busy()) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + /* 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) + break; + + case EMCMOT_TELEOP: ++ if (availability_transition_busy()) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + rtapi_print_msg(RTAPI_MSG_DBG, "TELEOP"); + switch_to_teleop_mode(); + break; +@@ -679,10 +760,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); +- emcmot_config_change(); + if (joint == 0) { + break; + } ++ if (emcmotStatus->joint_status[joint_num].availability.controlled && ++ emcmotCommand->home_sequence != 999) { ++ reportError(_("availability-controlled joint %d cannot define HOME_SEQUENCE"), ++ joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; ++ break; ++ } ++ emcmot_config_change(); + update_joint_homing_params(joint_num, + emcmotCommand->offset, + emcmotCommand->home, +@@ -795,6 +883,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + SET_JOINT_ERROR_FLAG(joint, 1); + break; + } ++ if (!GET_MOTION_TELEOP_FLAG() && ++ emcmotStatus->joint_status[joint_num].availability.controlled && ++ emcmotStatus->joint_status[joint_num].availability.state != ++ EMCMOT_AVAILABILITY_AVAILABLE) { ++ reportError(_("Can't jog unavailable joint %d."), joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + // cannot jog if jog-inhibit is TRUE + if (*(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) + SET_JOINT_ERROR_FLAG(joint, 1); + break; + } ++ if (!GET_MOTION_TELEOP_FLAG() && ++ emcmotStatus->joint_status[joint_num].availability.controlled && ++ emcmotStatus->joint_status[joint_num].availability.state != ++ EMCMOT_AVAILABILITY_AVAILABLE) { ++ reportError(_("Can't jog unavailable joint %d."), joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + // cannot jog if jog-inhibit is TRUE + if (*(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) + SET_JOINT_ERROR_FLAG(joint, 1); + break; + } ++ if (!GET_MOTION_TELEOP_FLAG() && ++ emcmotStatus->joint_status[joint_num].availability.controlled && ++ emcmotStatus->joint_status[joint_num].availability.state != ++ EMCMOT_AVAILABILITY_AVAILABLE) { ++ reportError(_("Can't jog unavailable joint %d."), joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + // cannot jog if jog-inhibit is TRUE + if (*(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) + break; + + case EMCMOT_SET_SPINDLESYNC: ++ if (emcmotCommand->spindlesync != 0.0 && ++ emcmotCommand->spindle >= 0 && ++ emcmotCommand->spindle < emcmotConfig->numSpindles && ++ emcmotStatus->spindle_status[emcmotCommand->spindle].availability.controlled && ++ emcmotStatus->spindle_status[emcmotCommand->spindle].availability.state != ++ EMCMOT_AVAILABILITY_AVAILABLE) { ++ reportError(_("cannot synchronize to unavailable spindle %d"), ++ emcmotCommand->spindle); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + tpSetSpindleSync(&emcmotInternal->coord_tp, emcmotCommand->spindle, emcmotCommand->spindlesync, emcmotCommand->flags); + break; + +@@ -1380,6 +1503,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; ++ availability_cancel(1); + if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { + emcmotInternal->teleoperating = 0; + emcmotInternal->coordinating = 0; +@@ -1392,10 +1516,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"); ++ /* Initial availability belongs to a disabled-to-enabled request. ++ * 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 ) { + reportError(_("can't enable motion, enable input is false")); + } else { +- emcmotInternal->enabling = 1; ++ emcmotInternal->enabling = 0; ++ emcmotInternal->availability_machine_on = 1; ++ emcmotInternal->availability_resource = 0; + if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { + emcmotInternal->teleoperating = 0; + emcmotInternal->coordinating = 0; +@@ -1412,6 +1542,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + if (joint == 0) { + break; + } ++ /* Availability owns activation, including the temporary active ++ * phase needed to finish or cancel acquisition homing. */ ++ if (emcmotStatus->joint_status[joint_num].availability.controlled) { ++ reportError(_("joint %d activation is owned by availability"), joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + SET_JOINT_ACTIVE_FLAG(joint, 1); + break; + +@@ -1424,6 +1561,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + if (joint == 0) { + break; + } ++ /* Availability owns activation, including the temporary active ++ * phase needed to finish or cancel acquisition homing. */ ++ if (emcmotStatus->joint_status[joint_num].availability.controlled) { ++ reportError(_("joint %d activation is owned by availability"), joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + SET_JOINT_ACTIVE_FLAG(joint, 0); + break; + +@@ -1435,6 +1579,13 @@ 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) { ++ 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) + if (!GET_MOTION_ENABLE_FLAG()) { + break; + } +- + // Negative joint_num specifies homeall + do_home_joint(joint_num); + break; +@@ -1468,6 +1618,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) + return; + } + ++ if (joint_num >= 0 && joint_num < ALL_JOINTS && ++ emcmotStatus->joint_status[joint_num].availability.controlled) { ++ reportError(_("availability-controlled joint %d can only be unhomed by release"), ++ joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ if (joint_num == -1) { ++ int n; ++ for (n = 0; n < ALL_JOINTS; n++) { ++ if (emcmotStatus->joint_status[n].availability.controlled) { ++ reportError(_("cannot unhome all joints while joint %d is availability-controlled"), ++ n); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ } ++ if (n < ALL_JOINTS) break; ++ } ++ + // 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) + + break; + ++ case EMCMOT_SET_JOINT_AVAILABILITY_CONFIG: { ++ availability_status_t *availability; ++ /* Homed extra joints have an external posthome command owner. There ++ * is no handoff protocol with that owner, so acquisition is unsupported. */ ++ if (emcmotCommand->availability_control && IS_EXTRA_JOINT(joint_num)) { ++ rtapi_print_msg(RTAPI_MSG_ERR, ++ "availability control is unsupported for extra joint %d\n", joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; ++ break; ++ } ++ if (joint_num < 0 || joint_num >= ALL_JOINTS) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; ++ break; ++ } ++ if (emcmotCommand->availability_control && ++ get_home_sequence(joint_num) != 999) { ++ rtapi_print_msg(RTAPI_MSG_ERR, ++ "availability-controlled joint %d cannot define HOME_SEQUENCE\n", ++ joint_num); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; ++ break; ++ } ++ availability = &emcmotStatus->joint_status[joint_num].availability; ++ availability->controlled = !!emcmotCommand->availability_control; ++ availability->initial_available = 0; ++ availability->volatile_home = !!emcmotCommand->volatile_home; ++ availability->timeout = emcmotCommand->availability_timeout; ++ availability->fault = EMCMOT_AVAILABILITY_FAULT_NONE; ++ availability->state = availability->controlled ++ ? EMCMOT_AVAILABILITY_DISABLED : EMCMOT_AVAILABILITY_AVAILABLE; ++ availability->target_available = !availability->controlled; ++ availability->phase = AVAIL_PHASE_IDLE; ++ availability->held_position = joints[joint_num].pos_cmd; ++ if (availability->controlled) { ++ SET_JOINT_ENABLE_FLAG(&joints[joint_num], 0); ++ SET_JOINT_ACTIVE_FLAG(&joints[joint_num], 0); ++ } ++ emcmot_config_change(); ++ break; ++ } ++ ++ case EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG: { ++ availability_status_t *availability; ++ if (emcmotCommand->spindle < 0 || ++ emcmotCommand->spindle >= emcmotConfig->numSpindles) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; ++ break; ++ } ++ availability = &emcmotStatus->spindle_status[emcmotCommand->spindle].availability; ++ availability->controlled = !!emcmotCommand->availability_control; ++ availability->initial_available = !!emcmotCommand->initial_availability; ++ availability->timeout = emcmotCommand->availability_timeout; ++ availability->fault = EMCMOT_AVAILABILITY_FAULT_NONE; ++ availability->state = availability->controlled ++ ? EMCMOT_AVAILABILITY_DISABLED : EMCMOT_AVAILABILITY_AVAILABLE; ++ availability->target_available = !availability->controlled; ++ availability->phase = AVAIL_PHASE_IDLE; ++ emcmot_config_change(); ++ break; ++ } ++ ++ case EMCMOT_SET_JOINT_AVAILABILITY: { ++ availability_status_t *availability; ++ if (joint_num < 0 || joint_num >= ALL_JOINTS) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; ++ break; ++ } ++ availability = &emcmotStatus->joint_status[joint_num].availability; ++ if (availability_transition_busy()) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ if (!availability->controlled || ++ (availability->state != EMCMOT_AVAILABILITY_DISABLED && ++ availability->state != EMCMOT_AVAILABILITY_AVAILABLE && ++ availability->state != EMCMOT_AVAILABILITY_FAULT)) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ if (emcmotCommand->available && ++ availability->state == EMCMOT_AVAILABILITY_AVAILABLE) break; ++ if (!emcmotCommand->available && ++ availability->state == EMCMOT_AVAILABILITY_DISABLED) break; ++ if (motion_joint_release_state(joint_num) == ++ MOTION_JOINT_RELEASE_BLOCKED) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ if (emcmotCommand->available && !get_homed(joint_num) && ++ *(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) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ availability_begin(availability, 1); ++ } else { ++ if (availability->state == EMCMOT_AVAILABILITY_AVAILABLE) ++ availability_begin_joint_release(joint_num); ++ else ++ availability_release_joint(joint_num, EMCMOT_AVAILABILITY_FAULT_NONE); ++ } ++ break; ++ } ++ ++ case EMCMOT_SET_SPINDLE_AVAILABILITY: { ++ spindle_status_t *spindle; ++ availability_status_t *availability; ++ spindle_num = emcmotCommand->spindle; ++ if (spindle_num < 0 || spindle_num >= emcmotConfig->numSpindles) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_PARAMS; ++ break; ++ } ++ spindle = &emcmotStatus->spindle_status[spindle_num]; ++ availability = &spindle->availability; ++ if (availability_transition_busy()) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ if (!availability->controlled || ++ (availability->state != EMCMOT_AVAILABILITY_DISABLED && ++ availability->state != EMCMOT_AVAILABILITY_AVAILABLE && ++ availability->state != EMCMOT_AVAILABILITY_FAULT)) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ if (emcmotCommand->available && ++ availability->state == EMCMOT_AVAILABILITY_AVAILABLE) break; ++ if (!emcmotCommand->available && ++ availability->state == EMCMOT_AVAILABILITY_DISABLED) break; ++ if (spindle->state || spindle->orient_state == EMCMOT_ORIENT_IN_PROGRESS || ++ (tpQueueDepth(&emcmotInternal->coord_tp) != 0 && ++ emcmotInternal->coord_tp.synchronized != TC_SYNC_NONE && ++ emcmotInternal->coord_tp.spindle.spindle_num == spindle_num)) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ if (emcmotCommand->available) { ++ if (!GET_MOTION_ENABLE_FLAG() || !*emcmot_hal_data->enable) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } ++ availability_begin(availability, 1); ++ } else { ++ availability_release_spindle(spindle_num, EMCMOT_AVAILABILITY_FAULT_NONE); ++ } ++ break; ++ } ++ + 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) + s0 = 0; + s1 = motion_num_spindles - 1; + } ++ if (!spindle_range_is_available(s0, s1)) { ++ reportError(_("cannot command an unavailable spindle")); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ 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) + s0 = 0; + s1 = motion_num_spindles - 1; + } ++ if (!spindle_range_is_available(s0, s1)) { ++ reportError(_("cannot orient an unavailable spindle")); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + for (n = s0; n<=s1; n++){ +- + 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) + s0 = 0; + s1 = motion_num_spindles - 1; + } ++ if (!spindle_range_is_available(s0, s1)) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + 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) + s0 = 0; + s1 = motion_num_spindles - 1; + } ++ if (!spindle_range_is_available(s0, s1)) { ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + 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) + s0 = 0; + s1 = motion_num_spindles - 1; + } ++ if (!spindle_range_is_available(s0, s1)) { ++ reportError(_("cannot release the brake of an unavailable spindle")); ++ emcmotStatus->commandStatus = EMCMOT_COMMAND_INVALID_COMMAND; ++ break; ++ } + for (n = s0; n<=s1; n++){ +- + emcmotStatus->spindle_status[n].brake = 0; + } + break; +diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c +index 8ed2cb3882..722c58545d 100644 +--- a/src/emc/motion/control.c ++++ b/src/emc/motion/control.c +@@ -46,6 +46,9 @@ static int switchkins_type = 0; + /* kinematics flags */ + KINEMATICS_FORWARD_FLAGS fflags = 0; + KINEMATICS_INVERSE_FLAGS iflags = 0; ++/* Shared by release and the encoder handshake. */ ++static int old_motion_index[EMCMOT_MAX_SPINDLES] = {0}; ++static int old_hal_index[EMCMOT_MAX_SPINDLES] = {0}; + + /*! \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]; + emcmotStatus structure. + */ + static void process_inputs(void); ++static void process_availability(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) + read_homing_in_pins(ALL_JOINTS); + handle_kinematicsSwitch(); + process_inputs(); ++ process_availability(); + 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) { + handle_jjogwheels(); + } +- if (!emcmotStatus->on_soft_limit && !*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, ++ get_homing_is_active()); ++ int availability_homing = 0, homing_cleanup = 0; ++ for (int n = 0; n < ALL_JOINTS; n++) { ++ availability_status_t *a = &emcmotStatus->joint_status[n].availability; ++ availability_homing |= a->state == EMCMOT_AVAILABILITY_HOMING; ++ homing_cleanup |= a->phase == AVAIL_PHASE_CANCEL_HOME; + } +- 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(); + } + +@@ -440,8 +453,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)) { ++ SET_JOINT_PHL_FLAG(joint, 1); ++ } else { ++ SET_JOINT_PHL_FLAG(joint, 0); ++ } ++ if (*(joint_data->neg_lim_sw)) { ++ SET_JOINT_NHL_FLAG(joint, 1); ++ } else { ++ SET_JOINT_NHL_FLAG(joint, 0); ++ } ++ 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)) { ++ SET_JOINT_FAULT_FLAG(joint, 1); ++ } else { ++ SET_JOINT_FAULT_FLAG(joint, 0); ++ } + if (!GET_JOINT_ACTIVE_FLAG(joint)) { +- /* if joint is not active, skip it */ ++ /* Keep released motion state frozen. The raw HAL feedback pin remains ++ live for hardware diagnostics and acquisition validation. */ + continue; + } + /* copy data from HAL to joint structure */ +@@ -489,25 +523,7 @@ static void process_inputs(void) + SET_JOINT_FERROR_FLAG(joint, 0); + } + +- /* read limit switches */ +- if (*(joint_data->pos_lim_sw)) { +- SET_JOINT_PHL_FLAG(joint, 1); +- } else { +- SET_JOINT_PHL_FLAG(joint, 0); +- } +- if (*(joint_data->neg_lim_sw)) { +- SET_JOINT_NHL_FLAG(joint, 1); +- } else { +- SET_JOINT_NHL_FLAG(joint, 0); +- } +- 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)) { +- SET_JOINT_FAULT_FLAG(joint, 1); +- } else { +- SET_JOINT_FAULT_FLAG(joint, 0); +- } ++ + } + + // a fault was signalled during a spindle-orient in progress +@@ -551,6 +567,394 @@ static void process_inputs(void) + } + } + ++/* Availability owns requests and completion, not homing or planner state. */ ++static void availability_clear_pending(availability_status_t *a) ++{ ++ 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. */ ++ a->state = a->state == EMCMOT_AVAILABILITY_FAULT ++ ? EMCMOT_AVAILABILITY_DISABLING : EMCMOT_AVAILABILITY_ENABLING; ++} ++ ++void availability_release_joint(int n, availability_fault_t fault) ++{ ++ availability_status_t *a = &emcmotStatus->joint_status[n].availability; ++ if (!a->controlled) return; ++ if (a->state == EMCMOT_AVAILABILITY_AVAILABLE || ++ a->state == EMCMOT_AVAILABILITY_HOMING) ++ a->held_position = joints[n].pos_cmd; ++ availability_clear_pending(a); ++ a->phase = AVAIL_PHASE_CANCEL_HOME; ++ a->fault = fault; ++ a->state = EMCMOT_AVAILABILITY_DISABLING; ++ a->transition_started = etime(); ++ *emcmot_hal_data->joint[n].availability_request = 0; ++ motion_cancel_joint(n); ++} ++ ++void availability_begin_joint_release(int n) ++{ ++ availability_status_t *a = &emcmotStatus->joint_status[n].availability; ++ /* Release admission has already completed planning. Capture its logical ++ * endpoint while the servo-side settled check drains the final sample. */ ++ a->held_position = joints[n].coarse_pos; ++ a->target_available = 0; ++ a->phase = AVAIL_PHASE_WAIT_SETTLED; ++ a->fault = EMCMOT_AVAILABILITY_FAULT_NONE; ++ a->state = EMCMOT_AVAILABILITY_DISABLING; ++ a->transition_started = etime(); ++} ++ ++void availability_release_spindle(int n, availability_fault_t fault) ++{ ++ spindle_status_t *s = &emcmotStatus->spindle_status[n]; ++ availability_status_t *a = &s->availability; ++ if (!a->controlled) return; ++ availability_clear_pending(a); ++ a->fault = fault; ++ a->state = EMCMOT_AVAILABILITY_DISABLING; ++ a->transition_started = etime(); ++ *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; ++ 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; ++} ++ ++void availability_cancel(int all) ++{ ++ int n; ++ int initial = emcmotInternal->availability_machine_on; ++ emcmotInternal->availability_machine_on = 0; ++ emcmotInternal->availability_resource = 0; ++ if (initial || all) emcmotInternal->enabling = 0; ++ /* Revoke mode restoration as well as acquisition. */ ++ if (all || initial) { ++ emcmotInternal->coordinating = 0; ++ emcmotInternal->teleoperating = 0; ++ } ++ for (n = 0; n < ALL_JOINTS; n++) { ++ availability_status_t *a = &emcmotStatus->joint_status[n].availability; ++ if ((all || initial || a->state == EMCMOT_AVAILABILITY_ENABLING || ++ a->state == EMCMOT_AVAILABILITY_HOMING || a->target_available) && ++ (all || initial || a->state != EMCMOT_AVAILABILITY_AVAILABLE)) ++ availability_release_joint(n, a->fault); ++ } ++ for (n = 0; n < emcmotConfig->numSpindles; n++) { ++ availability_status_t *a = &emcmotStatus->spindle_status[n].availability; ++ if ((all || initial || a->state == EMCMOT_AVAILABILITY_ENABLING || ++ a->target_available) && ++ (all || initial || a->state != EMCMOT_AVAILABILITY_AVAILABLE)) ++ availability_release_spindle(n, a->fault); ++ } ++} ++ ++/* Disable through the normal motion fault path, including already buffered ++ * interpolation. No further interpolation may run in the failing cycle. */ ++static void availability_motion_fault(void) ++{ ++ tpAbort(&emcmotInternal->coord_tp); ++ axis_jog_abort_all(1); ++ emcmotInternal->availability_motion_error = 1; ++ SET_MOTION_ERROR_FLAG(1); ++ emcmotInternal->enabling = 0; ++ set_operating_mode(); ++} ++ ++static void set_joint_availability_fault(int n, availability_fault_t fault) ++{ ++ availability_release_joint(n, fault); ++ reportError(_("joint %d availability failed (%d)"), n, fault); ++ availability_motion_fault(); ++} ++ ++static void set_spindle_availability_fault(int n, availability_fault_t fault) ++{ ++ availability_release_spindle(n, fault); ++ reportError(_("spindle %d availability failed (%d)"), n, fault); ++ availability_motion_fault(); ++} ++ ++static bool validate_joint_position(int n) ++{ ++ 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 expected = a->held_position + joint->backlash_filt + joint->motor_offset; ++ double tolerance = joint->min_ferror; ++ return isfinite(feedback) && isfinite(expected) && isfinite(tolerance) && ++ tolerance >= 0.0 && fabs(feedback - expected) <= tolerance; ++} ++ ++/* The homing request owns this provisional joint-space synchronization. It ++ * gives the normal homing state machine a stationary start at the acquired ++ * hardware position; only successful homing makes the position valid. */ ++static bool availability_start_homing(int n) ++{ ++ emcmot_joint_t *joint = &joints[n]; ++ double motor = *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); ++ 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 = ++ joint->free_tp.last_pos_cmd = position; ++ joint->free_tp.curr_vel = joint->free_tp.curr_acc = ++ joint->free_tp.curr_jerk = 0.0; ++ joint->free_tp.enable = joint->free_tp.active = 0; ++ joint->vel_cmd = joint->acc_cmd = joint->jerk_cmd = 0.0; ++ joint->ferror = 0.0; ++ SET_JOINT_FERROR_FLAG(joint, 0); ++ SET_JOINT_ACTIVE_FLAG(joint, 1); ++ SET_JOINT_ENABLE_FLAG(joint, GET_MOTION_ENABLE_FLAG()); ++ return true; ++} ++ ++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) ++{ ++ availability_complete_joint(n); ++} ++ ++static void process_availability(void) ++{ ++ int n; ++ double now = etime(); ++ if (!*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; ++ if (!a->controlled) { ++ a->state = EMCMOT_AVAILABILITY_AVAILABLE; ++ } else switch (a->state) { ++ case EMCMOT_AVAILABILITY_DISABLED: ++ if (ack) set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_UNEXPECTED); ++ break; ++ case EMCMOT_AVAILABILITY_ENABLING: ++ if (ack && !*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; ++ a->state = EMCMOT_AVAILABILITY_HOMING; ++ a->phase = AVAIL_PHASE_WAIT_FREE; ++ } else { ++ if (!validate_joint_position(n)) { ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_POSITION_MISMATCH); ++ break; ++ } ++ SET_JOINT_ACTIVE_FLAG(&joints[n], 1); ++ SET_JOINT_ENABLE_FLAG(&joints[n], GET_MOTION_ENABLE_FLAG()); ++ availability_complete_joint(n); ++ } ++ } else if (now - a->transition_started >= a->timeout) ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACQUIRE_TIMEOUT); ++ break; ++ case EMCMOT_AVAILABILITY_HOMING: ++ if (!ack) { ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); ++ } else if (a->phase == AVAIL_PHASE_WAIT_FREE) { ++ 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); ++ } ++ break; ++ case EMCMOT_AVAILABILITY_AVAILABLE: ++ if (!get_homed(n)) ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_HOME_FAILED); ++ else if (!ack) ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); ++ break; ++ case EMCMOT_AVAILABILITY_DISABLING: ++ if (a->phase == AVAIL_PHASE_WAIT_SETTLED) { ++ if (!ack) { ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); ++ break; ++ } ++ if (motion_joint_release_state(n) != MOTION_JOINT_RELEASE_READY) { ++ if (now - a->transition_started >= a->timeout) ++ set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_TRANSITION_ABORTED); ++ break; ++ } ++ /* Cubic points and commanded derivatives are drained. Finish ++ * the final sampled position at the commanded endpoint. */ ++ a->held_position = joints[n].coarse_pos; ++ joints[n].pos_cmd = a->held_position; ++ availability_release_joint(n, EMCMOT_AVAILABILITY_FAULT_NONE); ++ } ++ /* Leave the joint active until the homing engine consumes abort. */ ++ if (a->phase == AVAIL_PHASE_CANCEL_HOME) { ++ if (!get_home_is_idle(n)) break; ++ /* Cancellation may stop acquisition homing at a new ++ * unreferenced location. Keep that result internal while the ++ * joint remains unavailable. Volatile joints freeze the ++ * final commanded homing location before invalidating it. */ ++ if (a->volatile_home && GET_JOINT_ACTIVE_FLAG(&joints[n])) ++ a->held_position = joints[n].pos_cmd; ++ joints[n].pos_fb = a->held_position; ++ joints[n].motor_pos_fb = a->held_position + ++ joints[n].backlash_filt + joints[n].motor_offset; ++ joints[n].vel_cmd = joints[n].acc_cmd = joints[n].jerk_cmd = 0.0; ++ joints[n].free_tp.curr_vel = joints[n].free_tp.curr_acc = ++ joints[n].free_tp.curr_jerk = 0.0; ++ joints[n].free_tp.enable = joints[n].free_tp.active = 0; ++ SET_JOINT_INPOS_FLAG(&joints[n], 1); ++ if (a->volatile_home && GET_JOINT_ACTIVE_FLAG(&joints[n])) ++ set_unhomed(n, emcmotStatus->motion_state); ++ SET_JOINT_ACTIVE_FLAG(&joints[n], 0); ++ a->phase = AVAIL_PHASE_IDLE; ++ } ++ if (!ack) { ++ if (a->target_available) { ++ a->state = EMCMOT_AVAILABILITY_ENABLING; ++ a->transition_started = now; ++ } else a->state = a->fault ? EMCMOT_AVAILABILITY_FAULT : EMCMOT_AVAILABILITY_DISABLED; ++ } else if (now - a->transition_started >= a->timeout) { ++ availability_clear_pending(a); ++ if (!a->fault) a->fault = EMCMOT_AVAILABILITY_FAULT_RELEASE_TIMEOUT; ++ a->state = EMCMOT_AVAILABILITY_FAULT; ++ reportError(_("joint %d availability release timed out"), n); ++ availability_motion_fault(); ++ } ++ break; ++ case EMCMOT_AVAILABILITY_FAULT: break; ++ } ++ *hal->availability_request = a->controlled && a->target_available && ++ (a->state == EMCMOT_AVAILABILITY_ENABLING || ++ 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; ++ } ++ 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; ++ 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) { ++ set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_STALE_HIGH); ++ break; ++ } ++ if (ack) { a->state = EMCMOT_AVAILABILITY_AVAILABLE; a->phase = AVAIL_PHASE_IDLE; } ++ else if (now - a->transition_started >= a->timeout) ++ set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACQUIRE_TIMEOUT); ++ break; ++ case EMCMOT_AVAILABILITY_AVAILABLE: ++ if (!ack) set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_ACK_LOST); ++ break; ++ case EMCMOT_AVAILABILITY_DISABLING: ++ if (!ack) { ++ if (a->target_available) { ++ a->state = EMCMOT_AVAILABILITY_ENABLING; ++ a->transition_started = now; ++ } else a->state = a->fault ? EMCMOT_AVAILABILITY_FAULT : EMCMOT_AVAILABILITY_DISABLED; ++ } else if (now - a->transition_started >= a->timeout) { ++ availability_clear_pending(a); ++ if (!a->fault) a->fault = EMCMOT_AVAILABILITY_FAULT_RELEASE_TIMEOUT; ++ a->state = EMCMOT_AVAILABILITY_FAULT; ++ reportError(_("spindle %d availability release timed out"), n); ++ availability_motion_fault(); ++ } ++ break; ++ case EMCMOT_AVAILABILITY_HOMING: ++ set_spindle_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_TRANSITION_ABORTED); ++ 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; ++ } ++ if (emcmotInternal->availability_machine_on) { ++ for (n = 0; n < ALL_JOINTS; n++) { ++ availability_status_t *a = &emcmotStatus->joint_status[n].availability; ++ if (a->controlled && a->fault) { availability_cancel(1); return; } ++ } ++ for (n = 0; n < emcmotConfig->numSpindles; n++) { ++ availability_status_t *a = &emcmotStatus->spindle_status[n].availability; ++ if (a->controlled && a->fault) { availability_cancel(1); return; } ++ } ++ while (emcmotInternal->availability_resource < emcmotConfig->numSpindles) { ++ n = emcmotInternal->availability_resource; ++ availability_status_t *a = &emcmotStatus->spindle_status[n].availability; ++ if (!a->controlled || !a->initial_available || a->state == EMCMOT_AVAILABILITY_AVAILABLE) { ++ emcmotInternal->availability_resource++; ++ continue; ++ } ++ if (a->state == EMCMOT_AVAILABILITY_DISABLED) availability_begin(a, 0); ++ break; ++ } ++ if (emcmotInternal->availability_resource == emcmotConfig->numSpindles) { ++ if (*emcmot_hal_data->enable) { ++ emcmotInternal->availability_machine_on = 0; ++ emcmotInternal->enabling = 1; ++ } else availability_cancel(1); ++ } ++ } ++} ++ + static void joint_jog_abort_all(bool immediate) + { + int jNum; +@@ -613,7 +1017,7 @@ static void do_forward_kins(void) + at the traj rate */ + + double joint_pos[EMCMOT_MAX_JOINTS] = {0,}; +- int joint_num, result; ++ int joint_num, result = 0; + emcmot_joint_t *joint; + + /* copy joint position feedback to local array */ +@@ -795,7 +1199,9 @@ static void check_for_faults(void) + } + /* check for spindle ampfifier errors */ + for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ +- if(emcmotStatus->spindle_status[spindle_num].fault && GET_MOTION_ENABLE_FLAG()){ ++ availability_status_t *a = &emcmotStatus->spindle_status[spindle_num].availability; ++ if (emcmotStatus->spindle_status[spindle_num].fault && GET_MOTION_ENABLE_FLAG() && ++ (!a->controlled || a->state == EMCMOT_AVAILABILITY_AVAILABLE)) { + reportError(_("spindle %d amplifier fault"), spindle_num); + emcmotInternal->enabling = 0; + } +@@ -867,6 +1273,7 @@ static void set_operating_mode(void) + + /* check for disabling */ + if (!emcmotInternal->enabling && GET_MOTION_ENABLE_FLAG()) { ++ availability_cancel(1); + /* 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) + } + } + SET_MOTION_ENABLE_FLAG(1); +- /* clear any outstanding motion errors when going into enabled state */ +- SET_MOTION_ERROR_FLAG(0); ++ /* Re-enable explicitly acknowledges the previous motion fault. */ ++ emcmotInternal->availability_motion_error = 0; ++ if (!emcmotInternal->availability_motion_error) { SET_MOTION_ERROR_FLAG(0); } + } + + /* check for entering teleop mode */ +@@ -950,7 +1358,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); +- SET_MOTION_ERROR_FLAG(0); ++ if (!emcmotInternal->availability_motion_error) { SET_MOTION_ERROR_FLAG(0); } + + kinematicsForward(positions, &emcmotStatus->carte_pos_cmd, &fflags, &iflags); + // entering teleop (INPOS), remove ext offsets +@@ -994,7 +1402,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) + } + 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) + /* point to joint data */ + joint_data = &(emcmot_hal_data->joint[joint_num]); + joint = &joints[joint_num]; +- if (!GET_JOINT_ACTIVE_FLAG(joint)) { +- /* if joint is not active, skip it */ +- continue; +- } ++ if (emcmotStatus->joint_status[joint_num].availability.controlled && ++ 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); ++ continue; ++ } ++ if (!GET_JOINT_ACTIVE_FLAG(joint)) { ++ /* if joint is not active, skip it */ ++ continue; ++ } + + // disallow accel bogus fractions + if ( (*(joint_data->jjog_accel_fraction) > 1) +@@ -1066,6 +1481,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; ++ if (availability_transition_busy()) continue; + /* initialization complete */ + if ( first_pass ) { + continue; +@@ -1197,6 +1613,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, + reportError(_("kinematicsInverse gave non-finite joint location on joint %d"), n); + return -1; + } ++ availability_status_t *a = &emcmotStatus->joint_status[n].availability; ++ if (a->controlled && a->state != EMCMOT_AVAILABILITY_AVAILABLE) { ++ /* Absolute tolerance in configured joint units (length or degrees). ++ * Never move the reference after accepting roundoff. */ ++ if (fabs(positions[n] - a->held_position) > 1e-9) { ++ reportError(_("motion would command unavailable joint %d"), n); ++ return -1; ++ } ++ positions[n] = a->held_position; ++ } + 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) + for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { + /* point to joint struct */ + joint = &joints[joint_num]; +- if (!GET_JOINT_ACTIVE_FLAG(joint)) { ++ if (!GET_JOINT_ACTIVE_FLAG(joint) || ++ (emcmotStatus->joint_status[joint_num].availability.controlled && ++ emcmotStatus->joint_status[joint_num].availability.state != EMCMOT_AVAILABILITY_AVAILABLE && ++ emcmotStatus->joint_status[joint_num].availability.state != EMCMOT_AVAILABILITY_HOMING)) { + /* if joint is not active, skip it */ + continue; + } +@@ -1430,8 +1859,7 @@ static void get_pos_cmds(long period) + result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, + positions, staged_cubics); + if (result != 0) { +- SET_MOTION_ERROR_FLAG(1); +- emcmotInternal->enabling = 0; ++ availability_motion_fault(); + break; + } + for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { +@@ -1492,8 +1920,7 @@ static void get_pos_cmds(long period) + result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, + positions, staged_cubics); + if (result != 0) { +- SET_MOTION_ERROR_FLAG(1); +- emcmotInternal->enabling = 0; ++ availability_motion_fault(); + break; + } + for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { +@@ -1504,6 +1931,8 @@ static void get_pos_cmds(long period) + &joint->vel_cmd, &joint->acc_cmd, &joint->jerk_cmd); + } + ++ SET_MOTION_INPOS_FLAG(!axis_jog_is_active()); ++ + + /* END OF OUTPUT KINS */ + +@@ -1520,10 +1949,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 */ +- emcmotStatus->carte_pos_cmd = emcmotStatus->carte_pos_fb; ++ emcmotStatus->carte_pos_cmd = emcmotStatus->carte_pos_fb; + for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { + /* point to joint struct */ + joint = &joints[joint_num]; ++ if (emcmotStatus->joint_status[joint_num].availability.controlled && ++ emcmotStatus->joint_status[joint_num].availability.state != EMCMOT_AVAILABILITY_AVAILABLE) ++ continue; + /* 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) + double inch_mult; + emcmot_joint_t *joint; + joint_hal_t *joint_data; +- static int old_motion_index[EMCMOT_MAX_SPINDLES] = {0}; +- 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) + + for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ + double speed; ++ int spindle_available = ++ emcmotStatus->spindle_status[spindle_num].availability.state == ++ EMCMOT_AVAILABILITY_AVAILABLE; + 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) + } + } + ++ 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; ++ } + *(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; ++ spindle_available && ++ 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) + + /* 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; ++ 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); ++ availability_status_t *availability = ++ &emcmotStatus->joint_status[joint_num].availability; ++ *(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; +diff --git a/src/emc/motion/mot_priv.h b/src/emc/motion/mot_priv.h +index 2050ad51a3..631c146ee2 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; ++ + } 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_bit_t *unlock; /* WPI: command that axis should unlock for rotation */ + hal_bit_t *is_unlocked; /* RPI: axis is currently unlocked */ + +@@ -356,4 +370,11 @@ typedef enum { + motion_joint_release_state_t motion_joint_release_state(int joint_num); + void motion_cancel_joint(int joint_num); + ++void availability_begin(availability_status_t *a, int runtime); ++void availability_begin_joint_release(int n); ++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); ++ + #endif /* MOT_PRIV_H */ +diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c +index 7f81108901..87f1a06205 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; + /* 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) + 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; ++ emcmotStatus->spindle_status[spindle_num].availability.state = EMCMOT_AVAILABILITY_AVAILABLE; ++ emcmotStatus->spindle_status[spindle_num].availability.timeout = 5.0; + } + + axis_init_all(); +@@ -936,6 +950,8 @@ static int init_comm_buffers(void) + joint->min_ferror = 0.01; + joint->max_ferror = 1.0; + joint->backlash = 0.0; ++ emcmotStatus->joint_status[joint_num].availability.state = EMCMOT_AVAILABILITY_AVAILABLE; ++ emcmotStatus->joint_status[joint_num].availability.timeout = 5.0; + + 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 +--- 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 */ + + EMCMOT_SET_SPINDLE_PARAMS, /* One command to set all spindle params */ ++ EMCMOT_SET_JOINT_AVAILABILITY_CONFIG, ++ EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG, ++ EMCMOT_SET_JOINT_AVAILABILITY, ++ EMCMOT_SET_SPINDLE_AVAILABILITY, + + } cmd_code_t; + +@@ -277,6 +281,10 @@ extern "C" { + struct state_tag_t tag; + int g76_pass_id; /* internal G76 pass ownership, zero otherwise */ + int g76_pass_clearance;/* 1: clearance retract, 2: approach endpoint */ ++ int availability_control; ++ int initial_availability; ++ int available; ++ double availability_timeout; + } 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.. + #define EMCMOT_JOINT_MIN_HARD_LIMIT_BIT 0x0020 + #define EMCMOT_JOINT_FERROR_BIT 0x0040 + #define EMCMOT_JOINT_FAULT_BIT 0x0080 +- + /*! \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.. + EMCMOT_ORIENT_FAULTED, + } orient_state_t; + ++ typedef enum { ++ EMCMOT_AVAILABILITY_DISABLED = 0, ++ EMCMOT_AVAILABILITY_ENABLING = 1, ++ EMCMOT_AVAILABILITY_HOMING = 2, ++ EMCMOT_AVAILABILITY_AVAILABLE = 3, ++ EMCMOT_AVAILABILITY_DISABLING = 4, ++ EMCMOT_AVAILABILITY_FAULT = 5, ++ } availability_state_t; ++ ++ typedef enum { ++ EMCMOT_AVAILABILITY_FAULT_NONE = 0, ++ EMCMOT_AVAILABILITY_FAULT_ACK_STALE_HIGH = 1, ++ EMCMOT_AVAILABILITY_FAULT_ACQUIRE_TIMEOUT = 2, ++ EMCMOT_AVAILABILITY_FAULT_RELEASE_TIMEOUT = 3, ++ EMCMOT_AVAILABILITY_FAULT_ACK_LOST = 4, ++ EMCMOT_AVAILABILITY_FAULT_ACK_UNEXPECTED = 5, ++ EMCMOT_AVAILABILITY_FAULT_HOME_FAILED = 6, ++ EMCMOT_AVAILABILITY_FAULT_HOME_ABORTED = 7, ++ EMCMOT_AVAILABILITY_FAULT_POSITION_MISMATCH = 8, ++ EMCMOT_AVAILABILITY_FAULT_TRANSITION_ABORTED = 9, ++ } availability_fault_t; ++ ++ typedef enum { ++ AVAIL_PHASE_IDLE, ++ AVAIL_PHASE_INITIAL_ACK, ++ AVAIL_PHASE_RUNTIME_ACK, ++ AVAIL_PHASE_WAIT_FREE, ++ AVAIL_PHASE_WAIT_HOME_START, ++ AVAIL_PHASE_WAIT_HOME_FINISH, ++ AVAIL_PHASE_WAIT_SETTLED, ++ AVAIL_PHASE_CANCEL_HOME, ++ } availability_phase_t; ++ ++ typedef struct { ++ int controlled; ++ int initial_available; ++ int volatile_home; ++ 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; ++ double transition_started; ++ } availability_status_t; ++ + /* 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.. + EMCMOT_JOINT_FLAG flag; /* see above for bit details */ + bool homed; + bool homing; ++ availability_status_t availability; + + 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.. + double home_search_vel; + int home_sequence; + double increment; ++ availability_status_t availability; + } spindle_status_t; + + typedef struct { +@@ -763,6 +819,9 @@ 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 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 +--- 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) + case EMC_JOINT_UNHOME_TYPE: + ((EMC_JOINT_UNHOME *) buffer)->update(cms); + break; ++ case EMC_JOINT_SET_AVAILABILITY_TYPE: ++ ((EMC_JOINT_SET_AVAILABILITY *) buffer)->update(cms); ++ break; + case EMC_JOG_CONT_TYPE: + ((EMC_JOG_CONT *) buffer)->update(cms); + break; +@@ -160,6 +163,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) + case EMC_SPINDLE_OFF_TYPE: + ((EMC_SPINDLE_OFF *) buffer)->update(cms); + break; ++ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: ++ ((EMC_SPINDLE_SET_AVAILABILITY *) buffer)->update(cms); ++ break; + case EMC_SPINDLE_ON_TYPE: + ((EMC_SPINDLE_ON *) buffer)->update(cms); + break; +@@ -375,6 +381,8 @@ const char *emc_symbol_lookup(uint32_t type) + return "EMC_JOINT_HOME"; + case EMC_JOINT_UNHOME_TYPE: + return "EMC_JOINT_UNHOME"; ++ case EMC_JOINT_SET_AVAILABILITY_TYPE: ++ return "EMC_JOINT_SET_AVAILABILITY"; + 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) + return "EMC_SPINDLE_INCREASE"; + case EMC_SPINDLE_OFF_TYPE: + return "EMC_SPINDLE_OFF"; ++ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: ++ return "EMC_SPINDLE_SET_AVAILABILITY"; + 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) + cms->update(_spindle); + } + ++void EMC_SPINDLE_SET_AVAILABILITY::update(CMS * cms) ++{ ++ EMC_SPINDLE_CMD_MSG::update(cms); ++ cms->update(spindle); ++ cms->update(available); ++} ++ + /* + * 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) + cms->update(spindle_override_enabled); + cms->update(at_speed); + cms->update(homed); ++ cms->update(available); ++ cms->update(availability_state); ++ cms->update(availability_fault); + } + + /* +@@ -1337,6 +1357,15 @@ void EMC_JOINT_STAT::update(CMS * cms) + cms->update(minHardLimit); + cms->update(maxHardLimit); + cms->update(overrideLimits); ++ cms->update(available); ++ cms->update(availability_state); ++ cms->update(availability_fault); ++} ++ ++void EMC_JOINT_SET_AVAILABILITY::update(CMS * cms) ++{ ++ EMC_JOINT_CMD_MSG::update(cms); ++ cms->update(available); + } + + /* +diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh +index 0dca92c7e0..32ca6fbaa0 100644 +--- a/src/emc/nml_intf/emc.hh ++++ b/src/emc/nml_intf/emc.hh +@@ -74,6 +74,7 @@ struct PM_CARTESIAN; + #define EMC_JOINT_SET_BACKLASH_TYPE ((NMLTYPE) 134) + #define EMC_JOINT_UNHOME_TYPE ((NMLTYPE) 135) + #define EMC_JOG_STOP_TYPE ((NMLTYPE) 136) ++#define EMC_JOINT_SET_AVAILABILITY_TYPE ((NMLTYPE) 137) + + #define EMC_JOINT_STAT_TYPE ((NMLTYPE) 198) + #define EMC_AXIS_STAT_TYPE ((NMLTYPE) 199) +@@ -180,6 +181,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) ++#define EMC_SPINDLE_SET_AVAILABILITY_TYPE ((NMLTYPE) 1319) + + #define EMC_SPINDLE_STAT_TYPE ((NMLTYPE) 1399) + +@@ -340,6 +342,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); + + + extern int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints); ++extern bool emcJointAvailabilityControlled(int index); ++extern int emcJointSetAvailabilityConfig(int joint, int controlled, ++ double timeout, int volatile_home); ++extern int emcJointSetAvailability(int joint, int available); + + extern int emcJointSetMaxJerk(int joint, double jerk); + +@@ -451,6 +457,11 @@ extern int emcSpindleBrakeRelease(int spindle); + extern int emcSpindleBrakeEngage(int spindle); + + extern int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles); ++extern bool emcSpindleAvailabilityControlled(int index); ++extern int emcSpindleSetAvailabilityConfig(int spindle, int controlled, ++ int initial_available, ++ double timeout); ++extern int emcSpindleSetAvailability(int spindle, int available); + + // 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 +--- 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 { + void update(CMS * cms); + }; + ++class EMC_JOINT_SET_AVAILABILITY:public EMC_JOINT_CMD_MSG { ++ public: ++ EMC_JOINT_SET_AVAILABILITY() ++ : EMC_JOINT_CMD_MSG(EMC_JOINT_SET_AVAILABILITY_TYPE, ++ sizeof(EMC_JOINT_SET_AVAILABILITY)), ++ available(0) ++ {}; ++ void update(CMS * cms); ++ int available; ++}; ++ + 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 { + 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 ++ int available; ++ int availability_state; ++ int availability_fault; + }; + + // declarations for EMC_TRAJ classes +@@ -1148,6 +1162,9 @@ class EMC_SPINDLE_STAT:public EMC_SPINDLE_STAT_MSG { + bool spindle_override_enabled; + bool at_speed; + bool homed; ++ int available; ++ int availability_state; ++ int availability_fault; + }; + + 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 + }; + ++class EMC_SPINDLE_SET_AVAILABILITY:public EMC_SPINDLE_CMD_MSG { ++ public: ++ EMC_SPINDLE_SET_AVAILABILITY() ++ : EMC_SPINDLE_CMD_MSG(EMC_SPINDLE_SET_AVAILABILITY_TYPE, ++ sizeof(EMC_SPINDLE_SET_AVAILABILITY)), ++ spindle(0), available(0) ++ {}; ++ void update(CMS * cms); ++ int spindle; ++ int available; ++}; ++ + class EMC_SPINDLE_INCREASE:public EMC_SPINDLE_CMD_MSG { + public: + EMC_SPINDLE_INCREASE() +diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc +index 6d91ef1bd0..6215d7d68c 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() + maxSoftLimit(0), + minHardLimit(0), + maxHardLimit(0), +- overrideLimits(0) ++ overrideLimits(0), ++ available(1), ++ availability_state(3), ++ availability_fault(0) + { + } + +@@ -198,7 +201,10 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() + orient_fault(0), + spindle_override_enabled(OFF), + at_speed(OFF), +- homed(OFF) ++ homed(OFF), ++ available(1), ++ availability_state(3), ++ availability_fault(0) + { + } + +diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc +index e0fe4e3616..ac4a55781b 100644 +--- a/src/emc/task/emctask.cc ++++ b/src/emc/task/emctask.cc +@@ -234,6 +234,7 @@ void emcTaskQueueTaskPlanSynchCmd() + + int emcTaskAbort() + { ++ emcTaskCancelAvailability(); + emcMotionAbort(); + + // clear out the pending command +diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc +index 59021c7dcb..1314163557 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -169,6 +169,60 @@ volatile int done; + static int emctask_shutdown(void); + extern void backtrace(int signo); + int _task = 1; // control preview behaviour when remapping ++// Populated only after usrmotWriteEmcmotCommand confirms motion acceptance. ++// The ordinary executor wait and queued PLAN_SYNCH own completion. ++static struct { ++ bool active = false; ++ bool spindle = false; ++ int index = 0; ++ bool available = false; ++ bool cancelled = false; ++ bool failed = false; ++} availability_pending; ++ ++void emcTaskCancelAvailability() ++{ ++ auto &op = availability_pending; ++ if (!op.active) return; ++ op.cancelled = true; ++ op.failed |= emcStatus->motion.status == RCS_STATUS::ERROR || ++ emcStatus->io.status == RCS_STATUS::ERROR || ++ (op.spindle ? emcStatus->motion.spindle[op.index].availability_fault ++ : emcStatus->motion.joint[op.index].availability_fault); ++} ++ ++static bool availability_transition(int state) ++{ ++ return state == EMCMOT_AVAILABILITY_ENABLING || ++ state == EMCMOT_AVAILABILITY_HOMING || ++ state == EMCMOT_AVAILABILITY_DISABLING; ++} ++ ++// Check the particular accepted operation, never infer success from motion DONE. ++static EMC_TASK_EXEC availability_completion() ++{ ++ // Dispatch can run before this cycle's normal status update. A failed or ++ // stale read must not turn command acceptance into completion. ++ if (emcMotionUpdate(&emcStatus->motion) != 0) ++ return EMC_TASK_EXEC::WAITING_FOR_MOTION; ++ const auto &op = availability_pending; ++ int state = op.spindle ? emcStatus->motion.spindle[op.index].availability_state ++ : emcStatus->motion.joint[op.index].availability_state; ++ int fault = op.spindle ? emcStatus->motion.spindle[op.index].availability_fault ++ : emcStatus->motion.joint[op.index].availability_fault; ++ if (availability_transition(state)) return EMC_TASK_EXEC::WAITING_FOR_MOTION; ++ if (op.cancelled) { ++ availability_pending.failed |= fault != 0; ++ return EMC_TASK_EXEC::DONE; ++ } ++ if (fault || state != (op.available ? EMCMOT_AVAILABILITY_AVAILABLE ++ : EMCMOT_AVAILABILITY_DISABLED)) { ++ emcOperatorError(_("availability operation failed for %s %d"), ++ op.spindle ? "spindle" : "joint", op.index); ++ return EMC_TASK_EXEC::ERROR; ++ } ++ return EMC_TASK_EXEC::DONE; ++} + 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 + + int all_homed(void) { + for (int i = 0; i < emcStatus->motion.traj.joints; i++) { +- if(!emcStatus->motion.joint[i].homed) // XXX +- return 0; ++ const auto &joint = emcStatus->motion.joint[i]; ++ if (emcJointAvailabilityControlled(i)) { ++ if (joint.availability_fault) return 0; ++ if (joint.availability_state == EMCMOT_AVAILABILITY_DISABLED) continue; ++ if (joint.availability_state != EMCMOT_AVAILABILITY_AVAILABLE) return 0; ++ } ++ if (!joint.homed) return 0; + } + return 1; + } +@@ -836,6 +895,13 @@ static bool emcTaskArmSingleStep() + return true; + } + ++static void emcTaskPausedSingleStep() ++{ ++ if (!emcTaskArmSingleStep()) { ++ emcStatus->task.interpState = interpResumeState; ++ } ++} ++ + static void emcTaskStopClear() + { + bool was_active = emcStatus && +@@ -1029,6 +1095,31 @@ static int emcTaskPlan(void) + return emcTaskIssueCommand(emcCommand); + } + ++ if (type == EMC_JOINT_SET_AVAILABILITY_TYPE || ++ type == EMC_SPINDLE_SET_AVAILABILITY_TYPE) { ++ // External admission only: canonical commands use the ordered executor. ++ if (availability_pending.active || ++ emcStatus->task.interpState != EMC_TASK_INTERP::IDLE || ++ emcStatus->task.execState != EMC_TASK_EXEC::DONE || ++ emcStatus->task.task_paused || ++ emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE || ++ emcTaskCommand || interp_list.len() || mdi_execute_queue.len() || ++ mdi_execute_wait || mdi_execute_next || mdi_execute_level >= 0 || ++ emcTaskPlanIsWait() || ++ emcStatus->motion.status != RCS_STATUS::DONE || ++ emcStatus->io.status != RCS_STATUS::DONE) { ++ emcOperatorError(_("direct availability request requires idle task")); ++ return -1; ++ } ++ retval = emcTaskIssueCommand(emcCommand); ++ if (!retval) { ++ emcTaskPlanSetWait(); ++ emcTaskQueueTaskPlanSynchCmd(); ++ emcStatus->task.execState = EMC_TASK_EXEC::WAITING_FOR_MOTION; ++ } ++ return retval; ++ } ++ + 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) + return 0; + } + ++ if (availability_pending.active) { ++ // Do not interpret or admit motion across an availability transaction. ++ // Cleanup and resumable program controls retain their normal semantics. ++ switch (type) { ++ case EMC_TASK_ABORT_TYPE: ++ case EMC_TASK_PLAN_PAUSE_TYPE: ++ case EMC_TASK_PLAN_RESUME_TYPE: ++ case EMC_JOG_STOP_TYPE: ++ case EMC_SPINDLE_OFF_TYPE: ++ return emcTaskIssueCommand(emcCommand); ++ case EMC_TASK_SET_STATE_TYPE: ++ if (static_cast(emcCommand)->state == EMC_TASK_STATE::ON) ++ return -1; ++ return emcTaskIssueCommand(emcCommand); ++ case EMC_TASK_PLAN_STEP_TYPE: ++ if (emcStatus->task.mode != EMC_TASK_MODE::AUTO) return -1; ++ if (emcStatus->task.interpState == EMC_TASK_INTERP::PAUSED) ++ emcTaskPausedSingleStep(); ++ else ++ emcTaskArmSingleStep(); ++ return 0; ++ case 0: ++ case EMC_NULL_TYPE: ++ return 0; ++ default: ++ emcOperatorError(_("command rejected during availability operation")); ++ return -1; ++ } ++ } ++ + // handle any new command + switch (emcStatus->task.state) { + case EMC_TASK_STATE::OFF: +@@ -1559,9 +1680,7 @@ static int emcTaskPlan(void) + break; + + case EMC_TASK_PLAN_STEP_TYPE: +- if (!emcTaskArmSingleStep()) { +- emcStatus->task.interpState = interpResumeState; +- } ++ emcTaskPausedSingleStep(); + break; + + // otherwise we can't handle it +@@ -1824,6 +1943,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: ++ case EMC_JOINT_SET_AVAILABILITY_TYPE: ++ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: + return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; + break; + +@@ -1993,6 +2114,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + retval = emcJointUnhome(unhome_msg->joint); + break; + ++ case EMC_JOINT_SET_AVAILABILITY_TYPE: { ++ if (availability_pending.active) return -1; ++ auto *message = reinterpret_cast(cmd); ++ if (message->joint < 0 || message->joint >= emcStatus->motion.traj.joints || ++ !emcJointAvailabilityControlled(message->joint)) { ++ emcOperatorError(_("invalid or uncontrolled joint availability resource %d"), ++ message->joint); ++ retval = -1; ++ } else { ++ retval = emcJointSetAvailability(message->joint, message->available); ++ if (retval == 0) { ++ availability_pending = {true, false, message->joint, ++ !!message->available, false}; ++ } ++ } ++ break; ++ } ++ + 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); + break; + ++ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: { ++ if (availability_pending.active) return -1; ++ auto *message = reinterpret_cast(cmd); ++ if (message->spindle < 0 || ++ message->spindle >= emcStatus->motion.traj.spindles || ++ !emcSpindleAvailabilityControlled(message->spindle)) { ++ emcOperatorError(_("invalid or uncontrolled spindle availability resource %d"), ++ message->spindle); ++ retval = -1; ++ } else { ++ retval = emcSpindleSetAvailability(message->spindle, ++ message->available); ++ if (retval == 0) { ++ availability_pending = {true, true, message->spindle, ++ !!message->available, false}; ++ } ++ } ++ break; ++ } ++ + 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) + break; + + case EMC_TASK_PLAN_SYNCH_TYPE: ++ if (availability_pending.active && ++ availability_completion() != EMC_TASK_EXEC::DONE) return -1; + retval = emcTaskPlanSynch(); ++ availability_pending.active = false; ++ if (emcStatus->task.interpState == EMC_TASK_INTERP::IDLE) ++ emcTaskPlanClearWait(); + if (retval > INTERP_MIN_ERROR) { + retval = -1; + } +@@ -2887,6 +3051,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) + return EMC_TASK_EXEC::DONE; + break; + ++ case EMC_JOINT_SET_AVAILABILITY_TYPE: ++ case EMC_SPINDLE_SET_AVAILABILITY_TYPE: ++ return EMC_TASK_EXEC::WAITING_FOR_MOTION; ++ break; ++ + 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) + int status; // status of child from EMC_SYSTEM_CMD + pid_t pid; // pid returned from waitpid() + ++ // Abort flushes the program and queues its normal synchronization command. ++ // Keep admission closed until the cancelled resource finishes RT cleanup. ++ if (availability_pending.active && availability_pending.cancelled && ++ emcStatus->task.execState == EMC_TASK_EXEC::DONE) ++ emcStatus->task.execState = EMC_TASK_EXEC::WAITING_FOR_MOTION; ++ + // first check for an abandoned system command and abort it + if (emcSystemCmdPid != 0 && + emcStatus->task.execState != +@@ -3067,11 +3242,32 @@ static int emcTaskExecute(void) + break; + + case EMC_TASK_EXEC::WAITING_FOR_MOTION: ++ if (availability_pending.active) { ++ auto completion = availability_completion(); ++ if (completion == EMC_TASK_EXEC::WAITING_FOR_MOTION) break; ++ if (availability_pending.cancelled) { ++ availability_pending.active = false; ++ emcStatus->task.execState = EMC_TASK_EXEC::DONE; ++ retval = availability_pending.failed ? -1 : 0; ++ break; ++ } ++ if (completion == EMC_TASK_EXEC::ERROR) { ++ emcStatus->task.execState = completion; ++ break; ++ } ++ } + STEPPING_CHECK(); + if (emcStatus->motion.status == RCS_STATUS::ERROR) { + // emcOperatorError(0, "error in motion controller"); + emcStatus->task.execState = EMC_TASK_EXEC::ERROR; + } else if (emcStatus->motion.status == RCS_STATUS::DONE) { ++ if (emcStatus->task.mode == EMC_TASK_MODE::AUTO && ++ emcStatus->task.interpState != EMC_TASK_INTERP::IDLE && ++ !no_force_homing && !all_homed()) { ++ emcOperatorError(_("Cannot continue AUTO with unhomed joints")); ++ emcStatus->task.execState = EMC_TASK_EXEC::ERROR; ++ break; ++ } + emcStatus->task.execState = EMC_TASK_EXEC::DONE; + emcTaskEager = 1; + } +diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh +index 79dbeb68bc..223886ebb2 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 emcTaskCancelAvailability(); + int emcTaskSetMode(EMC_TASK_MODE mode); + 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 +--- a/src/emc/task/taskintf.cc ++++ b/src/emc/task/taskintf.cc +@@ -990,6 +990,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 ++ stat[joint_num].availability_state = joint->availability.state; ++ stat[joint_num].availability_fault = joint->availability.fault; ++ stat[joint_num].available = ++ joint->availability.state == EMCMOT_AVAILABILITY_AVAILABLE; + // for + // all + +@@ -1015,6 +1019,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) + return 0; + } + ++bool emcJointAvailabilityControlled(int index) ++{ ++ return index >= 0 && index < EMCMOT_MAX_JOINTS && ++ emcmotStatus.joint_status[index].availability.controlled; ++} ++ ++int emcJointSetAvailabilityConfig(int joint, int controlled, double timeout, ++ int volatile_home) ++{ ++ if (joint < 0 || joint >= EMCMOT_MAX_JOINTS || timeout <= 0.0) return -1; ++ emcmotCommand.command = EMCMOT_SET_JOINT_AVAILABILITY_CONFIG; ++ emcmotCommand.joint = joint; ++ emcmotCommand.availability_control = controlled; ++ emcmotCommand.availability_timeout = timeout; ++ emcmotCommand.volatile_home = volatile_home; ++ return usrmotWriteEmcmotCommand(&emcmotCommand); ++} ++ ++int emcJointSetAvailability(int joint, int available) ++{ ++ if (joint < 0 || joint >= EMCMOT_MAX_JOINTS) return -1; ++ emcmotCommand.command = EMCMOT_SET_JOINT_AVAILABILITY; ++ emcmotCommand.joint = joint; ++ emcmotCommand.available = !!available; ++ return usrmotWriteEmcmotCommand(&emcmotCommand); ++} ++ + // EMC_TRAJ functions + + int emcTrajSetJoints(int joints) +@@ -1839,9 +1870,11 @@ int emcMotionInit() + + int emcMotionHalt() + { +- int r1, r2, r3, r4, r5; ++ int r1, r2, r3, r4, r5, r6; + int t; + ++ // Revoke acquisition and deferred homing before individual jog aborts. ++ r6 = emcTrajAbort(); + r1 = -1; + for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { + if (0 == emcJointHalt(t)) { +@@ -1854,7 +1887,7 @@ int emcMotionHalt() + r4 = emcPositionSave(); + r5 = ini_hal_exit(); + +- return (r1 == 0 && r2 == 0 && r3 == 0 && r4 == 0 && r5 == 0) ? 0 : -1; ++ return (r1 == 0 && r2 == 0 && r3 == 0 && r4 == 0 && r5 == 0 && r6 == 0) ? 0 : -1; + } + + int emcMotionAbort() +@@ -1864,6 +1897,8 @@ int emcMotionAbort() + int r3 = 0; + int t; + ++ // Revoke acquisition and deferred homing before individual jog aborts. ++ r2 = emcTrajAbort(); + r1 = -1; + for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { + if (0 == emcJogAbort(t)) { +@@ -1871,8 +1906,6 @@ int emcMotionAbort() + } + } + +- r2 = emcTrajAbort(); +- + return (r1 == 0 && r2 == 0 && r3 == 0) ? 0 : -1; + } + +@@ -2057,10 +2090,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; ++ stat[s].availability_state = emcmotStatus.spindle_status[s].availability.state; ++ stat[s].availability_fault = emcmotStatus.spindle_status[s].availability.fault; ++ stat[s].available = emcmotStatus.spindle_status[s].availability.state == ++ EMCMOT_AVAILABILITY_AVAILABLE; + } + return 0; + } + ++bool emcSpindleAvailabilityControlled(int index) ++{ ++ return index >= 0 && index < EMCMOT_MAX_SPINDLES && ++ emcmotStatus.spindle_status[index].availability.controlled; ++} ++ ++int emcSpindleSetAvailabilityConfig(int spindle, int controlled, ++ int initial_available, double timeout) ++{ ++ if (spindle < 0 || spindle >= EMCMOT_MAX_SPINDLES || timeout <= 0.0) ++ return -1; ++ emcmotCommand.command = EMCMOT_SET_SPINDLE_AVAILABILITY_CONFIG; ++ emcmotCommand.spindle = spindle; ++ emcmotCommand.availability_control = controlled; ++ emcmotCommand.initial_availability = initial_available; ++ emcmotCommand.availability_timeout = timeout; ++ return usrmotWriteEmcmotCommand(&emcmotCommand); ++} ++ ++int emcSpindleSetAvailability(int spindle, int available) ++{ ++ if (spindle < 0 || spindle >= EMCMOT_MAX_SPINDLES) return -1; ++ emcmotCommand.command = EMCMOT_SET_SPINDLE_AVAILABILITY; ++ emcmotCommand.spindle = spindle; ++ emcmotCommand.available = !!available; ++ return usrmotWriteEmcmotCommand(&emcmotCommand); ++} ++ + int emcMotionUpdate(EMC_MOTION_STAT * stat) + { + int r1, r2, r3, r4; +@@ -2133,6 +2198,18 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) + + // FIXME-AJ: joints not axes + for (joint = 0; joint < stat->traj.joints; joint++) { ++ availability_status_t *availability = ++ &emcmotStatus.joint_status[joint].availability; ++ // The realtime fault path raises MOTION_ERROR and inhibits outputs. ++ // Keep the resource fault latched in status, but do not re-abort task ++ // forever after Abort has acknowledged that motion error: idle recovery ++ // must be able to execute its ordered release/synchronization command. ++ if (availability->controlled && ++ (availability->state == EMCMOT_AVAILABILITY_ENABLING || ++ availability->state == EMCMOT_AVAILABILITY_HOMING || ++ availability->state == EMCMOT_AVAILABILITY_DISABLING)) { ++ exec = 1; ++ } + if (stat->joint[joint].status == RCS_STATUS::ERROR) { + error = 1; + break; +@@ -2142,6 +2219,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) + break; + } + } ++ for (int spindle = 0; spindle < stat->traj.spindles; spindle++) { ++ availability_status_t *availability = ++ &emcmotStatus.spindle_status[spindle].availability; ++ if (availability->controlled && ++ (availability->state == EMCMOT_AVAILABILITY_ENABLING || ++ availability->state == EMCMOT_AVAILABILITY_HOMING || ++ availability->state == EMCMOT_AVAILABILITY_DISABLING)) ++ exec = 1; ++ } + if (stat->traj.status == RCS_STATUS::ERROR) { + 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 +--- 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) { + F2("min_hard_limit", minHardLimit); + F2("max_hard_limit", maxHardLimit); + F2("override_limits", overrideLimits); ++ F(available); ++ F(availability_state); ++ F(availability_fault); + return res; + } + #undef F +@@ -1463,6 +1466,9 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { + F(homed); + F(orient_state); + F(orient_fault); ++ F(available); ++ F(availability_state); ++ F(availability_fault); + return res; + } + #undef F +@@ -2021,6 +2027,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { + return Py_None; + } + ++static PyObject *set_joint_availability(pyCommandChannel *s, PyObject *o) { ++ EMC_JOINT_SET_AVAILABILITY m; ++ if(!PyArg_ParseTuple(o, "ip", &m.joint, &m.available)) return NULL; ++ emcSendCommand(s, m); ++ Py_RETURN_NONE; ++} ++ ++static PyObject *set_spindle_availability(pyCommandChannel *s, PyObject *o) { ++ EMC_SPINDLE_SET_AVAILABILITY m; ++ if(!PyArg_ParseTuple(o, "ip", &m.spindle, &m.available)) return NULL; ++ emcSendCommand(s, m); ++ Py_RETURN_NONE; ++} ++ + // 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[] = { + "JOINT can be a valid joint number (0-9), or -1 to home all joints.\n" + }, + {"unhome", (PyCFunction)unhome, METH_VARARGS, NULL}, ++ {"set_joint_availability", (PyCFunction)set_joint_availability, ++ METH_VARARGS, "set_joint_availability(JOINT, AVAILABLE)"}, ++ {"set_spindle_availability", (PyCFunction)set_spindle_availability, ++ METH_VARARGS, "set_spindle_availability(SPINDLE, AVAILABLE)"}, + {"jog", (PyCFunction)jog, METH_VARARGS, + "jog(JOG_CONTINUOUS, joint_flag, index, speed)\n" + "jog(JOG_INCREMENT, joint_flag, index, speed, increment)\n" +diff --git a/tests/motion-logger/basic/expected.builtin-startup.in b/tests/motion-logger/basic/expected.builtin-startup.in +index d8bd807543..8ed60094c8 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 + 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 +@@ -28,6 +29,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 +@@ -38,6 +40,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 +@@ -48,6 +51,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 +@@ -58,6 +62,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 +@@ -68,6 +73,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 +@@ -78,6 +84,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 +@@ -88,6 +95,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 +@@ -98,6 +106,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 +@@ -154,6 +163,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 +@@ -170,11 +181,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 +@@ -191,7 +202,6 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + SPINDLE_OFF + + # +@@ -207,6 +217,7 @@ ENABLE + # + + COORD ++ABORT + JOG_ABORT joint=0 + JOG_ABORT joint=1 + JOG_ABORT joint=2 +@@ -223,4 +234,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 +--- 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 + SET_JOINT_VEL_LIMIT joint=0, vel=400 + 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 +@@ -28,6 +29,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 ++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=-40, max=0 +@@ -38,6 +40,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 ++SET_JOINT_AVAILABILITY_CONFIG joint=2, controlled=0, timeout=5, volatile_home=0 + 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 + 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 ++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 +@@ -74,11 +79,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 +@@ -95,10 +100,10 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + SPINDLE_OFF + ENABLE + COORD ++ABORT + JOG_ABORT joint=0 + JOG_ABORT joint=1 + JOG_ABORT joint=2 +@@ -115,7 +120,6 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + 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 + 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 +--- 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 + 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 +@@ -33,6 +34,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 +@@ -43,6 +45,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_AXIS_POSITION_LIMITS axis=0, min=-40, max=0 + +@@ -84,6 +87,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 ++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 +@@ -100,7 +105,6 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + SPINDLE_OFF + DISABLE + JOINT_UNHOME joint=-2 +@@ -121,6 +125,7 @@ FREE + # The test UI immediately sent an Abort. + # + ++ABORT + JOG_ABORT joint=0 + JOG_ABORT joint=1 + JOG_ABORT joint=2 +@@ -154,6 +159,6 @@ JOG_ABORT joint=12 + JOG_ABORT joint=13 + JOG_ABORT joint=14 + JOG_ABORT joint=15 +-ABORT + SPINDLE_OFF ++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/pending-pre2/0018-availability-mcodes.patch b/linuxcnc-patches/pending-pre2/0018-availability-mcodes.patch new file mode 100644 index 0000000..7e8da6e --- /dev/null +++ b/linuxcnc-patches/pending-pre2/0018-availability-mcodes.patch @@ -0,0 +1,1296 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: Dariusz Majnert +Date: Thu, 17 Sep 2026 18:00:42 +0200 +Subject: [PATCH] availability-mcodes + +--- + 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 + +diff --git a/docs/src/gcode/m-code.adoc b/docs/src/gcode/m-code.adoc +index 1cb15521ad..0f3b65c8e4 100644 +--- a/docs/src/gcode/m-code.adoc ++++ b/docs/src/gcode/m-code.adoc +@@ -22,6 +22,7 @@ + |<> | Spindle Override Control + |<> | Adaptive Feed Control + |<> | Feed Stop Control ++|<> | Acquire or Release a Joint or Spindle Resource + |<> | 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. + * 'M53 P0' - disable the feed stop switch. The state of 'motion.feed-hold' + will have no effect on feed when M53 is not active. + ++[[mcode:m54-m55]] ++== M54, M55 Resource Availability ++ ++(((M54 Resource Acquire)))(((M55 Resource Release))) ++ ++`M54` acquires one availability-controlled physical resource and ++`M55` releases it. A `P` word selects a joint number and the ++standard `$` word selects a spindle number: ++ ++---- ++M54 P2 (acquire joint 2) ++M55 P2 (release joint 2) ++M54 $0 (acquire spindle 0) ++M55 $0 (release spindle 0) ++---- ++ ++Exactly one selector is required. Joint numbers must be nonnegative integers; ++spindle group selectors such as `$-1` are not supported. These commands are ++ordered barriers: subsequent G-code is not executed until the transition has ++completed or failed. LinuxCNC does not pair resources or roll back a preceding ++transition automatically. M54 and M55 must be the only command in their block; ++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. ++ ++The execution boundary is: finish preceding motion and IO, dispatch the runtime ++API request, wait for its shared completion boundary or failure, then continue. ++Held-position validation, homing whenever an acquired joint is unhomed, and normal ++task/interpreter synchronization are part of that runtime API completion for ++both NML/Python callers and M54. ACK alone does not permit continuation. ++Sequential M54/M55 blocks work in AUTO and MDI because each finishes before the ++next is interpreted. External direct requests require an idle task and cannot ++interrupt an in-program operation. Use Abort to cancel ACK wait or acquisition ++homing: it terminates the program and prevents subsequent blocks from executing, ++even if ACK arrives late. Ordinary M55/release does not cancel acquisition. ++Failure stops execution; subsequent blocks are not run. These M-codes use the same ++lifecycle as the NML/Python command API and provide no resource pairing or ++machine-specific switching sequence. ++ + [[mcode:m61]] + == M61 Set Current Tool + +diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc +index 5bb208e611..b2fd837823 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: + - M7 (activate coolant mist) + - M8 (activate coolant flood) + - M9 (deactivate coolant mist and flood) ++- M54, M55 (acquire and release joints or spindles) + - 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 + |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 | | +-|50-59 | | | | |M54 |M55 |M56 |M57 |M58 |M59 ++|50-59 | | | | | | |M56 |M57 |M58 |M59 + |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 + + All M-codes from `M100` to `M199` are user-defined M-codes already, and should not be remapped. + ++M54 and M55 are built-in resource acquisition and release commands. They may ++still be overridden with REMAP for compatibility with existing configurations; ++a configured remap supplies its own argument and execution behavior. ++ + All M-codes from `M200` to `M999` are available for remapping. + + == 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 +--- 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 + speed, change to the speed given with this command. */ + + extern void STOP_SPINDLE_TURNING(int spindle); ++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 +--- 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*/) {} ++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*/) {} +diff --git a/src/emc/rs274ngc/interp_array.cc b/src/emc/rs274ngc/interp_array.cc +index ba393b5b9f..606365a3bd 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 + 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 ++ 9, 9, 9, 9, 9, 9, -1, -1, -1, -1, // 59 + 4, 6, 5, 5, 5, 5, 5, 5, 5, -1, // 69 + 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 +--- a/src/emc/rs274ngc/interp_check.cc ++++ b/src/emc/rs274ngc/interp_check.cc +@@ -17,6 +17,7 @@ + #include + #include + #include ++#include + #include + #include + #include "rs274ngc.hh" +@@ -175,6 +176,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 + { ++ if (((block->m_modes[9] == 54) || (block->m_modes[9] == 55)) && ++ !is_user_defined_m_code(block, &(_setup), 9)) { ++ CHKS((block->p_flag == block->dollar_flag), ++ _("M54/M55 requires exactly one P joint selector or $ spindle selector")); ++ CHKS((!block->is_standalone(1)), ++ _("M54/M55 must be the only command in its block")); ++ CHKS((block->p_flag && (!isfinite(block->p_number) || block->p_number < 0 || ++ floor(block->p_number) != block->p_number || block->p_number > INT_MAX)), ++ _("M54/M55 P selector must be a non-negative integer joint number")); ++ CHKS((block->dollar_flag && (block->dollar_value != block->dollar_number || ++ block->dollar_number < 0)), ++ _("M54/M55 $ selector must be a non-negative integer spindle number")); ++ } + + 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 + (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) && +- (block->m_modes[9] != 51) && (! block->s_flag)), +- _("$ (spindle selection) word with no M3, M4, M5, M19, M51, G33, G33.1, G76, G95, G96 or G97 to use it")); ++ (block->m_modes[9] != 51) && (block->m_modes[9] != 54) && ++ (block->m_modes[9] != 55) && (! block->s_flag)), ++ _("$ (spindle selection) word with no M3, M4, M5, M19, M51, M54, M55, G33, G33.1, G76, G95, G96 or G97 to use it")); + } + + 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) && + (motion != G_74) && (motion != G_84) && + (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) && ++ (block->m_modes[9] != 55) && (block->m_modes[5] != 62) && (block->m_modes[5] != 63) && + (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" +- " 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 +--- 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)){ + } + } + ++if (((block->m_modes[9] == 54) || (block->m_modes[9] == 55)) && ONCE_M(9)) { ++ const int available = block->m_modes[9] == 54; ++ FINISH(); ++ if (block->p_flag) ++ SET_JOINT_AVAILABILITY((int)block->p_number, available); ++ else ++ SET_SPINDLE_AVAILABILITY(block->dollar_number, available); ++ // execute_block reaches its normal end, then returns the queue barrier. ++ ++ } ++ + if (is_user_defined_m_code(block, settings, 10) && ONCE_M(10)) { + 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 +--- 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) + return (INTERP_EXECUTE_FINISH); + ++ if ((block->m_modes[9] == 54 || block->m_modes[9] == 55) && ++ !is_user_defined_m_code(block, settings, 9)) ++ return INTERP_EXECUTE_FINISH; ++ + // All changes to settings are complete + 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 +--- 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 + block->line_number = -1; + block->n_number = -1; + block->motion_to_be = -1; ++ block->item_count = 0; + block->m_count = 0; + 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 +--- a/src/emc/rs274ngc/interp_internal.hh ++++ b/src/emc/rs274ngc/interp_internal.hh +@@ -454,12 +454,19 @@ struct block_struct + int line_number{}; + int saved_line_number{}; // value of sequence_number when a remap was encountered + int motion_to_be{}; ++ int item_count{}; // non-comment block items, excluding the line number + int m_count{}; + int m_modes[11]{}; + int user_m{}; + int dollar_number{}; ++ double dollar_value{}; // unrounded selector for standalone resource validation + int g_modes[GM_MAX_MODAL_GROUPS]{}; + ++ bool is_standalone(int argument_items = 0) const ++ { ++ return item_count == argument_items + 1; ++ } ++ + bool a_flag{}; + 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 +--- a/src/emc/rs274ngc/interp_read.cc ++++ b/src/emc/rs274ngc/interp_read.cc +@@ -20,6 +20,7 @@ + #include + #include + #include ++#include + #include + #include + #include +@@ -406,7 +407,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)); +- block->dollar_number = value; ++ block->dollar_value = value; ++ /* Preserve existing truncation for representable legacy selectors, but ++ retain the original value so M54/M55 can require an exact integer. */ ++ block->dollar_number = isfinite(value) && value >= INT_MIN && value <= INT_MAX ++ ? static_cast(value) : -2; + block->dollar_flag = true; + return INTERP_OK; + } +@@ -870,7 +875,9 @@ int Interp::read_items(block_pointer block, //!< pointer to a block being f + } + + for (; counter < length;) { ++ const char item = line[counter]; + CHP(read_one_item(line, &counter, block, parameters)); ++ if (item != '(' && item != ';') block->item_count++; + } + return INTERP_OK; + } +diff --git a/src/emc/rs274ngc/interp_remap.cc b/src/emc/rs274ngc/interp_remap.cc +index b13bdc0a5e..a944478d8d 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) + m_code == 7 || + m_code == 8 || + m_code == 9 || ++ m_code == 54 || ++ m_code == 55 || + 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 +--- a/src/emc/sai/saicanon.cc ++++ b/src/emc/sai/saicanon.cc +@@ -491,6 +491,11 @@ void STOP_SPINDLE_TURNING(int spindle) + _sai._spindle_turning[spindle] = CANON_STOPPED; + } + ++void SET_JOINT_AVAILABILITY(int joint, int available) ++{ PRINT("SET_JOINT_AVAILABILITY(%d, %d)\n", joint, available); } ++void SET_SPINDLE_AVAILABILITY(int spindle, int available) ++{ PRINT("SET_SPINDLE_AVAILABILITY(%d, %d)\n", spindle, available); } ++ + void SPINDLE_RETRACT() + {PRINT("SPINDLE_RETRACT()\n");} + +diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc +index 9f36a8de8e..f61e55bcfa 100644 +--- a/src/emc/task/emccanon.cc ++++ b/src/emc/task/emccanon.cc +@@ -3091,6 +3091,24 @@ void STOP_SPINDLE_TURNING(int s) + canon.spindle[s].dir = 0; + } + ++void SET_JOINT_AVAILABILITY(int joint, int available) ++{ ++ auto message = std::make_unique(); ++ flush_segments(); ++ message->joint = joint; ++ message->available = !!available; ++ interp_list.append(std::move(message)); ++} ++ ++void SET_SPINDLE_AVAILABILITY(int spindle, int available) ++{ ++ auto message = std::make_unique(); ++ flush_segments(); ++ message->spindle = spindle; ++ message->available = !!available; ++ interp_list.append(std::move(message)); ++} ++ + 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 From cbec1ff2bb4536bde42f4eb5735451ec85fca89c Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 12 Nov 2026 03:56:43 +0100 Subject: [PATCH 09/45] feat(linuxcnc): port patches 0004-0006 to v2.10.0-pre2 0004 (resumable Stop) is ported with fixes from two review rounds. Beyond the port it now reports STOPPED only at rest, keeps a pending spindle at-speed wait across Stop, finishes a whole chain of G33 moves and a queued G28.2 homing cycle before STOPPED, and leaves single-step mode on Resume. Its regression grows from 16 to 23 scenarios, three of them also run under the trapezoidal planner. A third round of fixes from the second review is still to come. 0005 is rebuilt on upstream's --disable-gui and --disable-manpages and reduced to what a backend-only install still needs: optional Tcl without Tk, no desktop entries, a launcher that never starts the graphical picker, and the Debian headless and nodoc profiles. --enable-headless and --disable-build-manpages no longer exist, so the Dockerfile and CI configure with upstream's options. 0006 (ordered realtime component search path) is ported onto upstream's rewritten halrmt and rtapi_app loader. The six patches build with -Werror on v2.10.0-pre2, also with --with-extra-rtlib-dirs and headless; the regression suite passes (326 of 326). --- .github/workflows/ci.yml | 4 +- Dockerfile | 4 +- .../0004-resumable-stop.patch | 1087 ++++++++++++++--- .../0005-headless-build-option.patch | 689 +++++++++++ ...dered-realtime-component-search-path.patch | 296 ++--- linuxcnc-patches/README.md | 75 +- .../0005-headless-build-option.patch | 852 ------------- 7 files changed, 1789 insertions(+), 1218 deletions(-) rename linuxcnc-patches/{pending-pre2 => }/0004-resumable-stop.patch (65%) create mode 100644 linuxcnc-patches/0005-headless-build-option.patch rename linuxcnc-patches/{pending-pre2 => }/0006-ordered-realtime-component-search-path.patch (81%) delete mode 100644 linuxcnc-patches/pending-pre2/0005-headless-build-option.patch diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e03839e..0ff4411 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/Dockerfile b/Dockerfile index 71e1722..fd466b1 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/linuxcnc-patches/pending-pre2/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch similarity index 65% rename from linuxcnc-patches/pending-pre2/0004-resumable-stop.patch rename to linuxcnc-patches/0004-resumable-stop.patch index bff1a70..75e4aa1 100644 --- a/linuxcnc-patches/pending-pre2/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -4,81 +4,95 @@ 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 that no longer stays behind in the shared motion command, so a later S-word change still arms the next feed's at-speed wait. +- 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. Halting at the start of the next G33 left the axis behind the turning spindle and Resume lunged to catch up. +- 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, and the planner drops its pointer to the synchronized segment when that run is over or the queue empties. +- motion-logger logs EMCMOT_STOP. +- tests/resumable-stop gains the scenarios dwell-atspeed, homing, homing-interrupted, speed-change-atspeed, queued-feed-atspeed, g33-chain and step-resume-stopping, fails if STOPPED is reported while moving, re-runs three 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/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/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/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(-) + docs/src/config/python-interface.adoc | 12 + + docs/src/gui/halui.adoc | 3 +- + docs/src/man/man1/halui.1.adoc | 5 +- + src/emc/motion-logger/motion-logger.c | 4 + + src/emc/motion/command.c | 34 +- + src/emc/motion/control.c | 13 + + 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 | 358 +++++- + src/emc/task/taskintf.cc | 34 +- + src/emc/tp/tp.c | 110 +- + src/emc/tp/tp_types.h | 7 + + src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + + src/emc/usr_intf/halui.cc | 9 +- + tests/resumable-stop/README | 30 + + tests/resumable-stop/after-abort.ngc | 4 + + tests/resumable-stop/checkresult | 4 + + tests/resumable-stop/core_sim.hal | 42 + + tests/resumable-stop/css.ngc | 6 + + tests/resumable-stop/dwell-atspeed.ngc | 7 + + tests/resumable-stop/dwell.ngc | 5 + + tests/resumable-stop/feed-atspeed.ngc | 7 + + tests/resumable-stop/fperrev.ngc | 7 + + tests/resumable-stop/g76.ngc | 7 + + tests/resumable-stop/homing.ngc | 6 + + 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/speed-change.ngc | 9 + + tests/resumable-stop/tap.ngc | 7 + + tests/resumable-stop/test-ui.py | 1143 +++++++++++++++++ + tests/resumable-stop/test.ini | 98 ++ + tests/resumable-stop/test.ngc | 9 + + tests/resumable-stop/test.sh | 69 + + tests/resumable-stop/thread-chain.ngc | 8 + + tests/resumable-stop/thread-then-steps.ngc | 10 + + tests/resumable-stop/thread.ngc | 7 + + tests/resumable-stop/tool.tbl | 1 + + 44 files changed, 2165 insertions(+), 22 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-atspeed.ngc create mode 100644 tests/resumable-stop/dwell.ngc + create mode 100644 tests/resumable-stop/feed-atspeed.ngc create mode 100644 tests/resumable-stop/fperrev.ngc create mode 100644 tests/resumable-stop/g76.ngc + create mode 100644 tests/resumable-stop/homing.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/speed-change.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-chain.ngc + create mode 100644 tests/resumable-stop/thread-then-steps.ngc create mode 100644 tests/resumable-stop/thread.ngc create mode 100644 tests/resumable-stop/tool.tbl -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..fa546b7 100644 --- a/docs/src/config/python-interface.adoc +++ b/docs/src/config/python-interface.adoc @@ -209,6 +209,10 @@ see <> for an example. @@ -92,13 +106,15 @@ index 219a873d24..0278680c8e 100644 *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 +644,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 +122,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 +136,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,21 +151,39 @@ 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..62dc717 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,12 @@ 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. */ ++ emcmotInternal->coord_tp.stopping = 0; ++ emcmotInternal->coord_tp.stop_tc = 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 +1329,15 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) emcmotStatus->paused = 1; break; @@ -165,7 +199,7 @@ 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 +1357,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) /* can happen at any time */ rtapi_print_msg(RTAPI_MSG_DBG, "RESUME"); emcmotStatus->stepping = 0; @@ -177,7 +211,7 @@ index fa7beb3c72..efe02af73d 100644 break; case EMCMOT_STEP: -@@ -1665,7 +1680,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1800,7 +1818,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) } apply_spindle_limits(&emcmotStatus->spindle_status[n]); } @@ -190,12 +224,29 @@ index fa7beb3c72..efe02af73d 100644 // check whether it's passed correctly if (!emcmotStatus->atspeed_next_feed){ +@@ -1839,8 +1861,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; + + case EMCMOT_SPINDLE_ORIENT: diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 9e23ea480a..0a5d550480 100644 +index 17fb96b..fd88fd9 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; +@@ -2071,6 +2071,19 @@ static void output_to_hal(void) + hal_set_real(emcmot_hal_data->requested_vel, 0.0); } + /* @@ -215,10 +266,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 +278,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..eb11553 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -81,6 +81,7 @@ to another. @@ -246,7 +297,7 @@ 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.. +@@ -645,6 +647,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 +306,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..25e5f5a 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 +319,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 +329,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 +338,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 +347,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 +359,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 +367,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 +375,15 @@ index 282edd98ec..4665d2fe6c 100644 cms->update(homed); } -@@ -1380,6 +1397,7 @@ void EMC_TASK_STAT::update(CMS * cms) +@@ -1388,6 +1405,7 @@ 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(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 +1761,7 @@ void EMC_TRAJ_STAT::update(CMS * cms) cms->update(queueFull); cms->update(id); cms->update(paused); @@ -340,7 +391,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 +1924,11 @@ void EMC_TRAJ_PAUSE::update(CMS * cms) EMC_TRAJ_CMD_MSG::update(cms); } @@ -353,7 +404,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..6c61f5a 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -93,6 +93,7 @@ struct PM_CARTESIAN; @@ -364,7 +415,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 +423,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,13 @@ enum class EMC_TASK_INTERP { WAITING = 4 }; @@ -386,7 +437,7 @@ index 20bb4bba56..eadd123b99 100644 // types for motion control enum class EMC_TRAJ_MODE { FREE = 1, // independent-axis motion, -@@ -364,6 +373,7 @@ extern int emcTrajEnable(); +@@ -369,6 +378,7 @@ extern int emcTrajEnable(); extern int emcTrajDisable(); extern int emcTrajAbort(); extern int emcTrajPause(); @@ -395,10 +446,10 @@ index 20bb4bba56..eadd123b99 100644 extern int emcTrajForward(); extern int emcTrajStep(); diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh -index 38f67b98bd..6b94fa62f0 100644 +index 3d8c617..0d4ab6c 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 +465,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 +473,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 +481,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 +489,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 +505,19 @@ 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,7 @@ 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 + // 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..a6b2345 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 +525,15 @@ 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,7 @@ 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), callLevel(0), + callStack{}, motionLine(0), - currentLine(0), -@@ -186,6 +188,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() +@@ -203,6 +205,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() spindle_scale(1.0), css_maximum(0.0), css_factor(1.0), @@ -490,7 +541,7 @@ index 6e068c2708..734079d3af 100644 state(0), direction(0), brake(1), -@@ -194,6 +197,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() +@@ -211,6 +214,7 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() orient_state(0), orient_fault(0), spindle_override_enabled(OFF), @@ -499,7 +550,7 @@ index 6e068c2708..734079d3af 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 3bf13a702d..2810757914 100644 +index a3b5256..564e4a1 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -124,6 +124,37 @@ static int emcTaskEager = 0; @@ -540,7 +591,18 @@ index 3bf13a702d..2810757914 100644 // delay counter static double taskExecDelayTimeout = 0.0; -@@ -487,6 +518,9 @@ extern int emcTaskMopup(); +@@ -414,6 +445,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 +557,9 @@ extern int emcTaskMopup(); void readahead_reading(void) { @@ -550,7 +612,7 @@ index 3bf13a702d..2810757914 100644 int readRetval; int execRetval; -@@ -701,6 +735,9 @@ static void mdi_execute_hook(void) +@@ -737,6 +775,9 @@ static void mdi_execute_hook(void) void readahead_waiting(void) { @@ -560,7 +622,7 @@ 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 +822,197 @@ static bool allow_while_idle_type() { return 0; } @@ -609,7 +671,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) { @@ -656,7 +718,16 @@ index 3bf13a702d..2810757914 100644 +{ + switch (emcStatus->task.stopState) { + case EMC_TASK_STOP_STATE::STOPPING: { -+ if (!emcStatus->motion.traj.stopped) { ++ /* ++ * A queued G28.2 homing cycle cannot be paused and resumed part way, ++ * so, like position-synchronized motion, it runs to completion before ++ * Stop is reached. 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. ++ */ ++ if (emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_HOMING || ++ !emcStatus->motion.traj.stopped) { + return; + } + @@ -688,7 +759,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; + } + } @@ -749,7 +820,7 @@ index 3bf13a702d..2810757914 100644 /* emcTaskPlan() -@@ -773,6 +992,28 @@ static int emcTaskPlan(void) +@@ -809,6 +1041,29 @@ static int emcTaskPlan(void) return retval; } @@ -764,7 +835,8 @@ index 3bf13a702d..2810757914 100644 + 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) { @@ -778,7 +850,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 +1989,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 +2193,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcTrajPause(); break; @@ -790,7 +870,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 +2300,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE: wait_spindle_orient_complete_msg = reinterpret_cast(cmd); @@ -802,7 +882,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 +2365,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_ORIENT_TYPE: spindle_orient_msg = reinterpret_cast(cmd); @@ -817,7 +897,7 @@ 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 +2465,52 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // task commands @@ -828,8 +908,14 @@ index 3bf13a702d..2810757914 100644 + emcStatus->motion.traj.queue > 0 || + interp_list.len() > 0 || + emcTaskCommand != nullptr; ++ // 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; @@ -864,7 +950,7 @@ 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 +2534,9 @@ 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 @@ -874,7 +960,7 @@ index 3bf13a702d..2810757914 100644 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 +2581,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_SET_STATE_TYPE: state_msg = reinterpret_cast(cmd); @@ -884,7 +970,7 @@ index 3bf13a702d..2810757914 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2368,11 +2672,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2484,11 +2809,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -897,7 +983,7 @@ index 3bf13a702d..2810757914 100644 retval = 0; break; -@@ -2569,6 +2870,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3023,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -905,7 +991,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 +3069,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -913,10 +999,10 @@ 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) +@@ -3040,6 +3365,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -935,7 +1021,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 +3963,7 @@ int main(int argc, char *argv[]) prev_traj_enabled = emcStatus->motion.traj.enabled; // synchronize subordinate states if (emcStatus->io.aux.estop) { @@ -943,7 +1029,7 @@ index 3bf13a702d..2810757914 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3406,6 +3723,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4045,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -951,7 +1037,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 +4081,12 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -964,7 +1050,7 @@ index 3bf13a702d..2810757914 100644 // update task-specific status emcTaskUpdate(&emcStatus->task); -@@ -3461,6 +3785,9 @@ int main(int argc, char *argv[]) +@@ -3762,6 +4107,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 +1061,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..689031d 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 +1078,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 +1086,51 @@ 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,6 +2073,23 @@ int emcSpindleOrient(int spindle, double orientation, int mode) + } + + ++/* ++ * emcSpindleSpeed() sends EMCMOT_SPINDLE_ON with whatever at-speed request the ++ * last spindle command left in emcmotCommand. A resumable Stop's ++ * EMCMOT_SPINDLE_AT_SPEED_PRESERVE must not become that request, or a later ++ * S-word change would leave the next feed's at-speed wait unarmed. ++ */ ++static int writeSpindleCommand(int wait_for_at_speed) ++{ ++ unsigned char previous = emcmotCommand.wait_for_spindle_at_speed; ++ 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.wait_for_spindle_at_speed = previous; ++ } ++ return retval; ++} ++ + int emcSpindleOn(int spindle, double speed, double css_factor, double offset, int wait_for_at_speed) + { + emcmotCommand.command = EMCMOT_SPINDLE_ON; +@@ -2073,8 +2098,7 @@ int emcSpindleOn(int spindle, double speed, double css_factor, double offset, in + 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(wait_for_at_speed); + } + + int emcSpindleOff(int spindle, int wait_for_at_speed) +@@ -2082,8 +2106,7 @@ 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(wait_for_at_speed); + } + + int emcSpindleBrakeRelease(int spindle) +@@ -2137,6 +2160,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 +1141,36 @@ 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..f138f62 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,25 @@ STATIC int tpGetMachineActiveLimit(double * const act_limit, PmCartesian const * + } + + ++/** ++ * Check whether a resumable Stop holds a segment at feed scale 0. ++ * Stop lets the position-synchronized segment that was active when it ++ * arrived (stop_tc) run to its end, together with the position-synchronized ++ * segments after it that continue the same spindle synchronization without ++ * waiting for a new index pulse: stopping part way along that run would ++ * leave the axis behind the spindle. Every other segment is held. ++ */ ++STATIC bool tpStopHolds(TP_STRUCT const * const tp, ++ TC_STRUCT const * const tc) { ++ if (!tp->stopping || tc == tp->stop_tc) { ++ return false; ++ } ++ return !(tp->stop_tc && ++ tc->synchronized == TC_SYNC_POSITION && ++ 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 +258,11 @@ STATIC double tpGetFeedScale(TP_STRUCT const * const tp, return 0.0; } //All reasons to disable feed override go here @@ -1023,11 +1179,11 @@ 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 +478,8 @@ int tpClear(TP_STRUCT * const tp) tp->depth = tp->activeDepth = 0; tp->aborting = 0; tp->pausing = 0; @@ -1036,7 +1192,7 @@ index e5667b3f29..e48127c5a9 100644 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 +2841,24 @@ int tpCalculateSCurveAccel(TP_STRUCT const * const tp, TC_STRUCT * const tc, TC_ } // Check pause/abort state @@ -1045,7 +1201,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 +1220,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 +3364,9 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) tpUpdateMovementStatus(tp, NULL); @@ -1075,7 +1231,7 @@ index e5667b3f29..e48127c5a9 100644 } /** Wrapper function to unlock rotary axes */ -@@ -3711,6 +3731,9 @@ STATIC int tpUpdateCycle(TP_STRUCT * const tp, +@@ -3812,6 +3851,9 @@ STATIC int tpUpdateCycle(TP_STRUCT * const tp, int planner_type = GET_TRAJ_PLANNER_TYPE(); if(mode == NULL) planner_type = 0; @@ -1085,13 +1241,15 @@ index e5667b3f29..e48127c5a9 100644 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 +4295,39 @@ 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) { ++ // tcqInit() has emptied the slot stop_tc pointed at. ++ tp->stop_tc = 0; + tp->pausing = 1; + emcmotStatus->stopped = 1; + } @@ -1101,20 +1259,48 @@ 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; drop the pointer ++ // before its queue slot can be reused. ++ tp->stop_tc = 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; + } + tc_debug_print("-------------------\n"); -@@ -4227,7 +4268,19 @@ int tpPause(TP_STRUCT * const tp) +@@ -4270,6 +4341,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 +4448,19 @@ int tpPause(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -1135,7 +1321,7 @@ index e5667b3f29..e48127c5a9 100644 return TP_ERR_OK; } -@@ -4237,6 +4290,9 @@ int tpResume(TP_STRUCT * const tp) +@@ -4375,6 +4470,9 @@ int tpResume(TP_STRUCT * const tp) return TP_ERR_FAIL; } tp->pausing = 0; @@ -1146,10 +1332,10 @@ index e5667b3f29..e48127c5a9 100644 } diff --git a/src/emc/tp/tp_types.h b/src/emc/tp/tp_types.h -index 6687ef3a2d..8d8aa3a362 100644 +index 0e9ab84..57fcada 100644 --- a/src/emc/tp/tp_types.h +++ b/src/emc/tp/tp_types.h -@@ -136,6 +136,13 @@ typedef struct { +@@ -149,6 +149,13 @@ typedef struct { syncdio_t syncdio; //record tpSetDout's here @@ -1164,10 +1350,10 @@ index 6687ef3a2d..8d8aa3a362 100644 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..13069fb 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,7 @@ static PyMemberDef Stat_members[] = { }, { "exec_state", T_INT, O(task.execState), READONLY, NULL}, { "interp_state", T_INT, O(task.interpState), READONLY, NULL}, @@ -1175,7 +1361,7 @@ index 3345c0a6a0..750663187b 100644 { "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 +2004,13 @@ static PyObject *emcabort(pyCommandChannel *s, PyObject * /*o*/) { return Py_None; } @@ -1189,7 +1375,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 +2413,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,7 +1383,7 @@ 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 +3392,11 @@ 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); @@ -1210,10 +1396,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 +1413,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) @@ -1238,10 +1424,10 @@ index 6e7c462197..bcb62bf9f9 100644 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 +index 0000000..ee83269 --- /dev/null +++ b/tests/resumable-stop/README -@@ -0,0 +1,10 @@ +@@ -0,0 +1,30 @@ +Verify resumable Stop preserves an active AUTO program and resumes or +single-steps it. + @@ -1249,12 +1435,32 @@ index 0000000000..e457195324 +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. 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 and fperrev scenarios run a second time with the default ++trapezoidal planner (PLANNER_TYPE = 0). 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, 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. ++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. diff --git a/tests/resumable-stop/after-abort.ngc b/tests/resumable-stop/after-abort.ngc new file mode 100644 -index 0000000000..df711f6b3d +index 0000000..df711f6 --- /dev/null +++ b/tests/resumable-stop/after-abort.ngc @@ -0,0 +1,4 @@ @@ -1264,16 +1470,17 @@ index 0000000000..df711f6b3d +M2 diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult new file mode 100755 -index 0000000000..c491888fc8 +index 0000000..dcdfb2d --- /dev/null +++ b/tests/resumable-stop/checkresult -@@ -0,0 +1,3 @@ +@@ -0,0 +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 26 +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 +index 0000000..bbc7166 --- /dev/null +++ b/tests/resumable-stop/core_sim.hal @@ -0,0 +1,42 @@ @@ -1321,7 +1528,7 @@ index 0000000000..bbc7166567 +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 +index 0000000..382aaff --- /dev/null +++ b/tests/resumable-stop/css.ngc @@ -0,0 +1,6 @@ @@ -1331,9 +1538,22 @@ index 0000000000..382aaffcec +G1 X10 F60 +M5 +M2 +diff --git a/tests/resumable-stop/dwell-atspeed.ngc b/tests/resumable-stop/dwell-atspeed.ngc +new file mode 100644 +index 0000000..be7e5af +--- /dev/null ++++ b/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/tests/resumable-stop/dwell.ngc b/tests/resumable-stop/dwell.ngc new file mode 100644 -index 0000000000..f7a54f80d5 +index 0000000..f7a54f8 --- /dev/null +++ b/tests/resumable-stop/dwell.ngc @@ -0,0 +1,5 @@ @@ -1342,9 +1562,22 @@ index 0000000000..f7a54f80d5 +G4 P3 +G1 X5 F600 +M2 +diff --git a/tests/resumable-stop/feed-atspeed.ngc b/tests/resumable-stop/feed-atspeed.ngc +new file mode 100644 +index 0000000..8af98dc +--- /dev/null ++++ b/tests/resumable-stop/feed-atspeed.ngc +@@ -0,0 +1,7 @@ ++G21 G90 ++G0 X0 ++F600 ++S300 M3 ++G1 X5 ++M5 ++M2 diff --git a/tests/resumable-stop/fperrev.ngc b/tests/resumable-stop/fperrev.ngc new file mode 100644 -index 0000000000..92dbe87412 +index 0000000..92dbe87 --- /dev/null +++ b/tests/resumable-stop/fperrev.ngc @@ -0,0 +1,7 @@ @@ -1357,7 +1590,7 @@ index 0000000000..92dbe87412 +M2 diff --git a/tests/resumable-stop/g76.ngc b/tests/resumable-stop/g76.ngc new file mode 100644 -index 0000000000..1c6a3ea852 +index 0000000..1c6a3ea --- /dev/null +++ b/tests/resumable-stop/g76.ngc @@ -0,0 +1,7 @@ @@ -1368,9 +1601,21 @@ index 0000000000..1c6a3ea852 +G1 X20 F600 +M5 +M2 +diff --git a/tests/resumable-stop/homing.ngc b/tests/resumable-stop/homing.ngc +new file mode 100644 +index 0000000..4f214ea +--- /dev/null ++++ b/tests/resumable-stop/homing.ngc +@@ -0,0 +1,6 @@ ++G21 G90 ++F600 ++G1 X5 ++G28.2 P0 ++G1 X30 ++M2 diff --git a/tests/resumable-stop/multi-spindle.ngc b/tests/resumable-stop/multi-spindle.ngc new file mode 100644 -index 0000000000..ba2e66f6da +index 0000000..ba2e66f --- /dev/null +++ b/tests/resumable-stop/multi-spindle.ngc @@ -0,0 +1,4 @@ @@ -1380,7 +1625,7 @@ index 0000000000..ba2e66f6da +M2 diff --git a/tests/resumable-stop/orient.ngc b/tests/resumable-stop/orient.ngc new file mode 100644 -index 0000000000..bb08db3994 +index 0000000..bb08db3 --- /dev/null +++ b/tests/resumable-stop/orient.ngc @@ -0,0 +1,6 @@ @@ -1392,7 +1637,7 @@ index 0000000000..bb08db3994 +M2 diff --git a/tests/resumable-stop/pause.ngc b/tests/resumable-stop/pause.ngc new file mode 100644 -index 0000000000..6fe71e34bc +index 0000000..6fe71e3 --- /dev/null +++ b/tests/resumable-stop/pause.ngc @@ -0,0 +1,7 @@ @@ -1405,7 +1650,7 @@ index 0000000000..6fe71e34bc +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 +index 0000000..c562a57 --- /dev/null +++ b/tests/resumable-stop/rapid-then-feed.ngc @@ -0,0 +1,7 @@ @@ -1418,7 +1663,7 @@ index 0000000000..c562a572dc +M2 diff --git a/tests/resumable-stop/single-step.ngc b/tests/resumable-stop/single-step.ngc new file mode 100644 -index 0000000000..8955e51e55 +index 0000000..8955e51 --- /dev/null +++ b/tests/resumable-stop/single-step.ngc @@ -0,0 +1,10 @@ @@ -1432,9 +1677,24 @@ index 0000000000..8955e51e55 +M9 +M5 +M2 +diff --git a/tests/resumable-stop/speed-change.ngc b/tests/resumable-stop/speed-change.ngc +new file mode 100644 +index 0000000..927c3ca +--- /dev/null ++++ b/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/tests/resumable-stop/tap.ngc b/tests/resumable-stop/tap.ngc new file mode 100644 -index 0000000000..3060ac429e +index 0000000..3060ac4 --- /dev/null +++ b/tests/resumable-stop/tap.ngc @@ -0,0 +1,7 @@ @@ -1447,10 +1707,10 @@ index 0000000000..3060ac429e +M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py new file mode 100755 -index 0000000000..d3c9646b11 +index 0000000..18ea01b --- /dev/null +++ b/tests/resumable-stop/test-ui.py -@@ -0,0 +1,772 @@ +@@ -0,0 +1,1143 @@ +#!/usr/bin/env python3 + +import math @@ -1477,7 +1737,7 @@ index 0000000000..d3c9646b11 + if predicate(): + return + time.sleep(0.02) -+ fail(message) ++ fail(message() if callable(message) else message) + + +def wait_complete(message, timeout=10.0): @@ -1586,6 +1846,16 @@ index 0000000000..d3c9646b11 + 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( @@ -1827,8 +2097,6 @@ index 0000000000..d3c9646b11 + 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: @@ -2115,6 +2383,50 @@ index 0000000000..d3c9646b11 + 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_IDLE ++ and 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_multi_spindle_stop_resume_test(): + open_auto_program("multi-spindle.ngc") + c.spindle(linuxcnc.SPINDLE_FORWARD, 120.0, 0) @@ -2197,6 +2509,318 @@ index 0000000000..d3c9646b11 + 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): ++ 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"], ++ 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. ++ c.program_stop() ++ wait_for( ++ lambda: s.stop_state == linuxcnc.STOP_STOPPING, ++ "Stop was not accepted during G28.2", ++ timeout=1.0, ++ ) ++ 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) ++ 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_IDLE ++ 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, ++ ) ++ ++ ++def run_step_then_resume_while_stopping_test(): ++ # Step followed by Resume while Stop waits for G33 must resume the ++ # program normally rather than single-step it. ++ 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, ++ ) ++ ++ # Stop completes only on STOPPED, so do not wait for it here. ++ c.program_stop() ++ wait_for( ++ lambda: s.stop_state == linuxcnc.STOP_STOPPING, ++ "Stop did not wait for the active G33", ++ timeout=1.0, ++ ) ++ c.auto(linuxcnc.AUTO_STEP) ++ c.auto(linuxcnc.AUTO_RESUME) ++ s.poll() ++ if s.stop_state != linuxcnc.STOP_STOPPING: ++ fail("G33 finished before Step and Resume were sent") ++ ++ 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), ++ lambda: "program did not run to completion after Step and Resume: " ++ "X=%.3f interp=%d paused=%d stop=%d" ++ % (s.position[0], s.interp_state, s.task_paused, s.stop_state), ++ timeout=20.0, ++ ) ++ assert_outputs_stopped_after_program() ++ ++ +SCENARIOS = { + "idle-rejected": run_idle_program_stop_rejected_test, + "ordinary": run_ordinary_stop_resume_test, @@ -2212,8 +2836,15 @@ index 0000000000..d3c9646b11 + "rigid-tap": run_rigid_tap_stop_resume_test, + "orientation": run_spindle_orientation_stop_test, + "dwell": run_dwell_stop_resume_test, ++ "dwell-atspeed": run_dwell_atspeed_barrier_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, ++ "step-resume-stopping": run_step_then_resume_while_stopping_test, +} + +scenario = os.environ.get("RESUMABLE_STOP_SCENARIO") @@ -2225,10 +2856,10 @@ index 0000000000..d3c9646b11 +sys.exit(0) diff --git a/tests/resumable-stop/test.ini b/tests/resumable-stop/test.ini new file mode 100644 -index 0000000000..b73c0956b5 +index 0000000..a422788 --- /dev/null +++ b/tests/resumable-stop/test.ini -@@ -0,0 +1,95 @@ +@@ -0,0 +1,98 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0x0 @@ -2280,7 +2911,10 @@ index 0000000000..b73c0956b5 + +[JOINT_0] +TYPE = LINEAR -+HOME = 0 ++# 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 @@ -2326,7 +2960,7 @@ index 0000000000..b73c0956b5 +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 +index 0000000..416044b --- /dev/null +++ b/tests/resumable-stop/test.ngc @@ -0,0 +1,9 @@ @@ -2341,10 +2975,10 @@ index 0000000000..416044b08c +M2 diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh new file mode 100755 -index 0000000000..7a9a863436 +index 0000000..7c34d26 --- /dev/null +++ b/tests/resumable-stop/test.sh -@@ -0,0 +1,42 @@ +@@ -0,0 +1,69 @@ +#!/bin/bash -e + +set -o pipefail @@ -2369,27 +3003,84 @@ index 0000000000..7a9a863436 + rigid-tap + orientation + dwell ++ dwell-atspeed + multi-spindle + css ++ homing ++ homing-interrupted ++ speed-change-atspeed ++ queued-feed-atspeed ++ g33-chain ++ step-resume-stopping +) + -+scenario_log=$(mktemp) -+trap 'rm -f "$scenario_log"' EXIT ++# test.ini selects the jerk-limited planner. Repeat the scenarios whose ++# unsynchronized motion is most planner dependent with the default ++# trapezoidal planner. ++trapezoidal_scenarios=( ++ ordinary ++ single-step ++ fperrev ++) + -+for scenario in "${scenarios[@]}"; do -+ echo "Running resumable-stop scenario: $scenario" ++scenario_log=$(mktemp) ++trapezoidal_ini=test-trapezoidal.ini ++trap 'rm -f "$scenario_log" "$trapezoidal_ini"' EXIT ++sed 's/^PLANNER_TYPE = 1$/PLANNER_TYPE = 0/' test.ini > "$trapezoidal_ini" ++grep -q '^PLANNER_TYPE = 0$' "$trapezoidal_ini" ++ ++run_scenario() { ++ local ini=$1 scenario=$2 ++ echo "Running resumable-stop scenario: $scenario ($ini)" + : > "$scenario_log" -+ RESUMABLE_STOP_SCENARIO="$scenario" linuxcnc -r test.ini 2>&1 | ++ 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 ++} ++ ++for scenario in "${scenarios[@]}"; do ++ run_scenario test.ini "$scenario" ++done ++for scenario in "${trapezoidal_scenarios[@]}"; do ++ run_scenario "$trapezoidal_ini" "$scenario" +done +echo "resumable stop scenarios complete" +diff --git a/tests/resumable-stop/thread-chain.ngc b/tests/resumable-stop/thread-chain.ngc +new file mode 100644 +index 0000000..ca80839 +--- /dev/null ++++ b/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/tests/resumable-stop/thread-then-steps.ngc b/tests/resumable-stop/thread-then-steps.ngc +new file mode 100644 +index 0000000..e744543 +--- /dev/null ++++ b/tests/resumable-stop/thread-then-steps.ngc +@@ -0,0 +1,10 @@ ++G21 G90 ++G0 X0 Z0 ++S6 M3 ++G33 Z-5 K10 ++G1 X5 F600 ++M8 ++G1 X10 ++M9 ++M5 ++M2 diff --git a/tests/resumable-stop/thread.ngc b/tests/resumable-stop/thread.ngc new file mode 100644 -index 0000000000..5976979e44 +index 0000000..5976979 --- /dev/null +++ b/tests/resumable-stop/thread.ngc @@ -0,0 +1,7 @@ @@ -2402,7 +3093,7 @@ index 0000000000..5976979e44 +M2 diff --git a/tests/resumable-stop/tool.tbl b/tests/resumable-stop/tool.tbl new file mode 100644 -index 0000000000..68840ea75c +index 0000000..68840ea --- /dev/null +++ b/tests/resumable-stop/tool.tbl @@ -0,0 +1 @@ diff --git a/linuxcnc-patches/0005-headless-build-option.patch b/linuxcnc-patches/0005-headless-build-option.patch new file mode 100644 index 0000000..473948d --- /dev/null +++ b/linuxcnc-patches/0005-headless-build-option.patch @@ -0,0 +1,689 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: linuxcnc-node maintainers +Date: Tue, 21 Jul 2026 20:00:00 +0200 +Subject: [PATCH] Complete headless backend-only builds on top of --disable-gui + +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/.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 096b3f4..da87935 100755 +--- a/debian/configure ++++ b/debian/configure +@@ -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="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='' ++fi + YAPPS_RUNTIME="python3-yapps" + DEBHELPER="debhelper (>= 12)" + COMPAT="12" +@@ -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" \ ++ -e "s#@GUI_RUNTIME_DEPENDS@#$GUI_RUNTIME_DEPENDS#g" \ ++ -e "s#@GUI_RUNTIME_RECOMMENDS@#$GUI_RUNTIME_RECOMMENDS#g" \ + -e "s#@KERNEL_DEPENDS@#$KERNEL_DEPENDS#g" \ + -e "s#@KERNEL_DEPENDS_BUILD@#$KERNEL_DEPENDS_BUILD#g" \ + -e "s#@KERNEL_HEADERS@#$KERNEL_HEADERS#g" \ +@@ -209,7 +219,14 @@ subst control.top.in > control + echo >> control + subst control.main-pkg.in >> control + +-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 ++ # GUI assets the build still installs but the headless package omits ++ subst linuxcnc-headless.not-installed.in > not-installed ++else ++ 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 + +diff --git a/debian/control.main-pkg.in b/debian/control.main-pkg.in +index e964cbb..7017e20 100644 +--- a/debian/control.main-pkg.in ++++ b/debian/control.main-pkg.in +@@ -13,32 +13,16 @@ Depends: + ${shlibs:Depends}, + @KERNEL_DEPENDS@, + @MODUTILS_DEPENDS@, +- blt, +- mesa-utils, +- python3-tk, ++ @GUI_RUNTIME_DEPENDS@, + python3-numpy, +- python3-cairo, +- python3-gi-cairo, +- python3-opengl, +- python3-configobj, +- python3-xlib, +- libgtksourceview-4-dev, + tcl@TCLTK_VERSION@, +- tk@TCLTK_VERSION@, +- bwidget (>= 1.7), + tclreadline, +- tclx, +- @QTVCP_DEPENDS@, + procps, psmisc, + udev + Recommends: +- linuxcnc-doc-en | linuxcnc-doc, +- librsvg2-dev, +- x11-xserver-utils, ++ @GUI_RUNTIME_RECOMMENDS@, + python3-paho-mqtt, +- @EXTRA_RECOMMENDS@, +- @PYTHON_IMAGING@, +- @PYTHON_IMAGING_TK@ ++ @EXTRA_RECOMMENDS@ + Suggests: + mesaflash, + python3-poppler-qt5, +diff --git a/debian/control.top.in b/debian/control.top.in +index f08b047..64b4665 100644 +--- a/debian/control.top.in ++++ b/debian/control.top.in +@@ -14,63 +14,64 @@ Build-Depends: + @EXTRA_BUILD@, + groff-base , + imagemagick , +- asciidoctor, ++ asciidoctor , + libunicode-linebreak-perl , + autoconf, + automake, +- bwidget (>= 1.7), +- desktop-file-utils, ++ bwidget (>= 1.7) , ++ desktop-file-utils , + intltool, + libboost-python-dev, +- libepoxy-dev, +- libgl-dev | libgl1-mesa-dev, +- libglu1-mesa-dev, +- libgtk-3-dev, ++ libepoxy-dev , ++ libgl-dev | libgl1-mesa-dev , ++ libglu1-mesa-dev , ++ libgtk-3-dev , + libcap-dev, + libmodbus-dev (>= 3.0), + libgpiod-dev, + @LIBREADLINE_DEV@, + libtirpc-dev, + libusb-1.0-0-dev, +- libxmu-dev, ++ libxmu-dev , + netcat-traditional | netcat-openbsd | netcat, +- netpbm, ++ netpbm , + po4a , + procps, + 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 , +- python3-pyqt5.qtsvg , +- python3-pyqt5.qtopengl , +- python3-pyqt5.qtwebengine , +- pyqt5-dev-tools , +- python3-dbus , +- python3-dbus.mainloop.pyqt5 , +- python3-qtpy , ++ imagemagick , ++ python3-opengl , ++ python3-pyqt5 , ++ python3-pyqt5.qsci , ++ python3-pyqt5.qtsvg , ++ python3-pyqt5.qtopengl , ++ python3-pyqt5.qtwebengine , ++ pyqt5-dev-tools , ++ 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 , ++ gir1.2-gtk-3.0 , ++ gir1.2-gtksource-4 , + python3-numpy , +- python3-configobj , ++ python3-configobj , + libfmt-dev, ++ libglib2.0-dev, + yapps2 + Build-Depends-Indep: + @DOC_DEPENDS@, +diff --git a/debian/linuxcnc-headless.install.in b/debian/linuxcnc-headless.install.in +new file mode 100644 +index 0000000..1491d02 +--- /dev/null ++++ b/debian/linuxcnc-headless.install.in +@@ -0,0 +1,16 @@ ++etc ++ ++usr/bin ++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 a7cf564..dee33e7 100644 +--- a/debian/rules.in ++++ b/debian/rules.in +@@ -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))) ++configure_profile_args += --disable-gui ++endif ++ifneq (,$(filter nodoc,$(DEB_BUILD_PROFILES))) ++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 +@@ -52,6 +61,7 @@ override_dh_auto_configure: + --mandir=/usr/share/man \ + $(configure_realtime_arg) \ + $(enable_build_documentation) \ ++ $(configure_profile_args) \ + --disable-check-runtime-deps + + 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 +@@ -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 + +@@ -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 + +diff --git a/scripts/linuxcnc.in b/scripts/linuxcnc.in +index 3ab645d..027e3b3 100644 +--- a/scripts/linuxcnc.in ++++ b/scripts/linuxcnc.in +@@ -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 (not in builds without a GUI) + + $ $P [Options] path/to/your_ini_file + Name the configuration INI file using its path +@@ -235,7 +237,9 @@ EOF + fi + esac + +-if [ -z "$RUNTESTS" ]; 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,12 +250,12 @@ fi + # shellcheck disable=SC2317,SC2329 + function ErrorCheck () { + result=$? +- if [ -n "$DISPLAY" ]; then ++ if [ "$BUILD_GUI" = yes ] && [ -n "$DISPLAY" ]; then + echo "catch {send -async popimage destroy .}; destroy ." | @WISH@ + fi + + 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 + # nothing specified, get from the user + # it returns either a path, or nothing at all +diff --git a/src/Makefile b/src/Makefile +index 927b122..af616fb 100644 +--- a/src/Makefile ++++ b/src/Makefile +@@ -24,7 +24,7 @@ default: build-software + + install: install-software install-docs + +-install-software: install-kernel-dep install-kernel-indep install-menu ++install-software: install-kernel-dep install-kernel-indep + + ifeq ($(origin KERNELRELEASE), undefined) + #MAKEFLAGS += --warn-undefined-variables +@@ -121,6 +121,12 @@ ifeq ($(RTPREFIX),) + $(error Makefile.inc must specify RTPREFIX and other variables) + endif + ++# 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)) +@@ -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 +@@ -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 ffaaa80..3e21a48 100644 +--- a/src/Makefile.inc.in ++++ b/src/Makefile.inc.in +@@ -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_GUI = @BUILD_GUI@ ++BUILD_TCL = @BUILD_TCL@ + CC = @CC@ + MANDB = @MANDB@ + HIDRAW_H_USABLE = @HIDRAW_H_USABLE@ +diff --git a/src/configure.ac b/src/configure.ac +index 88d7959..901de31 100644 +--- a/src/configure.ac ++++ b/src/configure.ac +@@ -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 + ++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 ++ ++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/tclsh$TCL_VERSION; then ++ TCLSH=$TCL_EXEC_PREFIX/bin/tclsh$TCL_VERSION ++elif test -f $TCL_EXEC_PREFIX/bin/tclsh; then ++ TCLSH=$TCL_EXEC_PREFIX/bin/tclsh ++else ++ TCLSH=tclsh ++fi ++else ++ TCLSH=tclsh ++fi ++AC_SUBST([BUILD_TCL]) ++ ++if test "$BUILD_GUI" = "yes"; then + AC_MSG_CHECKING([for tk]) + + AC_ARG_WITH(tkConfig, +@@ -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 + +-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 +- TCLSH=$TCL_EXEC_PREFIX/bin/tclsh +-else +- TCLSH=tclsh +-fi +- + AC_ARG_ENABLE(check-runtime-deps, + AS_HELP_STRING( + [--disable-check-runtime-deps], +@@ -1543,7 +1560,6 @@ install with "sudo apt-get install python3-gi"]) + fi + + else +- TCLSH=tclsh + WISH=wish + fi + +diff --git a/src/emc/usr_intf/Submakefile b/src/emc/usr_intf/Submakefile +index cb99070..5437969 100644 +--- a/src/emc/usr_intf/Submakefile ++++ b/src/emc/usr_intf/Submakefile +@@ -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 ++# 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 +-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 + +diff --git a/src/emc/usr_intf/emcsh.cc b/src/emc/usr_intf/emcsh.cc +index b040345..8e71c3f 100644 +--- a/src/emc/usr_intf/emcsh.cc ++++ b/src/emc/usr_intf/emcsh.cc +@@ -20,7 +20,9 @@ + #include + #include + #include ++#ifndef LINUXCNC_HEADLESS + #include ++#endif + + #include + #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; + } + ++#ifndef LINUXCNC_HEADLESS + #include + + static int multihead(ClientData /*clientdata*/, +@@ -3620,6 +3625,7 @@ static int multihead(ClientData /*clientdata*/, + } + return TCL_OK; + } ++#endif + + static void sigQuit(int /*sig*/) + { +@@ -3995,8 +4001,10 @@ int Linuxcnc_Init(Tcl_Interp * interp) + Tcl_CreateObjCommand(interp, "round", localround, (ClientData) NULL, + (Tcl_CmdDeleteProc *) NULL); + ++#ifndef LINUXCNC_HEADLESS + Tcl_CreateObjCommand(interp, "multihead", multihead, (ClientData) NULL, + (Tcl_CmdDeleteProc*) NULL); ++#endif + + /* + * Specify a user-specific startup file to invoke if the application +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 + diff --git a/linuxcnc-patches/pending-pre2/0006-ordered-realtime-component-search-path.patch b/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch similarity index 81% rename from linuxcnc-patches/pending-pre2/0006-ordered-realtime-component-search-path.patch rename to linuxcnc-patches/0006-ordered-realtime-component-search-path.patch index 7ea8914..90df789 100644 --- a/linuxcnc-patches/pending-pre2/0006-ordered-realtime-component-search-path.patch +++ b/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch @@ -8,21 +8,21 @@ 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 ++++-- + src/rtapi/uspace_rtapi_main.cc | 42 +++++-- tests/rtmod-path/expected | 1 + tests/rtmod-path/load.hal | 2 + - tests/rtmod-path/test.c | 73 +++++++++++ + tests/rtmod-path/test.c | 109 +++++++++++++++++ tests/rtmod-path/test.sh | 8 ++ - 18 files changed, 470 insertions(+), 75 deletions(-) + 18 files changed, 513 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 @@ -31,10 +31,10 @@ Subject: [PATCH] hal: add ordered trusted realtime component search path 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 +64,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 +78,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 +92,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 +123,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 +216,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 +227,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 +298,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 +373,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 +419,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 +432,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 +633,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 +672,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 +683,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 +709,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,31 +724,36 @@ 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 +index 0000000..55233dc --- /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 +index 0000000..b443927 --- /dev/null +++ b/tests/rtmod-path/load.hal @@ -0,0 +1,2 @@ @@ -787,10 +761,10 @@ index 0000000000..b44392754d +unloadrt all diff --git a/tests/rtmod-path/test.c b/tests/rtmod-path/test.c new file mode 100644 -index 0000000000..3bc258f2fe +index 0000000..fffdf47 --- /dev/null +++ b/tests/rtmod-path/test.c -@@ -0,0 +1,73 @@ +@@ -0,0 +1,109 @@ +#include "config.h" +#include "rtapi/rtmod_path.h" + @@ -826,10 +800,28 @@ index 0000000000..3bc258f2fe + 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) { -+ puts("rtmod-path: configure with two extra rtlib directories for ordered lookup tests"); ++ /* 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; @@ -858,6 +850,24 @@ index 0000000000..3bc258f2fe + 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); @@ -866,7 +876,7 @@ index 0000000000..3bc258f2fe +} diff --git a/tests/rtmod-path/test.sh b/tests/rtmod-path/test.sh new file mode 100755 -index 0000000000..d4e8e6777f +index 0000000..d4e8e67 --- /dev/null +++ b/tests/rtmod-path/test.sh @@ -0,0 +1,8 @@ diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 061be2b..0a13dd6 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -190,30 +190,63 @@ 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. + +`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. + 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. + +Spindle and coolant are restored without adding a task-level spindle-at-speed +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. + +The `tests/resumable-stop` LinuxCNC regression runs 23 scenarios with the +jerk-limited planner and repeats three of them with the trapezoidal planner. +They cover Stop/Resume and Stop/Single-Step preserving the queued program, +spindle and coolant handling, the at-speed cases above, `G33` threading +including a chain of `G33` moves, `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 diff --git a/linuxcnc-patches/pending-pre2/0005-headless-build-option.patch b/linuxcnc-patches/pending-pre2/0005-headless-build-option.patch deleted file mode 100644 index 3544393..0000000 --- a/linuxcnc-patches/pending-pre2/0005-headless-build-option.patch +++ /dev/null @@ -1,852 +0,0 @@ -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 - -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. ---- - 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(-) - create mode 100644 debian/linuxcnc-headless.install.in - -diff --git a/debian/configure b/debian/configure -index 096b3f4a5e..7eed1f95eb 100755 ---- a/debian/configure -+++ b/debian/configure -@@ -122,6 +122,13 @@ 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" -+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" -+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 \ - -e "s#@DOC_DEPENDS@#$DOC_DEPENDS#g" \ - -e "s#@EXTRA_BUILD@#$EXTRA_BUILD#g" \ - -e "s#@EXTRA_RECOMMENDS@#$EXTRA_RECOMMENDS#g" \ -+ -e "s#@GUI_RUNTIME_DEPENDS@#$GUI_RUNTIME_DEPENDS#g" \ -+ -e "s#@GUI_RUNTIME_RECOMMENDS@#$GUI_RUNTIME_RECOMMENDS#g" \ - -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 - - 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 -+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 -+else -+ rm -f ${MAIN_PACKAGE_NAME}.manpages -+fi - - 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 ---- a/debian/control.main-pkg.in -+++ b/debian/control.main-pkg.in -@@ -13,32 +13,13 @@ Depends: - ${shlibs:Depends}, - @KERNEL_DEPENDS@, - @MODUTILS_DEPENDS@, -- blt, -- mesa-utils, -- python3-tk, -+ @GUI_RUNTIME_DEPENDS@, - python3-numpy, -- python3-cairo, -- python3-gi-cairo, -- python3-opengl, -- python3-configobj, -- python3-xlib, -- libgtksourceview-4-dev, - tcl@TCLTK_VERSION@, -- tk@TCLTK_VERSION@, -- bwidget (>= 1.7), - tclreadline, -- tclx, -- @QTVCP_DEPENDS@, - procps, psmisc, - udev --Recommends: -- linuxcnc-doc-en | linuxcnc-doc, -- librsvg2-dev, -- x11-xserver-utils, -- @EXTRA_RECOMMENDS@, -- @PYTHON_IMAGING@, -- @PYTHON_IMAGING_TK@ --Suggests: -+@GUI_RUNTIME_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 ---- a/debian/control.top.in -+++ b/debian/control.top.in -@@ -14,57 +14,58 @@ Build-Depends: - @EXTRA_BUILD@, - groff-base , - imagemagick , -- asciidoctor, -+ asciidoctor , - libunicode-linebreak-perl , - autoconf, - automake, -- bwidget (>= 1.7), -- desktop-file-utils, -+ bwidget (>= 1.7) , -+ desktop-file-utils , - intltool, - libboost-python-dev, -- libepoxy-dev, -- libgl-dev | libgl1-mesa-dev, -- libglu1-mesa-dev, -- libgtk-3-dev, -+ libepoxy-dev , -+ libgl-dev | libgl1-mesa-dev , -+ libglu1-mesa-dev , -+ libgtk-3-dev , - libcap-dev, - libmodbus-dev (>= 3.0), - libgpiod-dev, - @LIBREADLINE_DEV@, - libtirpc-dev, - libusb-1.0-0-dev, -- libxmu-dev, -+ libxmu-dev , - netcat-traditional | netcat-openbsd | netcat, -- netpbm, -+ netpbm , - po4a , - procps, - psmisc, - python3, - python3-dev, -- python3-tk, -- python3-xlib, -+ python3-tk , -+ python3-xlib , - tcl@TCLTK_VERSION@-dev, -- tclx, -- tk@TCLTK_VERSION@-dev, -- xvfb , -- x11-xserver-utils , -- python3-opengl , -- python3-pyqt5 , -- python3-pyqt5.qsci , -- python3-pyqt5.qtsvg , -- python3-pyqt5.qtopengl , -- python3-pyqt5.qtwebengine , -- pyqt5-dev-tools , -- 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 , -+ python3-opengl , -+ python3-pyqt5 , -+ python3-pyqt5.qsci , -+ python3-pyqt5.qtsvg , -+ python3-pyqt5.qtopengl , -+ python3-pyqt5.qtwebengine , -+ pyqt5-dev-tools , -+ python3-dbus , -+ python3-dbus.mainloop.pyqt5 , -+ python3-qtpy , -+ python3-cairo , -+ python3-gi , -+ python3-gi-cairo , -+ gir1.2-gtk-3.0 , -+ gir1.2-gtksource-4 , - python3-numpy , -- python3-configobj , -+ python3-configobj , - libfmt-dev, -+ libglib2.0-dev, - yapps2 - Build-Depends-Indep: - @DOC_DEPENDS@, -diff --git a/debian/linuxcnc-headless.install.in b/debian/linuxcnc-headless.install.in -new file mode 100644 -index 0000000000..2660b6ba4a ---- /dev/null -+++ b/debian/linuxcnc-headless.install.in -@@ -0,0 +1,3 @@ -+usr/bin -+usr/lib -+usr/share/linuxcnc -diff --git a/debian/rules.in b/debian/rules.in -index 50b52e8ff6..467ec47631 100644 ---- a/debian/rules.in -+++ b/debian/rules.in -@@ -32,6 +32,12 @@ export TIME:=$(shell LANG=C date --date='@$(TIMESTAMP)' '+%T') - - kernel_version = @KERNEL_VERSION@ - configure_realtime_arg = @CONFIGURE_REALTIME_ARG@ -+ifneq (,$(filter pkg.linuxcnc.headless,$(DEB_BUILD_PROFILES))) -+enable_headless = --enable-headless -+endif -+ifneq (,$(filter nodoc,$(DEB_BUILD_PROFILES))) -+disable_docs = --disable-build-documentation --disable-build-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 \ - --mandir=/usr/share/man \ - $(configure_realtime_arg) \ -+ $(enable_headless) \ -+ $(disable_docs) \ - $(enable_build_documentation) \ - --disable-check-runtime-deps - -@@ -83,12 +91,15 @@ 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); - - # 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: - mv debian/@MAIN_PACKAGE_NAME@/usr/share/doc/@MAIN_PACKAGE_NAME@/examples debian/@MAIN_PACKAGE_NAME@/usr/share/doc/linuxcnc - - 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 -+endif - - 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 ---- 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: - This help - - $ $P [Options] -- Choose the configuration INI file graphically -+ Choose the configuration INI file graphically (non-headless builds only) - - $ $P [Options] path/to/your_ini_file - Name the configuration INI file using its path -@@ -235,7 +236,7 @@ EOF - fi - esac - --if [ -z "$RUNTESTS" ]; then -+if [ -z "$RUNTESTS" ] && [ "$BUILD_HEADLESS" != yes ]; then - if ! tty -s; then - exec 2>> "$DEBUG_FILE" - exec >> "$PRINT_FILE" -@@ -246,7 +247,7 @@ fi - # shellcheck disable=SC2317,SC2329 - function ErrorCheck () { - result=$? -- if [ -n "$DISPLAY" ]; then -+ if [ "$BUILD_HEADLESS" != yes ] && [ -n "$DISPLAY" ]; then - echo "catch {send -async popimage destroy .}; destroy ." | @WISH@ - fi - -@@ -344,6 +345,11 @@ if [ -n "$USE_LAST_INIFILE" ]; then - 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 ---- a/src/Makefile -+++ b/src/Makefile -@@ -24,7 +24,7 @@ default: build-software - - install: install-software install-docs - --install-software: install-kernel-dep install-kernel-indep install-menu -+install-software: - - ifeq ($(origin KERNELRELEASE), undefined) - #MAKEFLAGS += --warn-undefined-variables -@@ -121,6 +121,12 @@ ifeq ($(RTPREFIX),) - $(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 -+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 - $(FILE) objects/*.msg $(DESTDIR)$(tcldir)/msgs - $(EXE) ../scripts/realtime $(DESTDIR)$(prefix)/lib/linuxcnc - $(EXE) ../scripts/halrun $(DESTDIR)$(bindir) -diff --git a/src/Makefile.inc.in b/src/Makefile.inc.in -index 848adcbd28..b88d758f19 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)\" - MODULE_EXT = @MODEXT@ - BUILD_SYS = @BUILD_SYS@ -+BUILD_HEADLESS = @BUILD_HEADLESS@ -+BUILD_MANPAGES = @BUILD_MANPAGES@ - 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 ---- a/src/configure.ac -+++ b/src/configure.ac -@@ -802,6 +802,19 @@ else - 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 -+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 -+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 -+ TCLSH=$TCL_EXEC_PREFIX/bin/tclsh -+else -+ TCLSH=tclsh -+fi -+ -+if test "$BUILD_HEADLESS" != yes; then - AC_MSG_CHECKING([for tk]) - - AC_ARG_WITH(tkConfig, -@@ -1461,14 +1510,6 @@ else - WISH=wish - 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 -- TCLSH=$TCL_EXEC_PREFIX/bin/tclsh --else -- TCLSH=tclsh --fi -- - 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 - 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"]) - 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 ---- a/src/emc/usr_intf/Submakefile -+++ b/src/emc/usr_intf/Submakefile -@@ -18,11 +18,11 @@ 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,) - - ../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) - TARGETS += ../tcl/linuxcnc.so - - ../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 ---- a/src/emc/usr_intf/emcsh.cc -+++ b/src/emc/usr_intf/emcsh.cc -@@ -20,7 +20,9 @@ - #include - #include - #include -+#ifndef LINUXCNC_HEADLESS - #include -+#endif - - #include - #include -@@ -3582,6 +3584,7 @@ static int localround(ClientData /*clientdata*/, - return TCL_OK; - } - -+#ifndef LINUXCNC_HEADLESS - #include - - static int multihead(ClientData /*clientdata*/, -@@ -3621,6 +3624,7 @@ static int multihead(ClientData /*clientdata*/, - } - return TCL_OK; - } -+#endif - - static void sigQuit(int /*sig*/) - { -@@ -3996,8 +4000,10 @@ int Linuxcnc_Init(Tcl_Interp * interp) - Tcl_CreateObjCommand(interp, "round", localround, (ClientData) NULL, - (Tcl_CmdDeleteProc *) NULL); - -+#ifndef LINUXCNC_HEADLESS - Tcl_CreateObjCommand(interp, "multihead", multihead, (ClientData) NULL, - (Tcl_CmdDeleteProc*) NULL); -+#endif - - /* - * 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) - 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 From 5445eecd78024ba18505d5f7cb411c90f1e180c2 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 12 Nov 2026 08:38:52 +0100 Subject: [PATCH 10/45] feat(linuxcnc): port patches 0007 and 0008 to v2.10.0-pre2 Patch 0004 now carries every review fix from the port: the Stop chain is tracked by a flag instead of a dangling segment pointer, STOPPED clears the spindle synchronization record, and Stop's spindle commands no longer leak at-speed or spindle state into later S words. tests/resumable-stop runs 25 scenarios plus four under the trapezoidal planner. Patch 0007 follows upstream's split of #5401-#5409 (stored) and #5081-#5089 (applied), applies the automatic offset together with the tool change, refuses M61 under cutter compensation, limits tool lines to 510 characters and rolls back failed saves. Patch 0008 passes upstream's G76 synchronized-feed check on every tapered pass. Verified on the stack: clean -Werror build, 335/335 regression tests, tests/resumable-stop three more times, and a headless build with a test subset. --- linuxcnc-patches/0004-resumable-stop.patch | 409 +- .../0007-native-automatic-tool-wear.patch | 5420 +++++++++++++++++ .../0008-tapered-g76-drive-lines.patch | 835 ++- linuxcnc-patches/README.md | 43 +- .../0007-native-automatic-tool-wear.patch | 2054 ------- 5 files changed, 6481 insertions(+), 2280 deletions(-) create mode 100644 linuxcnc-patches/0007-native-automatic-tool-wear.patch rename linuxcnc-patches/{pending-pre2 => }/0008-tapered-g76-drive-lines.patch (54%) delete mode 100644 linuxcnc-patches/pending-pre2/0007-native-automatic-tool-wear.patch diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 75e4aa1..254488d 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -11,19 +11,20 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: - 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 that no longer stays behind in the shared motion command, so a later S-word change still arms the next feed's at-speed wait. +- 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. Halting at the start of the next G33 left the axis behind the turning spindle and Resume lunged to catch up. +- 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, and the planner drops its pointer to the synchronized segment when that run is over or the queue empties. +- 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 and step-resume-stopping, fails if STOPPED is reported while moving, re-runs three scenarios under the trapezoidal planner, and its checkresult now fails when the scenario count is wrong. +- 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/python-interface.adoc | 12 + docs/src/gui/halui.adoc | 3 +- docs/src/man/man1/halui.1.adoc | 5 +- src/emc/motion-logger/motion-logger.c | 4 + - src/emc/motion/command.c | 34 +- + src/emc/motion/command.c | 38 +- src/emc/motion/control.c | 13 + src/emc/motion/motion.c | 1 + src/emc/motion/motion.h | 3 + @@ -31,13 +32,13 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: 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 | 358 +++++- - src/emc/task/taskintf.cc | 34 +- - src/emc/tp/tp.c | 110 +- - src/emc/tp/tp_types.h | 7 + + src/emc/task/emctaskmain.cc | 358 ++++- + src/emc/task/taskintf.cc | 40 +- + src/emc/tp/tp.c | 133 +- + src/emc/tp/tp_types.h | 12 + src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + src/emc/usr_intf/halui.cc | 9 +- - tests/resumable-stop/README | 30 + + tests/resumable-stop/README | 37 + tests/resumable-stop/after-abort.ngc | 4 + tests/resumable-stop/checkresult | 4 + tests/resumable-stop/core_sim.hal | 42 + @@ -47,6 +48,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/feed-atspeed.ngc | 7 + tests/resumable-stop/fperrev.ngc | 7 + tests/resumable-stop/g76.ngc | 7 + + tests/resumable-stop/homing-long.ngc | 6 + tests/resumable-stop/homing.ngc | 6 + tests/resumable-stop/multi-spindle.ngc | 4 + tests/resumable-stop/orient.ngc | 6 + @@ -54,16 +56,18 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/rapid-then-feed.ngc | 7 + tests/resumable-stop/single-step.ngc | 10 + tests/resumable-stop/speed-change.ngc | 9 + + tests/resumable-stop/spindle-state.ngc | 10 + tests/resumable-stop/tap.ngc | 7 + - tests/resumable-stop/test-ui.py | 1143 +++++++++++++++++ + tests/resumable-stop/test-ui.py | 1259 +++++++++++++++++ tests/resumable-stop/test.ini | 98 ++ tests/resumable-stop/test.ngc | 9 + - tests/resumable-stop/test.sh | 69 + + tests/resumable-stop/test.sh | 72 + tests/resumable-stop/thread-chain.ngc | 8 + + tests/resumable-stop/thread-g95-thread.ngc | 9 + tests/resumable-stop/thread-then-steps.ngc | 10 + tests/resumable-stop/thread.ngc | 7 + tests/resumable-stop/tool.tbl | 1 + - 44 files changed, 2165 insertions(+), 22 deletions(-) + 47 files changed, 2352 insertions(+), 24 deletions(-) create mode 100644 tests/resumable-stop/README create mode 100644 tests/resumable-stop/after-abort.ngc create mode 100755 tests/resumable-stop/checkresult @@ -74,6 +78,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: create mode 100644 tests/resumable-stop/feed-atspeed.ngc create mode 100644 tests/resumable-stop/fperrev.ngc create mode 100644 tests/resumable-stop/g76.ngc + create mode 100644 tests/resumable-stop/homing-long.ngc create mode 100644 tests/resumable-stop/homing.ngc create mode 100644 tests/resumable-stop/multi-spindle.ngc create mode 100644 tests/resumable-stop/orient.ngc @@ -81,12 +86,14 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: 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/speed-change.ngc + create mode 100644 tests/resumable-stop/spindle-state.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-chain.ngc + create mode 100644 tests/resumable-stop/thread-g95-thread.ngc create mode 100644 tests/resumable-stop/thread-then-steps.ngc create mode 100644 tests/resumable-stop/thread.ngc create mode 100644 tests/resumable-stop/tool.tbl @@ -167,30 +174,34 @@ index 36b77e5..24d0fea 100644 log_print("RESUME\n"); break; diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index e2ecb07..62dc717 100644 +index e2ecb07..4c0b914 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -536,6 +536,12 @@ 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. */ ++ 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_tc = 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); -@@ -1323,6 +1329,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; @@ -199,19 +210,19 @@ index e2ecb07..62dc717 100644 case EMCMOT_REVERSE: /* run motion in reverse*/ /* only allowed during a pause */ -@@ -1342,8 +1357,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: -@@ -1800,7 +1818,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1800,7 +1822,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) } apply_spindle_limits(&emcmotStatus->spindle_status[n]); } @@ -224,7 +235,7 @@ index e2ecb07..62dc717 100644 // check whether it's passed correctly if (!emcmotStatus->atspeed_next_feed){ -@@ -1839,8 +1861,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1839,8 +1865,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 @@ -242,7 +253,7 @@ index e2ecb07..62dc717 100644 case EMCMOT_SPINDLE_ORIENT: diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 17fb96b..fd88fd9 100644 +index 17fb96b..7a85db9 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c @@ -2071,6 +2071,19 @@ static void output_to_hal(void) @@ -252,12 +263,12 @@ index 17fb96b..fd88fd9 100644 + /* + * 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; + } @@ -1061,7 +1072,7 @@ index a3b5256..564e4a1 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 4215d22..689031d 100644 +index 4215d22..7db2314 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc @@ -1497,6 +1497,13 @@ int emcTrajPause() @@ -1086,23 +1097,27 @@ index 4215d22..689031d 100644 stat->scale = emcmotStatus.feed_scale; stat->rapid_scale = emcmotStatus.rapid_scale; -@@ -2065,6 +2073,23 @@ int emcSpindleOrient(int spindle, double orientation, int mode) +@@ -2065,25 +2073,42 @@ int emcSpindleOrient(int spindle, double orientation, int mode) } +/* -+ * emcSpindleSpeed() sends EMCMOT_SPINDLE_ON with whatever at-speed request the -+ * last spindle command left in emcmotCommand. A resumable Stop's -+ * EMCMOT_SPINDLE_AT_SPEED_PRESERVE must not become that request, or a later -+ * S-word change would leave the next feed's at-speed wait unarmed. ++ * 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 wait_for_at_speed) ++static int writeSpindleCommand(int state, int wait_for_at_speed) +{ -+ unsigned char previous = emcmotCommand.wait_for_spindle_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.wait_for_spindle_at_speed = previous; ++ emcmotCommand.state = previous_state; ++ emcmotCommand.wait_for_spindle_at_speed = previous_wait; + } + return retval; +} @@ -1110,27 +1125,28 @@ index 4215d22..689031d 100644 int emcSpindleOn(int spindle, double speed, double css_factor, double offset, int wait_for_at_speed) { emcmotCommand.command = EMCMOT_SPINDLE_ON; -@@ -2073,8 +2098,7 @@ int emcSpindleOn(int spindle, double speed, double css_factor, double offset, in + 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(wait_for_at_speed); ++ return writeSpindleCommand(1, wait_for_at_speed); } int emcSpindleOff(int spindle, int wait_for_at_speed) -@@ -2082,8 +2106,7 @@ int emcSpindleOff(int spindle, int wait_for_at_speed) + { emcmotCommand.command = EMCMOT_SPINDLE_OFF; - emcmotCommand.state = 0; +- emcmotCommand.state = 0; emcmotCommand.spindle = spindle; - emcmotCommand.wait_for_spindle_at_speed = wait_for_at_speed; - return usrmotWriteEmcmotCommand(&emcmotCommand); -+ return writeSpindleCommand(wait_for_at_speed); ++ return writeSpindleCommand(0, wait_for_at_speed); } int emcSpindleBrakeRelease(int spindle) -@@ -2137,6 +2160,9 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ +@@ -2137,6 +2162,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; @@ -1141,36 +1157,42 @@ index 4215d22..689031d 100644 return 0; } diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index c75c795..f138f62 100644 +index c75c795..8ef21c3 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c -@@ -229,6 +229,25 @@ STATIC int tpGetMachineActiveLimit(double * const act_limit, PmCartesian const * +@@ -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. -+ * Stop lets the position-synchronized segment that was active when it -+ * arrived (stop_tc) run to its end, together with the position-synchronized -+ * segments after it that continue the same spindle synchronization without -+ * waiting for a new index pulse: stopping part way along that run would -+ * leave the axis behind the spindle. Every other segment is held. ++ * 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 || tc == tp->stop_tc) { ++ if (!tp->stopping) { + return false; + } -+ return !(tp->stop_tc && -+ tc->synchronized == TC_SYNC_POSITION && -+ emcmotStatus->spindleSync); ++ 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 +258,11 @@ STATIC double tpGetFeedScale(TP_STRUCT const * const tp, +@@ -239,7 +264,11 @@ STATIC double tpGetFeedScale(TP_STRUCT const * const tp, return 0.0; } //All reasons to disable feed override go here @@ -1183,16 +1205,16 @@ index c75c795..f138f62 100644 bool aborting = tp->aborting; if (pausing) { tc_debug_print("pausing\n"); -@@ -455,6 +478,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; -@@ -2816,12 +2841,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 @@ -1220,7 +1242,7 @@ index c75c795..f138f62 100644 // Normal operation parameters double effective_max_vel = tc_target_vel; double effective_target_vel = tc_finalvel; -@@ -3327,7 +3364,9 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) +@@ -3327,7 +3370,9 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) tpUpdateMovementStatus(tp, NULL); @@ -1231,7 +1253,7 @@ index c75c795..f138f62 100644 } /** Wrapper function to unlock rotary axes */ -@@ -3812,6 +3851,9 @@ STATIC int tpUpdateCycle(TP_STRUCT * const tp, +@@ -3812,6 +3857,9 @@ STATIC int tpUpdateCycle(TP_STRUCT * const tp, int planner_type = GET_TRAJ_PLANNER_TYPE(); if(mode == NULL) planner_type = 0; @@ -1241,15 +1263,14 @@ index c75c795..f138f62 100644 if(planner_type != 1){ // If the slowdown is not too great, use velocity ramping instead of trapezoidal velocity -@@ -4253,10 +4295,39 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4253,10 +4301,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) { -+ // tcqInit() has emptied the slot stop_tc pointed at. -+ tp->stop_tc = 0; ++ tp->stop_sync_run = 0; + tp->pausing = 1; + emcmotStatus->stopped = 1; + } @@ -1261,9 +1282,8 @@ index c75c795..f138f62 100644 + if (tpStopHolds(tp, tc)) { + tp->pausing = 1; -+ // Any synchronized run Stop was finishing is over; drop the pointer -+ // before its queue slot can be reused. -+ tp->stop_tc = 0; ++ // Any synchronized run Stop was finishing is over. ++ tp->stop_sync_run = 0; + } + + /* @@ -1276,12 +1296,23 @@ index c75c795..f138f62 100644 + 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"); -@@ -4270,6 +4341,18 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4270,6 +4356,18 @@ int tpRunCycle(TP_STRUCT * const tp, long period) return TP_ERR_STOPPED; } @@ -1300,7 +1331,7 @@ index c75c795..f138f62 100644 //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 +4448,19 @@ int tpPause(TP_STRUCT * const tp) +@@ -4365,7 +4463,27 @@ int tpPause(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -1308,11 +1339,19 @@ index c75c795..f138f62 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 { @@ -1321,21 +1360,21 @@ index c75c795..f138f62 100644 return TP_ERR_OK; } -@@ -4375,6 +4470,9 @@ int tpResume(TP_STRUCT * const tp) +@@ -4375,6 +4493,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 0e9ab84..57fcada 100644 +index 0e9ab84..d11e695 100644 --- a/src/emc/tp/tp_types.h +++ b/src/emc/tp/tp_types.h -@@ -149,6 +149,13 @@ typedef struct { +@@ -149,6 +149,18 @@ typedef struct { syncdio_t syncdio; //record tpSetDout's here @@ -1344,7 +1383,12 @@ index 0e9ab84..57fcada 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; @@ -1424,10 +1468,10 @@ index 1d0cb6e..65b890a 100644 counts = new_halui_data.mv_counts; diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README new file mode 100644 -index 0000000..ee83269 +index 0000000..e5da45f --- /dev/null +++ b/tests/resumable-stop/README -@@ -0,0 +1,30 @@ +@@ -0,0 +1,37 @@ +Verify resumable Stop preserves an active AUTO program and resumes or +single-steps it. + @@ -1438,8 +1482,9 @@ index 0000000..ee83269 +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 and fperrev scenarios run a second time with the default -+trapezoidal planner (PLANNER_TYPE = 0). Every run rejects zero-limit Ruckig ++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 @@ -1447,7 +1492,8 @@ index 0000000..ee83269 +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, and ++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 @@ -1455,9 +1501,14 @@ index 0000000..ee83269 +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 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 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. diff --git a/tests/resumable-stop/after-abort.ngc b/tests/resumable-stop/after-abort.ngc new file mode 100644 index 0000000..df711f6 @@ -1470,13 +1521,13 @@ index 0000000..df711f6 +M2 diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult new file mode 100755 -index 0000000..dcdfb2d +index 0000000..c40d14c --- /dev/null +++ b/tests/resumable-stop/checkresult @@ -0,0 +1,4 @@ +#!/bin/sh +set -e -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 26 ++test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 29 +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 @@ -1601,6 +1652,18 @@ index 0000000..1c6a3ea +G1 X20 F600 +M5 +M2 +diff --git a/tests/resumable-stop/homing-long.ngc b/tests/resumable-stop/homing-long.ngc +new file mode 100644 +index 0000000..2cc583c +--- /dev/null ++++ b/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/tests/resumable-stop/homing.ngc b/tests/resumable-stop/homing.ngc new file mode 100644 index 0000000..4f214ea @@ -1692,6 +1755,22 @@ index 0000000..927c3ca +G1 X6 +M5 +M2 +diff --git a/tests/resumable-stop/spindle-state.ngc b/tests/resumable-stop/spindle-state.ngc +new file mode 100644 +index 0000000..c5f21ab +--- /dev/null ++++ b/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/tests/resumable-stop/tap.ngc b/tests/resumable-stop/tap.ngc new file mode 100644 index 0000000..3060ac4 @@ -1707,10 +1786,10 @@ index 0000000..3060ac4 +M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py new file mode 100755 -index 0000000..18ea01b +index 0000000..aa7c6a3 --- /dev/null +++ b/tests/resumable-stop/test-ui.py -@@ -0,0 +1,1143 @@ +@@ -0,0 +1,1259 @@ +#!/usr/bin/env python3 + +import math @@ -1798,7 +1877,7 @@ index 0000000..18ea01b + fail("rejected program Stop changed Stop state") + + -+def resume_and_wait_for_x_motion(stopped_x): ++def resume_and_wait_for_x_motion(stopped_x, on_poll=None): + c.auto(linuxcnc.AUTO_RESUME) + + saw_restored_spindle = False @@ -1806,6 +1885,8 @@ index 0000000..18ea01b + 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"): @@ -2057,7 +2138,8 @@ index 0000000..18ea01b + wait_for_program_complete(6.0) + + -+def stop_during_sync_motion(program, active_predicate, complete_predicate, message, expected_z): ++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) @@ -2109,14 +2191,40 @@ index 0000000..18ea01b + % (message, s.position[0], s.position[2]) + ) + -+ if s.position[0] > 0.05: ++ # 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] -+ resume_and_wait_for_x_motion(stopped_x) ++ 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() + @@ -2555,8 +2663,8 @@ index 0000000..18ea01b + wait_for_program_complete(30.0) + + -+def wait_for_queued_homing(message): -+ open_auto_program("homing.ngc") ++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 @@ -2617,12 +2725,15 @@ index 0000000..18ea01b + + 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=1.0, ++ 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") @@ -2646,7 +2757,10 @@ index 0000000..18ea01b + ("mode", interrupt_mode), + ("stop and abort", interrupt_stop_abort), + ): -+ wait_for_queued_homing("program did not enter G28.2 before %s" % name) ++ 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 @@ -2780,6 +2894,7 @@ index 0000000..18ea01b + lambda: s.position[2] <= -4.90, + "consecutive G33 threading", + expected_z=-5.0, ++ resume_max_vel=1.05, + ) + + @@ -2821,6 +2936,84 @@ index 0000000..18ea01b + assert_outputs_stopped_after_program() + + ++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, @@ -2845,6 +3038,8 @@ index 0000000..18ea01b + "queued-feed-atspeed": run_queued_feed_atspeed_test, + "g33-chain": run_threading_chain_stop_resume_test, + "step-resume-stopping": run_step_then_resume_while_stopping_test, ++ "g95-between-g33": run_g95_between_g33_stop_resume_test, ++ "spindle-state": run_stopped_spindle_s_word_test, +} + +scenario = os.environ.get("RESUMABLE_STOP_SCENARIO") @@ -2975,10 +3170,10 @@ index 0000000..416044b +M2 diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh new file mode 100755 -index 0000000..7c34d26 +index 0000000..6c37e51 --- /dev/null +++ b/tests/resumable-stop/test.sh -@@ -0,0 +1,69 @@ +@@ -0,0 +1,72 @@ +#!/bin/bash -e + +set -o pipefail @@ -3012,15 +3207,18 @@ index 0000000..7c34d26 + queued-feed-atspeed + g33-chain + step-resume-stopping ++ g95-between-g33 ++ spindle-state +) + +# test.ini selects the jerk-limited planner. Repeat the scenarios whose -+# unsynchronized motion is most planner dependent with the default -+# trapezoidal planner. ++# unsynchronized motion is most planner dependent, and g33-chain (which ends ++# in a blend arc only with this planner), with the default trapezoidal planner. +trapezoidal_scenarios=( + ordinary + single-step + fperrev ++ g33-chain +) + +scenario_log=$(mktemp) @@ -3062,6 +3260,21 @@ index 0000000..ca80839 +G1 X10 F60 +M5 +M2 +diff --git a/tests/resumable-stop/thread-g95-thread.ngc b/tests/resumable-stop/thread-g95-thread.ngc +new file mode 100644 +index 0000000..d6630aa +--- /dev/null ++++ b/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 F60 ++M5 ++M2 diff --git a/tests/resumable-stop/thread-then-steps.ngc b/tests/resumable-stop/thread-then-steps.ngc new file mode 100644 index 0000000..e744543 diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch new file mode 100644 index 0000000..bd0552b --- /dev/null +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -0,0 +1,5420 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +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 | 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 | 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 | 171 ++++++--- + src/emc/rs274ngc/interp_internal.hh | 2 - + src/emc/rs274ngc/interp_parameter_def.hh | 10 + + src/emc/rs274ngc/pyemctypes.cc | 2 + + 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 | 61 ++- + src/emc/task/emctask.cc | 4 + + src/emc/task/emctaskmain.cc | 31 +- + src/emc/task/taskclass.cc | 79 +++- + src/emc/task/taskclass.hh | 5 +- + 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 | 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-line-length/expected | 23 ++ + tests/interp/tool-line-length/missing-t2.ngc | 3 + + tests/interp/tool-line-length/missing-t3.ngc | 3 + + tests/interp/tool-line-length/missing-t4.ngc | 3 + + tests/interp/tool-line-length/test.ngc | 12 + + tests/interp/tool-line-length/test.sh | 17 + + tests/interp/tool-line-length/test.tbl | 5 + + tests/interp/tool-wear/expected | 69 ++++ + tests/interp/tool-wear/invalid-i.ngc | 3 + + tests/interp/tool-wear/invalid-j.ngc | 3 + + tests/interp/tool-wear/invalid-m61-comp.ngc | 5 + + .../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 | 46 +++ + tests/interp/tool-wear/test.sh | 27 ++ + tests/interp/tool-wear/test.tbl | 3 + + tests/remap/introspect/expected | 25 +- + tests/remap/oword-pycall/expected | 25 +- + 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/tool-line-length-save/.gitignore | 3 + + tests/tool-line-length-save/checkresult | 2 + + tests/tool-line-length-save/lathe.ini | 85 +++++ + tests/tool-line-length-save/make-table.py | 9 + + tests/tool-line-length-save/test-ui.py | 86 +++++ + tests/tool-line-length-save/test.sh | 4 + + tests/tool-wear-abort/.gitignore | 3 + + tests/tool-wear-abort/change-move.ngc | 5 + + tests/tool-wear-abort/change-then-end.ngc | 3 + + tests/tool-wear-abort/checkresult | 2 + + tests/tool-wear-abort/core_sim_handshake.hal | 18 + + tests/tool-wear-abort/interp-error-m6.ngc | 7 + + tests/tool-wear-abort/lathe.ini | 85 +++++ + tests/tool-wear-abort/move-origin.ngc | 5 + + tests/tool-wear-abort/postgui.hal | 5 + + tests/tool-wear-abort/readahead-g43.ngc | 6 + + tests/tool-wear-abort/readahead-m61.ngc | 7 + + tests/tool-wear-abort/test-ui.py | 359 ++++++++++++++++++ + tests/tool-wear-abort/test.sh | 6 + + tests/tool-wear-abort/tool.tbl.original | 2 + + tests/tool-wear-restart/.gitignore | 3 + + tests/tool-wear-restart/checkresult | 2 + + tests/tool-wear-restart/common.py | 72 ++++ + tests/tool-wear-restart/run1.ini | 85 +++++ + tests/tool-wear-restart/run1.py | 10 + + tests/tool-wear-restart/run2.ini | 85 +++++ + tests/tool-wear-restart/run2.py | 18 + + tests/tool-wear-restart/test.sh | 12 + + tests/tool-wear-restart/tool.tbl.original | 2 + + tests/tool-wear-task/.gitignore | 3 + + tests/tool-wear-task/checkresult | 2 + + tests/tool-wear-task/lathe.ini | 90 +++++ + tests/tool-wear-task/remap.py | 15 + + tests/tool-wear-task/test-ui.py | 297 +++++++++++++++ + tests/tool-wear-task/test.sh | 6 + + tests/tool-wear-task/tool.tbl.original | 2 + + tests/tool-wear-task/toplevel.py | 1 + + tests/toolchanger/m61/test-ui.py | 28 +- + .../nonrandom/expected-gcode-output | 12 +- + .../random/expected-gcode-output | 12 +- + tests/tooldb/db-g10-offset/README | 4 +- + tests/tooldb/db-g10-offset/db_test.py | 10 +- + tests/tooldb/db-g10-offset/dbtest_lib.py | 16 +- + tests/tooldb/db-g10-offset/test-ui.py | 15 + + tests/tooldb/db-g10-offset/verify-ui.py | 5 +- + tests/tooldb/db-line-length/.gitignore | 5 + + tests/tooldb/db-line-length/base.inc | 98 +++++ + tests/tooldb/db-line-length/checkresult | 2 + + tests/tooldb/db-line-length/db_long.py | 30 ++ + tests/tooldb/db-line-length/long-ui.py | 34 ++ + tests/tooldb/db-line-length/long.ini | 5 + + tests/tooldb/db-line-length/test-ui.py | 18 + + tests/tooldb/db-line-length/test.ini | 5 + + tests/tooldb/db-line-length/test.sh | 14 + + 128 files changed, 2806 insertions(+), 283 deletions(-) + create mode 100644 tests/interp/tool-line-length/expected + create mode 100644 tests/interp/tool-line-length/missing-t2.ngc + create mode 100644 tests/interp/tool-line-length/missing-t3.ngc + create mode 100644 tests/interp/tool-line-length/missing-t4.ngc + create mode 100644 tests/interp/tool-line-length/test.ngc + create mode 100755 tests/interp/tool-line-length/test.sh + create mode 100644 tests/interp/tool-line-length/test.tbl + 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-m61-comp.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 + create mode 100644 tests/tool-line-length-save/.gitignore + create mode 100755 tests/tool-line-length-save/checkresult + create mode 100644 tests/tool-line-length-save/lathe.ini + create mode 100755 tests/tool-line-length-save/make-table.py + create mode 100755 tests/tool-line-length-save/test-ui.py + create mode 100755 tests/tool-line-length-save/test.sh + create mode 100644 tests/tool-wear-abort/.gitignore + create mode 100644 tests/tool-wear-abort/change-move.ngc + create mode 100644 tests/tool-wear-abort/change-then-end.ngc + create mode 100755 tests/tool-wear-abort/checkresult + create mode 100644 tests/tool-wear-abort/core_sim_handshake.hal + create mode 100644 tests/tool-wear-abort/interp-error-m6.ngc + create mode 100644 tests/tool-wear-abort/lathe.ini + create mode 100644 tests/tool-wear-abort/move-origin.ngc + create mode 100644 tests/tool-wear-abort/postgui.hal + create mode 100644 tests/tool-wear-abort/readahead-g43.ngc + create mode 100644 tests/tool-wear-abort/readahead-m61.ngc + create mode 100755 tests/tool-wear-abort/test-ui.py + create mode 100755 tests/tool-wear-abort/test.sh + create mode 100644 tests/tool-wear-abort/tool.tbl.original + create mode 100644 tests/tool-wear-restart/.gitignore + create mode 100755 tests/tool-wear-restart/checkresult + create mode 100644 tests/tool-wear-restart/common.py + create mode 100644 tests/tool-wear-restart/run1.ini + create mode 100755 tests/tool-wear-restart/run1.py + create mode 100644 tests/tool-wear-restart/run2.ini + create mode 100755 tests/tool-wear-restart/run2.py + create mode 100755 tests/tool-wear-restart/test.sh + create mode 100644 tests/tool-wear-restart/tool.tbl.original + create mode 100644 tests/tool-wear-task/.gitignore + create mode 100755 tests/tool-wear-task/checkresult + create mode 100644 tests/tool-wear-task/lathe.ini + create mode 100644 tests/tool-wear-task/remap.py + create mode 100755 tests/tool-wear-task/test-ui.py + create mode 100755 tests/tool-wear-task/test.sh + create mode 100644 tests/tool-wear-task/tool.tbl.original + create mode 100644 tests/tool-wear-task/toplevel.py + create mode 100644 tests/tooldb/db-line-length/.gitignore + create mode 100644 tests/tooldb/db-line-length/base.inc + create mode 100755 tests/tooldb/db-line-length/checkresult + create mode 100755 tests/tooldb/db-line-length/db_long.py + create mode 100755 tests/tooldb/db-line-length/long-ui.py + create mode 100644 tests/tooldb/db-line-length/long.ini + create mode 100755 tests/tooldb/db-line-length/test-ui.py + create mode 100644 tests/tooldb/db-line-length/test.ini + create mode 100755 tests/tooldb/db-line-length/test.sh + +diff --git a/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini b/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini +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 + + # optional features - a bit mask to selectively turn on experimental/dubious features + # see +-# RETAIN_G43 0x00000001 + # OWORD_N_ARGS 0x00000002 + # INI_VARS 0x00000004 + # HAL_PIN_VARS 0x00000008 +diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc +index a99a87e..2d7a99e 100644 +--- a/docs/src/config/ini-config.adoc ++++ b/docs/src/config/ini-config.adoc +@@ -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. +-* `RETAIN_G43 = 0` (Default: 0) + +- When set, you can turn on G43 after loading the first tool, and then not worry about it through the program. +- When you finally unload the last tool, G43 mode is canceled. + * `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) + +@@ -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: + ---- +-FEATURES & 0x1 -> RETAIN_G43 + FEATURES & 0x2 -> OWORD_NARGS + 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 fa546b7..5355172 100644 +--- a/docs/src/config/python-interface.adoc ++++ b/docs/src/config/python-interface.adoc +@@ -368,7 +368,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, +- woffset, diameter, frontangle, backangle, orientation. The id and orientation ++ woffset, diameter, frontangle, backangle, orientation, wxoffset, wyoffset, ++ wzoffset, waoffset, wboffset, wcoffset, wuoffset, wvoffset, wwoffset. The id and orientation + are integers and the rest are floats. + [source,python] + ---- +@@ -389,7 +390,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', +- 'xoffset','yoffset', ... 'woffset', 'comment'. + ++ 'xoffset','yoffset', ... 'woffset', 'wxoffset','wyoffset', ... ++ 'wwoffset', 'comment'. + + As an example, the following script + [source,python] + ---- +diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc +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. + |<> |Radius Mode (lathe) + |<> |Reload Tool Table Data + |<> |Set Tool Table Entry ++|<> |Set Tool Wear Offset + |<> |Set Tool Table, Calculated, Workpiece + |<> |Set Tool Table, Calculated, Fixture + |<> |Coordinate System Origin Setting +@@ -705,7 +706,7 @@ current tool loaded in spindle. + + [NOTE] + +-When using G10 L0, tool parameters (#5401-#5413) 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 +@@ -748,6 +749,29 @@ It is an error if: + For more information on cutter orientation used by the 'Q' word, + see the <> diagram. + ++[[gcode:g10-l3]] ++== G10 L3 Set Tool Wear Offset(((G10 L3 Tool Wear Offset))) ++ ++[source,ngc] ++---- ++G10 L3 P- axes ++---- ++ ++G10 L3 replaces the supplied absolute wear values for an existing nonzero ++tool. Omitted axes remain unchanged and an explicit zero clears that wear ++axis. Values use ordinary program-unit conversion; X also follows G7/G8 ++diameter/radius interpretation. R, I, J, and Q are not allowed. ++ ++[source,ngc] ++---- ++G10 L3 P7 X0.050 Z-0.010 ++---- ++ ++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))) + +@@ -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'. + + [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 + +-* 'G43.2 H__n__' - applies an additional simultaneous tool offset to subsequent motions by adding the offset(s) of tool _n_. ++* 'G43.2 H__n__' - applies an additional simultaneous tool offset to subsequent motions by adding the geometry plus wear offset(s) of tool _n_. + + * 'G43.2 axes' - applies an additional simultaneous tool offset to subsequent motions by adding the value(s) of any axis words. + +@@ -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) + ---- + +-You can sum together an arbitrary number of offsets by calling G43.2 +-more times. There are no built-in assumptions about which numbers are +-geometry offsets and which are wear offsets, or that you should have +-only one of each. ++You can sum together an arbitrary number of independent offsets by calling ++G43.2 more times. + + 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. +@@ -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))) + +-* 'G49' - cancels tool length compensation ++* 'G49' - cancels the complete active tool length compensation without ++ changing stored geometry or wear. It remains cancelled until G43 or a ++ subsequent built-in tool change. + + '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 afa69cc..e74ef24 100644 +--- a/docs/src/gcode/m-code.adoc ++++ b/docs/src/gcode/m-code.adoc +@@ -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. ++* The selected tool's geometry plus wear offset is activated automatically. + * 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'. + +@@ -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). + +-[WARNING] +-The tool length offset is not changed by 'M6', use '<>' after the +-'M6' to change the tool length offset. ++An explicit tool-offset command in the same block is applied afterward, so ++`M6 G49` completes with compensation cancelled. A remapped M6 that bypasses ++the built-in tool-change path is responsible for its own compensation. + + The tool change may include axis motion. + It is OK (but not useful) to program a change to the tool already in the spindle. +@@ -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. + +-[WARNING] +-The tool length offset is not changed by 'M61', use '<>' after +-the 'M61' to change the tool length offset. ++The built-in M61 activates the resulting tool's geometry plus wear offset. ++An explicit command in the same block, such as `M61 Q7 G49`, takes precedence. + + 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 90f9a06..777efc6 100644 +--- a/docs/src/gcode/overview.adoc ++++ b/docs/src/gcode/overview.adoc +@@ -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. 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 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. + The file is located in the same directory as your configuration and is called 'tool.tbl' by default. + A file name may be specified with the INI file [EMCIO]TOOL_TABLE setting. + The tools might be in a tool changer or just changed manually. +-The file can be edited with a text editor or be updated using G10 L1. ++The file can be edited with a text editor or be updated using G10 L1 or G10 L3. + See the <> section for an example of the lathe tool table format. + The maximum pocket number is 1000. + +@@ -72,6 +72,7 @@ In general, the tool table line format is: + - T - tool number (tool numbers must be unique) + - P - pocket number, 1-1000 (pocket numbers must be unique, Pocket 0 represents the spindle) + - X..W - tool offset on specified axis - floating-point ++- WX, WY, WZ, WA, WB, WC, WU, WV, WW - wear offset on the specified axis - floating-point + - D - tool diameter - floating-point, absolute value + - I - front angle (lathe only) - floating-point + - J - back angle (lathe only) - floating-point +@@ -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. + ++Wear offsets are stored independently from geometry offsets. Missing wear ++fields mean zero. For example: ++ ++[source] ++---- ++T7 P7 X+12.000000 Z+40.000000 WX+0.025000 WZ-0.010000 ++---- ++ ++When G43 is active, LinuxCNC applies the sum of the geometry and wear ++offsets for every axis. ++ + 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 +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. + ++Wear Offset Numbers (optional):: ++The `W`-prefixed axis columns (`WX` through `WW`) contain stored wear ++corrections. They can be positive, negative, or zero and are added to the ++corresponding geometry offsets by G43. ++ + 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 +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. +-LinuxCNC pushes updates to the data source (`[EMCIO]TOOL_TABLE` or `[EMCIO]DB_PROGRAM`) for G-codes G10L1, G10L10, G10L11, M61. ++LinuxCNC pushes updates to the data source (`[EMCIO]TOOL_TABLE` or `[EMCIO]DB_PROGRAM`) for G-codes G10L1, G10L3, G10L10, G10L11, M61. + LinuxCNC can pull tooldata updates from the data source by UI (user-interface) commands (Python example: `linuxcnc.command().load_tool_table()`) or by the G-code: `G10L0`. + + .Random Location Tool Changers +diff --git a/docs/src/tooldatabase/tooldatabase.adoc b/docs/src/tooldatabase/tooldatabase.adoc +index 0fab019..04d7c54 100644 +--- a/docs/src/tooldatabase/tooldatabase.adoc ++++ b/docs/src/tooldatabase/tooldatabase.adoc +@@ -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. + +-=== *db_program* operation (v2.1) ++=== *db_program* operation (v2.2) + + When a *db_progam* is specified, operation is as follows: + + . At startup, LinuxCNC starts the *db_program* and connects to its stdin and stdout. +-. The *db_program* must respond by writing a single line acknowledgement consisting of a version string (e.g., "v2.1"). ++. The *db_program* must respond by writing a single line acknowledgement consisting of the version string "v2.2". + 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. ++ 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: + +-* "p" put data changes caused by G10L1, G10L10, G10L11 G-codes. The tool data line will include all elements of a tool table text line. ++* "p" put data changes caused by G10L1, G10L3, G10L10, G10L11 G-codes. The tool data line will include all elements of a tool table text line, including wear fields. + * "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 8ce720a..55a5dfe 100644 +--- a/lib/python/tooldb.py ++++ b/lib/python/tooldb.py +@@ -8,7 +8,7 @@ import traceback + # 2) all writes to stdout go to host + # (caller: use stderr for debug prints) + #----------------------------------------------------------- +-DB_VERSION = 'v2.1' ++DB_VERSION = 'v2.2' + + #----------------------------------------------------------- + # functions for import by user +diff --git a/src/emc/ini/linuxcnc_check_ini.py b/src/emc/ini/linuxcnc_check_ini.py +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(): + ("EMCIO", "RANDOM_TOOLCHANGER"), + ("RS274NGC", "INI_VARS"), + ("RS274NGC", "HAL_PIN_VARS"), +- ("RS274NGC", "RETAIN_G43"), + ("RS274NGC", "OWORD_NARGS"), + ("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 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": + if features != None: + features = int(features) + section = re.sub("FEATURES.*?\n", "", section) +- section += ("RETAIN_G43 = %s\n" % ("1" if features & 0x1 else "0")) + section += ("INI_VARS = %s\n" % ("1" if features & 0x4 else "0")) + 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 96e558d..68cf5d4 100644 +--- a/src/emc/nml_intf/canon.hh ++++ b/src/emc/nml_intf/canon.hh +@@ -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 */ +-extern void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, double diameter, ++extern void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, double diameter, + double frontangle, double backangle, int orientation); + 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 25e5f5a..d8d1d9d 100644 +--- a/src/emc/nml_intf/emc.cc ++++ b/src/emc/nml_intf/emc.cc +@@ -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); ++ EmcPose_update(cms, &wear_offset); ++ cms->update(wear_offset_valid); + cms->update(diameter); + cms->update(frontangle); + cms->update(backangle); +@@ -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); ++ EmcPose_update(cms, &x->wear_offset); + cms->update(x->diameter); + 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 6c61f5a..9435447 100644 +--- a/src/emc/nml_intf/emc.hh ++++ b/src/emc/nml_intf/emc.hh +@@ -430,9 +430,18 @@ extern int emcToolPrepare(int tool); + extern int emcToolLoad(); + extern int emcToolUnload(); + extern int emcToolLoadToolTable(const char *file); +-extern int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, double diameter, +- double frontangle, double backangle, int orientation); ++extern int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, bool wear_offset_valid, ++ 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 0d4ab6c..89aba60 100644 +--- a/src/emc/nml_intf/emc_nml.hh ++++ b/src/emc/nml_intf/emc_nml.hh +@@ -1637,13 +1637,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 { +@@ -1680,6 +1689,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { + pocket(0), + toolno(0), + offset{}, ++ wear_offset{}, ++ wear_offset_valid(false), + diameter(0.0), + frontangle(0.0), + backangle(0.0), +@@ -1694,6 +1705,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { + int pocket; + int toolno; + EmcPose offset; ++ EmcPose wear_offset; ++ bool wear_offset_valid; + double diameter; + double frontangle; + double backangle; +@@ -1704,7 +1717,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. +@@ -1713,6 +1728,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 3935368..ea18394 100644 +--- a/src/emc/nml_intf/emctool.h ++++ b/src/emc/nml_intf/emctool.h +@@ -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 { + int toolno; + int pocketno; + EmcPose offset; ++ EmcPose wear_offset; + 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 cb3d7ab..91d4b7b 100644 +--- a/src/emc/rs274ngc/gcodemodule.cc ++++ b/src/emc/rs274ngc/gcodemodule.cc +@@ -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*/, ++void SET_TOOL_TABLE_ENTRY(int /*pocket*/, int /*toolno*/, const EmcPose& /*offset*/, ++ const EmcPose& /*wear_offset*/, double /*diameter*/, + double /*frontangle*/, double /*backangle*/, int /*orientation*/) { + } + +@@ -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 = 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 6eb4e1c..a900d33 100644 +--- a/src/emc/rs274ngc/interp_array.cc ++++ b/src/emc/rs274ngc/interp_array.cc +@@ -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 ++ 5430, 5431, 5432, 5433, 5434, 5435, 5436, 5437, 5438, // loaded tool wear X Y ... W + }; + 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 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 + CHKS((mode1 == G_2 || mode1 == G_3), _("G4 not allowed with G2 or G3 because they both use P")); + } else if (mode0 == G_10) { + (block->p_number >= 0) ? p_int = (int) (block->p_number +0.5) :p_int = (int) (block->p_number -0.5); +- CHKS((block->l_number != 0 && block->l_number != 2 && block->l_number != 1 && block->l_number != 20 && block->l_number != 10 && block->l_number != 11), _("Line with G10 does not have L0, L1, L10, L11, L2, or L20")); ++ CHKS((block->l_number != 0 && block->l_number != 2 && block->l_number != 1 && block->l_number != 3 && block->l_number != 20 && block->l_number != 10 && block->l_number != 11), _("Line with G10 does not have L0, L1, L3, L10, L11, L2, or L20")); + CHKS((((block->p_number + 0.0001) - p_int) > 0.0002), _("P value not an integer with G10")); + CHKS((((block->l_number == 2 || block->l_number == 20) && ((p_int < 0) || (p_int > 9)))), _("P value out of range (0-9) with G10 L%d"), block->l_number); +- CHKS((((block->l_number == 1 || block->l_number == 10 || block->l_number == 11) && p_int < 1)), _("P value out of range with G10 L%d"), block->l_number); ++ CHKS((((block->l_number == 1 || block->l_number == 3 || block->l_number == 10 || block->l_number == 11) && p_int < 1)), _("P value out of range with G10 L%d"), block->l_number); + } else if (mode0 == G_28) { + } 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 450922e..10bf98d 100644 +--- a/src/emc/rs274ngc/interp_convert.cc ++++ b/src/emc/rs274ngc/interp_convert.cc +@@ -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; ++ int changed_toolno = -1; + double timeout; // timeout for M66 + + /* The M62-65 commands are used for DIO */ +@@ -4148,6 +4150,8 @@ 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)); ++ builtin_tool_change = true; ++ changed_toolno = settings->selected_tool; + } + break; + +@@ -4160,6 +4164,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 +4177,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(); ++ builtin_tool_change = true; ++ changed_toolno = toolno; + } + break; + +@@ -4180,22 +4190,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) || +- (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[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); +- block->g_modes[gees[G_49]] = G_49; +- CHP(convert_tool_length_offset(G_49, &g49, settings)); +- } +- } ++ if (builtin_tool_change) { ++ struct block_struct automatic_tlo; ++ init_block(&automatic_tlo); ++ const bool no_tool = !settings->random_toolchanger && changed_toolno <= 0; ++ if (no_tool) { ++ for (int param = 5430; param <= 5438; ++param) { ++ settings->parameters[param] = 0; ++ } ++ } else { ++ const CANON_TOOL_TABLE &loaded_tool = settings->tool_table[settings->current_pocket]; ++ settings->parameters[5430] = loaded_tool.wear_offset.tran.x; ++ settings->parameters[5431] = loaded_tool.wear_offset.tran.y; ++ settings->parameters[5432] = loaded_tool.wear_offset.tran.z; ++ settings->parameters[5433] = loaded_tool.wear_offset.a; ++ settings->parameters[5434] = loaded_tool.wear_offset.b; ++ settings->parameters[5435] = loaded_tool.wear_offset.c; ++ settings->parameters[5436] = loaded_tool.wear_offset.u; ++ settings->parameters[5437] = loaded_tool.wear_offset.v; ++ settings->parameters[5438] = loaded_tool.wear_offset.w; ++ } ++ // 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)) { +@@ -4464,7 +4483,7 @@ int Interp::convert_modal_0(int code, //!< G-code, must be from group 0 + { + + if (code == G_10) { +- if(block->l_number == 1 || block->l_number == 10 || block->l_number == 11) ++ if(block->l_number == 1 || block->l_number == 3 || block->l_number == 10 || block->l_number == 11) + CHP(convert_setup_tool(block, settings)); + else if (block->l_number == 0) { + int tno = settings->tool_table[0].toolno; +@@ -4731,7 +4750,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; +- int direct = block->l_number == 1; ++ const bool direct = block->l_number == 1; ++ const bool wear = block->l_number == 3; + + is_near_int(&toolno, block->p_number); + +@@ -4742,9 +4762,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")); ++ ++ 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); ++ if(block->y_flag) ++ settings->tool_table[idx].wear_offset.tran.y = PROGRAM_TO_USER_LEN(block->y_number); ++ 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_AX(AXIS_A, block->a_number); ++ if(block->b_flag) ++ 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_AX(AXIS_C, block->c_number); ++ if(block->u_flag) ++ 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_AX(AXIS_V, block->v_number); ++ if(block->w_flag) ++ 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) +@@ -4844,10 +4886,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.; +- if(block->i_flag) settings->tool_table[idx].frontangle = block->i_number; +- if(block->j_flag) settings->tool_table[idx].backangle = block->j_number; +- if(block->q_number != -1.0) { ++ if(!wear && block->r_flag) settings->tool_table[idx].diameter = PROGRAM_TO_USER_LEN(block->r_number) * 2.; ++ if(!wear && block->i_flag) settings->tool_table[idx].frontangle = block->i_number; ++ if(!wear && block->j_flag) settings->tool_table[idx].backangle = block->j_number; ++ if(!wear && block->q_number != -1.0) { + 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; +@@ -4856,6 +4898,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, ++ settings->tool_table[idx].wear_offset, + settings->tool_table[idx].diameter, + settings->tool_table[idx].frontangle, + settings->tool_table[idx].backangle, +@@ -4910,6 +4953,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; ++ settings->parameters[5430] = settings->tool_table[0].wear_offset.tran.x; ++ settings->parameters[5431] = settings->tool_table[0].wear_offset.tran.y; ++ settings->parameters[5432] = settings->tool_table[0].wear_offset.tran.z; ++ settings->parameters[5433] = settings->tool_table[0].wear_offset.a; ++ settings->parameters[5434] = settings->tool_table[0].wear_offset.b; ++ settings->parameters[5435] = settings->tool_table[0].wear_offset.c; ++ settings->parameters[5436] = settings->tool_table[0].wear_offset.u; ++ settings->parameters[5437] = settings->tool_table[0].wear_offset.v; ++ settings->parameters[5438] = settings->tool_table[0].wear_offset.w; + + // if the modified tool is currently in the spindle, then copy its + // information to index 0 of the tool table (which signifies the +@@ -4919,6 +4971,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, ++ settings->tool_table[idx].wear_offset, + settings->tool_table[idx].diameter, + settings->tool_table[idx].frontangle, + settings->tool_table[idx].backangle, +@@ -6438,11 +6491,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. + +-Note that if a different tool is put into the spindle, the current_z +-location setting will be incorrect. It is assumed the program will +-contain an appropriate USE_TOOL_LENGTH_OFFSET (G43) command before any +-subsequent motion. It is also assumed that the program will restart the +-spindle and make new entry moves if necessary. ++After this built-in path returns, convert_m applies the resulting tool's ++stored geometry plus wear offset. It is assumed that the program will ++restart the spindle and make new entry moves if necessary. + + */ + +@@ -6662,15 +6713,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_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_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 || +@@ -6697,15 +6748,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_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_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 +6800,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 +6851,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 8066f0e..6f90dbe 100644 +--- a/src/emc/rs274ngc/interp_internal.hh ++++ b/src/emc/rs274ngc/interp_internal.hh +@@ -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, +@@ -887,7 +886,6 @@ struct setup + bool iscircle; + + #define FEATURE(x) (_setup.feature_set & FEATURE_ ## x) +-#define FEATURE_RETAIN_G43 0x00000001 + #define FEATURE_OWORD_N_ARGS 0x00000002 + #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 d0c81d3..666b4d5 100644 +--- a/src/emc/rs274ngc/interp_parameter_def.hh ++++ b/src/emc/rs274ngc/interp_parameter_def.hh +@@ -206,6 +206,16 @@ enum InterpParameterIndex { + RELATIVE_POSITION_U, + RELATIVE_POSITION_V, + RELATIVE_POSITION_W, ++// 5430-5438 - Stored wear offsets for the loaded tool for X, Y, Z, A, B, C, U, V & W. Volatile. ++ TOOL_WEAR_OFFSET_X=5430, ++ TOOL_WEAR_OFFSET_Y, ++ TOOL_WEAR_OFFSET_Z, ++ TOOL_WEAR_OFFSET_A, ++ TOOL_WEAR_OFFSET_B, ++ TOOL_WEAR_OFFSET_C, ++ TOOL_WEAR_OFFSET_U, ++ TOOL_WEAR_OFFSET_V, ++ TOOL_WEAR_OFFSET_W, + // 5599 - Flag for controlling the output of (DEBUG,) statements. 1=output, 0=no output; default=1. Volatile. + DEBUG_LEVEL_FLAG=5599, + RS274NGC_MAX_PARAMETERS=5602 +diff --git a/src/emc/rs274ngc/pyemctypes.cc b/src/emc/rs274ngc/pyemctypes.cc +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) { + static void tool_zero( CANON_TOOL_TABLE &t) { + t.toolno = -1; + ZERO_EMC_POSE(t.offset); ++ ZERO_EMC_POSE(t.wear_offset); + t.diameter = 0.0; + t.frontangle = 0.0; + t.backangle = 0.0; +@@ -106,6 +107,7 @@ void export_EmcTypes() + class_("CANON_TOOL_TABLE","Tool description" ,no_init) + .def_readwrite("toolno", &CANON_TOOL_TABLE::toolno) + .def_readwrite("offset", &CANON_TOOL_TABLE::offset) ++ .def_readwrite("wear_offset", &CANON_TOOL_TABLE::wear_offset) + .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 ac70436..2ea3ba1 100644 +--- a/src/emc/rs274ngc/rs274ngc_pre.cc ++++ b/src/emc/rs274ngc/rs274ngc_pre.cc +@@ -933,8 +933,6 @@ int Interp::init() + _setup.feature_set |= FEATURE_HAL_PIN_VARS; + + // Now those that (currently) default to off +- if (inifile.findBoolV("RETAIN_G43", "RS274NGC", false)) +- _setup.feature_set |= FEATURE_RETAIN_G43; + if (inifile.findBoolV("OWORD_NARGS", "RS274NGC", false)) + _setup.feature_set |= FEATURE_OWORD_N_ARGS; + if (inifile.findBoolV("NO_DOWNCASE_OWORD", "RS274NGC", false)) +@@ -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; ++ _setup.parameters[5430] = _setup.tool_table[0].wear_offset.tran.x; ++ _setup.parameters[5431] = _setup.tool_table[0].wear_offset.tran.y; ++ _setup.parameters[5432] = _setup.tool_table[0].wear_offset.tran.z; ++ _setup.parameters[5433] = _setup.tool_table[0].wear_offset.a; ++ _setup.parameters[5434] = _setup.tool_table[0].wear_offset.b; ++ _setup.parameters[5435] = _setup.tool_table[0].wear_offset.c; ++ _setup.parameters[5436] = _setup.tool_table[0].wear_offset.u; ++ _setup.parameters[5437] = _setup.tool_table[0].wear_offset.v; ++ _setup.parameters[5438] = _setup.tool_table[0].wear_offset.w; + } else { + // non random_toolchanger: no tool at startup, one-time init + if (_setup.tool_table[0].toolno == -1) { + default_tool_parameters(); ++ } else { ++ set_tool_parameters(); + } + } + return 0; +@@ -2657,6 +2678,9 @@ int Interp::default_tool_parameters() + _setup.parameters[5411] = 0; // frontangle + _setup.parameters[5412] = 0; // backangle + _setup.parameters[5413] = 0; // orientation ++ for (int param = 5430; param <= 5438; ++param) { ++ _setup.parameters[param] = 0; ++ } + return 0; + } + +@@ -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; ++ _setup.parameters[5430] = _setup.tool_table[0].wear_offset.tran.x; ++ _setup.parameters[5431] = _setup.tool_table[0].wear_offset.tran.y; ++ _setup.parameters[5432] = _setup.tool_table[0].wear_offset.tran.z; ++ _setup.parameters[5433] = _setup.tool_table[0].wear_offset.a; ++ _setup.parameters[5434] = _setup.tool_table[0].wear_offset.b; ++ _setup.parameters[5435] = _setup.tool_table[0].wear_offset.c; ++ _setup.parameters[5436] = _setup.tool_table[0].wear_offset.u; ++ _setup.parameters[5437] = _setup.tool_table[0].wear_offset.v; ++ _setup.parameters[5438] = _setup.tool_table[0].wear_offset.w; + + return 0; + } +diff --git a/src/emc/sai/saicanon.cc b/src/emc/sai/saicanon.cc +index d60d661..73a77d2 100644 +--- a/src/emc/sai/saicanon.cc ++++ b/src/emc/sai/saicanon.cc +@@ -513,12 +513,14 @@ void USE_NO_SPINDLE_FORCE() + {PRINT("USE_NO_SPINDLE_FORCE()\n");} + + /* Tool Functions */ +-void SET_TOOL_TABLE_ENTRY(int idx, int toolno, const EmcPose& offset, double diameter, ++void SET_TOOL_TABLE_ENTRY(int idx, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, double diameter, + double frontangle, double backangle, int orientation) { + + #ifdef TOOL_NML //{ + _sai._tools[idx].toolno = toolno; + _sai._tools[idx].offset = offset; ++ _sai._tools[idx].wear_offset = wear_offset; + _sai._tools[idx].diameter = diameter; + _sai._tools[idx].frontangle = frontangle; + _sai._tools[idx].backangle = backangle; +@@ -530,6 +532,7 @@ void SET_TOOL_TABLE_ENTRY(int idx, int toolno, const EmcPose& offset, double dia + } + tdata.toolno = toolno; + tdata.offset = offset; ++ tdata.wear_offset = wear_offset; + tdata.diameter = diameter; + tdata.frontangle = frontangle; + tdata.backangle = backangle; +diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc +index 706a6e4..92c2d99 100644 +--- a/src/emc/task/emccanon.cc ++++ b/src/emc/task/emccanon.cc +@@ -2914,13 +2914,16 @@ void USE_NO_SPINDLE_FORCE(void) + /* Tool Functions */ + + /* this is called with distances in external (machine) units */ +-void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, double diameter, ++void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, double diameter, + double frontangle, double backangle, int orientation) { + auto o = std::make_unique(); + flush_segments(); + o->pocket = pocket; + o->toolno = toolno; + o->offset = offset; ++ o->wear_offset = wear_offset; ++ o->wear_offset_valid = true; + o->diameter = diameter; + o->frontangle = frontangle; + o->backangle = backangle; +@@ -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 564e4a1..df94f0c 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -610,6 +610,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 +@@ -1854,6 +1857,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; + +@@ -1931,6 +1939,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; +@@ -2434,9 +2448,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(); +@@ -2452,6 +2470,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, ++ emc_tool_set_offset_msg->wear_offset, ++ emc_tool_set_offset_msg->wear_offset_valid, + emc_tool_set_offset_msg->diameter, + emc_tool_set_offset_msg->frontangle, + emc_tool_set_offset_msg->backangle, +@@ -2461,6 +2481,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 +@@ -3050,6 +3074,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; + +@@ -3616,7 +3641,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; +@@ -4066,6 +4092,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 6694667..6ba96b9 100644 +--- a/src/emc/task/taskclass.cc ++++ b/src/emc/task/taskclass.cc +@@ -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); } +-int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, double diameter, +- double frontangle, double backangle, int orientation) { +- return task_methods->emcToolSetOffset( pocket, toolno, offset, diameter, +- frontangle, backangle, orientation); } ++int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, bool wear_offset_valid, ++ double diameter, double frontangle, double backangle, ++ int orientation) { ++ return task_methods->emcToolSetOffset(pocket, toolno, offset, wear_offset, ++ wear_offset_valid, diameter, frontangle, ++ 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) + { + task_methods = new Task(emcioStatus); +@@ -392,6 +424,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 +546,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 +556,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 +589,10 @@ int Task::emcToolLoadToolTable(const char *file)//EMC_TOOL_LOAD_TOOL_TABLE_TYPE + return 0; + } + +-int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, double diameter, +- double frontangle, double backangle, int orientation)//EMC_TOOL_SET_OFFSET ++int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, bool wear_offset_valid, ++ double diameter, double frontangle, double backangle, ++ int orientation)//EMC_TOOL_SET_OFFSET + { + + int o; +@@ -574,8 +612,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) { ++ tdata.wear_offset = wear_offset; ++ } + tdata.diameter = d; + tdata.frontangle = f; + tdata.backangle = b; +@@ -583,17 +625,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; + } ++ rcs_print_error("tool %d: offsets not stored, tool table unchanged\n", toolno); ++ emcioStatus.status = RCS_STATUS::ERROR; + } + + return 0; +@@ -674,6 +723,10 @@ int Task::read_tool_inputs(void) + 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 ++ // the new tool's offset takes effect with the tool ++ 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 6f4aff7..75572ea 100644 +--- a/src/emc/task/taskclass.hh ++++ b/src/emc/task/taskclass.hh +@@ -67,8 +67,9 @@ public: + virtual int emcCoolantMistOff(); + virtual int emcCoolantFloodOn(); + virtual int emcCoolantFloodOff(); +- virtual int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, double diameter, +- double frontangle, double backangle, int orientation); ++ virtual int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, bool wear_offset_valid, double diameter, ++ double frontangle, double backangle, int orientation); + virtual int emcToolPrepare(int tool); + virtual int emcToolLoad(); + virtual int emcToolLoadToolTable(const char *file); +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 3447f4d..ceefe9b 100644 +--- a/src/emc/tooldata/tooldata_common.cc ++++ b/src/emc/tooldata/tooldata_common.cc +@@ -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" + + #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; +- EmcPose offset; //tlo ++ EmcPose offset; // geometry tlo ++ EmcPose wear_offset; + double diameter, frontangle, backangle; + int idx = 0; + int realpocket = 0; +@@ -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; ++ wear_offset = empty.wear_offset; + + char* saveptr; + buff = strtok_r(work_line, ";", &saveptr); +@@ -160,8 +168,20 @@ int tooldata_read_entry(const char *input_line) + valid = 0; + break; + case 'W': +- if (sscanf(&token[1], "%lf", &offset.w) != 1) +- valid = 0; ++ // Wear fields are two-letter tokens and must be recognized ++ // before the legacy single-letter W geometry axis. ++ switch (toupper(token[1])) { ++ case 'X': if (sscanf(&token[2], "%lf", &wear_offset.tran.x) != 1) valid = 0; break; ++ case 'Y': if (sscanf(&token[2], "%lf", &wear_offset.tran.y) != 1) valid = 0; break; ++ case 'Z': if (sscanf(&token[2], "%lf", &wear_offset.tran.z) != 1) valid = 0; break; ++ case 'A': if (sscanf(&token[2], "%lf", &wear_offset.a) != 1) valid = 0; break; ++ case 'B': if (sscanf(&token[2], "%lf", &wear_offset.b) != 1) valid = 0; break; ++ case 'C': if (sscanf(&token[2], "%lf", &wear_offset.c) != 1) valid = 0; break; ++ case 'U': if (sscanf(&token[2], "%lf", &wear_offset.u) != 1) valid = 0; break; ++ case 'V': if (sscanf(&token[2], "%lf", &wear_offset.v) != 1) valid = 0; break; ++ case 'W': if (sscanf(&token[2], "%lf", &wear_offset.w) != 1) valid = 0; break; ++ default: if (sscanf(&token[1], "%lf", &offset.w) != 1) valid = 0; break; ++ } + break; + case 'I': + if (sscanf(&token[1], "%lf", &frontangle) != 1) +@@ -196,6 +216,7 @@ int tooldata_read_entry(const char *input_line) + tdata.toolno = toolno; + tdata.pocketno = realpocket; + tdata.offset = offset; ++ tdata.wear_offset = wear_offset; + tdata.diameter = diameter; + tdata.frontangle = frontangle; + tdata.backangle = backangle; +@@ -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"); ++ F_ITEM(wear_offset.tran.x, "WX"); ++ F_ITEM(wear_offset.tran.y, "WY"); ++ F_ITEM(wear_offset.tran.z, "WZ"); ++ F_ITEM(wear_offset.a, "WA"); ++ F_ITEM(wear_offset.b, "WB"); ++ F_ITEM(wear_offset.c, "WC"); ++ F_ITEM(wear_offset.u, "WU"); ++ F_ITEM(wear_offset.v, "WV"); ++ F_ITEM(wear_offset.w, "WW"); + 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 4a5f885..963f4a5 100644 +--- a/src/emc/tooldata/tooldata_db.cc ++++ b/src/emc/tooldata/tooldata_db.cc +@@ -27,7 +27,7 @@ + #include "tooldata.hh" + #include + +-#define DB_VERSION "v2.1" ++#define DB_VERSION "v2.2" + #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 13069fb..8e91c88 100644 +--- a/src/emc/usr_intf/axis/extensions/emcmodule.cc ++++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc +@@ -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); ++ dict_add(res, "wxoffset", tdata.wear_offset.tran.x); ++ dict_add(res, "wyoffset", tdata.wear_offset.tran.y); ++ dict_add(res, "wzoffset", tdata.wear_offset.tran.z); ++ dict_add(res, "waoffset", tdata.wear_offset.a); ++ dict_add(res, "wboffset", tdata.wear_offset.b); ++ dict_add(res, "wcoffset", tdata.wear_offset.c); ++ dict_add(res, "wuoffset", tdata.wear_offset.u); ++ dict_add(res, "wvoffset", tdata.wear_offset.v); ++ dict_add(res, "wwoffset", tdata.wear_offset.w); + + PyDict_SetItemString(res, "comment", o= PyUnicode_FromString(tdata.comment)); + Py_DECREF(o); +@@ -1485,6 +1494,15 @@ static PyStructSequence_Field tool_fields[] = { + {(char*)"frontangle", NULL}, + {(char*)"backangle", NULL}, + {(char*)"orientation", NULL}, ++ {(char*)"wxoffset", NULL}, ++ {(char*)"wyoffset", NULL}, ++ {(char*)"wzoffset", NULL}, ++ {(char*)"waoffset", NULL}, ++ {(char*)"wboffset", NULL}, ++ {(char*)"wcoffset", NULL}, ++ {(char*)"wuoffset", NULL}, ++ {(char*)"wvoffset", NULL}, ++ {(char*)"wwoffset", NULL}, + {}, + }; + +@@ -1492,7 +1510,7 @@ static PyStructSequence_Desc tool_result_desc = { + (char*)"tool_result", /* name */ + (char*)"", /* doc */ + tool_fields, +- 14 ++ 23 + }; + + static PyTypeObject ToolResultType; +@@ -1530,6 +1548,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)); ++ PyStructSequence_SET_ITEM(tool, 14, PyFloat_FromDouble(t.wear_offset.tran.x)); ++ PyStructSequence_SET_ITEM(tool, 15, PyFloat_FromDouble(t.wear_offset.tran.y)); ++ PyStructSequence_SET_ITEM(tool, 16, PyFloat_FromDouble(t.wear_offset.tran.z)); ++ PyStructSequence_SET_ITEM(tool, 17, PyFloat_FromDouble(t.wear_offset.a)); ++ PyStructSequence_SET_ITEM(tool, 18, PyFloat_FromDouble(t.wear_offset.b)); ++ PyStructSequence_SET_ITEM(tool, 19, PyFloat_FromDouble(t.wear_offset.c)); ++ PyStructSequence_SET_ITEM(tool, 20, PyFloat_FromDouble(t.wear_offset.u)); ++ PyStructSequence_SET_ITEM(tool, 21, PyFloat_FromDouble(t.wear_offset.v)); ++ PyStructSequence_SET_ITEM(tool, 22, PyFloat_FromDouble(t.wear_offset.w)); + PyTuple_SetItem(res, j, tool); + j++; + } +diff --git a/tests/ccomp/lathe-comp/expected b/tests/ccomp/lathe-comp/expected +index 4fabddb..bba4efd 100644 +--- a/tests/ccomp/lathe-comp/expected ++++ b/tests/ccomp/lathe-comp/expected +@@ -13,6 +13,7 @@ + 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..... STRAIGHT_TRAVERSE(0.3000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("interpreter: cutter radius compensation off") + N..... STRAIGHT_FEED(0.1000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) +@@ -26,6 +27,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) ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... STRAIGHT_TRAVERSE(0.3000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + N..... COMMENT("interpreter: cutter radius compensation on left") + N..... STRAIGHT_FEED(0.0500, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) +@@ -40,6 +42,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) ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... STRAIGHT_TRAVERSE(0.3000, 0.0000, 1.8500, 0.0000, 0.0000, 0.0000) + N..... STRAIGHT_TRAVERSE(-0.3000, 0.0000, 1.8500, 0.0000, 0.0000, 0.0000) + N..... COMMENT("interpreter: cutter radius compensation on right") +@@ -56,6 +59,7 @@ + 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..... 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) +diff --git a/tests/ccomp/mill-g90g91g92/expected b/tests/ccomp/mill-g90g91g92/expected +index f58e400..7327c18 100644 +--- a/tests/ccomp/mill-g90g91g92/expected ++++ b/tests/ccomp/mill-g90g91g92/expected +@@ -8,6 +8,7 @@ + N..... SELECT_TOOL(3) + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.5000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... STRAIGHT_TRAVERSE(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) + 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 ab893c5..ea4339f 100644 +--- a/tests/ccomp/mill-line-arc-entry/expected ++++ b/tests/ccomp/mill-line-arc-entry/expected +@@ -24,6 +24,7 @@ + N..... SELECT_TOOL(4) + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + 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 4bc9ee3..6f3aab5 100644 +--- a/tests/interp/cam-nisley/expected ++++ b/tests/interp/cam-nisley/expected +@@ -51,6 +51,7 @@ + N..... SELECT_TOOL(1) + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 12.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... COMMENT("-----------------") + 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 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) {} + void LOCK_SPINDLE_Z() {} + void USE_SPINDLE_FORCE() {} + void USE_NO_SPINDLE_FORCE() {} +-void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, double diameter, ++void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, ++ const EmcPose& wear_offset, double diameter, + double frontangle, double backangle, int orientation) {} + 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 0cad340..2c183bd 100644 +--- a/tests/interp/g10/g10-l1-l10/expected ++++ b/tests/interp/g10/g10-l1-l10/expected +@@ -16,6 +16,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) ++ 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(" 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) +@@ -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) ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + 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) +@@ -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) ++ 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(" 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) +@@ -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) ++ 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(" 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) +diff --git a/tests/interp/g10/g10-l11/expected b/tests/interp/g10/g10-l11/expected +index 867b953..68d9ed6 100644 +--- a/tests/interp/g10/g10-l11/expected ++++ b/tests/interp/g10/g10-l11/expected +@@ -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..... 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) + 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..... 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, -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 1096d6d..5bf7314 100644 +--- a/tests/interp/g72-facing/expected ++++ b/tests/interp/g72-facing/expected +@@ -11,6 +11,7 @@ + N..... SELECT_TOOL(2) + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 2.5400, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... COMMENT("interpreter: cutter radius compensation off") + 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 56181de..0498594 100644 +--- a/tests/interp/g72-missing-iteration/expected ++++ b/tests/interp/g72-missing-iteration/expected +@@ -11,6 +11,7 @@ + N..... SELECT_TOOL(2) + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 2.5400, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... COMMENT("interpreter: cutter radius compensation off") + 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 488e01b..d94d652 100644 +--- a/tests/interp/g76/expected ++++ b/tests/interp/g76/expected +@@ -14,6 +14,7 @@ + N..... STOP_SPINDLE_TURNING(0) + N..... CHANGE_TOOL() + N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) ++ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) + N..... SET_SPINDLE_SPEED(0, 800.0000) + N..... START_SPINDLE_CLOCKWISE(0) + N..... DWELL(1.0000) +diff --git a/tests/interp/tool-line-length/expected b/tests/interp/tool-line-length/expected +new file mode 100644 +index 0000000..43d9c1a +--- /dev/null ++++ b/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/tests/interp/tool-line-length/missing-t2.ngc b/tests/interp/tool-line-length/missing-t2.ngc +new file mode 100644 +index 0000000..a05d8bd +--- /dev/null ++++ b/tests/interp/tool-line-length/missing-t2.ngc +@@ -0,0 +1,3 @@ ++g21 ++g43 h2 ++m2 +diff --git a/tests/interp/tool-line-length/missing-t3.ngc b/tests/interp/tool-line-length/missing-t3.ngc +new file mode 100644 +index 0000000..c7e3b12 +--- /dev/null ++++ b/tests/interp/tool-line-length/missing-t3.ngc +@@ -0,0 +1,3 @@ ++g21 ++g43 h3 ++m2 +diff --git a/tests/interp/tool-line-length/missing-t4.ngc b/tests/interp/tool-line-length/missing-t4.ngc +new file mode 100644 +index 0000000..369efa7 +--- /dev/null ++++ b/tests/interp/tool-line-length/missing-t4.ngc +@@ -0,0 +1,3 @@ ++g21 ++g43 h4 ++m2 +diff --git a/tests/interp/tool-line-length/test.ngc b/tests/interp/tool-line-length/test.ngc +new file mode 100644 +index 0000000..aea66da +--- /dev/null ++++ b/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/tests/interp/tool-line-length/test.sh b/tests/interp/tool-line-length/test.sh +new file mode 100755 +index 0000000..0822c76 +--- /dev/null ++++ b/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/tests/interp/tool-line-length/test.tbl b/tests/interp/tool-line-length/test.tbl +new file mode 100644 +index 0000000..134455e +--- /dev/null ++++ b/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/tests/interp/tool-wear/expected b/tests/interp/tool-wear/expected +new file mode 100644 +index 0000000..e9e62dc +--- /dev/null ++++ b/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/tests/interp/tool-wear/invalid-i.ngc b/tests/interp/tool-wear/invalid-i.ngc +new file mode 100644 +index 0000000..3ee52a2 +--- /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 0000000..3613d39 +--- /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-m61-comp.ngc b/tests/interp/tool-wear/invalid-m61-comp.ngc +new file mode 100644 +index 0000000..1f2d11a +--- /dev/null ++++ b/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/tests/interp/tool-wear/invalid-missing-tool.ngc b/tests/interp/tool-wear/invalid-missing-tool.ngc +new file mode 100644 +index 0000000..c9cf799 +--- /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 0000000..c995e9b +--- /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 0000000..8ef7a87 +--- /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 0000000..3a172d8 +--- /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 0000000..fb5f4d5 +--- /dev/null ++++ b/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 tests/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/tests/interp/tool-wear/test.sh b/tests/interp/tool-wear/test.sh +new file mode 100755 +index 0000000..955dbcd +--- /dev/null ++++ b/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/tests/interp/tool-wear/test.tbl b/tests/interp/tool-wear/test.tbl +new file mode 100644 +index 0000000..1a6d140 +--- /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 2f33b4b..7655928 100644 +--- a/tests/remap/introspect/expected ++++ b/tests/remap/introspect/expected +@@ -9,9 +9,10 @@ executing + 8 N..... SELECT_TOOL(3) + 9 N..... STOP_SPINDLE_TURNING(0) + 10 N..... CHANGE_TOOL() +- 11 N..... SET_FEED_RATE(200.0000) +- 12 N..... SET_SPINDLE_SPEED(0, 3000.0000) +- 13 N..... START_SPINDLE_CLOCKWISE(0) ++ 11 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 32.3342, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) ++ 12 N..... SET_FEED_RATE(200.0000) ++ 13 N..... SET_SPINDLE_SPEED(0, 3000.0000) ++ 14 N..... START_SPINDLE_CLOCKWISE(0) + debug: 1073741824 logging: 0 + call_level= 1 + 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_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) +- 17 N..... SET_FEED_MODE(0, 0) +- 18 N..... SET_FEED_RATE(0.0000) +- 19 N..... STOP_SPINDLE_TURNING(0) +- 20 N..... SET_SPINDLE_MODE(0 0.0000) +- 21 N..... PROGRAM_END() +- 22 N..... ON_RESET() ++ 15 N..... MESSAGE(" after introspect: return value=2.718280 call_level= 0.000000") ++ 16 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) ++ 17 N..... SET_XY_ROTATION(0.0000) ++ 18 N..... SET_FEED_MODE(0, 0) ++ 19 N..... SET_FEED_RATE(0.0000) ++ 20 N..... STOP_SPINDLE_TURNING(0) ++ 21 N..... SET_SPINDLE_MODE(0 0.0000) ++ 22 N..... PROGRAM_END() ++ 23 N..... ON_RESET() +diff --git a/tests/remap/oword-pycall/expected b/tests/remap/oword-pycall/expected +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 + 9 N..... STOP_SPINDLE_TURNING(0) + 10 N..... CHANGE_TOOL() + 11 N..... USE_TOOL_LENGTH_OFFSET(10.0000 0.0000 20.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) +- 12 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) +- 13 N..... SET_TOOL_TABLE_ENTRY(1, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) +- 14 N..... SET_TOOL_TABLE_ENTRY(0, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) +- 15 N..... USE_TOOL_LENGTH_OFFSET(20.0000 30.0000 40.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) +- 16 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) +- 17 N..... SET_XY_ROTATION(0.0000) +- 18 N..... SET_FEED_MODE(0, 0) +- 19 N..... SET_FEED_RATE(0.0000) +- 20 N..... STOP_SPINDLE_TURNING(0) +- 21 N..... SET_SPINDLE_MODE(0 0.0000) +- 22 N..... PROGRAM_END() +- 23 N..... ON_RESET() ++ 12 N..... USE_TOOL_LENGTH_OFFSET(10.0000 0.0000 20.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) ++ 13 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) ++ 14 N..... SET_TOOL_TABLE_ENTRY(1, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) ++ 15 N..... SET_TOOL_TABLE_ENTRY(0, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) ++ 16 N..... USE_TOOL_LENGTH_OFFSET(20.0000 30.0000 40.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) ++ 17 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) ++ 18 N..... SET_XY_ROTATION(0.0000) ++ 19 N..... SET_FEED_MODE(0, 0) ++ 20 N..... SET_FEED_RATE(0.0000) ++ 21 N..... STOP_SPINDLE_TURNING(0) ++ 22 N..... SET_SPINDLE_MODE(0 0.0000) ++ 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 9d94ac4..196289e 100644 +--- a/tests/t0/nonrandom/expected-gcode-output ++++ b/tests/t0/nonrandom/expected-gcode-output +@@ -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 = 2.000000 + +@@ -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 = 0.000000 + +diff --git a/tests/t0/random-with-t0/expected-gcode-output b/tests/t0/random-with-t0/expected-gcode-output +index d23b22c..d16fc25 100644 +--- a/tests/t0/random-with-t0/expected-gcode-output ++++ b/tests/t0/random-with-t0/expected-gcode-output +@@ -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 = 2.000000 + +diff --git a/tests/t0/random-without-t0/expected-gcode-output b/tests/t0/random-without-t0/expected-gcode-output +index 71fa114..2075e4a 100644 +--- a/tests/t0/random-without-t0/expected-gcode-output ++++ b/tests/t0/random-without-t0/expected-gcode-output +@@ -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 = 2.000000 + +diff --git a/tests/tlo/test-ui.py b/tests/tlo/test-ui.py +index 42fe939..2814fe0 100755 +--- a/tests/tlo/test-ui.py ++++ b/tests/tlo/test-ui.py +@@ -153,14 +153,14 @@ verify_tool( + ) + + +-print("*** load T100 but dont apply TLO") ++print("*** load T100 and automatically apply its TLO") + + c.mdi('t100 m6') + c.wait_complete() + + verify_tool( + tool=100, +- x=0, y=0, z=0, ++ x=-2, y=0, z=-1, + a=0, b=0, c=0, + u=0, v=0, w=0, + diameter=0.125, +@@ -169,7 +169,7 @@ verify_tool( + ) + + +-print("*** apply TLO of loaded tool (T100)") ++print("*** reapply TLO of loaded tool (T100), idempotently") + + c.mdi('g43') + c.wait_complete() +@@ -347,4 +347,3 @@ verify_tool( + + # if we get here it all worked! + sys.exit(0) +- +diff --git a/tests/tool-line-length-save/.gitignore b/tests/tool-line-length-save/.gitignore +new file mode 100644 +index 0000000..f7b4787 +--- /dev/null ++++ b/tests/tool-line-length-save/.gitignore +@@ -0,0 +1,3 @@ ++sim.var ++sim.var.bak ++tool.tbl +diff --git a/tests/tool-line-length-save/checkresult b/tests/tool-line-length-save/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/tool-line-length-save/lathe.ini b/tests/tool-line-length-save/lathe.ini +new file mode 100644 +index 0000000..01a896f +--- /dev/null ++++ b/tests/tool-line-length-save/lathe.ini +@@ -0,0 +1,85 @@ ++# A metric lathe whose tool table has a line too long to load (T3). ++# Saving the table would delete that line, so saves are refused. ++ ++[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/tests/tool-line-length-save/make-table.py b/tests/tool-line-length-save/make-table.py +new file mode 100755 +index 0000000..3e2f0be +--- /dev/null ++++ b/tests/tool-line-length-save/make-table.py +@@ -0,0 +1,9 @@ ++#!/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. ++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 ++print("T1 P1 X+5.000000 Z+10.000000 WX+0.200000 WZ-0.100000 Q3 ;front tool") ++print(t3) +diff --git a/tests/tool-line-length-save/test-ui.py b/tests/tool-line-length-save/test-ui.py +new file mode 100755 +index 0000000..9840cd3 +--- /dev/null ++++ b/tests/tool-line-length-save/test-ui.py +@@ -0,0 +1,86 @@ ++#!/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() ++ ++ ++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") ++c.wait_complete() ++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("*** 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/tests/tool-line-length-save/test.sh b/tests/tool-line-length-save/test.sh +new file mode 100755 +index 0000000..3744834 +--- /dev/null ++++ b/tests/tool-line-length-save/test.sh +@@ -0,0 +1,4 @@ ++#!/bin/bash ++python3 make-table.py > tool.tbl ++rm -f sim.var ++exec linuxcnc -r lathe.ini +diff --git a/tests/tool-wear-abort/.gitignore b/tests/tool-wear-abort/.gitignore +new file mode 100644 +index 0000000..f7b4787 +--- /dev/null ++++ b/tests/tool-wear-abort/.gitignore +@@ -0,0 +1,3 @@ ++sim.var ++sim.var.bak ++tool.tbl +diff --git a/tests/tool-wear-abort/change-move.ngc b/tests/tool-wear-abort/change-move.ngc +new file mode 100644 +index 0000000..df79eee +--- /dev/null ++++ b/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/tests/tool-wear-abort/change-then-end.ngc b/tests/tool-wear-abort/change-then-end.ngc +new file mode 100644 +index 0000000..e02acfd +--- /dev/null ++++ b/tests/tool-wear-abort/change-then-end.ngc +@@ -0,0 +1,3 @@ ++G21 G90 ++T2 M6 ++M2 +diff --git a/tests/tool-wear-abort/checkresult b/tests/tool-wear-abort/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/tool-wear-abort/core_sim_handshake.hal b/tests/tool-wear-abort/core_sim_handshake.hal +new file mode 100644 +index 0000000..b1fdce4 +--- /dev/null ++++ b/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/tests/tool-wear-abort/interp-error-m6.ngc b/tests/tool-wear-abort/interp-error-m6.ngc +new file mode 100644 +index 0000000..ac36eff +--- /dev/null ++++ b/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/tests/tool-wear-abort/lathe.ini b/tests/tool-wear-abort/lathe.ini +new file mode 100644 +index 0000000..128bace +--- /dev/null ++++ b/tests/tool-wear-abort/lathe.ini +@@ -0,0 +1,85 @@ ++# A metric lathe whose tool changer waits for the UI to complete the ++# prepare and change handshakes, so a tool change can be aborted while ++# it is pending. T1 and T2 differ in X and Z geometry and wear. ++ ++[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 = core_sim_handshake.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/tests/tool-wear-abort/move-origin.ngc b/tests/tool-wear-abort/move-origin.ngc +new file mode 100644 +index 0000000..1d66847 +--- /dev/null ++++ b/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/tests/tool-wear-abort/postgui.hal b/tests/tool-wear-abort/postgui.hal +new file mode 100644 +index 0000000..114712d +--- /dev/null ++++ b/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/tests/tool-wear-abort/readahead-g43.ngc b/tests/tool-wear-abort/readahead-g43.ngc +new file mode 100644 +index 0000000..b0ab68c +--- /dev/null ++++ b/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/tests/tool-wear-abort/readahead-m61.ngc b/tests/tool-wear-abort/readahead-m61.ngc +new file mode 100644 +index 0000000..e9fa7e5 +--- /dev/null ++++ b/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/tests/tool-wear-abort/test-ui.py b/tests/tool-wear-abort/test-ui.py +new file mode 100755 +index 0000000..be0836e +--- /dev/null ++++ b/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/tests/tool-wear-abort/test.sh b/tests/tool-wear-abort/test.sh +new file mode 100755 +index 0000000..5a480e2 +--- /dev/null ++++ b/tests/tool-wear-abort/test.sh +@@ -0,0 +1,6 @@ ++#!/bin/bash ++ ++cp -f tool.tbl.original tool.tbl ++rm -f sim.var ++ ++exec linuxcnc -r lathe.ini +diff --git a/tests/tool-wear-abort/tool.tbl.original b/tests/tool-wear-abort/tool.tbl.original +new file mode 100644 +index 0000000..1026231 +--- /dev/null ++++ b/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/tests/tool-wear-restart/.gitignore b/tests/tool-wear-restart/.gitignore +new file mode 100644 +index 0000000..f7b4787 +--- /dev/null ++++ b/tests/tool-wear-restart/.gitignore +@@ -0,0 +1,3 @@ ++sim.var ++sim.var.bak ++tool.tbl +diff --git a/tests/tool-wear-restart/checkresult b/tests/tool-wear-restart/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/tool-wear-restart/common.py b/tests/tool-wear-restart/common.py +new file mode 100644 +index 0000000..ed5a426 +--- /dev/null ++++ b/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/tests/tool-wear-restart/run1.ini b/tests/tool-wear-restart/run1.ini +new file mode 100644 +index 0000000..06ce653 +--- /dev/null ++++ b/tests/tool-wear-restart/run1.ini +@@ -0,0 +1,85 @@ ++# A metric lathe with a random toolchanger, which keeps the tool in the ++# spindle (P0) across a restart; T1 and T2 carry X and Z wear. ++ ++[EMC] ++VERSION = 1.1 ++DEBUG = 0 ++ ++[DISPLAY] ++DISPLAY = ./run1.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 = 1 ++ ++[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/tests/tool-wear-restart/run1.py b/tests/tool-wear-restart/run1.py +new file mode 100755 +index 0000000..3523810 +--- /dev/null ++++ b/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/tests/tool-wear-restart/run2.ini b/tests/tool-wear-restart/run2.ini +new file mode 100644 +index 0000000..859f7a3 +--- /dev/null ++++ b/tests/tool-wear-restart/run2.ini +@@ -0,0 +1,85 @@ ++# A metric lathe with a random toolchanger, which keeps the tool in the ++# spindle (P0) across a restart; T1 and T2 carry X and Z wear. ++ ++[EMC] ++VERSION = 1.1 ++DEBUG = 0 ++ ++[DISPLAY] ++DISPLAY = ./run2.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 = 1 ++ ++[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/tests/tool-wear-restart/run2.py b/tests/tool-wear-restart/run2.py +new file mode 100755 +index 0000000..5feff1a +--- /dev/null ++++ b/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/tests/tool-wear-restart/test.sh b/tests/tool-wear-restart/test.sh +new file mode 100755 +index 0000000..54bcc33 +--- /dev/null ++++ b/tests/tool-wear-restart/test.sh +@@ -0,0 +1,12 @@ ++#!/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 ++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 ++linuxcnc -r run2.ini +diff --git a/tests/tool-wear-restart/tool.tbl.original b/tests/tool-wear-restart/tool.tbl.original +new file mode 100644 +index 0000000..1026231 +--- /dev/null ++++ b/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/tests/tool-wear-task/.gitignore b/tests/tool-wear-task/.gitignore +new file mode 100644 +index 0000000..f7b4787 +--- /dev/null ++++ b/tests/tool-wear-task/.gitignore +@@ -0,0 +1,3 @@ ++sim.var ++sim.var.bak ++tool.tbl +diff --git a/tests/tool-wear-task/checkresult b/tests/tool-wear-task/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/tool-wear-task/lathe.ini b/tests/tool-wear-task/lathe.ini +new file mode 100644 +index 0000000..e2dc531 +--- /dev/null ++++ b/tests/tool-wear-task/lathe.ini +@@ -0,0 +1,90 @@ ++# A metric lathe running through task, for native tool wear: the tool ++# table carries X and Z wear for a front tool (T1) and a back tool (T2). ++ ++[EMC] ++VERSION = 1.1 ++DEBUG = 0 ++ ++[DISPLAY] ++DISPLAY = ./test-ui.py ++LATHE = 1 ++ ++[RS274NGC] ++PARAMETER_FILE = sim.var ++# M7 reads tool entries out of range through emccanon (remap.py) ++REMAP = M7 modalgroup=8 python=out_of_range_tools ++ ++[PYTHON] ++PATH_PREPEND = . ++TOPLEVEL = toplevel.py ++ ++[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/tests/tool-wear-task/remap.py b/tests/tool-wear-task/remap.py +new file mode 100644 +index 0000000..05e1a69 +--- /dev/null ++++ b/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/tests/tool-wear-task/test-ui.py b/tests/tool-wear-task/test-ui.py +new file mode 100755 +index 0000000..a6a6fd6 +--- /dev/null ++++ b/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/tests/tool-wear-task/test.sh b/tests/tool-wear-task/test.sh +new file mode 100755 +index 0000000..5a480e2 +--- /dev/null ++++ b/tests/tool-wear-task/test.sh +@@ -0,0 +1,6 @@ ++#!/bin/bash ++ ++cp -f tool.tbl.original tool.tbl ++rm -f sim.var ++ ++exec linuxcnc -r lathe.ini +diff --git a/tests/tool-wear-task/tool.tbl.original b/tests/tool-wear-task/tool.tbl.original +new file mode 100644 +index 0000000..feb7fa0 +--- /dev/null ++++ b/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/tests/tool-wear-task/toplevel.py b/tests/tool-wear-task/toplevel.py +new file mode 100644 +index 0000000..0dc38fa +--- /dev/null ++++ b/tests/tool-wear-task/toplevel.py +@@ -0,0 +1 @@ ++import remap +diff --git a/tests/toolchanger/m61/test-ui.py b/tests/toolchanger/m61/test-ui.py +index 025cc58..8514d33 100755 +--- a/tests/toolchanger/m61/test-ui.py ++++ b/tests/toolchanger/m61/test-ui.py +@@ -175,6 +175,10 @@ do_tool_change_handshake(tool_number=1, pocket_number=1) + print("*** tool change complete") + verify_tool_number(1) + ++# #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, 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 +-verify_interp_param(5422, 0) # current z ++verify_interp_param(5422, -1) # current z + verify_interp_param(5423, 0) # current a + verify_interp_param(5424, 0) # current b + verify_interp_param(5425, 0) # current c +@@ -202,6 +206,10 @@ verify_interp_param(5428, 0) # current w + c.mdi('g43') + c.wait_complete() + ++# Repeating G43 is idempotent. ++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 + verify_interp_param(5422, -1) # current z +@@ -239,6 +247,8 @@ verify_stable_pin_values( + + verify_tool_number(10) + ++# 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, 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 +-verify_interp_param(5422, -1) # current z ++verify_interp_param(5422, -3) # current z + verify_interp_param(5423, 0) # current a + verify_interp_param(5424, 0) # current b + verify_interp_param(5425, 0) # current c +@@ -266,6 +276,10 @@ verify_interp_param(5428, 0) # current w + c.mdi('g43') + c.wait_complete() + ++# Repeating G43 is idempotent. ++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 + 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) + + + # +@@ -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) + + + # +@@ -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) + + + # if we get here it all worked! + 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 edc3501..554663c 100644 +--- a/tests/toolchanger/toolno-pocket-differ/nonrandom/expected-gcode-output ++++ b/tests/toolchanger/toolno-pocket-differ/nonrandom/expected-gcode-output +@@ -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 = 1.000000 + +@@ -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.183000 + +@@ -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.229000 + +@@ -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.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.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.067000 + +diff --git a/tests/toolchanger/toolno-pocket-differ/random/expected-gcode-output b/tests/toolchanger/toolno-pocket-differ/random/expected-gcode-output +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,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 = 1.000000 + +@@ -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.183000 + +@@ -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.229000 + +@@ -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.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.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.067000 + +diff --git a/tests/tooldb/db-g10-offset/README b/tests/tooldb/db-g10-offset/README +index 095d3fb..face3c8 100644 +--- a/tests/tooldb/db-g10-offset/README ++++ b/tests/tooldb/db-g10-offset/README +@@ -1,5 +1,5 @@ +-Verify that tool offsets set with G10 L1/L10/L11 are persisted when an +-[EMCIO]DB_PROGRAM is configured. ++Verify that tool offsets set with G10 L1/L10/L11, and tool wear set with ++G10 L3, are persisted when an [EMCIO]DB_PROGRAM is configured. + + In db mode with a nonrandom toolchanger no tool table file is written, so the + db program must be notified of the new offsets ('p' command). Without that +diff --git a/tests/tooldb/db-g10-offset/db_test.py b/tests/tooldb/db-g10-offset/db_test.py +index ee22030..eaae357 100755 +--- a/tests/tooldb/db-g10-offset/db_test.py ++++ b/tests/tooldb/db-g10-offset/db_test.py +@@ -48,12 +48,18 @@ def toolno_of(toolline): + if item.startswith("T"): return int(item[1:]) + raise ValueError("no toolno in <%s>"%toolline) + ++def word(item): ++ # the letters of a tool-line item: one (Z) or two for wear (WZ) ++ letters = item.rstrip("+-.0123456789") ++ return letters, item[len(letters):] ++ + def merge(toolline,params): + # apply the letter parameters of params to toolline +- D = dict((item[0],item[1:]) for item in toolline.upper().split()) ++ D = dict(word(item) for item in toolline.upper().split()) + for item in params.upper().split(): + if item.startswith(";"): break +- D[item[0]] = item[1:] ++ letters, value = word(item) ++ D[letters] = value + letters = ["T","P"] + sorted(set(D) - set(["T","P"])) + return " ".join("%s%s"%(letter,D[letter]) for letter in letters) + +diff --git a/tests/tooldb/db-g10-offset/dbtest_lib.py b/tests/tooldb/db-g10-offset/dbtest_lib.py +index fbb6e18..b4221eb 100644 +--- a/tests/tooldb/db-g10-offset/dbtest_lib.py ++++ b/tests/tooldb/db-g10-offset/dbtest_lib.py +@@ -62,8 +62,19 @@ def tool_table_zoffset(s, idx): + return s.tool_table[idx].zoffset + + ++def tool_table_wzoffset(s, idx): ++ s.poll() ++ return s.tool_table[idx].wzoffset ++ ++ + def db_zoffset(toolno, timeout=0): + """Z offset recorded by the db program for toolno, or None.""" ++ return db_word(toolno, "Z", timeout) ++ ++ ++def db_word(toolno, word, timeout=0): ++ """Value of a tool-line word (Z, WZ, ...) recorded by the db program ++ for toolno, or None.""" + deadline = time.time() + timeout + while True: + try: +@@ -73,8 +84,9 @@ def db_zoffset(toolno, timeout=0): + if "T%d" % toolno not in items: + continue + for item in items: +- if item.startswith("Z"): +- return float(item[1:]) ++ letters = item.rstrip("+-.0123456789") ++ if letters == word: ++ return float(item[len(letters):]) + except IOError: + pass + if time.time() >= deadline: +diff --git a/tests/tooldb/db-g10-offset/test-ui.py b/tests/tooldb/db-g10-offset/test-ui.py +index 6d429fb..6499e6f 100755 +--- a/tests/tooldb/db-g10-offset/test-ui.py ++++ b/tests/tooldb/db-g10-offset/test-ui.py +@@ -8,6 +8,7 @@ + import sys + + from dbtest_lib import start_machine, check, fail, tool_table_zoffset, db_zoffset ++from dbtest_lib import tool_table_wzoffset, db_word + + (c, s) = start_machine() + +@@ -84,4 +85,18 @@ check("db zoffset for tool 5 after G10 L11", got, 1.75) + c.mdi("G10 L2 P1 Z0") + c.wait_complete() + ++# 5) G10 L3 sets stored wear; the db program gets it as a WZ word and the ++# geometry it already has is left alone. ++c.mdi("G10 L3 P1 Z-0.02") ++c.wait_complete() ++ ++check("tool 1 wzoffset after G10 L3", tool_table_wzoffset(s, 1), -0.02) ++check("tool 1 zoffset after G10 L3", tool_table_zoffset(s, 1), 0.5) ++ ++got = db_word(1, "WZ", timeout=5) ++if got is None: ++ fail("db program was not notified of the G10 L3 wear for tool 1") ++check("db wzoffset for tool 1 after G10 L3", got, -0.02) ++check("db zoffset for tool 1 after G10 L3", db_zoffset(1), 0.5) ++ + sys.exit(0) +diff --git a/tests/tooldb/db-g10-offset/verify-ui.py b/tests/tooldb/db-g10-offset/verify-ui.py +index f3c8f43..6585266 100755 +--- a/tests/tooldb/db-g10-offset/verify-ui.py ++++ b/tests/tooldb/db-g10-offset/verify-ui.py +@@ -5,7 +5,7 @@ + + import sys + +-from dbtest_lib import start_machine, check, tool_table_zoffset ++from dbtest_lib import start_machine, check, tool_table_zoffset, tool_table_wzoffset + + (c, s) = start_machine() + +@@ -14,7 +14,8 @@ check("tool 2 zoffset after restart (G10 L1)", tool_table_zoffset(s, 2), -6.789) + check("tool 4 zoffset after restart (G10 L10)", tool_table_zoffset(s, 4), 1.5) + check("tool 5 zoffset after restart (G10 L11)", tool_table_zoffset(s, 5), 1.75) + +-# tool 1 was never touched ++# tool 1 only had its wear set (G10 L3) + check("tool 1 zoffset after restart", tool_table_zoffset(s, 1), 0.5) ++check("tool 1 wzoffset after restart (G10 L3)", tool_table_wzoffset(s, 1), -0.02) + + sys.exit(0) +diff --git a/tests/tooldb/db-line-length/.gitignore b/tests/tooldb/db-line-length/.gitignore +new file mode 100644 +index 0000000..3a2d845 +--- /dev/null ++++ b/tests/tooldb/db-line-length/.gitignore +@@ -0,0 +1,5 @@ ++sim.var ++sim.var.bak ++long.inc ++long-run.ini ++db_spindle.tbl +diff --git a/tests/tooldb/db-line-length/base.inc b/tests/tooldb/db-line-length/base.inc +new file mode 100644 +index 0000000..9f95539 +--- /dev/null ++++ b/tests/tooldb/db-line-length/base.inc +@@ -0,0 +1,98 @@ ++[EMC] ++# The version string for this INI file. ++VERSION = 1.1 ++DEBUG = 0x0 ++ ++[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] ++# the library file provides the estop and toolchange loopbacks needed here ++HALFILE = LIB:core_sim.hal ++ ++[TRAJ] ++NO_FORCE_HOMING=1 ++COORDINATES = XYZ ++HOME = 0 0 0 ++LINEAR_UNITS = inch ++ANGULAR_UNITS = degree ++DEFAULT_LINEAR_VELOCITY = 1.2 ++MAX_LINEAR_ACCELERATION = 123.45 ++MAX_LINEAR_VELOCITY = 45.67 ++ ++[EMCIO] ++# no TOOL_TABLE: tool data is provided by the db program ++TOOL_CHANGE_QUILL_UP = 1 ++RANDOM_TOOLCHANGER = 0 ++DB_PROGRAM = ./db_long.py ++ ++[KINS] ++KINEMATICS = trivkins coordinates=XYZ ++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 = -40.0 ++MAX_LIMIT = 40.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 = -40.0 ++MAX_LIMIT = 40.0 ++FERROR = 0.050 ++MIN_FERROR = 0.010 +diff --git a/tests/tooldb/db-line-length/checkresult b/tests/tooldb/db-line-length/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/tests/tooldb/db-line-length/checkresult +@@ -0,0 +1,2 @@ ++#!/bin/sh ++exit 0 # test failure is indicated by test.sh exit value +diff --git a/tests/tooldb/db-line-length/db_long.py b/tests/tooldb/db-line-length/db_long.py +new file mode 100755 +index 0000000..8e388f1 +--- /dev/null ++++ b/tests/tooldb/db-line-length/db_long.py +@@ -0,0 +1,30 @@ ++#!/usr/bin/env python3 ++# [EMCIO]DB_PROGRAM whose T1 line is exactly 510 characters (the longest ++# allowed), or 600 with the argument "long", which also adds a T3 line of ++# 5000 characters, longer than one pipe packet. The WZ word ends each long ++# line, so a reader that cut a line would cut that number. ++import sys ++ ++from tooldb import tooldb_callbacks, tooldb_tools, tooldb_loop ++ ++length = 600 if sys.argv[1:] == ["long"] else 510 ++ ++head = "T1 P1 X+1 Z+2 WX+0.5 D0." ++tail = " WZ-0.7555555555" ++t1 = head + "0" * (length - len(head) - len(tail)) + tail ++assert len(t1) == length ++ ++tools = {1: t1, 2: "T2 P2 Z+3 WZ-0.125"} ++if length == 600: ++ head3 = "T3 P3 Z+4 D0." ++ tools[3] = head3 + "0" * (5000 - len(head3) - len(tail)) + tail ++ ++def get_tool(tno): ++ return tools[tno] ++ ++def ignore(tno, params): ++ pass ++ ++tooldb_callbacks(get_tool, ignore, ignore, ignore) ++tooldb_tools(sorted(tools)) ++tooldb_loop() +diff --git a/tests/tooldb/db-line-length/long-ui.py b/tests/tooldb/db-line-length/long-ui.py +new file mode 100755 +index 0000000..86eb97f +--- /dev/null ++++ b/tests/tooldb/db-line-length/long-ui.py +@@ -0,0 +1,34 @@ ++#!/usr/bin/env python3 ++# A 600-character T1 line and a 5000-character T3 line (two pipe packets) ++# from the db program are refused, each read to its end: ++# T1 is not in the tool table (not with a number cut short), T2 after it is ++# loaded, and the db program is still in step for the next exchange. ++import sys ++sys.path.insert(0, "../db-g10-offset") ++from dbtest_lib import start_machine, check, fail ++ ++import linuxcnc ++ ++(c, s) = start_machine() ++s.poll() ++for t in s.tool_table[1:]: ++ if t.id == 1: ++ fail("T1 loaded from a 600-character line: wzoffset=%f" % t.wzoffset) ++ if t.id == 3: ++ fail("T3 loaded from a 5000-character line: wzoffset=%f" % t.wzoffset) ++print("ok: the 600- and 5000-character lines were refused") ++t2 = [t for t in s.tool_table[1:] if t.id == 2] ++if len(t2) != 1: ++ fail("T2, after the refused line, was not loaded") ++check("T2 wzoffset", t2[0].wzoffset, -0.125) ++ ++# a G10 notifies the db program and reads its reply: out of step, this ++# would read leftovers of the refused line instead ++c.mdi("G10 L1 P2 Z4") ++c.wait_complete() ++s.poll() ++if s.state != linuxcnc.RCS_DONE: ++ fail("G10 L1 after the refused line failed: state %d" % s.state) ++t2 = [t for t in s.tool_table[1:] if t.id == 2] ++check("T2 zoffset after G10 L1", t2[0].zoffset, 4.0) ++sys.exit(0) +diff --git a/tests/tooldb/db-line-length/long.ini b/tests/tooldb/db-line-length/long.ini +new file mode 100644 +index 0000000..bb7d822 +--- /dev/null ++++ b/tests/tooldb/db-line-length/long.ini +@@ -0,0 +1,5 @@ ++# a 600-character tool line from the db program is refused, not cut ++[DISPLAY] ++DISPLAY = ./long-ui.py ++ ++#INCLUDE base.inc +diff --git a/tests/tooldb/db-line-length/test-ui.py b/tests/tooldb/db-line-length/test-ui.py +new file mode 100755 +index 0000000..b9a3191 +--- /dev/null ++++ b/tests/tooldb/db-line-length/test-ui.py +@@ -0,0 +1,18 @@ ++#!/usr/bin/env python3 ++# The 510-character T1 line from the db program loads with every number. ++import sys ++sys.path.insert(0, "../db-g10-offset") ++from dbtest_lib import start_machine, check, fail ++ ++(c, s) = start_machine() ++s.poll() ++t1 = [t for t in s.tool_table[1:] if t.id == 1] ++if len(t1) != 1: ++ fail("T1 (a 510-character line) was not loaded") ++check("T1 xoffset", t1[0].xoffset, 1.0) ++check("T1 wzoffset at the end of the line", t1[0].wzoffset, -0.7555555555) ++t2 = [t for t in s.tool_table[1:] if t.id == 2] ++if len(t2) != 1: ++ fail("T2 was not loaded") ++check("T2 wzoffset", t2[0].wzoffset, -0.125) ++sys.exit(0) +diff --git a/tests/tooldb/db-line-length/test.ini b/tests/tooldb/db-line-length/test.ini +new file mode 100644 +index 0000000..6b56dc2 +--- /dev/null ++++ b/tests/tooldb/db-line-length/test.ini +@@ -0,0 +1,5 @@ ++# a 510-character tool line from the db program loads whole ++[DISPLAY] ++DISPLAY = ./test-ui.py ++ ++#INCLUDE base.inc +diff --git a/tests/tooldb/db-line-length/test.sh b/tests/tooldb/db-line-length/test.sh +new file mode 100755 +index 0000000..649e412 +--- /dev/null ++++ b/tests/tooldb/db-line-length/test.sh +@@ -0,0 +1,14 @@ ++#!/bin/bash ++set -x ++set -e ++ ++rm -f sim.var* ++ ++# run 1: the longest allowed line loads whole ++linuxcnc -r test.ini ++ ++# run 2: a longer line is refused (the db program is told to send one) ++sed -e 's#^DB_PROGRAM = ./db_long.py$#DB_PROGRAM = ./db_long.py long#' base.inc > long.inc ++sed -e 's#^\#INCLUDE base.inc#\#INCLUDE long.inc#' long.ini > long-run.ini ++linuxcnc -r long-run.ini ++rm -f long.inc long-run.ini diff --git a/linuxcnc-patches/pending-pre2/0008-tapered-g76-drive-lines.patch b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch similarity index 54% rename from linuxcnc-patches/pending-pre2/0008-tapered-g76-drive-lines.patch rename to linuxcnc-patches/0008-tapered-g76-drive-lines.patch index 345049c..ffc8792 100644 --- a/linuxcnc-patches/pending-pre2/0008-tapered-g76-drive-lines.patch +++ b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch @@ -4,33 +4,74 @@ 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. A D word in a block with both G96 and G76 is +reported as ambiguous before it is range-checked as an infeed mode. +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 ++++++++++++++++++ + docs/src/gcode/g-code.adoc | 52 ++- + src/emc/rs274ngc/interp_check.cc | 13 +- + src/emc/rs274ngc/interp_convert.cc | 253 +++++++++-- + src/emc/rs274ngc/rs274ngc_interp.hh | 4 + + tests/g76-tapered-pitch/README | 34 ++ + tests/g76-tapered-pitch/checkresult | 2 + + tests/g76-tapered-pitch/core_sim.hal | 18 + + tests/g76-tapered-pitch/test-ui.py | 173 ++++++++ + tests/g76-tapered-pitch/test.ini | 67 +++ + tests/g76-tapered-pitch/test.sh | 3 + + tests/interp/g76-tapered/README | 14 + + tests/interp/g76-tapered/expected | 403 ++++++++++++++++++ .../interp/g76-tapered/invalid-d-fraction.ngc | 5 + tests/interp/g76-tapered/invalid-d2.ngc | 5 + + .../g76-tapered/invalid-g96-d-limit.ngc | 5 + tests/interp/g76-tapered/invalid-g96-d.ngc | 5 + tests/interp/g76-tapered/invalid-y.ngc | 5 + + tests/interp/g76-tapered/invalid-zero-z.ngc | 5 + tests/interp/g76-tapered/test.ngc | 63 +++ - tests/interp/g76-tapered/test.sh | 14 + - 11 files changed, 653 insertions(+), 21 deletions(-) + tests/interp/g76-tapered/test.sh | 31 ++ + 20 files changed, 1118 insertions(+), 42 deletions(-) + create mode 100644 tests/g76-tapered-pitch/README + create mode 100755 tests/g76-tapered-pitch/checkresult + create mode 100644 tests/g76-tapered-pitch/core_sim.hal + create mode 100755 tests/g76-tapered-pitch/test-ui.py + create mode 100644 tests/g76-tapered-pitch/test.ini + create mode 100755 tests/g76-tapered-pitch/test.sh 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-limit.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/invalid-zero-z.ngc create mode 100644 tests/interp/g76-tapered/test.ngc create mode 100644 tests/interp/g76-tapered/test.sh diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index fa46049723..4160cfb4a2 100644 +index f8f9d01..950dc5c 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. +@@ -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))) +@@ -2217,15 +2221,24 @@ In example S100 with 1.25MM per revolution thread pitch gives a feed of F125. [source,ngc] ---- @@ -59,7 +100,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,7 +2267,17 @@ 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. @@ -78,7 +119,7 @@ index fa46049723..4160cfb4a2 100644 * '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. +@@ -2274,8 +2297,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,22 +132,35 @@ 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 +2323,21 @@ 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. ++* A 'D-' word is given in a block with both 'G96' and 'G76', where it could be ++ either the G96 spindle speed limit or the G76 infeed mode. * The 'R-' degression value is less than 1.0. * All the required words are not specified. * 'P-', 'J-', 'K-' or 'H-' is negative. + * '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. + + [NOTE] + The spindle speed override is held for the whole G76 cycle at the value in diff --git a/src/emc/rs274ngc/interp_check.cc b/src/emc/rs274ngc/interp_check.cc -index cf3b8050c9..3b139a0ca6 100644 +index c65a3b2..50781c6 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 +@@ -262,9 +262,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) && @@ -118,114 +172,180 @@ index cf3b8050c9..3b139a0ca6 100644 } if (block->dollar_flag) { -@@ -383,6 +383,13 @@ int Interp::check_other_codes(block_pointer block) //!< pointer to a block +@@ -397,6 +397,15 @@ 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")); ++ // G96 reads D as its spindle speed limit; check this first so a limit ++ // such as D2000 is not reported as a bad infeed mode. + CHKS((block->g_modes[GM_SPINDLE_MODE] == G_96), + _("D cannot select both G76 infeed mode and G96 spindle limit in the same block")); ++ CHKS((block->d_number_float != 0.0 && block->d_number_float != 1.0), ++ _("In G76, D must be 0 or 1")); + } } return INTERP_OK; diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 99f9e6fdb8..373916cfb0 100644 +index 10bf98d..196d48c 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, +@@ -5984,6 +5984,152 @@ threading_pass(setup_pointer settings, block_pointer block, 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 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 * ++ g.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; -+ -+ STRAIGHT_TRAVERSE(block->line_number, -+ cut_start_x - depth_direction * end_depth, -+ start_y, pass_start_z, AABBCC); // back -+ -+ 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); ++ 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); ++ } ++ ++ 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; ++} ++ ++// 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, +@@ -5991,6 +6137,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,7 +354,7 @@ 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, +@@ -6030,7 +6178,18 @@ 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; @@ -254,7 +374,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, +@@ -6042,7 +6201,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 +384,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, +@@ -6053,44 +6213,77 @@ int Interp::convert_threading_cycle(block_pointer block, double depth, zoff; int pass = 1; @@ -272,6 +392,31 @@ 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. ++ struct threading_pass_plan { ++ double depth, zoff; ++ }; ++ std::vector passes; + depth = start_depth; - zoff = (depth - full_dia_depth) * tan(compound_angle); + zoff = (depth - full_dia_depth) * compound_tangent; @@ -284,18 +429,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}); 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,46 +437,440 @@ 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, 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, ++ 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/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; ++ + 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/tests/g76-tapered-pitch/README b/tests/g76-tapered-pitch/README +new file mode 100644 +index 0000000..7c9fb65 +--- /dev/null ++++ b/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 D1 (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/tests/g76-tapered-pitch/checkresult b/tests/g76-tapered-pitch/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/g76-tapered-pitch/core_sim.hal b/tests/g76-tapered-pitch/core_sim.hal +new file mode 100644 +index 0000000..47884cf +--- /dev/null ++++ b/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/tests/g76-tapered-pitch/test-ui.py b/tests/g76-tapered-pitch/test-ui.py +new file mode 100755 +index 0000000..b8107b9 +--- /dev/null ++++ b/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 D1", ++ ["g8 g0 x10 z0", "g96 s100 d201 m3"], EXTERNAL + " d1", ++ ["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/tests/g76-tapered-pitch/test.ini b/tests/g76-tapered-pitch/test.ini +new file mode 100644 +index 0000000..8c04f36 +--- /dev/null ++++ b/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/tests/g76-tapered-pitch/test.sh b/tests/g76-tapered-pitch/test.sh +new file mode 100755 +index 0000000..411ae8c +--- /dev/null ++++ b/tests/g76-tapered-pitch/test.sh +@@ -0,0 +1,3 @@ ++#!/bin/bash -e ++ ++linuxcnc -r test.ini diff --git a/tests/interp/g76-tapered/README b/tests/interp/g76-tapered/README new file mode 100644 -index 0000000000..645af3ae97 +index 0000000..969bf22 --- /dev/null +++ b/tests/interp/g76-tapered/README -@@ -0,0 +1,8 @@ +@@ -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 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. ++paths. 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, invalid D modes, and a same-block G96 D word whether it looks like an ++infeed mode (D1) or a spindle limit (D2000). ++ ++The pitch check against the axis velocity limits needs a machine and is tested ++in tests/g76-tapered-pitch. diff --git a/tests/interp/g76-tapered/expected b/tests/interp/g76-tapered/expected new file mode 100644 -index 0000000000..ec0ccc9fb4 +index 0000000..98bbf96 --- /dev/null +++ b/tests/interp/g76-tapered/expected -@@ -0,0 +1,377 @@ +@@ -0,0 +1,403 @@ + 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) @@ -356,6 +884,7 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -372,9 +901,11 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -391,10 +922,12 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -411,11 +944,13 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -432,10 +967,12 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -452,9 +989,11 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -471,9 +1010,11 @@ index 0000000000..ec0ccc9fb4 + 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) @@ -498,9 +1039,11 @@ index 0000000000..ec0ccc9fb4 + 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) @@ -525,9 +1068,11 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -544,9 +1089,11 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -595,9 +1142,11 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -630,9 +1179,11 @@ index 0000000000..ec0ccc9fb4 + 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() @@ -673,9 +1224,11 @@ index 0000000000..ec0ccc9fb4 + 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("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() @@ -708,6 +1261,7 @@ index 0000000000..ec0ccc9fb4 + 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) @@ -722,7 +1276,7 @@ index 0000000000..ec0ccc9fb4 + 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 +index 0000000..6eb002d --- /dev/null +++ b/tests/interp/g76-tapered/invalid-d-fraction.ngc @@ -0,0 +1,5 @@ @@ -733,7 +1287,7 @@ index 0000000000..6eb002dc8a +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 +index 0000000..87e8094 --- /dev/null +++ b/tests/interp/g76-tapered/invalid-d2.ngc @@ -0,0 +1,5 @@ @@ -742,9 +1296,20 @@ index 0000000000..87e80949f9 +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-limit.ngc b/tests/interp/g76-tapered/invalid-g96-d-limit.ngc +new file mode 100644 +index 0000000..5061982 +--- /dev/null ++++ b/tests/interp/g76-tapered/invalid-g96-d-limit.ngc +@@ -0,0 +1,5 @@ ++g21 g18 g8 ++s500 m3 ++g0 x10 z0 ++g96 s100 d2000 g76 p1.5 x8 z-20 i-1 j.2 k1 h0 q30 ++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 +index 0000000..66e30e8 --- /dev/null +++ b/tests/interp/g76-tapered/invalid-g96-d.ngc @@ -0,0 +1,5 @@ @@ -755,7 +1320,7 @@ index 0000000000..66e30e804a +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 +index 0000000..f79aa85 --- /dev/null +++ b/tests/interp/g76-tapered/invalid-y.ngc @@ -0,0 +1,5 @@ @@ -764,9 +1329,20 @@ index 0000000000..f79aa85850 +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/invalid-zero-z.ngc b/tests/interp/g76-tapered/invalid-zero-z.ngc +new file mode 100644 +index 0000000..9384803 +--- /dev/null ++++ b/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/tests/interp/g76-tapered/test.ngc b/tests/interp/g76-tapered/test.ngc new file mode 100644 -index 0000000000..fc3f9a5545 +index 0000000..fc3f9a5 --- /dev/null +++ b/tests/interp/g76-tapered/test.ngc @@ -0,0 +1,63 @@ @@ -835,10 +1411,10 @@ index 0000000000..fc3f9a5545 +m2 diff --git a/tests/interp/g76-tapered/test.sh b/tests/interp/g76-tapered/test.sh new file mode 100644 -index 0000000000..949e9fdf47 +index 0000000..70f3986 --- /dev/null +++ b/tests/interp/g76-tapered/test.sh -@@ -0,0 +1,14 @@ +@@ -0,0 +1,31 @@ +#!/bin/bash + +rs274 -g test.ngc | awk '{$1=""; print}' @@ -847,9 +1423,26 @@ index 0000000000..949e9fdf47 + exit "$result" +fi + ++# Each invalid program must be rejected with its own message. ++declare -A expected_error=( ++ [invalid-d-fraction.ngc]="In G76, D must be 0 or 1" ++ [invalid-d2.ngc]="In G76, D must be 0 or 1" ++ [invalid-g96-d.ngc]="D cannot select both G76 infeed mode and G96 spindle limit in the same block" ++ [invalid-g96-d-limit.ngc]="D cannot select both G76 infeed mode and G96 spindle limit in the same block" ++ [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 -+ if rs274 -g "$invalid_program" >/dev/null 2>&1; then -+ echo "$invalid_program unexpectedly succeeded" >&2 ++ 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-patches/README.md b/linuxcnc-patches/README.md index 0a13dd6..d8db87b 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -214,12 +214,19 @@ 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. -The `tests/resumable-stop` LinuxCNC regression runs 23 scenarios with the -jerk-limited planner and repeats three of them with the trapezoidal planner. +`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 `tests/resumable-stop` LinuxCNC regression runs 25 scenarios with the +jerk-limited planner and repeats four of them with the trapezoidal planner. They cover Stop/Resume and Stop/Single-Step preserving the queued program, spindle and coolant handling, the at-speed cases above, `G33` threading -including a chain of `G33` moves, `G33.1` rigid tapping, Stop during and after -an interrupted `G28.2`, and that `STOPPED` is never reported while moving. +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` @@ -272,9 +279,25 @@ and M61 activate the resulting combined offset automatically; G49 still cancels compensation and same-block explicit G-codes take precedence. 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. The G-code preview applies the same geometry-plus-wear offset +as the machine. ### 0008 — Tapered G76 drive lines and alternating infeed @@ -297,6 +320,12 @@ 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 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 diff --git a/linuxcnc-patches/pending-pre2/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/pending-pre2/0007-native-automatic-tool-wear.patch deleted file mode 100644 index e2c860f..0000000 --- a/linuxcnc-patches/pending-pre2/0007-native-automatic-tool-wear.patch +++ /dev/null @@ -1,2054 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Dariusz Majnert -Date: Fri, 14 Aug 2026 18:32:49 +0200 -Subject: [PATCH] native automatic tool wear - ---- - 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 +- - 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/rs274ngc/interp_array.cc | 1 + - src/emc/rs274ngc/interp_check.cc | 4 +- - src/emc/rs274ngc/interp_convert.cc | 145 ++++++++++++------ - src/emc/rs274ngc/interp_internal.hh | 2 - - src/emc/rs274ngc/interp_parameter_def.hh | 10 ++ - src/emc/rs274ngc/pyemctypes.cc | 2 + - src/emc/rs274ngc/rs274ngc_pre.cc | 30 +++- - 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 +++- - tests/ccomp/lathe-comp/expected | 4 + - tests/ccomp/mill-g90g91g92/expected | 1 + - tests/ccomp/mill-line-arc-entry/expected | 1 + - 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/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/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 - -diff --git a/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini b/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini -index 37daf10754..bbcdfc2a93 100644 ---- a/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini -+++ b/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini -@@ -61,7 +61,6 @@ SUBROUTINE_PATH = macros - - # optional features - a bit mask to selectively turn on experimental/dubious features - # see --# RETAIN_G43 0x00000001 - # OWORD_N_ARGS 0x00000002 - # 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 ---- 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: - 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. --* `RETAIN_G43 = 0` (Default: 0) + -- When set, you can turn on G43 after loading the first tool, and then not worry about it through the program. -- When you finally unload the last tool, G43 mode is canceled. - * `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 - This INI tag will no longer work. + - For reference: - ---- --FEATURES & 0x1 -> RETAIN_G43 - FEATURES & 0x2 -> OWORD_NARGS - 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 ---- a/docs/src/config/python-interface.adoc -+++ b/docs/src/config/python-interface.adoc -@@ -368,7 +368,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, -- woffset, diameter, frontangle, backangle, orientation. The id and orientation -+ woffset, diameter, frontangle, backangle, orientation, wxoffset, wyoffset, -+ wzoffset, waoffset, wboffset, wcoffset, wuoffset, wvoffset, wwoffset. The id and orientation - are integers and the rest are floats. - [source,python] - ---- -@@ -389,7 +390,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', -- 'xoffset','yoffset', ... 'woffset', 'comment'. + -+ 'xoffset','yoffset', ... 'woffset', 'wxoffset','wyoffset', ... -+ 'wwoffset', 'comment'. + - As an example, the following script - [source,python] - ---- -diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index 66f1a2b776..fa46049723 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. - |<> |Radius Mode (lathe) - |<> |Reload Tool Table Data - |<> |Set Tool Table Entry -+|<> |Set Tool Wear Offset - |<> |Set Tool Table, Calculated, Workpiece - |<> |Set Tool Table, Calculated, Fixture - |<> |Coordinate System Origin Setting -@@ -702,7 +703,8 @@ 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 - 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: - For more information on cutter orientation used by the 'Q' word, - see the <> diagram. - -+[[gcode:g10-l3]] -+== G10 L3 Set Tool Wear Offset(((G10 L3 Tool Wear Offset))) -+ -+[source,ngc] -+---- -+G10 L3 P- axes -+---- -+ -+G10 L3 replaces the supplied absolute wear values for an existing nonzero -+tool. Omitted axes remain unchanged and an explicit zero clears that wear -+axis. Values use ordinary program-unit conversion; X also follows G7/G8 -+diameter/radius interpretation. R, I, J, and Q are not allowed. -+ -+[source,ngc] -+---- -+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. -+ - [[gcode:g10-l2]] - == G10 L2 Set Coordinate System(((G10 L2 Coordinate System))) - -@@ -1404,7 +1427,8 @@ 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 active tool length compensation values are stored in the numbered - parameters '5401-5409'. -@@ -1473,7 +1497,7 @@ G43.2 H- or axes- - - * 'H' - tool number - --* 'G43.2 H__n__' - applies an additional simultaneous tool offset to subsequent motions by adding the offset(s) of tool _n_. -+* 'G43.2 H__n__' - applies an additional simultaneous tool offset to subsequent motions by adding the geometry plus wear offset(s) of tool _n_. - - * '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 - M2 (end program) - ---- - --You can sum together an arbitrary number of offsets by calling G43.2 --more times. There are no built-in assumptions about which numbers are --geometry offsets and which are wear offsets, or that you should have --only one of each. -+You can sum together an arbitrary number of independent offsets by calling -+G43.2 more times. - - 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. - [[gcode:g49]] - == G49 Cancel Tool Length Compensation(((G49 Cancel Tool Length Offset))) - --* 'G49' - cancels tool length compensation -+* 'G49' - cancels the complete active tool length compensation without -+ 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 -diff --git a/docs/src/gcode/m-code.adoc b/docs/src/gcode/m-code.adoc -index 253358f25f..1cb15521ad 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: - * 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. -+* The selected tool's geometry plus wear offset is activated automatically. - * 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: - The 'T-' word is an integer number designating the tool pocket number in - the carousel (not its index). - --[WARNING] --The tool length offset is not changed by 'M6', use '<>' after the --'M6' to change the tool length offset. -+An explicit tool-offset command in the same block is applied afterward, so -+`M6 G49` completes with compensation cancelled. A remapped M6 that bypasses -+the built-in tool-change path is responsible for its own compensation. - - 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. - currently in the spindle you can set that tool number without - doing a tool change. - --[WARNING] --The tool length offset is not changed by 'M61', use '<>' after --the 'M61' to change the tool length offset. -+The built-in M61 activates the resulting tool's geometry plus wear offset. -+An explicit command in the same block, such as `M61 Q7 G49`, takes precedence. - - It is an error if: - -diff --git a/docs/src/gcode/overview.adoc b/docs/src/gcode/overview.adoc -index 3a201f1c11..6be6e716b6 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 - * '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. - * '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 ---- 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. - The file is located in the same directory as your configuration and is called 'tool.tbl' by default. - A file name may be specified with the INI file [EMCIO]TOOL_TABLE setting. - The tools might be in a tool changer or just changed manually. --The file can be edited with a text editor or be updated using G10 L1. -+The file can be edited with a text editor or be updated using G10 L1 or G10 L3. - See the <> section for an example of the lathe tool table format. - The maximum pocket number is 1000. - -@@ -72,6 +72,7 @@ In general, the tool table line format is: - - T - tool number (tool numbers must be unique) - - P - pocket number, 1-1000 (pocket numbers must be unique, Pocket 0 represents the spindle) - - X..W - tool offset on specified axis - floating-point -+- WX, WY, WZ, WA, WB, WC, WU, WV, WW - wear offset on the specified axis - floating-point - - 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. - - The units used for the length, diameter, etc., are in machine units. - -+Wear offsets are stored independently from geometry offsets. Missing wear -+fields mean zero. For example: -+ -+[source] -+---- -+T7 P7 X+12.000000 Z+40.000000 WX+0.025000 WZ-0.010000 -+---- -+ -+When G43 is active, LinuxCNC applies the sum of the geometry and wear -+offsets for every axis. -+ - 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 - 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. - -+Wear Offset Numbers (optional):: -+The `W`-prefixed axis columns (`WX` through `WW`) contain stored wear -+corrections. They can be positive, negative, or zero and are added to the -+corresponding geometry offsets by G43. -+ - 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. - 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. --LinuxCNC pushes updates to the data source (`[EMCIO]TOOL_TABLE` or `[EMCIO]DB_PROGRAM`) for G-codes G10L1, G10L10, G10L11, M61. -+LinuxCNC pushes updates to the data source (`[EMCIO]TOOL_TABLE` or `[EMCIO]DB_PROGRAM`) for G-codes G10L1, G10L3, G10L10, G10L11, M61. - LinuxCNC can pull tooldata updates from the data source by UI (user-interface) commands (Python example: `linuxcnc.command().load_tool_table()`) or by the G-code: `G10L0`. - - .Random Location Tool Changers -diff --git a/docs/src/tooldatabase/tooldatabase.adoc b/docs/src/tooldatabase/tooldatabase.adoc -index 0fab0191b2..8528da146e 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 - 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. - --=== *db_program* operation (v2.1) -+=== *db_program* operation (v2.2) - - When a *db_progam* is specified, operation is as follows: - - . At startup, LinuxCNC starts the *db_program* and connects to its stdin and stdout. --. The *db_program* must respond by writing a single line acknowledgement consisting of a version string (e.g., "v2.1"). -+. The *db_program* must respond by writing a single line acknowledgement consisting of the version string "v2.2". - 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* - - The commands issued for tool data changes are: - --* "p" put data changes caused by G10L1, G10L10, G10L11 G-codes. The tool data line will include all elements of a tool table text line. -+* "p" put data changes caused by G10L1, G10L3, G10L10, G10L11 G-codes. The tool data line will include all elements of a tool table text line, including wear fields. - * "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/tooldb.py b/lib/python/tooldb.py -index 8ce720aadc..55a5dfe977 100644 ---- a/lib/python/tooldb.py -+++ b/lib/python/tooldb.py -@@ -8,7 +8,7 @@ import traceback - # 2) all writes to stdout go to host - # (caller: use stderr for debug prints) - #----------------------------------------------------------- --DB_VERSION = 'v2.1' -+DB_VERSION = 'v2.2' - - #----------------------------------------------------------- - # 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 ---- a/src/emc/ini/linuxcnc_check_ini.py -+++ b/src/emc/ini/linuxcnc_check_ini.py -@@ -231,7 +231,6 @@ def check_bools(): - ("EMCIO", "RANDOM_TOOLCHANGER"), - ("RS274NGC", "INI_VARS"), - ("RS274NGC", "HAL_PIN_VARS"), -- ("RS274NGC", "RETAIN_G43"), - ("RS274NGC", "OWORD_NARGS"), - ("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 ---- 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": - if features != None: - features = int(features) - section = re.sub("FEATURES.*?\n", "", section) -- section += ("RETAIN_G43 = %s\n" % ("1" if features & 0x1 else "0")) - section += ("INI_VARS = %s\n" % ("1" if features & 0x4 else "0")) - 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 ---- a/src/emc/nml_intf/canon.hh -+++ b/src/emc/nml_intf/canon.hh -@@ -652,7 +652,8 @@ extern void USE_SPINDLE_FORCE(); - extern void USE_NO_SPINDLE_FORCE(); - - /* Tool Functions */ --extern void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, double diameter, -+extern void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, double diameter, - double frontangle, double backangle, int orientation); - 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 ---- 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) - cms->update(pocket); - cms->update(toolno); - EmcPose_update(cms, &offset); -+ EmcPose_update(cms, &wear_offset); -+ cms->update(wear_offset_valid); - cms->update(diameter); - cms->update(frontangle); - cms->update(backangle); -@@ -1241,6 +1243,7 @@ void CANON_TOOL_TABLE_update(CMS * cms, CANON_TOOL_TABLE * x) - { - cms->update(x->toolno); - EmcPose_update(cms, &x->offset); -+ EmcPose_update(cms, &x->wear_offset); - cms->update(x->diameter); - 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 ---- a/src/emc/nml_intf/emc.hh -+++ b/src/emc/nml_intf/emc.hh -@@ -418,8 +418,10 @@ extern int emcToolPrepare(int tool); - extern int emcToolLoad(); - extern int emcToolUnload(); - extern int emcToolLoadToolTable(const char *file); --extern int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, double diameter, -- double frontangle, double backangle, int orientation); -+extern int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, bool wear_offset_valid, -+ double diameter, double frontangle, double backangle, -+ int orientation); - extern int emcToolSetNumber(int number); - - // 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 ---- 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 { - pocket(0), - toolno(0), - offset{}, -+ wear_offset{}, -+ wear_offset_valid(false), - diameter(0.0), - frontangle(0.0), - backangle(0.0), -@@ -1615,6 +1617,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { - int pocket; - int toolno; - EmcPose offset; -+ EmcPose wear_offset; -+ bool wear_offset_valid; - 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; -diff --git a/src/emc/nml_intf/emctool.h b/src/emc/nml_intf/emctool.h -index b8775910fe..12879116a4 100644 ---- a/src/emc/nml_intf/emctool.h -+++ b/src/emc/nml_intf/emctool.h -@@ -23,13 +23,14 @@ - ** 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 - #define CANON_TOOL_COMMENT_SIZE 40 // max comment string (include trailing null) - - struct CANON_TOOL_TABLE { - int toolno; - int pocketno; - EmcPose offset; -+ EmcPose wear_offset; - double diameter; - double frontangle; - double backangle; -diff --git a/src/emc/rs274ngc/gcodemodule.cc b/src/emc/rs274ngc/gcodemodule.cc -index 61c8f5fead..32aeed560b 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); - } - --void SET_TOOL_TABLE_ENTRY(int /*pocket*/, int /*toolno*/, const EmcPose& /*offset*/, double /*diameter*/, -+void SET_TOOL_TABLE_ENTRY(int /*pocket*/, int /*toolno*/, const EmcPose& /*offset*/, -+ const EmcPose& /*wear_offset*/, double /*diameter*/, - double /*frontangle*/, double /*backangle*/, int /*orientation*/) { - } - -@@ -680,7 +681,9 @@ 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); -diff --git a/src/emc/rs274ngc/interp_array.cc b/src/emc/rs274ngc/interp_array.cc -index ba233a1d88..ba393b5b9f 100644 ---- a/src/emc/rs274ngc/interp_array.cc -+++ b/src/emc/rs274ngc/interp_array.cc -@@ -243,6 +243,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 -+ 5430, 5431, 5432, 5433, 5434, 5435, 5436, 5437, 5438, // loaded tool wear X Y ... W - }; - 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 ---- 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 - CHKS((mode1 == G_2 || mode1 == G_3), _("G4 not allowed with G2 or G3 because they both use P")); - } else if (mode0 == G_10) { - (block->p_number >= 0) ? p_int = (int) (block->p_number +0.5) :p_int = (int) (block->p_number -0.5); -- CHKS((block->l_number != 0 && block->l_number != 2 && block->l_number != 1 && block->l_number != 20 && block->l_number != 10 && block->l_number != 11), _("Line with G10 does not have L0, L1, L10, L11, L2, or L20")); -+ CHKS((block->l_number != 0 && block->l_number != 2 && block->l_number != 1 && block->l_number != 3 && block->l_number != 20 && block->l_number != 10 && block->l_number != 11), _("Line with G10 does not have L0, L1, L3, L10, L11, L2, or L20")); - CHKS((((block->p_number + 0.0001) - p_int) > 0.0002), _("P value not an integer with G10")); - CHKS((((block->l_number == 2 || block->l_number == 20) && ((p_int < 0) || (p_int > 9)))), _("P value out of range (0-9) with G10 L%d"), block->l_number); -- CHKS((((block->l_number == 1 || block->l_number == 10 || block->l_number == 11) && p_int < 1)), _("P value out of range with G10 L%d"), block->l_number); -+ CHKS((((block->l_number == 1 || block->l_number == 3 || block->l_number == 10 || block->l_number == 11) && p_int < 1)), _("P value out of range with G10 L%d"), block->l_number); - } else if (mode0 == G_28) { - } 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 ---- 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 - { - int type; -+ bool builtin_tool_change = false; -+ int changed_toolno = -1; - 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 - - // 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; - } - 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; - 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; - } - break; - -@@ -3987,21 +3993,28 @@ 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->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)); -- } else { -- struct block_struct g49; -- init_block(&g49); -- block->g_modes[gees[G_49]] = G_49; -- CHP(convert_tool_length_offset(G_49, &g49, settings)); -- } -- } -+ if (builtin_tool_change) { -+ struct block_struct automatic_tlo; -+ init_block(&automatic_tlo); -+ const bool no_tool = !settings->random_toolchanger && changed_toolno <= 0; -+ if (no_tool) { -+ for (int param = 5430; param <= 5438; ++param) { -+ settings->parameters[param] = 0; -+ } -+ } else { -+ const CANON_TOOL_TABLE &loaded_tool = settings->tool_table[settings->current_pocket]; -+ settings->parameters[5430] = loaded_tool.wear_offset.tran.x; -+ settings->parameters[5431] = loaded_tool.wear_offset.tran.y; -+ settings->parameters[5432] = loaded_tool.wear_offset.tran.z; -+ settings->parameters[5433] = loaded_tool.wear_offset.a; -+ settings->parameters[5434] = loaded_tool.wear_offset.b; -+ settings->parameters[5435] = loaded_tool.wear_offset.c; -+ settings->parameters[5436] = loaded_tool.wear_offset.u; -+ 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; -+ 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 - { - - if (code == G_10) { -- if(block->l_number == 1 || block->l_number == 10 || block->l_number == 11) -+ if(block->l_number == 1 || block->l_number == 3 || block->l_number == 10 || block->l_number == 11) - 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) { - int idx = -1, toolno; - int q; - double tx, ty, tz, ta, tb, tc, tu, tv, tw; -- int direct = block->l_number == 1; -+ const bool direct = block->l_number == 1; -+ const bool wear = block->l_number == 3; - - is_near_int(&toolno, block->p_number); - -@@ -4542,9 +4556,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 (wear) { -+ if(block->x_flag) -+ settings->tool_table[idx].wear_offset.tran.x = PROGRAM_TO_USER_LEN(block->x_number); -+ if(block->y_flag) -+ settings->tool_table[idx].wear_offset.tran.y = PROGRAM_TO_USER_LEN(block->y_number); -+ 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); -+ if(block->b_flag) -+ settings->tool_table[idx].wear_offset.b = PROGRAM_TO_USER_ANG(block->b_number); -+ if(block->c_flag) -+ settings->tool_table[idx].wear_offset.c = PROGRAM_TO_USER_ANG(block->c_number); -+ if(block->u_flag) -+ settings->tool_table[idx].wear_offset.u = PROGRAM_TO_USER_LEN(block->u_number); -+ if(block->v_flag) -+ settings->tool_table[idx].wear_offset.v = PROGRAM_TO_USER_LEN(block->v_number); -+ if(block->w_flag) -+ settings->tool_table[idx].wear_offset.w = PROGRAM_TO_USER_LEN(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); - } - -- if(block->r_flag) settings->tool_table[idx].diameter = PROGRAM_TO_USER_LEN(block->r_number) * 2.; -- if(block->i_flag) settings->tool_table[idx].frontangle = block->i_number; -- if(block->j_flag) settings->tool_table[idx].backangle = block->j_number; -- if(block->q_number != -1.0) { -+ if(!wear && block->r_flag) settings->tool_table[idx].diameter = PROGRAM_TO_USER_LEN(block->r_number) * 2.; -+ if(!wear && block->i_flag) settings->tool_table[idx].frontangle = block->i_number; -+ if(!wear && block->j_flag) settings->tool_table[idx].backangle = block->j_number; -+ if(!wear && block->q_number != -1.0) { - 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) { - SET_TOOL_TABLE_ENTRY(idx, - settings->tool_table[idx].toolno, - settings->tool_table[idx].offset, -+ settings->tool_table[idx].wear_offset, - 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) { - settings->parameters[5411] = settings->tool_table[0].frontangle; - settings->parameters[5412] = settings->tool_table[0].backangle; - settings->parameters[5413] = settings->tool_table[0].orientation; -+ settings->parameters[5430] = settings->tool_table[0].wear_offset.tran.x; -+ settings->parameters[5431] = settings->tool_table[0].wear_offset.tran.y; -+ settings->parameters[5432] = settings->tool_table[0].wear_offset.tran.z; -+ settings->parameters[5433] = settings->tool_table[0].wear_offset.a; -+ settings->parameters[5434] = settings->tool_table[0].wear_offset.b; -+ settings->parameters[5435] = settings->tool_table[0].wear_offset.c; -+ settings->parameters[5436] = settings->tool_table[0].wear_offset.u; -+ settings->parameters[5437] = settings->tool_table[0].wear_offset.v; -+ settings->parameters[5438] = settings->tool_table[0].wear_offset.w; - - // 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) { - SET_TOOL_TABLE_ENTRY(0, - settings->tool_table[idx].toolno, - settings->tool_table[idx].offset, -+ settings->tool_table[idx].wear_offset, - 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. - 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. - --Note that if a different tool is put into the spindle, the current_z --location setting will be incorrect. It is assumed the program will --contain an appropriate USE_TOOL_LENGTH_OFFSET (G43) command before any --subsequent motion. It is also assumed that the program will restart the --spindle and make new entry moves if necessary. -+After this built-in path returns, convert_m applies the resulting tool's -+stored geometry plus wear offset. It is assumed that the program will -+restart the spindle and make new entry moves if necessary. - - */ - -@@ -6266,15 +6311,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.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); - 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 - 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.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); - } else { - if(block->x_flag) tool_offset.tran.x += block->x_number; - if(block->y_flag) tool_offset.tran.y += block->y_number; -diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh -index b734b66ee8..fed82a67d8 100644 ---- a/src/emc/rs274ngc/interp_internal.hh -+++ b/src/emc/rs274ngc/interp_internal.hh -@@ -342,7 +342,6 @@ enum phases { - STEP_PREPARE, - STEP_M_5, - STEP_M_6, -- STEP_RETAIN_G43, - STEP_M_7, - STEP_M_8, - STEP_M_9, -@@ -837,7 +836,6 @@ struct setup - bool iscircle; - - #define FEATURE(x) (_setup.feature_set & FEATURE_ ## x) --#define FEATURE_RETAIN_G43 0x00000001 - #define FEATURE_OWORD_N_ARGS 0x00000002 - #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 ---- a/src/emc/rs274ngc/interp_parameter_def.hh -+++ b/src/emc/rs274ngc/interp_parameter_def.hh -@@ -196,6 +196,16 @@ enum InterpParameterIndex { - RELATIVE_POSITION_U, - RELATIVE_POSITION_V, - RELATIVE_POSITION_W, -+// 5430-5438 - Stored wear offsets for the loaded tool for X, Y, Z, A, B, C, U, V & W. Volatile. -+ TOOL_WEAR_OFFSET_X=5430, -+ TOOL_WEAR_OFFSET_Y, -+ TOOL_WEAR_OFFSET_Z, -+ TOOL_WEAR_OFFSET_A, -+ TOOL_WEAR_OFFSET_B, -+ TOOL_WEAR_OFFSET_C, -+ TOOL_WEAR_OFFSET_U, -+ TOOL_WEAR_OFFSET_V, -+ TOOL_WEAR_OFFSET_W, - // 5599 - Flag for controlling the output of (DEBUG,) statements. 1=output, 0=no output; default=1. Volatile. - 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 ---- 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) { - static void tool_zero( CANON_TOOL_TABLE &t) { - t.toolno = -1; - ZERO_EMC_POSE(t.offset); -+ ZERO_EMC_POSE(t.wear_offset); - t.diameter = 0.0; - t.frontangle = 0.0; - t.backangle = 0.0; -@@ -106,6 +107,7 @@ void export_EmcTypes() - class_("CANON_TOOL_TABLE","Tool description" ,no_init) - .def_readwrite("toolno", &CANON_TOOL_TABLE::toolno) - .def_readwrite("offset", &CANON_TOOL_TABLE::offset) -+ .def_readwrite("wear_offset", &CANON_TOOL_TABLE::wear_offset) - .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_pre.cc b/src/emc/rs274ngc/rs274ngc_pre.cc -index 2ea4bf5550..a4ef597412 100644 ---- a/src/emc/rs274ngc/rs274ngc_pre.cc -+++ b/src/emc/rs274ngc/rs274ngc_pre.cc -@@ -901,8 +901,6 @@ int Interp::init() - _setup.feature_set |= FEATURE_HAL_PIN_VARS; - - // Now those that (currently) default to off -- if (inifile.findBoolV("RETAIN_G43", "RS274NGC", false)) -- _setup.feature_set |= FEATURE_RETAIN_G43; - 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() - _setup.parameters[5411] = _setup.tool_table[0].frontangle; - _setup.parameters[5412] = _setup.tool_table[0].backangle; - _setup.parameters[5413] = _setup.tool_table[0].orientation; -+ _setup.parameters[5430] = _setup.tool_table[0].wear_offset.tran.x; -+ _setup.parameters[5431] = _setup.tool_table[0].wear_offset.tran.y; -+ _setup.parameters[5432] = _setup.tool_table[0].wear_offset.tran.z; -+ _setup.parameters[5433] = _setup.tool_table[0].wear_offset.a; -+ _setup.parameters[5434] = _setup.tool_table[0].wear_offset.b; -+ _setup.parameters[5435] = _setup.tool_table[0].wear_offset.c; -+ _setup.parameters[5436] = _setup.tool_table[0].wear_offset.u; -+ _setup.parameters[5437] = _setup.tool_table[0].wear_offset.v; -+ _setup.parameters[5438] = _setup.tool_table[0].wear_offset.w; - } else { - // non random_toolchanger: no tool at startup, one-time init - if (_setup.tool_table[0].toolno == -1) { - default_tool_parameters(); -+ } else { -+ set_tool_parameters(); - } - } - return 0; -@@ -2562,6 +2571,9 @@ int Interp::default_tool_parameters() - _setup.parameters[5411] = 0; // frontangle - _setup.parameters[5412] = 0; // backangle - _setup.parameters[5413] = 0; // orientation -+ for (int param = 5430; param <= 5438; ++param) { -+ _setup.parameters[param] = 0; -+ } - 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; - _setup.parameters[5411] = _setup.tool_table[0].frontangle; - _setup.parameters[5412] = _setup.tool_table[0].backangle; - _setup.parameters[5413] = _setup.tool_table[0].orientation; -+ _setup.parameters[5430] = _setup.tool_table[0].wear_offset.tran.x; -+ _setup.parameters[5431] = _setup.tool_table[0].wear_offset.tran.y; -+ _setup.parameters[5432] = _setup.tool_table[0].wear_offset.tran.z; -+ _setup.parameters[5433] = _setup.tool_table[0].wear_offset.a; -+ _setup.parameters[5434] = _setup.tool_table[0].wear_offset.b; -+ _setup.parameters[5435] = _setup.tool_table[0].wear_offset.c; -+ _setup.parameters[5436] = _setup.tool_table[0].wear_offset.u; -+ _setup.parameters[5437] = _setup.tool_table[0].wear_offset.v; -+ _setup.parameters[5438] = _setup.tool_table[0].wear_offset.w; - - return 0; - } -diff --git a/src/emc/sai/saicanon.cc b/src/emc/sai/saicanon.cc -index c63354d6a4..b349f4952d 100644 ---- a/src/emc/sai/saicanon.cc -+++ b/src/emc/sai/saicanon.cc -@@ -507,12 +507,14 @@ void USE_NO_SPINDLE_FORCE() - {PRINT("USE_NO_SPINDLE_FORCE()\n");} - - /* Tool Functions */ --void SET_TOOL_TABLE_ENTRY(int idx, int toolno, const EmcPose& offset, double diameter, -+void SET_TOOL_TABLE_ENTRY(int idx, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, double diameter, - double frontangle, double backangle, int orientation) { - - #ifdef TOOL_NML //{ - _sai._tools[idx].toolno = toolno; - _sai._tools[idx].offset = offset; -+ _sai._tools[idx].wear_offset = wear_offset; - _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 - } - tdata.toolno = toolno; - tdata.offset = offset; -+ tdata.wear_offset = wear_offset; - tdata.diameter = diameter; - tdata.frontangle = frontangle; - tdata.backangle = backangle; -diff --git a/src/emc/task/emccanon.cc b/src/emc/task/emccanon.cc -index d2a0e0d0f2..e5d71a60e8 100644 ---- a/src/emc/task/emccanon.cc -+++ b/src/emc/task/emccanon.cc -@@ -3072,13 +3072,16 @@ void USE_NO_SPINDLE_FORCE(void) - /* Tool Functions */ - - /* this is called with distances in external (machine) units */ --void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, double diameter, -+void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, double diameter, - double frontangle, double backangle, int orientation) { - auto o = std::make_unique(); - flush_segments(); - o->pocket = pocket; - o->toolno = toolno; - o->offset = offset; -+ o->wear_offset = wear_offset; -+ o->wear_offset_valid = true; - o->diameter = diameter; - o->frontangle = frontangle; - o->backangle = backangle; -@@ -4362,4 +4365,3 @@ int LOCK_ROTARY(int /*line_number*/, int /*joint_num*/) { - canon.rotary_unlock_for_traverse = -1; - return 0; - } -- -diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 2810757914..64b5497e58 100644 ---- a/src/emc/task/emctaskmain.cc -+++ b/src/emc/task/emctaskmain.cc -@@ -2321,6 +2321,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, -+ emc_tool_set_offset_msg->wear_offset, -+ emc_tool_set_offset_msg->wear_offset_valid, - emc_tool_set_offset_msg->diameter, - emc_tool_set_offset_msg->frontangle, - emc_tool_set_offset_msg->backangle, -diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index c484e5a986..2869ee6fb7 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); } - int emcToolLoad() { return task_methods->emcToolLoad(); } - int emcToolUnload() { return task_methods->emcToolUnload(); } - int emcToolLoadToolTable(const char *file) { return task_methods->emcToolLoadToolTable(file); } --int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, double diameter, -- double frontangle, double backangle, int orientation) { -- return task_methods->emcToolSetOffset( pocket, toolno, offset, diameter, -- frontangle, backangle, orientation); } -+int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, bool wear_offset_valid, -+ double diameter, double frontangle, double backangle, -+ int orientation) { -+ return task_methods->emcToolSetOffset(pocket, toolno, offset, wear_offset, -+ wear_offset_valid, diameter, frontangle, -+ backangle, orientation); } - int emcToolSetNumber(int number) { return task_methods->emcToolSetNumber(number); } - - 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 - return 0; - } - --int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, double diameter, -- double frontangle, double backangle, int orientation)//EMC_TOOL_SET_OFFSET -+int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, bool wear_offset_valid, -+ double diameter, double frontangle, double backangle, -+ int orientation)//EMC_TOOL_SET_OFFSET - { - - int o; -@@ -547,6 +552,9 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, double di - } - tdata.toolno = toolno; - tdata.offset = offset; -+ if (wear_offset_valid) { -+ tdata.wear_offset = wear_offset; -+ } - tdata.diameter = d; - tdata.frontangle = f; - tdata.backangle = b; -diff --git a/src/emc/task/taskclass.hh b/src/emc/task/taskclass.hh -index b19c0a00aa..5e32a1a65d 100644 ---- a/src/emc/task/taskclass.hh -+++ b/src/emc/task/taskclass.hh -@@ -66,8 +66,9 @@ public: - virtual int emcCoolantMistOff(); - virtual int emcCoolantFloodOn(); - virtual int emcCoolantFloodOff(); -- virtual int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, double diameter, -- double frontangle, double backangle, int orientation); -+ virtual int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, bool wear_offset_valid, double diameter, -+ double frontangle, double backangle, int orientation); - virtual int emcToolPrepare(int tool); - virtual int emcToolLoad(); - virtual int emcToolLoadToolTable(const char *file); -diff --git a/src/emc/tooldata/tooldata_common.cc b/src/emc/tooldata/tooldata_common.cc -index 040ff7ad80..4e9651c86f 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; - - return tdata; -@@ -73,7 +74,8 @@ int tooldata_read_entry(const char *input_line) - const char *token; - char *buff, *comment; - int toolno,orientation,valid=1; -- EmcPose offset; //tlo -+ EmcPose offset; // geometry tlo -+ EmcPose wear_offset; - double diameter, frontangle, backangle; - int idx = 0; - int realpocket = 0; -@@ -93,6 +95,7 @@ int tooldata_read_entry(const char *input_line) - backangle = empty.backangle; - orientation = empty.orientation; - offset = empty.offset; -+ wear_offset = empty.wear_offset; - - char* saveptr; - buff = strtok_r(work_line, ";", &saveptr); -@@ -170,8 +173,20 @@ int tooldata_read_entry(const char *input_line) - valid = 0; - break; - case 'W': -- if (sscanf(&token[1], "%lf", &offset.w) != 1) -- valid = 0; -+ // Wear fields are two-letter tokens and must be recognized -+ // before the legacy single-letter W geometry axis. -+ switch (toupper(token[1])) { -+ case 'X': if (sscanf(&token[2], "%lf", &wear_offset.tran.x) != 1) valid = 0; break; -+ case 'Y': if (sscanf(&token[2], "%lf", &wear_offset.tran.y) != 1) valid = 0; break; -+ case 'Z': if (sscanf(&token[2], "%lf", &wear_offset.tran.z) != 1) valid = 0; break; -+ case 'A': if (sscanf(&token[2], "%lf", &wear_offset.a) != 1) valid = 0; break; -+ case 'B': if (sscanf(&token[2], "%lf", &wear_offset.b) != 1) valid = 0; break; -+ case 'C': if (sscanf(&token[2], "%lf", &wear_offset.c) != 1) valid = 0; break; -+ case 'U': if (sscanf(&token[2], "%lf", &wear_offset.u) != 1) valid = 0; break; -+ case 'V': if (sscanf(&token[2], "%lf", &wear_offset.v) != 1) valid = 0; break; -+ case 'W': if (sscanf(&token[2], "%lf", &wear_offset.w) != 1) valid = 0; break; -+ default: if (sscanf(&token[1], "%lf", &offset.w) != 1) valid = 0; break; -+ } - break; - case 'I': - if (sscanf(&token[1], "%lf", &frontangle) != 1) -@@ -206,6 +221,7 @@ int tooldata_read_entry(const char *input_line) - tdata.toolno = toolno; - tdata.pocketno = realpocket; - tdata.offset = offset; -+ tdata.wear_offset = wear_offset; - tdata.diameter = diameter; - tdata.frontangle = frontangle; - tdata.backangle = backangle; -@@ -272,6 +288,15 @@ void tooldata_format_toolline (int idx, - F_ITEM(offset.u, "U"); - F_ITEM(offset.v, "V"); - F_ITEM(offset.w, "W"); -+ F_ITEM(wear_offset.tran.x, "WX"); -+ F_ITEM(wear_offset.tran.y, "WY"); -+ F_ITEM(wear_offset.tran.z, "WZ"); -+ F_ITEM(wear_offset.a, "WA"); -+ F_ITEM(wear_offset.b, "WB"); -+ F_ITEM(wear_offset.c, "WC"); -+ F_ITEM(wear_offset.u, "WU"); -+ F_ITEM(wear_offset.v, "WV"); -+ F_ITEM(wear_offset.w, "WW"); - F_ITEM(frontangle, "I"); - F_ITEM(backangle, "J"); - I_ITEM(orientation, "Q"); -diff --git a/src/emc/tooldata/tooldata_db.cc b/src/emc/tooldata/tooldata_db.cc -index 32df138863..99e263f80d 100644 ---- a/src/emc/tooldata/tooldata_db.cc -+++ b/src/emc/tooldata/tooldata_db.cc -@@ -27,7 +27,7 @@ - #include "tooldata.hh" - #include - --#define DB_VERSION "v2.1" -+#define DB_VERSION "v2.2" - #define MAX_DB_PROGRAM_ARGS 10 - #define UNEXPECTED_MSG fprintf(stderr,"UNEXPECTED %s %d\n",__FILE__,__LINE__); - -diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index 5f47d78ec1..bd747787e4 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) { - dict_add(res, "uoffset", tdata.offset.u); - dict_add(res, "voffset", tdata.offset.v); - dict_add(res, "woffset", tdata.offset.w); -+ dict_add(res, "wxoffset", tdata.wear_offset.tran.x); -+ dict_add(res, "wyoffset", tdata.wear_offset.tran.y); -+ dict_add(res, "wzoffset", tdata.wear_offset.tran.z); -+ dict_add(res, "waoffset", tdata.wear_offset.a); -+ dict_add(res, "wboffset", tdata.wear_offset.b); -+ dict_add(res, "wcoffset", tdata.wear_offset.c); -+ dict_add(res, "wuoffset", tdata.wear_offset.u); -+ dict_add(res, "wvoffset", tdata.wear_offset.v); -+ dict_add(res, "wwoffset", tdata.wear_offset.w); - - PyDict_SetItemString(res, "comment", o= PyUnicode_FromString(tdata.comment)); - Py_DECREF(o); -@@ -1481,6 +1490,15 @@ static PyStructSequence_Field tool_fields[] = { - {(char*)"frontangle", NULL}, - {(char*)"backangle", NULL}, - {(char*)"orientation", NULL}, -+ {(char*)"wxoffset", NULL}, -+ {(char*)"wyoffset", NULL}, -+ {(char*)"wzoffset", NULL}, -+ {(char*)"waoffset", NULL}, -+ {(char*)"wboffset", NULL}, -+ {(char*)"wcoffset", NULL}, -+ {(char*)"wuoffset", NULL}, -+ {(char*)"wvoffset", NULL}, -+ {(char*)"wwoffset", NULL}, - {}, - }; - -@@ -1488,7 +1506,7 @@ static PyStructSequence_Desc tool_result_desc = { - (char*)"tool_result", /* name */ - (char*)"", /* doc */ - tool_fields, -- 14 -+ 23 - }; - - static PyTypeObject ToolResultType; -@@ -1526,6 +1544,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)); -+ PyStructSequence_SET_ITEM(tool, 14, PyFloat_FromDouble(t.wear_offset.tran.x)); -+ PyStructSequence_SET_ITEM(tool, 15, PyFloat_FromDouble(t.wear_offset.tran.y)); -+ PyStructSequence_SET_ITEM(tool, 16, PyFloat_FromDouble(t.wear_offset.tran.z)); -+ PyStructSequence_SET_ITEM(tool, 17, PyFloat_FromDouble(t.wear_offset.a)); -+ PyStructSequence_SET_ITEM(tool, 18, PyFloat_FromDouble(t.wear_offset.b)); -+ PyStructSequence_SET_ITEM(tool, 19, PyFloat_FromDouble(t.wear_offset.c)); -+ PyStructSequence_SET_ITEM(tool, 20, PyFloat_FromDouble(t.wear_offset.u)); -+ PyStructSequence_SET_ITEM(tool, 21, PyFloat_FromDouble(t.wear_offset.v)); -+ PyStructSequence_SET_ITEM(tool, 22, PyFloat_FromDouble(t.wear_offset.w)); - PyTuple_SetItem(res, j, tool); - j++; - } -diff --git a/tests/ccomp/lathe-comp/expected b/tests/ccomp/lathe-comp/expected -index 4fabddb4b7..bba4efd501 100644 ---- a/tests/ccomp/lathe-comp/expected -+++ b/tests/ccomp/lathe-comp/expected -@@ -13,6 +13,7 @@ - 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..... STRAIGHT_TRAVERSE(0.3000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) - N..... COMMENT("interpreter: cutter radius compensation off") - N..... STRAIGHT_FEED(0.1000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -@@ -26,6 +27,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) -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - N..... STRAIGHT_TRAVERSE(0.3000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) - N..... COMMENT("interpreter: cutter radius compensation on left") - N..... STRAIGHT_FEED(0.0500, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -@@ -40,6 +42,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) -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - N..... STRAIGHT_TRAVERSE(0.3000, 0.0000, 1.8500, 0.0000, 0.0000, 0.0000) - N..... STRAIGHT_TRAVERSE(-0.3000, 0.0000, 1.8500, 0.0000, 0.0000, 0.0000) - N..... COMMENT("interpreter: cutter radius compensation on right") -@@ -56,6 +59,7 @@ - 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..... 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) -diff --git a/tests/ccomp/mill-g90g91g92/expected b/tests/ccomp/mill-g90g91g92/expected -index f58e400842..7327c18c64 100644 ---- a/tests/ccomp/mill-g90g91g92/expected -+++ b/tests/ccomp/mill-g90g91g92/expected -@@ -8,6 +8,7 @@ - N..... SELECT_TOOL(3) - N..... STOP_SPINDLE_TURNING(0) - N..... CHANGE_TOOL() -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.5000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - N..... STRAIGHT_TRAVERSE(0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) - 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 ---- a/tests/ccomp/mill-line-arc-entry/expected -+++ b/tests/ccomp/mill-line-arc-entry/expected -@@ -24,6 +24,7 @@ - N..... SELECT_TOOL(4) - N..... STOP_SPINDLE_TURNING(0) - N..... CHANGE_TOOL() -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - 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/interp/cam-nisley/expected b/tests/interp/cam-nisley/expected -index 4bc9ee3753..6f3aab576f 100644 ---- a/tests/interp/cam-nisley/expected -+++ b/tests/interp/cam-nisley/expected -@@ -51,6 +51,7 @@ - N..... SELECT_TOOL(1) - N..... STOP_SPINDLE_TURNING(0) - N..... CHANGE_TOOL() -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 12.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - N..... COMMENT("-----------------") - 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 ---- 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) {} - void LOCK_SPINDLE_Z() {} - void USE_SPINDLE_FORCE() {} - void USE_NO_SPINDLE_FORCE() {} --void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, double diameter, -+void SET_TOOL_TABLE_ENTRY(int pocket, int toolno, const EmcPose& offset, -+ const EmcPose& wear_offset, double diameter, - double frontangle, double backangle, int orientation) {} - 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 ---- a/tests/interp/g10/g10-l1-l10/expected -+++ b/tests/interp/g10/g10-l1-l10/expected -@@ -16,6 +16,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) -+ 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(" 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 @@ - 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..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - 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 @@ - 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..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 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.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 @@ - 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..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 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.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 ---- a/tests/interp/g10/g10-l11/expected -+++ b/tests/interp/g10/g10-l11/expected -@@ -23,6 +23,7 @@ - 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..... 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) -diff --git a/tests/interp/g72-facing/expected b/tests/interp/g72-facing/expected -index 1096d6d415..5bf73147be 100644 ---- a/tests/interp/g72-facing/expected -+++ b/tests/interp/g72-facing/expected -@@ -11,6 +11,7 @@ - N..... SELECT_TOOL(2) - N..... STOP_SPINDLE_TURNING(0) - N..... CHANGE_TOOL() -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 2.5400, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - N..... COMMENT("interpreter: cutter radius compensation off") - 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 ---- a/tests/interp/g72-missing-iteration/expected -+++ b/tests/interp/g72-missing-iteration/expected -@@ -11,6 +11,7 @@ - N..... SELECT_TOOL(2) - N..... STOP_SPINDLE_TURNING(0) - N..... CHANGE_TOOL() -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 2.5400, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - N..... COMMENT("interpreter: cutter radius compensation off") - 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 ---- a/tests/interp/g76/expected -+++ b/tests/interp/g76/expected -@@ -14,6 +14,7 @@ - N..... STOP_SPINDLE_TURNING(0) - N..... CHANGE_TOOL() - N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.7000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) - 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 ---- a/tests/remap/introspect/expected -+++ b/tests/remap/introspect/expected -@@ -9,9 +9,10 @@ executing - 8 N..... SELECT_TOOL(3) - 9 N..... STOP_SPINDLE_TURNING(0) - 10 N..... CHANGE_TOOL() -- 11 N..... SET_FEED_RATE(200.0000) -- 12 N..... SET_SPINDLE_SPEED(0, 3000.0000) -- 13 N..... START_SPINDLE_CLOCKWISE(0) -+ 11 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 32.3342, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ 12 N..... SET_FEED_RATE(200.0000) -+ 13 N..... SET_SPINDLE_SPEED(0, 3000.0000) -+ 14 N..... START_SPINDLE_CLOCKWISE(0) - debug: 1073741824 logging: 0 - call_level= 1 - 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'] -- 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) -- 17 N..... SET_FEED_MODE(0, 0) -- 18 N..... SET_FEED_RATE(0.0000) -- 19 N..... STOP_SPINDLE_TURNING(0) -- 20 N..... SET_SPINDLE_MODE(0 0.0000) -- 21 N..... PROGRAM_END() -- 22 N..... ON_RESET() -+ 15 N..... MESSAGE(" after introspect: return value=2.718280 call_level= 0.000000") -+ 16 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ 17 N..... SET_XY_ROTATION(0.0000) -+ 18 N..... SET_FEED_MODE(0, 0) -+ 19 N..... SET_FEED_RATE(0.0000) -+ 20 N..... STOP_SPINDLE_TURNING(0) -+ 21 N..... SET_SPINDLE_MODE(0 0.0000) -+ 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 ---- a/tests/remap/oword-pycall/expected -+++ b/tests/remap/oword-pycall/expected -@@ -12,15 +12,16 @@ multiply: number of arguments= 3 - 9 N..... STOP_SPINDLE_TURNING(0) - 10 N..... CHANGE_TOOL() - 11 N..... USE_TOOL_LENGTH_OFFSET(10.0000 0.0000 20.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -- 12 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -- 13 N..... SET_TOOL_TABLE_ENTRY(1, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -- 14 N..... SET_TOOL_TABLE_ENTRY(0, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -- 15 N..... USE_TOOL_LENGTH_OFFSET(20.0000 30.0000 40.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -- 16 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -- 17 N..... SET_XY_ROTATION(0.0000) -- 18 N..... SET_FEED_MODE(0, 0) -- 19 N..... SET_FEED_RATE(0.0000) -- 20 N..... STOP_SPINDLE_TURNING(0) -- 21 N..... SET_SPINDLE_MODE(0 0.0000) -- 22 N..... PROGRAM_END() -- 23 N..... ON_RESET() -+ 12 N..... USE_TOOL_LENGTH_OFFSET(10.0000 0.0000 20.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ 13 N..... USE_TOOL_LENGTH_OFFSET(0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ 14 N..... SET_TOOL_TABLE_ENTRY(1, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -+ 15 N..... SET_TOOL_TABLE_ENTRY(0, 1, 20.0000 30.0000 40.0000 0.0000 0.0000 0.0000 0.0000 0.0000 0.0000, 0.0000, 0.0000, 0) -+ 16 N..... USE_TOOL_LENGTH_OFFSET(20.0000 30.0000 40.0000, 0.0000 0.0000 0.0000, 0.0000 0.0000 0.0000) -+ 17 N..... SET_G5X_OFFSET(1, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000) -+ 18 N..... SET_XY_ROTATION(0.0000) -+ 19 N..... SET_FEED_MODE(0, 0) -+ 20 N..... SET_FEED_RATE(0.0000) -+ 21 N..... STOP_SPINDLE_TURNING(0) -+ 22 N..... SET_SPINDLE_MODE(0 0.0000) -+ 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 ---- a/tests/t0/nonrandom/expected-gcode-output -+++ b/tests/t0/nonrandom/expected-gcode-output -@@ -134,9 +134,9 @@ 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 - - sequence number 101.000000 - X = 0.000000 -@@ -309,9 +309,9 @@ 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 - - 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 ---- 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 - 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 - - 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 ---- 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 - 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 - - 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 ---- a/tests/tlo/test-ui.py -+++ b/tests/tlo/test-ui.py -@@ -153,14 +153,14 @@ verify_tool( - ) - - --print("*** load T100 but dont apply TLO") -+print("*** load T100 and automatically apply its TLO") - - c.mdi('t100 m6') - c.wait_complete() - - verify_tool( - tool=100, -- x=0, y=0, z=0, -+ x=-2, y=0, z=-1, - a=0, b=0, c=0, - u=0, v=0, w=0, - diameter=0.125, -@@ -169,7 +169,7 @@ verify_tool( - ) - - --print("*** apply TLO of loaded tool (T100)") -+print("*** reapply TLO of loaded tool (T100), idempotently") - - c.mdi('g43') - c.wait_complete() -@@ -347,4 +347,3 @@ verify_tool( - - # if we get here it all worked! - sys.exit(0) -- -diff --git a/tests/toolchanger/m61/test-ui.py b/tests/toolchanger/m61/test-ui.py -index 83110f6ed2..51dd84d263 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) - 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. - 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(5420, 0) # current x - verify_interp_param(5421, 0) # current y --verify_interp_param(5422, 0) # current z -+verify_interp_param(5422, -1) # current z - 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 - 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(5420, 0) # current x - verify_interp_param(5421, 0) # current y -@@ -244,12 +243,10 @@ 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. - 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(5420, 0) # current x - verify_interp_param(5421, 0) # current y --verify_interp_param(5422, -1) # current z -+verify_interp_param(5422, -3) # current z - 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 - 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(5420, 0) # current x - verify_interp_param(5421, 0) # current y -@@ -297,6 +294,8 @@ 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(5422, 0) - - - # -@@ -307,6 +306,8 @@ 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(5422, -1) - - - # -@@ -317,8 +318,9 @@ 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(5422, 0) - - - # if we get here it all worked! - 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 ---- 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 - 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 - - sequence number 2.000000 - X = 0.111000 -@@ -64,9 +64,9 @@ 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 - - sequence number 10.000000 - X = 0.111000 -@@ -120,9 +120,9 @@ 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 - - sequence number 18.000000 - X = 0.111000 -@@ -176,9 +176,9 @@ 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 - - sequence number 26.000000 - X = 0.111000 -@@ -190,9 +190,9 @@ 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 - - sequence number 28.000000 - X = 0.111000 -@@ -204,9 +204,9 @@ 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 - - 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 ---- 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 - 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 - - sequence number 2.000000 - X = 0.111000 -@@ -64,9 +64,9 @@ 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 - - sequence number 10.000000 - X = 0.111000 -@@ -120,9 +120,9 @@ 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 - - sequence number 18.000000 - X = 0.111000 -@@ -176,9 +176,9 @@ 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 - - sequence number 26.000000 - X = 0.111000 -@@ -190,9 +190,9 @@ 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 - - sequence number 28.000000 - X = 0.111000 -@@ -204,9 +204,9 @@ 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 - - sequence number 30.000000 - X = 0.111000 From 18a0825bcca07e1934b3636f1caad84097bac141 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 12 Nov 2026 13:14:10 +0100 Subject: [PATCH 11/45] feat(linuxcnc): port patches 0009-0015 to v2.10.0-pre2 0009 merges onto the reworked Stop state of 0004 (a sync-run flag plus the G76 clearance target) and keeps upstream's G76 override lock in the first pass's Single Step unit. 0011 adds its in-flight scenarios; tests/resumable-stop now runs 35 scenarios plus four trapezoidal re-runs. 0010's recording canon matches pre2's canon interface. 0012 keeps 0007's tool-line limit and save refusal; the upstream tooldb tests that need DB_PROGRAM are skipped because 0012 refuses it. 0013, 0014 and 0015 apply unchanged in substance. Verified on the stack: clean -Werror build, 336/336 regression tests (5 skipped), tests/resumable-stop once more (39/39), headless build with a test subset. --- ...reading-stop-clear-and-pass-stepping.patch | 705 ++++++++---------- ...-add-recording-canon-preview-backend.patch | 74 +- ...-single-step-during-active-execution.patch | 231 ++++-- ...-own-transactional-tool-CRUD-in-task.patch | 411 ++++++---- ...4ngc-add-composable-executor-stdglue.patch | 231 ++++-- ...-publish-modal-CSS-maximum-in-status.patch | 30 +- ...ngc-pass-spindle-selectors-to-remaps.patch | 30 +- linuxcnc-patches/README.md | 14 +- 8 files changed, 1008 insertions(+), 718 deletions(-) rename linuxcnc-patches/{pending-pre2 => }/0009-threading-stop-clear-and-pass-stepping.patch (77%) rename linuxcnc-patches/{pending-pre2 => }/0010-rs274-add-recording-canon-preview-backend.patch (98%) rename linuxcnc-patches/{pending-pre2 => }/0011-motion-arm-single-step-during-active-execution.patch (67%) rename linuxcnc-patches/{pending-pre2 => }/0012-emc-own-transactional-tool-CRUD-in-task.patch (75%) rename linuxcnc-patches/{pending-pre2 => }/0013-rs274ngc-add-composable-executor-stdglue.patch (78%) rename linuxcnc-patches/{pending-pre2 => }/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch (92%) rename linuxcnc-patches/{pending-pre2 => }/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch (93%) diff --git a/linuxcnc-patches/pending-pre2/0009-threading-stop-clear-and-pass-stepping.patch b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch similarity index 77% rename from linuxcnc-patches/pending-pre2/0009-threading-stop-clear-and-pass-stepping.patch rename to linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch index c948eb7..38139b2 100644 --- a/linuxcnc-patches/pending-pre2/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -8,32 +8,43 @@ 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/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 | 5 +- + 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 | 12 + + src/emc/rs274ngc/interp_convert.cc | 18 +- src/emc/sai/saicanon.cc | 6 + - src/emc/task/emccanon.cc | 63 ++- + 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/task/taskintf.cc | 5 +- src/emc/tp/tc_types.h | 2 + - src/emc/tp/tp.c | 189 +++++++- + src/emc/tp/tp.c | 203 ++++++++++- src/emc/tp/tp.h | 3 +- - src/emc/tp/tp_types.h | 10 +- + src/emc/tp/tp_types.h | 16 +- tests/interp/compile/use-rs274.cc | 5 + - tests/resumable-stop/README | 22 +- - tests/resumable-stop/checkresult | 3 +- + tests/resumable-stop/README | 16 + + tests/resumable-stop/checkresult | 2 +- .../resumable-stop/g33-followed-by-rapid.ngc | 7 + tests/resumable-stop/g76-exit-taper.ngc | 7 + tests/resumable-stop/g76-handoff.ngc | 7 + @@ -41,10 +52,10 @@ Preserve pass ownership on synthetic blend arcs, make marked clearance endpoints .../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-ui.py | 330 +++++++++++++++++- tests/resumable-stop/test.ini | 1 + - tests/resumable-stop/test.sh | 15 + - 35 files changed, 957 insertions(+), 59 deletions(-) + tests/resumable-stop/test.sh | 13 + + 35 files changed, 895 insertions(+), 57 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 @@ -54,10 +65,10 @@ Preserve pass ownership on synthetic blend arcs, make marked clearance endpoints create mode 100644 tests/resumable-stop/g76-tapered.ngc diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index 4160cfb4a2..760cfe2384 100644 +index 950dc5c..f13ec12 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 +@@ -2307,6 +2307,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 +91,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 4c0b914..dfceb2a 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 +115,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 +164,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 +176,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 7a85db9..499824d 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1993,12 +1993,11 @@ static void output_to_hal(void) - /* +@@ -2075,10 +2075,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) +@@ -2306,10 +2309,20 @@ static void update_status(void) /* check to see if we should pause in order to implement single emcmotStatus->stepping */ @@ -207,23 +221,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 eb11553..019e6d1 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 +253,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 d8d1d9d..ded71c3 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 +266,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 +275,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 +287,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 +297,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 9435447..8e943ba 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 +308,23 @@ index a98ae39f20..d2ab16d3ba 100644 #define EMC_TASK_STAT_TYPE ((NMLTYPE) 599) -@@ -380,7 +381,9 @@ extern int emcTrajStep(); - extern int emcTrajResume(); +@@ -386,7 +387,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 89aba60..cf8bc14 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 +333,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 +342,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 +363,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 +413,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 +423,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 +443,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 +453,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 +467,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 196d48c..e894e64 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, +@@ -5943,11 +5943,13 @@ threading_pass(setup_pointer settings, block_pointer block, double start_y, double start_z, double zoff, 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 +486,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, +@@ -5958,6 +5960,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,7 +494,7 @@ 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, +@@ -5977,11 +5980,13 @@ threading_pass(setup_pointer settings, block_pointer block, start_y, target_z - zoff, AABBCC); //over } STOP_SPEED_FEED_SYNCH(); @@ -495,57 +507,61 @@ index 373916cfb0..33a35bda2e 100644 + 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 +@@ -6054,10 +6059,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, +@@ -6066,6 +6073,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 +@@ -6083,9 +6091,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, +@@ -6273,9 +6283,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 +575,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 +635,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 +644,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 +653,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 +663,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 +673,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 +684,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 +697,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 df94f0c..fe2a371 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 +@@ -501,6 +501,22 @@ static int programStartLine = 0; // which line to run program from int stepping = 0; int steppingWait = 0; static int steppedLine = 0; @@ -713,7 +729,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() +@@ -831,8 +847,7 @@ static void emcTaskResumeInterpreter() emcStatus->task.interpState = interpResumeState; } emcStatus->motion.traj.single_stepping = 0; @@ -723,7 +739,7 @@ index 64b5497e58..beb6d565d6 100644 } static void emcTaskStepInterpreter() -@@ -1420,6 +1435,10 @@ static int emcTaskPlan(void) +@@ -1473,6 +1488,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 +750,7 @@ index 64b5497e58..beb6d565d6 100644 break; // otherwise we can't handle it -@@ -1572,6 +1591,10 @@ static int emcTaskPlan(void) +@@ -1625,6 +1644,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 +761,7 @@ index 64b5497e58..beb6d565d6 100644 break; // otherwise we can't handle it -@@ -1824,6 +1847,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1882,6 +1905,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; @@ -757,10 +773,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, +@@ -2187,7 +2215,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,7 +784,7 @@ index 64b5497e58..beb6d565d6 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2401,6 +2431,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2560,6 +2590,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } else { // we can honour the modeswitch if (mode_msg->mode != emcStatus->task.mode) { emcTaskStopClear(); @@ -777,7 +793,7 @@ index 64b5497e58..beb6d565d6 100644 } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { -@@ -2434,8 +2466,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2593,8 +2625,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 +803,7 @@ index 64b5497e58..beb6d565d6 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2448,6 +2479,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2607,6 +2638,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) state_msg = reinterpret_cast(cmd); if (state_msg->state != EMC_TASK_STATE::ON) { emcTaskStopClear(); @@ -796,7 +812,7 @@ index 64b5497e58..beb6d565d6 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2532,8 +2565,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2691,8 +2724,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_EXECUTE_TYPE: emcStatus->motion.traj.single_stepping = 0; @@ -806,7 +822,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) +@@ -2787,8 +2819,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -816,7 +832,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) +@@ -2856,6 +2887,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -827,7 +843,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) +@@ -2964,6 +2999,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 +851,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) +@@ -3016,11 +3052,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) #define STEPPING_CHECK() \ if (stepping) { \ if (! steppingWait) { \ @@ -857,7 +873,7 @@ index 64b5497e58..beb6d565d6 100644 break; \ } \ } \ -@@ -2906,8 +2949,7 @@ static int emcTaskExecute(void) +@@ -3082,8 +3125,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 +883,15 @@ index 64b5497e58..beb6d565d6 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2929,6 +2971,7 @@ static int emcTaskExecute(void) - if (0 != emcTaskCommand) { +@@ -3105,6 +3147,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. +@@ -4101,8 +4144,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 +902,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 +919,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 7db2314..533265a 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 +942,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 +955,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 8ef21c3..c690207 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 +998,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 +1007,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 +1031,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,7 +1052,7 @@ 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); } @@ -1044,7 +1063,7 @@ index e48127c5a9..00a06f1a75 100644 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; } @@ -1055,17 +1074,17 @@ index e48127c5a9..00a06f1a75 100644 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,17 @@ int tpAddLine(TP_STRUCT * const tp, EmcPose end, int canon_motion_type, enables, atspeed); tc.tag = tag; @@ -1083,16 +1102,7 @@ index e48127c5a9..00a06f1a75 100644 // 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 +3429,7 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) tpUpdateMovementStatus(tp, NULL); @@ -1101,7 +1111,7 @@ index e48127c5a9..00a06f1a75 100644 tpResume(tp); } } -@@ -3381,6 +3437,17 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, +@@ -3432,6 +3491,17 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, // Clean up Ruckig planner resources tcCleanupRuckig(tc); @@ -1119,7 +1129,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) +@@ -4303,6 +4373,10 @@ int tpRunCycle(TP_STRUCT * const tp, long period) if(!tc) { if (tp->stopping) { tpHandleEmptyQueue(tp); @@ -1128,8 +1138,9 @@ index e48127c5a9..00a06f1a75 100644 + return TP_ERR_WAITING; + } if (tp->stopping) { + tp->stop_sync_run = 0; tp->pausing = 1; - emcmotStatus->stopped = 1; +@@ -4310,6 +4384,11 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -1141,19 +1152,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) { +@@ -4458,6 +4537,42 @@ int tpSetSpindleSync(TP_STRUCT * const tp, int spindle, double sync, int mode) { return TP_ERR_OK; } @@ -1196,7 +1195,7 @@ index e48127c5a9..00a06f1a75 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4270,12 +4382,59 @@ int tpPause(TP_STRUCT * const tp) +@@ -4465,22 +4580,75 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -1205,37 +1204,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 +1272,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; + } +@@ -4495,6 +4663,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 +1295,7 @@ index e48127c5a9..00a06f1a75 100644 emcmotStatus->stopped = 0; return TP_ERR_OK; } -@@ -4304,6 +4473,10 @@ int tpAbort(TP_STRUCT * const tp) +@@ -4507,6 +4686,10 @@ int tpAbort(TP_STRUCT * const tp) if (!tp->aborting) { /* const to abort, signal a pause and set our abort flag */ @@ -1286,24 +1307,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 +1334,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 +1355,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; } @@ -1340,17 +1371,14 @@ index 4a55bad0de..a5a795f475 100644 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 +index e5da45f..3a037f8 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 +@@ -35,3 +35,19 @@ 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 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 @@ -1358,30 +1386,27 @@ index e457195324..e845030ffb 100644 +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. ++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. ++least 20 task cycles before the cut endpoint. diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -index c491888fc8..4792b570e1 100755 +index c40d14c..efeaf20 100755 --- a/tests/resumable-stop/checkresult +++ b/tests/resumable-stop/checkresult -@@ -1,3 +1,4 @@ +@@ -1,4 +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 + set -e +-test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 29 ++test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 37 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 +index 0000000..a12bcb3 --- /dev/null +++ b/tests/resumable-stop/g33-followed-by-rapid.ngc @@ -0,0 +1,7 @@ @@ -1394,7 +1419,7 @@ index 0000000000..a12bcb3029 +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 +index 0000000..5b04e69 --- /dev/null +++ b/tests/resumable-stop/g76-exit-taper.ngc @@ -0,0 +1,7 @@ @@ -1407,7 +1432,7 @@ index 0000000000..5b04e6921e +M2 diff --git a/tests/resumable-stop/g76-handoff.ngc b/tests/resumable-stop/g76-handoff.ngc new file mode 100644 -index 0000000000..01a62a26a5 +index 0000000..01a62a2 --- /dev/null +++ b/tests/resumable-stop/g76-handoff.ngc @@ -0,0 +1,7 @@ @@ -1420,7 +1445,7 @@ index 0000000000..01a62a26a5 +M2 diff --git a/tests/resumable-stop/g76-step.ngc b/tests/resumable-stop/g76-step.ngc new file mode 100644 -index 0000000000..c8ee28f7ed +index 0000000..c8ee28f --- /dev/null +++ b/tests/resumable-stop/g76-step.ngc @@ -0,0 +1,4 @@ @@ -1430,7 +1455,7 @@ index 0000000000..c8ee28f7ed +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 +index 0000000..488d2a9 --- /dev/null +++ b/tests/resumable-stop/g76-tapered-exit-taper.ngc @@ -0,0 +1,7 @@ @@ -1443,7 +1468,7 @@ index 0000000000..488d2a9300 +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 +index 0000000..241f777 --- /dev/null +++ b/tests/resumable-stop/g76-tapered-step.ngc @@ -0,0 +1,4 @@ @@ -1453,7 +1478,7 @@ index 0000000000..241f777682 +M2 diff --git a/tests/resumable-stop/g76-tapered.ngc b/tests/resumable-stop/g76-tapered.ngc new file mode 100644 -index 0000000000..b0eb997e19 +index 0000000..b0eb997 --- /dev/null +++ b/tests/resumable-stop/g76-tapered.ngc @@ -0,0 +1,7 @@ @@ -1465,7 +1490,7 @@ index 0000000000..b0eb997e19 +M5 +M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index d3c9646b11..463ec75590 100755 +index aa7c6a3..a4fb758 100755 --- a/tests/resumable-stop/test-ui.py +++ b/tests/resumable-stop/test-ui.py @@ -2,6 +2,7 @@ @@ -1476,7 +1501,7 @@ index d3c9646b11..463ec75590 100755 import sys import time -@@ -17,14 +18,30 @@ def fail(message): +@@ -17,14 +18,32 @@ def fail(message): sys.exit(1) @@ -1488,8 +1513,10 @@ index d3c9646b11..463ec75590 100755 if predicate(): return - time.sleep(0.02) -- fail(message) +- fail(message() if callable(message) else message) + 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 " @@ -1510,51 +1537,7 @@ index d3c9646b11..463ec75590 100755 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(): +@@ -447,6 +466,41 @@ def run_threading_stop_resume_test(): ) @@ -1596,7 +1579,7 @@ index d3c9646b11..463ec75590 100755 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(): +@@ -511,9 +565,9 @@ def run_g76_stop_resume_test(): if s.position[2] > -4.90: fail("G76 stopped before its active threading TC completed") @@ -1608,7 +1591,7 @@ index d3c9646b11..463ec75590 100755 % s.position[0] ) -@@ -495,6 +584,307 @@ def run_g76_stop_resume_test(): +@@ -532,6 +586,264 @@ def run_g76_stop_resume_test(): assert_outputs_stopped_after_program() @@ -1786,49 +1769,6 @@ index d3c9646b11..463ec75590 100755 + ) + + -+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) @@ -1916,14 +1856,7 @@ index d3c9646b11..463ec75590 100755 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), +@@ -1232,8 +1544,16 @@ SCENARIOS = { "abort-empty": run_abort_from_empty_stopped_queue_test, "queued-g33": run_queued_threading_stop_resume_test, "g33": run_threading_stop_resume_test, @@ -1934,7 +1867,6 @@ index d3c9646b11..463ec75590 100755 + "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, @@ -1942,7 +1874,7 @@ index d3c9646b11..463ec75590 100755 "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 +index a422788..96b5a38 100644 --- a/tests/resumable-stop/test.ini +++ b/tests/resumable-stop/test.ini @@ -29,6 +29,7 @@ SPINDLES = 2 @@ -1954,10 +1886,10 @@ index b73c0956b5..ef31f9a636 100644 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 +index 6c37e51..d7b218d 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 +@@ -7,6 +7,11 @@ if nm -D -u "$EMC2_HOME/rtlib/motmod.so" | grep -q '[[:space:]]tpStop$'; then exit 1 fi @@ -1969,11 +1901,7 @@ index 7a9a863436..20e0d14d78 100755 scenarios=( idle-rejected ordinary - single-step -+ inflight-single-step - rapid-no-atspeed - paused-resume - paused-run +@@ -17,8 +22,11 @@ scenarios=( abort-empty queued-g33 g33 @@ -1985,14 +1913,15 @@ index 7a9a863436..20e0d14d78 100755 rigid-tap orientation dwell - multi-spindle - css +@@ -33,6 +41,11 @@ scenarios=( + step-resume-stopping + g95-between-g33 + spindle-state + g76-single-step + g76-tapered-single-step -+ g76-inflight-single-step + g76-exit-taper + g76-tapered-exit-taper + g76-handoff-stress ) - scenario_log=$(mktemp) + # test.ini selects the jerk-limited planner. Repeat the scenarios whose diff --git a/linuxcnc-patches/pending-pre2/0010-rs274-add-recording-canon-preview-backend.patch b/linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch similarity index 98% rename from linuxcnc-patches/pending-pre2/0010-rs274-add-recording-canon-preview-backend.patch rename to linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch index 8651f32..69e2b02 100644 --- a/linuxcnc-patches/pending-pre2/0010-rs274-add-recording-canon-preview-backend.patch +++ b/linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch @@ -3,11 +3,21 @@ From: Dariusz Majnert Date: Sun, 23 Aug 2026 22:34:37 +0200 Subject: [PATCH] rs274: add recording canon preview backend +Ported to v2.10.0-pre2. The recording canon implements the canon +interface as it is here: SET_MOTION_CONTROL_MODE takes upstream's planner +arguments and STOP_SPINDLE_TURNING its wait argument, and HOME_CYCLE, +HOME_CYCLE_JOINT, LOCK_SPEED_OVERRIDE, SELECT_KINS_TYPE, +GET_EXTERNAL_AXIS_MAX_VELOCITY, GET_EXTERNAL_SPINDLE_MAX_VELOCITY, +GET_EXTERNAL_KINS_TYPE and GET_EXTERNAL_KINS_TYPE_FLAGS are added with +the same preview behaviour as the Axis module. +tool_mmap_user() keeps upstream's record of the mapping descriptor +(8c8e048) instead of closing it; the mutex and the early return for an +existing mapping remain. --- src/emc/rs274ngc/interp_convert.cc | 6 + - src/emc/rs274ngc/recordingcanon.cc | 626 +++++++++++++++++++ + src/emc/rs274ngc/recordingcanon.cc | 636 +++++++++++++++++++ src/emc/rs274ngc/recordingcanon.hh | 147 +++++ - src/emc/tooldata/tooldata_mmap.cc | 5 + + 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 + @@ -17,15 +27,15 @@ Subject: [PATCH] rs274: add recording canon preview backend 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(+) + 13 files changed, 943 insertions(+) create mode 100644 src/emc/rs274ngc/recordingcanon.cc create mode 100644 src/emc/rs274ngc/recordingcanon.hh diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 33a35bda2e..e0c95f83cb 100644 +index e894e64..462eb90 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 +43,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 +53,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; @@ -54,10 +64,10 @@ index 33a35bda2e..e0c95f83cb 100644 diff --git a/src/emc/rs274ngc/recordingcanon.cc b/src/emc/rs274ngc/recordingcanon.cc new file mode 100644 -index 0000000000..235da9b7ea +index 0000000..f64dbd7 --- /dev/null +++ b/src/emc/rs274ngc/recordingcanon.cc -@@ -0,0 +1,626 @@ +@@ -0,0 +1,636 @@ +#include "recordingcanon.hh" + +#include @@ -407,6 +417,9 @@ index 0000000000..235da9b7ea + 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) @@ -425,7 +438,8 @@ index 0000000000..235da9b7ea +void SET_FEED_REFERENCE(CANON_FEED_REFERENCE) {} +void SET_FEED_MODE(int, int) {} + -+void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode, double tolerance) ++void SET_MOTION_CONTROL_MODE(CANON_MOTION_MODE mode, double tolerance, ++ int, double) +{ + auto &state = recording::active(); + state.motion_mode = mode; @@ -479,7 +493,7 @@ index 0000000000..235da9b7ea + recording::active().spindle_speed[spindle] = speed; +} + -+void STOP_SPINDLE_TURNING(int spindle) ++void STOP_SPINDLE_TURNING(int spindle, int) +{ + if (recording::valid_spindle(spindle)) + recording::active().spindle_direction[spindle] = CANON_STOPPED; @@ -525,6 +539,7 @@ index 0000000000..235da9b7ea +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; } @@ -563,11 +578,15 @@ index 0000000000..235da9b7ea +} +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; } @@ -683,10 +702,11 @@ index 0000000000..235da9b7ea +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/src/emc/rs274ngc/recordingcanon.hh b/src/emc/rs274ngc/recordingcanon.hh new file mode 100644 -index 0000000000..dca1242649 +index 0000000..dca1242 --- /dev/null +++ b/src/emc/rs274ngc/recordingcanon.hh @@ -0,0 +1,147 @@ @@ -838,7 +858,7 @@ index 0000000000..dca1242649 + +#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 +869,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 +879,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 +916,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 +936,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 +956,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 +1070,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 +1090,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 +1814,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 +1834,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 +1929,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/pending-pre2/0011-motion-arm-single-step-during-active-execution.patch b/linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch similarity index 67% rename from linuxcnc-patches/pending-pre2/0011-motion-arm-single-step-during-active-execution.patch rename to linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch index 00e7cd1..1c6db6c 100644 --- a/linuxcnc-patches/pending-pre2/0011-motion-arm-single-step-during-active-execution.patch +++ b/linuxcnc-patches/0011-motion-arm-single-step-during-active-execution.patch @@ -6,23 +6,29 @@ 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/README | 6 ++ tests/resumable-stop/checkresult | 2 +- tests/resumable-stop/inflight-step.ngc | 7 +++ - 8 files changed, 125 insertions(+), 54 deletions(-) + tests/resumable-stop/test-ui.py | 80 ++++++++++++++++++++++++++ + tests/resumable-stop/test.sh | 2 + + 10 files changed, 205 insertions(+), 52 deletions(-) create mode 100644 tests/resumable-stop/inflight-step.ngc diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index b6ad9c1504..c166af652b 100644 +index dfceb2a..8dc79dd 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) +@@ -1381,26 +1381,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_STEP: @@ -60,10 +66,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 499824d..aafe3a5 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2225,14 +2225,15 @@ static void update_status(void) +@@ -2311,14 +2311,15 @@ static void update_status(void) if (emcmotStatus->stepping) { TP_STRUCT *tp = &emcmotInternal->coord_tp; @@ -84,10 +90,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 fe2a371..0b20d68 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 +@@ -501,6 +501,7 @@ static int programStartLine = 0; // which line to run program from int stepping = 0; int steppingWait = 0; static int steppedLine = 0; @@ -95,7 +101,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() +@@ -516,6 +517,7 @@ void emcTaskResetSteppingState() steppedLine = 0; currentPassGroup = 0; steppedPassGroup = 0; @@ -103,7 +109,7 @@ index beb6d565d6..e01ef50ce8 100644 } // Variables to handle MDI call interrupts -@@ -818,6 +820,22 @@ static void emcTaskStepInterpreter() +@@ -861,6 +863,22 @@ static void emcTaskStepInterpreter() emcStatus->task.task_paused = 1; } @@ -126,7 +132,7 @@ index beb6d565d6..e01ef50ce8 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1432,13 +1450,7 @@ static int emcTaskPlan(void) +@@ -1485,13 +1503,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -141,7 +147,7 @@ index beb6d565d6..e01ef50ce8 100644 break; // otherwise we can't handle it -@@ -1512,17 +1524,9 @@ static int emcTaskPlan(void) +@@ -1565,17 +1577,9 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -160,7 +166,7 @@ index beb6d565d6..e01ef50ce8 100644 break; // otherwise we can't handle it -@@ -1588,13 +1592,7 @@ static int emcTaskPlan(void) +@@ -1641,13 +1645,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -175,7 +181,7 @@ index beb6d565d6..e01ef50ce8 100644 break; // otherwise we can't handle it -@@ -3676,6 +3674,10 @@ int main(int argc, char *argv[]) +@@ -4022,6 +4020,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); @@ -187,22 +193,22 @@ index beb6d565d6..e01ef50ce8 100644 // 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/tp.c b/src/emc/tp/tp.c -index 00a06f1a75..81d50e10d3 100644 +index c690207..dac694f 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, +@@ -357,9 +357,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 +497,11 @@ int tpClear(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; @@ -215,7 +221,7 @@ index 00a06f1a75..81d50e10d3 100644 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 +230,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,11 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc } } if (queued_tc && queued_tc->g76_pass_clearance && @@ -238,7 +244,7 @@ index 00a06f1a75..81d50e10d3 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) { -@@ -3442,10 +3445,11 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, +@@ -3496,10 +3499,11 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, tp->stop_tc = 0; tp->stop_pass_id = 0; } @@ -251,7 +257,7 @@ index 00a06f1a75..81d50e10d3 100644 } //TODO make progress to match target? -@@ -4220,7 +4224,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4384,7 +4388,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -260,7 +266,7 @@ 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) +@@ -4573,6 +4577,30 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) return tc ? tc->g76_pass_id : 0; } @@ -291,7 +297,7 @@ index 00a06f1a75..81d50e10d3 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4382,10 +4410,12 @@ int tpPause(TP_STRUCT * const tp) +@@ -4580,10 +4608,12 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -303,9 +309,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 +@@ -4630,7 +4660,7 @@ int tpPause(TP_STRUCT * const tp) tp->pausing = 1; } } else if (emcmotStatus->stepping && @@ -314,7 +320,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) +@@ -4639,15 +4669,25 @@ int tpPause(TP_STRUCT * const tp) int pass_id = tpGetQueuedG76PassId(tp); if (pass_id) { tp->step_pass_id = pass_id; @@ -344,15 +350,15 @@ index 00a06f1a75..81d50e10d3 100644 } } else { tp->pausing = 1; -@@ -4448,6 +4488,7 @@ int tpResume(TP_STRUCT * const tp) +@@ -4660,6 +4700,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; +@@ -4669,7 +4710,10 @@ int tpResume(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; @@ -364,7 +370,7 @@ index 00a06f1a75..81d50e10d3 100644 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) +@@ -4689,7 +4733,11 @@ int tpAbort(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; @@ -378,10 +384,10 @@ index 00a06f1a75..81d50e10d3 100644 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..819f508 100644 --- a/src/emc/tp/tp_types.h +++ b/src/emc/tp/tp_types.h -@@ -147,7 +147,11 @@ typedef struct { +@@ -171,7 +171,11 @@ typedef struct { TC_STRUCT *step_tc; int step_target_pending; int step_pass_id; @@ -395,20 +401,13 @@ index 15be0f3127..893a9df4c2 100644 } TP_STRUCT; diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -index e845030ffb..72607e0da2 100644 +index 3a037f8..17c6a5b 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. +@@ -47,6 +47,12 @@ 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 @@ -419,18 +418,18 @@ index e845030ffb..72607e0da2 100644 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 +index efeaf20..631b3a4 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 +-test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 37 ++test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 39 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 +index 0000000..1f72544 --- /dev/null +++ b/tests/resumable-stop/inflight-step.ngc @@ -0,0 +1,7 @@ @@ -441,3 +440,135 @@ index 0000000000..1f72544983 +G1 X30 +G1 X40 +M2 +diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py +index a4fb758..a8aa2ef 100755 +--- a/tests/resumable-stop/test-ui.py ++++ b/tests/resumable-stop/test-ui.py +@@ -245,6 +245,42 @@ def run_stop_single_step_test(): + 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_rapid_resume_without_at_speed_test(): + hal.set_p("spindle.0.at-speed", "false") +@@ -759,6 +795,48 @@ def run_tapered_g76_single_step_test(): + "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) +@@ -1538,6 +1616,7 @@ 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), +@@ -1551,6 +1630,7 @@ SCENARIOS = { + "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, +diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh +index d7b218d..832cb0f 100755 +--- a/tests/resumable-stop/test.sh ++++ b/tests/resumable-stop/test.sh +@@ -16,6 +16,7 @@ scenarios=( + idle-rejected + ordinary + single-step ++ inflight-single-step + rapid-no-atspeed + paused-resume + paused-run +@@ -43,6 +44,7 @@ scenarios=( + spindle-state + g76-single-step + g76-tapered-single-step ++ g76-inflight-single-step + g76-exit-taper + g76-tapered-exit-taper + g76-handoff-stress diff --git a/linuxcnc-patches/pending-pre2/0012-emc-own-transactional-tool-CRUD-in-task.patch b/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch similarity index 75% rename from linuxcnc-patches/pending-pre2/0012-emc-own-transactional-tool-CRUD-in-task.patch rename to linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch index 73acffd..e6f6405 100644 --- a/linuxcnc-patches/pending-pre2/0012-emc-own-transactional-tool-CRUD-in-task.patch +++ b/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch @@ -3,26 +3,48 @@ 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.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.cc | 238 ++++++++++++++++-- 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.hh | 14 ++ + src/emc/tooldata/tooldata_common.cc | 237 ++++++++++------- + 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 + + tests/tooldb/db-line-length/skip | 3 + + 14 files changed, 659 insertions(+), 119 deletions(-) + create mode 100644 tests/tooldb/db-g10-offset/skip + create mode 100644 tests/tooldb/db-line-length/skip diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index da68282b6d..7663c33f7e 100644 +index ded71c3..ce4110e 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 +57,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 +68,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 +99,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 8e943ba..8a8f0d1 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 +110,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 +119,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); +@@ -444,6 +447,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 cf8bc14..b40c76d 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 { +@@ -1730,6 +1730,50 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { int orientation; }; @@ -162,10 +184,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 0b20d68..dc34e1a 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1129,7 +1129,18 @@ static int emcTaskPlan(void) +@@ -1182,7 +1182,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -185,7 +207,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) +@@ -1311,6 +1322,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -204,7 +226,7 @@ index e01ef50ce8..0be1c528c2 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO -@@ -1383,6 +1406,18 @@ static int emcTaskPlan(void) +@@ -1436,6 +1459,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -223,7 +245,7 @@ index e01ef50ce8..0be1c528c2 100644 // otherwise we can't handle it default: -@@ -1718,6 +1753,18 @@ static int emcTaskPlan(void) +@@ -1771,6 +1806,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -242,7 +264,7 @@ index e01ef50ce8..0be1c528c2 100644 // otherwise we can't handle it default: -@@ -1821,6 +1868,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1874,6 +1921,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) case EMC_TOOL_LOAD_TOOL_TABLE_TYPE: case EMC_TOOL_SET_OFFSET_TYPE: @@ -251,7 +273,7 @@ index e01ef50ce8..0be1c528c2 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2357,6 +2406,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2506,6 +2555,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emc_tool_set_offset_msg->orientation); break; @@ -266,7 +288,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) +@@ -2980,6 +3037,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: @@ -276,19 +298,27 @@ index e01ef50ce8..0be1c528c2 100644 case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index 2869ee6fb7..bbdff026a4 100644 +index 6ba96b9..27c32fe 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, +@@ -26,6 +26,7 @@ + + #include "pythonplugin/python_plugin.hh" + #include "taskclass.hh" ++#include + + using namespace linuxcnc; + +@@ -122,6 +123,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 +208,10 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : if (auto t = inifile.findString("TOOL_TABLE", "EMCIO")) tooltable_filename = strdup(t->c_str()); @@ -308,7 +338,7 @@ index 2869ee6fb7..bbdff026a4 100644 } } -@@ -168,14 +165,6 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : +@@ -226,14 +224,6 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : #endif //} tooldata_init(random_toolchanger); @@ -323,7 +353,7 @@ 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,7 +236,7 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : } } @@ -332,7 +362,7 @@ index 2869ee6fb7..bbdff026a4 100644 rcs_print_error("can't load tool table.\n"); } -@@ -351,6 +340,10 @@ void Task::reload_tool_number(int toolno) { +@@ -409,6 +399,10 @@ void Task::reload_tool_number(int toolno) { int Task::emcIoInit()//EMC_TOOL_INIT { @@ -343,7 +373,7 @@ index 2869ee6fb7..bbdff026a4 100644 tooldata_load(tooltable_filename); reload_tool_number(emcioStatus.tool.toolInSpindle); -@@ -519,10 +512,26 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE +@@ -581,10 +575,28 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE return 0; } @@ -357,10 +387,11 @@ index 2869ee6fb7..bbdff026a4 100644 { 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)) return -1; + CANON_TOOL_TABLE loaded[CANON_POCKETS_MAX]; + int loaded_last = 0; -+ if (tooldata_load_snapshot(file, loaded, &loaded_last) || ++ bool refused_lines = false; ++ if (tooldata_load_snapshot(file, loaded, &loaded_last, &refused_lines) || + !valid_table(loaded, loaded_last, random_toolchanger) || + (emcioStatus.tool.toolInSpindle > 0 && + find_tool(loaded, loaded_last, emcioStatus.tool.toolInSpindle, @@ -368,10 +399,23 @@ index 2869ee6fb7..bbdff026a4 100644 + return -1; + } + if (tooldata_replace(loaded, loaded_last)) return -1; ++ tooldata_set_refused_lines(refused_lines); reload_tool_number(emcioStatus.tool.toolInSpindle); return 0; } -@@ -577,6 +586,191 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -626,9 +638,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)) { +@@ -648,6 +661,191 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, return 0; } @@ -476,8 +520,8 @@ index 2869ee6fb7..bbdff026a4 100644 + } + 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; ++ (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 -1; + if (random_toolchanger) { + destination = update.pocket; @@ -543,8 +587,8 @@ index 2869ee6fb7..bbdff026a4 100644 + 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; ++ (hal_get_bool(iocontrol_data->tool_prepare) && idx == hal_get_si32(iocontrol_data->tool_prep_index)) || ++ hal_get_bool(iocontrol_data->tool_change)) return -1; + table[idx] = tooldata_entry_init(); + while (last > 0 && table[last].toolno < 0) --last; + if (tooldata_save_snapshot(tooltable_filename, table, last)) { @@ -564,10 +608,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 75572ea..0a065c5 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,8 +620,8 @@ index 5e32a1a65d..dced9adeea 100644 int iocontrol_hal_init(void); void reload_tool_number(int toolno); -@@ -88,8 +90,7 @@ public: - hal_comp iocontrol; +@@ -89,8 +91,7 @@ public: + int comp_id; const char *ini_filename; const char *tooltable_filename {}; - char db_program[LINELEN] {}; @@ -587,7 +631,7 @@ index 5e32a1a65d..dced9adeea 100644 }; diff --git a/src/emc/tooldata/tooldata.hh b/src/emc/tooldata/tooldata.hh -index b0f0a756ce..19c0592b15 100644 +index db3e6b7..226f4bf 100644 --- a/src/emc/tooldata/tooldata.hh +++ b/src/emc/tooldata/tooldata.hh @@ -58,6 +58,8 @@ void tooldata_reset(void); @@ -599,13 +643,19 @@ 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,20 @@ 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: saves are refused ++// until a table without them is loaded ++void tooldata_set_refused_lines(bool refused); int tooldata_save(const char *filename); +int tooldata_save_snapshot(const char *filename, @@ -615,22 +665,23 @@ 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..2dcf5e5 100644 --- a/src/emc/tooldata/tooldata_common.cc +++ b/src/emc/tooldata/tooldata_common.cc -@@ -23,6 +23,11 @@ - */ +@@ -24,7 +24,12 @@ + #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 +38,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 +707,7 @@ index 4e9651c86f..cbb7299eff 100644 void tooldata_init(bool random_toolchanger) { -@@ -211,7 +235,7 @@ int tooldata_read_entry(const char *input_line) +@@ -206,7 +230,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 +716,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 +257,7 @@ int tooldata_read_entry(const char *input_line) ); } } @@ -674,14 +725,27 @@ index 4e9651c86f..cbb7299eff 100644 UNEXPECTED_MSG; } } else { -@@ -312,27 +336,15 @@ void tooldata_format_toolline (int idx, - return; +@@ -323,31 +347,27 @@ 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 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) ++void tooldata_set_refused_lines(bool refused) ++{ ++ table_has_refused_lines = refused; ++} ++ +int tooldata_load_snapshot(const char *filename, + CANON_TOOL_TABLE *staged, -+ int *last_index) ++ int *last_index, ++ bool *refused_lines) { FILE *fp; char input_line[CANON_TOOL_ENTRY_LEN]; @@ -702,11 +766,12 @@ index 4e9651c86f..cbb7299eff 100644 - // 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) +@@ -356,16 +376,17 @@ int tooldata_load(const char *filename) return -1; } @@ -722,11 +787,23 @@ 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; + int load_failed = 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 -@@ -361,38 +374,62 @@ int tooldata_load(const char *filename) +@@ -383,7 +404,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 +412,66 @@ 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) { @@ -758,14 +835,14 @@ index 4e9651c86f..cbb7299eff 100644 // close the file - fclose(fp); -- + if (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; ++ return 0; +} // tooldata_load_snapshot() -+ + +int tooldata_load(const char *filename) +{ + if (db_mode == DB_ACTIVE) { //expect data loaded from db @@ -779,35 +856,37 @@ 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)) return -1; ++ tooldata_set_refused_lines(refused_lines); + 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) ++// Write idx's tool line from table, or from the table in memory if table ++// is NULL; -1 if it is too long to write or the write fails. +static int write_tool_line(FILE* fp, 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); +@@ -433,63 +483,82 @@ static int write_tool_line(std::string &table,int idx) + tdata,theline)) { + return -1; + } +- table += theline; + if (fprintf(fp,"%s",theline) < 0) return -1; } -- return; -+ return 0; + return 0; } // write_tool_line() -int tooldata_save(const char *filename) @@ -833,8 +912,35 @@ 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; +- } + if (!filename || !filename[0] || !table || last_index < 0 || + last_index >= CANON_POCKETS_MAX || db_mode == DB_ACTIVE) return -1; ++ 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;} +- } ++ // a tool whose line is too long fails the write, 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 temporary = std::string(filename) + ".tmp.XXXXXX"; + int fd = mkstemp(temporary.data()); + if (fd < 0) return -1; @@ -847,12 +953,6 @@ index 4e9651c86f..cbb7299eff 100644 + 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 (!result && fflush(fp)) result = -1; + if (!result && fsync(fd)) result = -1; + if (fclose(fp)) result = -1; @@ -865,31 +965,45 @@ index 4e9651c86f..cbb7299eff 100644 + 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() +- // 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 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); +- 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)); ++ // 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; + } - return 0; -} //tooldata_save() + CANON_TOOL_TABLE table[CANON_POCKETS_MAX]; @@ -898,7 +1012,7 @@ index 4e9651c86f..cbb7299eff 100644 + 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 +1023,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 +1042,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 +1050,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 +1059,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 +1086,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 +1110,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 +1129,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 +1161,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 +1186,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 +1195,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 +1216,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 +1230,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 +1254,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 +1279,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 +1296,21 @@ 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/tests/tooldb/db-line-length/skip b/tests/tooldb/db-line-length/skip +new file mode 100644 +index 0000000..730d8c3 +--- /dev/null ++++ b/tests/tooldb/db-line-length/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/pending-pre2/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch similarity index 78% rename from linuxcnc-patches/pending-pre2/0013-rs274ngc-add-composable-executor-stdglue.patch rename to linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index b305ad0..a5865eb 100644 --- a/linuxcnc-patches/pending-pre2/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -3,21 +3,35 @@ 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 + + docs/src/remap/remap.adoc | 129 +++++++++ + nc_files/remap_lib/python-stdglue/stdglue.py | 260 ++++++++++++++++++- + src/emc/rs274ngc/interp_internal.hh | 3 + + src/emc/rs274ngc/interp_python.cc | 60 ++++- + src/emc/rs274ngc/interp_python.hh | 7 + + src/emc/rs274ngc/rs274ngc_pre.cc | 5 + 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(-) + 12 files changed, 816 insertions(+), 3 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 @@ -26,10 +40,10 @@ Subject: [PATCH] rs274ngc: add composable executor stdglue create mode 100644 tests/remap/executor/toplevel.py diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index 218062048c..b263f1e959 100644 +index 75e2a09..410381a 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,135 @@ 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: @@ -120,7 +134,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 +146,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..f7d7d47 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 +193,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,261 @@ def build_hal(self): except Exception as e: print(e) @@ -196,6 +212,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 + + @@ -333,13 +352,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 +377,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 +455,72 @@ 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 +913,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 - - 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 diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh -index fed82a67d8..e7e3497d34 100644 +index 6f90dbe..ff5f379 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh -@@ -594,6 +594,7 @@ struct pycontext { +@@ -618,6 +618,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; }; diff --git a/src/emc/rs274ngc/interp_python.cc b/src/emc/rs274ngc/interp_python.cc -index f8217637fc..6d304503b8 100644 +index e3f8b60..34f6fbc 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,6 +212,7 @@ 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 +528,39 @@ 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) { +@@ -264,6 +284,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 +323,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,36 +575,52 @@ 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/rs274ngc_pre.cc b/src/emc/rs274ngc/rs274ngc_pre.cc -index a4ef597412..55b048cad7 100644 +index 2ea3ba1..dea5749 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,6 +1246,10 @@ 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.call_stack_id = 0; + _setup.defining_sub = 0; +@@ -1760,6 +1764,7 @@ int Interp::unwind_call(int status, const char *file, int line, const char *func 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 +index 0000000..7fda879 --- /dev/null +++ b/tests/remap/executor/checkresult @@ -0,0 +1,5 @@ @@ -556,7 +631,7 @@ index 0000000000..7fda8799ba +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 +index 0000000..0198feb --- /dev/null +++ b/tests/remap/executor/remap.py @@ -0,0 +1,52 @@ @@ -614,7 +689,7 @@ index 0000000000..0198feb3fc + 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 +index 0000000..fb9b77b --- /dev/null +++ b/tests/remap/executor/test-ui.py @@ -0,0 +1,177 @@ @@ -797,7 +872,7 @@ index 0000000000..fb9b77b2dc +sys.exit(0) diff --git a/tests/remap/executor/test.ini b/tests/remap/executor/test.ini new file mode 100644 -index 0000000000..c3ee45b9ca +index 0000000..c3ee45b --- /dev/null +++ b/tests/remap/executor/test.ini @@ -0,0 +1,95 @@ @@ -898,7 +973,7 @@ index 0000000000..c3ee45b9ca +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 +index 0000000..4d496c4 --- /dev/null +++ b/tests/remap/executor/test.sh @@ -0,0 +1,8 @@ @@ -912,7 +987,7 @@ index 0000000000..4d496c4c58 +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 +index 0000000..4be91ba --- /dev/null +++ b/tests/remap/executor/toplevel.py @@ -0,0 +1,18 @@ @@ -928,9 +1003,9 @@ index 0000000000..1b41cf6b50 + self.memory_executor = remap.MemoryExecutor() + + 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.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-patches/pending-pre2/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch b/linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch similarity index 92% rename from linuxcnc-patches/pending-pre2/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch rename to linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch index 0287894..1b61696 100644 --- a/linuxcnc-patches/pending-pre2/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch +++ b/linuxcnc-patches/0014-fix-spindle-publish-modal-CSS-maximum-in-status.patch @@ -25,10 +25,10 @@ Subject: [PATCH] fix(spindle): publish modal CSS maximum in status create mode 100644 tests/css-status/tool.tbl 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 +40,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 dc34e1a..ba88a24 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -918,7 +918,7 @@ static void emcTaskStopProgress() +@@ -970,7 +970,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 +53,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 533265a..4ea2592 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){ +@@ -2157,7 +2157,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 +66,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 8e91c88..f5cc454 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) { +@@ -1462,6 +1462,7 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { F2("override_enabled", spindle_override_enabled); F(speed); F(feedback); @@ -79,7 +79,7 @@ index bd747787e4..03437fbce2 100644 F(orient_state); diff --git a/tests/css-status/README b/tests/css-status/README new file mode 100644 -index 0000000000..66ad330dd7 +index 0000000..66ad330 --- /dev/null +++ b/tests/css-status/README @@ -0,0 +1,6 @@ @@ -91,7 +91,7 @@ index 0000000000..66ad330dd7 +`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 +index 0000000..56f319c --- /dev/null +++ b/tests/css-status/checkresult @@ -0,0 +1,4 @@ @@ -101,7 +101,7 @@ index 0000000000..56f319c1fe +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 +index 0000000..e244f00 --- /dev/null +++ b/tests/css-status/core_sim.hal @@ -0,0 +1,10 @@ @@ -117,7 +117,7 @@ index 0000000000..e244f001df +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 +index 0000000..2372f6c --- /dev/null +++ b/tests/css-status/test-ui.py @@ -0,0 +1,61 @@ @@ -184,7 +184,7 @@ index 0000000000..2372f6c89e +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 +index 0000000..61ccf6b --- /dev/null +++ b/tests/css-status/test.ini @@ -0,0 +1,55 @@ @@ -245,7 +245,7 @@ index 0000000000..61ccf6bc64 +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 +index 0000000..13436c1 --- /dev/null +++ b/tests/css-status/test.sh @@ -0,0 +1,4 @@ @@ -255,4 +255,4 @@ index 0000000000..13436c16b1 +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 +index 0000000..e69de29 diff --git a/linuxcnc-patches/pending-pre2/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch b/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch similarity index 93% rename from linuxcnc-patches/pending-pre2/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch rename to linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch index d1d7dd2..488f289 100644 --- a/linuxcnc-patches/pending-pre2/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch +++ b/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch @@ -27,7 +27,7 @@ Subject: [PATCH] rs274ngc: pass spindle selectors to remaps create mode 100644 tests/remap/dollar-argspec/toplevel.py diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index b263f1e959..5bb208e611 100644 +index 410381a..6027d2b 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 +70,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 +81,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 +97,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, @@ -108,14 +108,14 @@ index c33df5a316..b13bdc0a5e 100644 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 +index 0000000..3758b4f --- /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 +index 0000000..518d1fe --- /dev/null +++ b/tests/remap/dollar-argspec/expected @@ -0,0 +1,29 @@ @@ -150,7 +150,7 @@ index 0000000000..518d1fe2f7 + 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 +index 0000000..e5495df --- /dev/null +++ b/tests/remap/dollar-argspec/m501.ngc @@ -0,0 +1,9 @@ @@ -165,7 +165,7 @@ index 0000000000..e5495df885 +% diff --git a/tests/remap/dollar-argspec/m502.ngc b/tests/remap/dollar-argspec/m502.ngc new file mode 100644 -index 0000000000..600c9a95f4 +index 0000000..600c9a9 --- /dev/null +++ b/tests/remap/dollar-argspec/m502.ngc @@ -0,0 +1,5 @@ @@ -176,7 +176,7 @@ index 0000000000..600c9a95f4 +% diff --git a/tests/remap/dollar-argspec/remap.py b/tests/remap/dollar-argspec/remap.py new file mode 100644 -index 0000000000..95f0e7b8e9 +index 0000000..95f0e7b --- /dev/null +++ b/tests/remap/dollar-argspec/remap.py @@ -0,0 +1,10 @@ @@ -192,7 +192,7 @@ index 0000000000..95f0e7b8e9 + 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 +index 0000000..36abfcb --- /dev/null +++ b/tests/remap/dollar-argspec/test.ini @@ -0,0 +1,18 @@ @@ -216,7 +216,7 @@ index 0000000000..36abfcbc62 +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 +index 0000000..b475564 --- /dev/null +++ b/tests/remap/dollar-argspec/test.ngc @@ -0,0 +1,11 @@ @@ -233,7 +233,7 @@ index 0000000000..b47556494a +M2 diff --git a/tests/remap/dollar-argspec/test.sh b/tests/remap/dollar-argspec/test.sh new file mode 100755 -index 0000000000..7a389520fa +index 0000000..7a38952 --- /dev/null +++ b/tests/remap/dollar-argspec/test.sh @@ -0,0 +1,3 @@ @@ -242,7 +242,7 @@ index 0000000000..7a389520fa +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 +index 0000000..0dc38fa --- /dev/null +++ b/tests/remap/dollar-argspec/toplevel.py @@ -0,0 +1 @@ diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index d8db87b..1225343 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -354,6 +354,12 @@ 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. +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 — Recording canon backend for native G-code preview Adds `recordingcanon.cc` and `recordingcanon.hh`, a separate link-selected @@ -375,7 +381,8 @@ 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 +bringing the resumable-stop suite to 35 scenarios plus four trapezoidal re-runs +on v2.10.0-pre2. 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. @@ -393,7 +400,10 @@ 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. Tool-table reload now preserves the live table when opening, parsing, or validation fails. Read-only mmap clients detect inode replacement after a From 8603ba40ed193ee00c58bee79b79f06261392614 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 12 Nov 2026 14:30:38 +0100 Subject: [PATCH 12/45] feat(linuxcnc): port patches 0016-0023 to v2.10.0-pre2 Completes the port of the series. 0017's acquisition homing now runs through the G28.2 home cycle (task's queued joint home and homing wait) instead of its own homing wait; everything else in 0016-0018 stands. 0019 lets an independently homed joint finish upstream's bounded homing return on its own. 0020 uses the opaque HAL API in halui. 0021 and 0023 were ported earlier and replay unchanged. 0022 stays dropped. pending-pre2/ is empty and removed, together with the migration section of the README. Verified on the stack: clean -Werror build, 347/347 regression tests (5 skipped), tests/resumable-stop once more (39/39), headless build with a test subset. --- ...0016-motion-joint-target-preparation.patch | 28 +- ...ntime-joint-and-spindle-availability.patch | 973 +++++++++++------- .../0018-availability-mcodes.patch | 260 +++-- ...w-concurrent-individual-joint-homing.patch | 235 +++-- ...otion-add-native-lathe-power-jogging.patch | 198 ++-- ...-cross-compiling-external-components.patch | 45 +- ...pose-native-thread-period-statistics.patch | 607 +++++++++++ linuxcnc-patches/README.md | 29 +- ...pose-native-thread-period-statistics.patch | 510 --------- 9 files changed, 1642 insertions(+), 1243 deletions(-) rename linuxcnc-patches/{pending-pre2 => }/0016-motion-joint-target-preparation.patch (96%) rename linuxcnc-patches/{pending-pre2 => }/0017-runtime-joint-and-spindle-availability.patch (83%) rename linuxcnc-patches/{pending-pre2 => }/0018-availability-mcodes.patch (89%) rename linuxcnc-patches/{pending-pre2 => }/0019-motion-allow-concurrent-individual-joint-homing.patch (76%) rename linuxcnc-patches/{pending-pre2 => }/0020-feat-motion-add-native-lathe-power-jogging.patch (89%) rename linuxcnc-patches/{pending-pre2 => }/0021-hal-support-cross-compiling-external-components.patch (95%) create mode 100644 linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch delete mode 100644 linuxcnc-patches/pending-pre2/0023-hal-expose-native-thread-period-statistics.patch diff --git a/linuxcnc-patches/pending-pre2/0016-motion-joint-target-preparation.patch b/linuxcnc-patches/0016-motion-joint-target-preparation.patch similarity index 96% rename from linuxcnc-patches/pending-pre2/0016-motion-joint-target-preparation.patch rename to linuxcnc-patches/0016-motion-joint-target-preparation.patch index ca06d24..ee84e84 100644 --- a/linuxcnc-patches/pending-pre2/0016-motion-joint-target-preparation.patch +++ b/linuxcnc-patches/0016-motion-joint-target-preparation.patch @@ -20,10 +20,10 @@ Subject: [PATCH] motion-joint-target-preparation create mode 100755 tests/motion-target-preparation/test.sh 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 +38,10 @@ index 25b74309be..ba87f42442 100644 } diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 040e534653..8ed2cb3882 100644 +index aafe3a5..fad2241 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1178,9 +1178,83 @@ static void handle_jjogwheels(void) +@@ -1249,9 +1249,83 @@ static void handle_jjogwheels(void) first_pass = 0; } @@ -126,7 +126,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) +@@ -1436,40 +1510,21 @@ static void get_pos_cmds(long period) ext_offset_coord_limit = 0; } @@ -179,7 +179,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) +@@ -1517,39 +1572,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 +234,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 +252,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 +274,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" { @@ -288,17 +288,17 @@ index 26f1a64b48..c4b10cd20d 100644 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 +index 0000000..99955ca --- /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 +index 0000000..e69de29 diff --git a/tests/motion-target-preparation/test.py b/tests/motion-target-preparation/test.py new file mode 100644 -index 0000000000..1fa2553aa3 +index 0000000..1fa2553 --- /dev/null +++ b/tests/motion-target-preparation/test.py @@ -0,0 +1,90 @@ @@ -394,7 +394,7 @@ index 0000000000..1fa2553aa3 + 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 +index 0000000..0cd44bb --- /dev/null +++ b/tests/motion-target-preparation/test.sh @@ -0,0 +1,3 @@ diff --git a/linuxcnc-patches/pending-pre2/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch similarity index 83% rename from linuxcnc-patches/pending-pre2/0017-runtime-joint-and-spindle-availability.patch rename to linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index aa640cd..0eaa6e5 100644 --- a/linuxcnc-patches/pending-pre2/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -3,8 +3,35 @@ 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/ini-config.adoc | 33 ++ docs/src/config/python-interface.adoc | 26 + docs/src/man/man9/motion.9.adoc | 26 + src/emc/ini/inijoint.cc | 36 +- @@ -12,20 +39,21 @@ Subject: [PATCH] runtime-joint-and-spindle-availability 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 | 374 +++++++++++- + src/emc/motion/control.c | 550 ++++++++++++++++-- src/emc/motion/mot_priv.h | 21 + src/emc/motion/motion.c | 16 + - src/emc/motion/motion.h | 61 +- + src/emc/motion/motion.h | 60 +- src/emc/nml_intf/emc.cc | 29 + src/emc/nml_intf/emc.hh | 11 + 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 | 230 +++++++- src/emc/task/task.hh | 1 + src/emc/task/taskintf.cc | 94 ++- src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + + .../expected.motion-logger | 17 +- .../basic/expected.builtin-startup.in | 16 +- .../mountaindew/expected.motion-logger | 11 +- .../expected.motion-logger.in | 9 +- @@ -67,7 +95,7 @@ Subject: [PATCH] runtime-joint-and-spindle-availability 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(-) + 64 files changed, 2806 insertions(+), 83 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 @@ -106,10 +134,10 @@ Subject: [PATCH] runtime-joint-and-spindle-availability create mode 100644 tests/runtime-availability/tool.tbl 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 < #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 +318,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 +328,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 +352,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 +405,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 +431,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 +464,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 +475,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 8dc79dd..56264d2 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 +536,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 +549,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 +580,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 +596,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) +@@ -610,6 +691,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 +608,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) +@@ -644,6 +730,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_COORD: @@ -569,7 +619,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) +@@ -666,6 +756,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_TELEOP: @@ -580,7 +630,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) +@@ -740,10 +834,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 +649,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) +@@ -856,6 +957,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) SET_JOINT_ERROR_FLAG(joint, 1); break; } @@ -612,9 +662,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) +@@ -925,6 +1034,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) SET_JOINT_ERROR_FLAG(joint, 1); break; } @@ -627,9 +677,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) +@@ -1005,6 +1122,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) SET_JOINT_ERROR_FLAG(joint, 1); break; } @@ -642,9 +692,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) +@@ -1068,6 +1193,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_SET_SPINDLESYNC: @@ -662,7 +712,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) +@@ -1501,6 +1637,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 +720,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) +@@ -1513,10 +1650,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 +728,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 +738,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) +@@ -1533,6 +1676,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (joint == 0) { break; } @@ -702,7 +752,7 @@ index c166af652b..a18acd066f 100644 SET_JOINT_ACTIVE_FLAG(joint, 1); break; -@@ -1424,6 +1561,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1545,6 +1695,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (joint == 0) { break; } @@ -716,29 +766,35 @@ index c166af652b..a18acd066f 100644 SET_JOINT_ACTIVE_FLAG(joint, 0); break; -@@ -1435,6 +1579,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1556,6 +1713,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 +@@ -1588,6 +1753,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (!GET_MOTION_ENABLE_FLAG()) { break; } -- ++ 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); - break; -@@ -1468,6 +1618,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1604,6 +1775,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) return; } @@ -765,7 +821,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) +@@ -1622,6 +1813,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; @@ -858,14 +914,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 +968,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 +982,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) +@@ -1818,6 +2163,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -936,11 +992,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)) +@@ -1916,8 +2266,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -954,7 +1008,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) +@@ -1967,6 +2321,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -965,7 +1019,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) +@@ -1991,6 +2349,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -976,7 +1030,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) +@@ -2037,8 +2399,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -991,10 +1045,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 fad2241..8a544ee 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 +1058,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 +1075,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,22 @@ 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++) { @@ -1043,19 +1098,22 @@ index 8ed2cb3882..722c58545d 100644 + && do_homing() && !availability_homing && !homing_cleanup) { switch_to_teleop_mode(); } ++ finish_availability_homing(); -@@ -440,8 +453,29 @@ static void process_inputs(void) + /* 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. */ +@@ -510,8 +525,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 +1121,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 +1133,17 @@ index 8ed2cb3882..722c58545d 100644 continue; } /* copy data from HAL to joint structure */ -@@ -489,25 +523,7 @@ static void process_inputs(void) +@@ -559,25 +595,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 +1151,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 +1160,7 @@ index 8ed2cb3882..722c58545d 100644 } // a fault was signalled during a spindle-orient in progress -@@ -551,6 +567,394 @@ static void process_inputs(void) +@@ -621,6 +639,391 @@ static void process_inputs(void) } } @@ -1111,14 +1169,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 +1194,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 +1220,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 +1291,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,7 +1304,7 @@ 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); @@ -1270,31 +1326,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 +1365,16 @@ 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; + } else { + if (!validate_joint_position(n)) { + set_joint_availability_fault(n, EMCMOT_AVAILABILITY_FAULT_POSITION_MISMATCH); @@ -1327,26 +1390,18 @@ index 8ed2cb3882..722c58545d 100644 + case EMCMOT_AVAILABILITY_HOMING: + 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_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 +1464,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 +1514,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 +1541,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 +1552,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) +@@ -683,7 +1086,7 @@ static void do_forward_kins(void) at the traj rate */ double joint_pos[EMCMOT_MAX_JOINTS] = {0,}; @@ -1506,7 +1561,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) +@@ -865,7 +1268,9 @@ static void check_for_faults(void) } /* check for spindle ampfifier errors */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1517,7 +1572,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) +@@ -937,6 +1342,7 @@ static void set_operating_mode(void) /* check for disabling */ if (!emcmotInternal->enabling && GET_MOTION_ENABLE_FLAG()) { @@ -1525,7 +1580,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) +@@ -991,8 +1397,9 @@ static void set_operating_mode(void) } } SET_MOTION_ENABLE_FLAG(1); @@ -1537,7 +1592,7 @@ index 8ed2cb3882..722c58545d 100644 } /* check for entering teleop mode */ -@@ -950,7 +1358,7 @@ static void set_operating_mode(void) +@@ -1020,7 +1427,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 +1601,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) +@@ -1064,7 +1471,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 */ +@@ -1084,7 +1491,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 */ +@@ -1119,10 +1526,17 @@ static void handle_jjogwheels(void) /* point to joint data */ joint_data = &(emcmot_hal_data->joint[joint_num]); joint = &joints[joint_num]; @@ -1576,7 +1631,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 +1640,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); +@@ -1137,6 +1551,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 +1649,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, +@@ -1268,6 +1683,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 +1666,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) +@@ -1357,7 +1782,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 +1678,7 @@ index 8ed2cb3882..722c58545d 100644 /* if joint is not active, skip it */ continue; } -@@ -1430,8 +1859,7 @@ static void get_pos_cmds(long period) +@@ -1513,8 +1941,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1633,7 +1688,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) +@@ -1575,8 +2002,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1643,7 +1698,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) +@@ -1587,6 +2013,8 @@ static void get_pos_cmds(long period) &joint->vel_cmd, &joint->acc_cmd, &joint->jerk_cmd); } @@ -1652,7 +1707,7 @@ index 8ed2cb3882..722c58545d 100644 /* END OF OUTPUT KINS */ -@@ -1520,10 +1949,13 @@ static void get_pos_cmds(long period) +@@ -1603,10 +2031,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 +1722,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) +@@ -1994,8 +2425,6 @@ static void output_to_hal(void) double inch_mult; emcmot_joint_t *joint; joint_hal_t *joint_data; @@ -1675,8 +1730,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()); +@@ -2037,6 +2466,9 @@ static void output_to_hal(void) for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ double speed; @@ -1686,97 +1741,96 @@ 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) +@@ -2071,14 +2503,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.); +@@ -2139,6 +2579,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); +@@ -2181,7 +2628,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)); ++ availability->phase == AVAIL_PHASE_WAIT_SETTLED))); - *(joint_data->coarse_pos_cmd) = joint->coarse_pos; - *(joint_data->joint_vel_cmd) = joint->vel_cmd; + 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/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_bool_t spindle_is_oriented; /* in: orientation completed */ + hal_sint_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 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_bool_t amp_fault; /* RPI: amp fault input */ + hal_bool_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 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 +1843,36 @@ 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..51b58d1 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)); +@@ -927,6 +939,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 +1881,7 @@ index 7f81108901..87f1a06205 100644 } axis_init_all(); -@@ -936,6 +950,8 @@ static int init_comm_buffers(void) +@@ -946,6 +960,8 @@ static int init_comm_buffers(void) joint->min_ferror = 0.01; joint->max_ferror = 1.0; joint->backlash = 0.0; @@ -1837,12 +1891,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 019e6d1..05ee23d 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 +1905,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 +1916,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 +1924,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 +1954,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 +1968,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 +1977,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 +1985,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.. +@@ -560,6 +614,7 @@ Suggestion: Split this in to an Error and a Status flag register.. double home_search_vel; int home_sequence; double increment; @@ -1940,7 +1993,7 @@ index dfc990f853..fd934976e2 100644 } spindle_status_t; typedef struct { -@@ -763,6 +819,9 @@ typedef struct emcmot_internal_t { +@@ -786,6 +841,9 @@ typedef struct emcmot_internal_t { int enabling; /* starts up disabled */ int coordinating; /* starts up in free mode */ int teleoperating; /* starts up in free mode */ @@ -1951,10 +2004,10 @@ index dfc990f853..fd934976e2 100644 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 ce4110e..f70a5e0 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 +2017,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 +2027,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 +2036,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 +2045,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 +2059,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 +2069,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 +2086,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 8a8f0d1..f2679d9 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -74,6 +74,7 @@ struct PM_CARTESIAN; @@ -2044,7 +2097,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 +2105,7 @@ 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); +@@ -344,6 +346,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); extern int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints); @@ -2063,7 +2116,7 @@ index 0dca92c7e0..32ca6fbaa0 100644 extern int emcJointSetMaxJerk(int joint, double jerk); -@@ -451,6 +457,11 @@ extern int emcSpindleBrakeRelease(int spindle); +@@ -469,6 +475,11 @@ extern int emcSpindleBrakeRelease(int spindle); extern int emcSpindleBrakeEngage(int spindle); extern int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles); @@ -2076,10 +2129,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 b40c76d..c03bfc3 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 +2150,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 +2160,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 +2170,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 +@@ -2000,6 +2017,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 +2190,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 a6b2345..2e672de 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 +2205,7 @@ index 6d91ef1bd0..6215d7d68c 100644 { } -@@ -198,7 +201,10 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() +@@ -215,7 +218,10 @@ EMC_SPINDLE_STAT::EMC_SPINDLE_STAT() orient_fault(0), spindle_override_enabled(OFF), at_speed(OFF), @@ -2165,10 +2218,10 @@ index 6d91ef1bd0..6215d7d68c 100644 } diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index e0fe4e3616..ac4a55781b 100644 +index 90cc136..5a1e60e 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 +2230,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 ba88a24..01e2b62 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -169,6 +169,60 @@ volatile int done; +@@ -169,6 +169,61 @@ volatile int done; static int emctask_shutdown(void); extern void backtrace(int signo); int _task = 1; // control preview behaviour when remapping @@ -2193,6 +2246,7 @@ index 59021c7dcb..1314163557 100644 + bool available = false; + bool cancelled = false; + bool failed = false; ++ bool home_issued = false; +} availability_pending; + +void emcTaskCancelAvailability() @@ -2241,7 +2295,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 +@@ -180,8 +235,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 +2311,7 @@ index 59021c7dcb..1314163557 100644 } return 1; } -@@ -836,6 +895,13 @@ static bool emcTaskArmSingleStep() +@@ -879,6 +939,13 @@ static bool emcTaskArmSingleStep() return true; } @@ -2271,7 +2325,7 @@ index 59021c7dcb..1314163557 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1029,6 +1095,31 @@ static int emcTaskPlan(void) +@@ -1081,6 +1148,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2303,7 +2357,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) +@@ -1100,6 +1192,36 @@ static int emcTaskPlan(void) return 0; } @@ -2340,7 +2394,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) +@@ -1612,9 +1734,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2351,7 +2405,7 @@ index 59021c7dcb..1314163557 100644 break; // otherwise we can't handle it -@@ -1824,6 +1943,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1877,6 +1997,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 +2414,7 @@ index 59021c7dcb..1314163557 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -1993,6 +2114,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2112,6 +2234,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2385,8 +2439,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); +@@ -2479,6 +2619,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 +2466,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) +@@ -2936,7 +3096,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2420,12 +2474,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) +@@ -3051,6 +3218,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2437,7 +2493,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) +@@ -3133,6 +3305,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2450,12 +2506,29 @@ 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) +@@ -3251,11 +3429,49 @@ 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) { ++ // 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; @@ -2483,8 +2556,19 @@ index 59021c7dcb..1314163557 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } +@@ -3470,7 +3686,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 79dbeb6..223886e 100644 --- a/src/emc/task/task.hh +++ b/src/emc/task/task.hh @@ -34,6 +34,7 @@ int emcTaskInit(); @@ -2496,10 +2580,10 @@ 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 4ea2592..6dc8665 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) +@@ -1035,6 +1035,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 +2594,7 @@ index d88c727d52..ca5c4dc3a2 100644 // for // all -@@ -1015,6 +1019,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) +@@ -1060,6 +1064,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) return 0; } @@ -2544,7 +2628,7 @@ index d88c727d52..ca5c4dc3a2 100644 // EMC_TRAJ functions int emcTrajSetJoints(int joints) -@@ -1839,9 +1870,11 @@ int emcMotionInit() +@@ -1918,9 +1949,11 @@ int emcMotionInit() int emcMotionHalt() { @@ -2557,7 +2641,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 +1966,7 @@ int emcMotionHalt() r4 = emcPositionSave(); r5 = ini_hal_exit(); @@ -2566,7 +2650,7 @@ index d88c727d52..ca5c4dc3a2 100644 } int emcMotionAbort() -@@ -1864,6 +1897,8 @@ int emcMotionAbort() +@@ -1943,6 +1976,8 @@ int emcMotionAbort() int r3 = 0; int t; @@ -2575,7 +2659,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 +1985,6 @@ int emcMotionAbort() } } @@ -2584,7 +2668,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){ +@@ -2168,10 +2201,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 +2711,7 @@ 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) +@@ -2261,6 +2326,18 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) // FIXME-AJ: joints not axes for (joint = 0; joint < stat->traj.joints; joint++) { @@ -2646,7 +2730,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) +@@ -2270,6 +2347,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) break; } } @@ -2663,10 +2747,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 f5cc454..7733e39 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) { +@@ -1418,6 +1418,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 +2760,7 @@ index 03437fbce2..28ee76096f 100644 return res; } #undef F -@@ -1463,6 +1466,9 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { +@@ -1467,6 +1470,9 @@ static PyObject *Stat_spindle_one(pyStatChannel *s, int spindleno) { F(homed); F(orient_state); F(orient_fault); @@ -2686,7 +2770,7 @@ index 03437fbce2..28ee76096f 100644 return res; } #undef F -@@ -2021,6 +2027,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { +@@ -2063,6 +2069,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { return Py_None; } @@ -2707,7 +2791,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[] = { +@@ -2449,6 +2469,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 +2802,136 @@ 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" +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 +2939,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 +2947,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 +2955,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 +2963,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 +2971,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 +2979,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 +2987,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 +2995,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 +3003,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 +3012,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 +3025,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 +3033,7 @@ index d8bd807543..8ed60094c8 100644 SPINDLE_OFF # -@@ -207,6 +217,7 @@ ENABLE +@@ -209,6 +219,7 @@ ENABLE # COORD @@ -2832,16 +3041,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 +3058,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 +3066,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 +3074,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 +3083,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 +3096,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 +3117,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 +3135,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 +3143,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 +3151,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 +3160,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 +3168,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,16 +3176,17 @@ 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 +index 99955ca..7958c18 100644 --- a/tests/motion-target-preparation/README +++ b/tests/motion-target-preparation/README @@ -1 +1,5 @@ @@ -2987,7 +3198,7 @@ index 99955caa22..7958c18d67 100644 +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 +index 0000000..00099d2 --- /dev/null +++ b/tests/motion-target-preparation/availability-cases.h @@ -0,0 +1,21 @@ @@ -3014,7 +3225,7 @@ index 0000000000..00099d2dfa +} 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 +index 0000000..dd4b2be --- /dev/null +++ b/tests/motion-target-preparation/availability-fixture.h @@ -0,0 +1,5 @@ @@ -3024,7 +3235,7 @@ index 0000000000..dd4b2be8dd +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 +index 1fa2553..8ac9a80 100644 --- a/tests/motion-target-preparation/test.py +++ b/tests/motion-target-preparation/test.py @@ -88,3 +88,60 @@ with tempfile.TemporaryDirectory() as tmp: @@ -3090,7 +3301,7 @@ index 1fa2553aa3..8ac9a8043d 100644 + 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 +index 0000000..425d52b --- /dev/null +++ b/tests/runtime-availability-regressions/.gitignore @@ -0,0 +1,2 @@ @@ -3098,7 +3309,7 @@ index 0000000000..425d52b6e7 +!/base.ini diff --git a/tests/runtime-availability-regressions/README b/tests/runtime-availability-regressions/README new file mode 100644 -index 0000000000..e1bde102e6 +index 0000000..e1bde10 --- /dev/null +++ b/tests/runtime-availability-regressions/README @@ -0,0 +1,20 @@ @@ -3124,7 +3335,7 @@ index 0000000000..e1bde102e6 +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 +index 0000000..71f455a --- /dev/null +++ b/tests/runtime-availability-regressions/base.ini @@ -0,0 +1,94 @@ @@ -3224,7 +3435,7 @@ index 0000000000..71f455ae57 +AVAILABILITY_TIMEOUT = 5 diff --git a/tests/runtime-availability-regressions/checkresult b/tests/runtime-availability-regressions/checkresult new file mode 100755 -index 0000000000..153f94a5fc +index 0000000..153f94a --- /dev/null +++ b/tests/runtime-availability-regressions/checkresult @@ -0,0 +1,5 @@ @@ -3235,7 +3446,7 @@ index 0000000000..153f94a5fc +done diff --git a/tests/runtime-availability-regressions/core.hal b/tests/runtime-availability-regressions/core.hal new file mode 100644 -index 0000000000..7e0cffcfb7 +index 0000000..7e0cffc --- /dev/null +++ b/tests/runtime-availability-regressions/core.hal @@ -0,0 +1,17 @@ @@ -3258,7 +3469,7 @@ index 0000000000..7e0cffcfb7 +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 +index 0000000..b69d67a --- /dev/null +++ b/tests/runtime-availability-regressions/dwell.ngc @@ -0,0 +1,4 @@ @@ -3268,7 +3479,7 @@ index 0000000000..b69d67a192 +M2 diff --git a/tests/runtime-availability-regressions/extra.hal b/tests/runtime-availability-regressions/extra.hal new file mode 100644 -index 0000000000..36c2c7ee86 +index 0000000..36c2c7e --- /dev/null +++ b/tests/runtime-availability-regressions/extra.hal @@ -0,0 +1,17 @@ @@ -3291,7 +3502,7 @@ index 0000000000..36c2c7ee86 +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 +index 0000000..5048be9 --- /dev/null +++ b/tests/runtime-availability-regressions/extra.ini.in @@ -0,0 +1,16 @@ @@ -3313,7 +3524,7 @@ index 0000000000..5048be901a +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 +index 0000000..b39d68b --- /dev/null +++ b/tests/runtime-availability-regressions/fault.ini.in @@ -0,0 +1,13 @@ @@ -3332,7 +3543,7 @@ index 0000000000..b39d68b962 +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 +index 0000000..ef0f630 --- /dev/null +++ b/tests/runtime-availability-regressions/fixture.py @@ -0,0 +1,75 @@ @@ -3413,7 +3624,7 @@ index 0000000000..ef0f630d93 +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 +index 0000000..949adc1 --- /dev/null +++ b/tests/runtime-availability-regressions/joghome.ini.in @@ -0,0 +1,6 @@ @@ -3425,7 +3636,7 @@ index 0000000000..949adc122d +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 +index 0000000..5ca302f --- /dev/null +++ b/tests/runtime-availability-regressions/record_abort.ngc @@ -0,0 +1,6 @@ @@ -3437,7 +3648,7 @@ index 0000000000..5ca302ff7f +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 +index 0000000..3786b15 --- /dev/null +++ b/tests/runtime-availability-regressions/sequence.ini.in @@ -0,0 +1,6 @@ @@ -3449,7 +3660,7 @@ index 0000000000..3786b1533f +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 +index 0000000..c9eea9d --- /dev/null +++ b/tests/runtime-availability-regressions/tail.hal @@ -0,0 +1,30 @@ @@ -3485,7 +3696,7 @@ index 0000000000..c9eea9dd0c +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 +index 0000000..cdf6f94 --- /dev/null +++ b/tests/runtime-availability-regressions/tail.ini.in @@ -0,0 +1,7 @@ @@ -3498,7 +3709,7 @@ index 0000000000..cdf6f940c4 +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 +index 0000000..468b03b --- /dev/null +++ b/tests/runtime-availability-regressions/test-ui.py @@ -0,0 +1,192 @@ @@ -3696,7 +3907,7 @@ index 0000000000..468b03b6f2 +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 +index 0000000..67dab70 --- /dev/null +++ b/tests/runtime-availability-regressions/test.ini.in @@ -0,0 +1,3 @@ @@ -3705,7 +3916,7 @@ index 0000000000..67dab70a3d +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 +index 0000000..e2dc178 --- /dev/null +++ b/tests/runtime-availability-regressions/test.sh @@ -0,0 +1,34 @@ @@ -3745,14 +3956,14 @@ index 0000000000..e2dc178445 +done diff --git a/tests/runtime-availability-regressions/tool.tbl b/tests/runtime-availability-regressions/tool.tbl new file mode 100644 -index 0000000000..a5800196af +index 0000000..a580019 --- /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 +index 0000000..5c7ef3f --- /dev/null +++ b/tests/runtime-availability-regressions/xzc.hal @@ -0,0 +1,12 @@ @@ -3770,7 +3981,7 @@ index 0000000000..5c7ef3f3f2 +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 +index 0000000..ada9398 --- /dev/null +++ b/tests/runtime-availability-regressions/xzc.ini.in @@ -0,0 +1,17 @@ @@ -3793,7 +4004,7 @@ index 0000000000..ada9398601 +MAX_LIMIT = 360 diff --git a/tests/runtime-availability/.gitignore b/tests/runtime-availability/.gitignore new file mode 100644 -index 0000000000..425d52b6e7 +index 0000000..425d52b --- /dev/null +++ b/tests/runtime-availability/.gitignore @@ -0,0 +1,2 @@ @@ -3801,7 +4012,7 @@ index 0000000000..425d52b6e7 +!/base.ini diff --git a/tests/runtime-availability/README b/tests/runtime-availability/README new file mode 100644 -index 0000000000..bdfd8cc4e3 +index 0000000..bdfd8cc --- /dev/null +++ b/tests/runtime-availability/README @@ -0,0 +1,8 @@ @@ -3815,7 +4026,7 @@ index 0000000000..bdfd8cc4e3 +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 +index 0000000..c8e0eab --- /dev/null +++ b/tests/runtime-availability/base.ini @@ -0,0 +1,99 @@ @@ -3920,7 +4131,7 @@ index 0000000000..c8e0eab3d2 +AVAILABILITY_TIMEOUT = 2 diff --git a/tests/runtime-availability/checkresult b/tests/runtime-availability/checkresult new file mode 100755 -index 0000000000..12624ae5b8 +index 0000000..12624ae --- /dev/null +++ b/tests/runtime-availability/checkresult @@ -0,0 +1,4 @@ @@ -3930,7 +4141,7 @@ index 0000000000..12624ae5b8 +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 +index 0000000..62edf53 --- /dev/null +++ b/tests/runtime-availability/core_sim.hal @@ -0,0 +1,17 @@ @@ -3953,7 +4164,7 @@ index 0000000000..62edf534b6 +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 +index 0000000..1c30ffa --- /dev/null +++ b/tests/runtime-availability/initial-ui.py @@ -0,0 +1,58 @@ @@ -4017,7 +4228,7 @@ index 0000000000..1c30ffabdd +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 +index 0000000..3b9c37c --- /dev/null +++ b/tests/runtime-availability/initial.ini.in @@ -0,0 +1,9 @@ @@ -4032,7 +4243,7 @@ index 0000000000..3b9c37cc3b +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 +index 0000000..3e7e61f --- /dev/null +++ b/tests/runtime-availability/make-fixtures.py @@ -0,0 +1,34 @@ @@ -4072,7 +4283,7 @@ index 0000000000..3e7e61f92e + ini.write(stream) diff --git a/tests/runtime-availability/paused.ngc b/tests/runtime-availability/paused.ngc new file mode 100644 -index 0000000000..c9e6f8a64f +index 0000000..c9e6f8a --- /dev/null +++ b/tests/runtime-availability/paused.ngc @@ -0,0 +1,3 @@ @@ -4081,7 +4292,7 @@ index 0000000000..c9e6f8a64f +M2 diff --git a/tests/runtime-availability/test-ui.py b/tests/runtime-availability/test-ui.py new file mode 100755 -index 0000000000..1f435daf96 +index 0000000..1f435da --- /dev/null +++ b/tests/runtime-availability/test-ui.py @@ -0,0 +1,297 @@ @@ -4384,7 +4595,7 @@ index 0000000000..1f435daf96 +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 +index 0000000..67dab70 --- /dev/null +++ b/tests/runtime-availability/test.ini.in @@ -0,0 +1,3 @@ @@ -4393,7 +4604,7 @@ index 0000000000..67dab70a3d +BASE = base.ini diff --git a/tests/runtime-availability/test.sh b/tests/runtime-availability/test.sh new file mode 100755 -index 0000000000..9a17bf2443 +index 0000000..9a17bf2 --- /dev/null +++ b/tests/runtime-availability/test.sh @@ -0,0 +1,5 @@ @@ -4404,4 +4615,4 @@ index 0000000000..9a17bf2443 +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 +index 0000000..e69de29 diff --git a/linuxcnc-patches/pending-pre2/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch similarity index 89% rename from linuxcnc-patches/pending-pre2/0018-availability-mcodes.patch rename to linuxcnc-patches/0018-availability-mcodes.patch index 7e8da6e..83d6945 100644 --- a/linuxcnc-patches/pending-pre2/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -3,8 +3,13 @@ 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/gcode/m-code.adoc | 40 ++++ docs/src/remap/remap.adoc | 7 +- src/emc/nml_intf/canon.hh | 2 + src/emc/rs274ngc/gcodemodule.cc | 2 + @@ -18,22 +23,22 @@ Subject: [PATCH] availability-mcodes 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 +++ + src/emc/task/emccanon.cc | 18 ++ .../.gitignore | 2 + - tests/availability-mcodes-regressions/README | 9 ++ + tests/availability-mcodes-regressions/README | 9 + .../checkresult | 5 + .../availability-mcodes-regressions/step.ngc | 6 + - .../test-ui.py | 74 +++++++++ - .../test.ini.in | 9 ++ + .../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/README | 10 + 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-ui.py | 171 ++++++++++++++++++ tests/availability-mcodes/test.ini | 1 + tests/availability-mcodes/test.sh | 5 + tests/availability-mcodes/timeout.ngc | 4 + @@ -42,8 +47,8 @@ Subject: [PATCH] availability-mcodes 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 ++++ + .../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 + @@ -66,10 +71,10 @@ Subject: [PATCH] availability-mcodes 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 ++++++++++ + 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(-) + 65 files changed, 664 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 @@ -122,10 +127,10 @@ Subject: [PATCH] availability-mcodes create mode 100644 tests/interp/availability-mcodes/valid-spindle.ngc diff --git a/docs/src/gcode/m-code.adoc b/docs/src/gcode/m-code.adoc -index 1cb15521ad..0f3b65c8e4 100644 +index e74ef24..b3cdbd0 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 +138,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,45 @@ 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. @@ -180,10 +185,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 6027d2b..e796ebb 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: +@@ -1930,6 +1930,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 +196,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 +@@ -2119,7 +2120,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 +205,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 +@@ -2128,6 +2129,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 +217,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 +256,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 50781c6..7981131 100644 --- a/src/emc/rs274ngc/interp_check.cc +++ b/src/emc/rs274ngc/interp_check.cc @@ -17,6 +17,7 @@ @@ -262,7 +267,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 +287,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 +299,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,17 +309,18 @@ 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 462eb90..fddac65 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)){ +@@ -4443,6 +4443,17 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ } } @@ -333,11 +339,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,7 +354,7 @@ 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 4ec4f7a..41e032d 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 @@ -360,10 +366,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 ff5f379..d642007 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh -@@ -454,12 +454,19 @@ struct block_struct +@@ -478,12 +478,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 +390,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 6e58d16..22eb924 100644 --- a/src/emc/rs274ngc/interp_read.cc +++ b/src/emc/rs274ngc/interp_read.cc @@ -20,6 +20,7 @@ @@ -394,8 +400,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 +414,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 +@@ -871,7 +876,9 @@ int Interp::read_items(block_pointer block, //!< pointer to a block being f } for (; counter < length;) { @@ -419,10 +425,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 || @@ -432,10 +438,10 @@ index b13bdc0a5e..a944478d8d 100644 m_code == 61 || m_code == 62 || diff --git a/src/emc/rs274ngc/recordingcanon.cc b/src/emc/rs274ngc/recordingcanon.cc -index 235da9b7ea..9593f45c44 100644 +index f64dbd7..61735a9 100644 --- a/src/emc/rs274ngc/recordingcanon.cc +++ b/src/emc/rs274ngc/recordingcanon.cc -@@ -425,6 +425,9 @@ void STOP_SPINDLE_TURNING(int spindle) +@@ -429,6 +429,9 @@ void STOP_SPINDLE_TURNING(int spindle, int) recording::active().spindle_direction[spindle] = CANON_STOPPED; } @@ -446,10 +452,10 @@ index 235da9b7ea..9593f45c44 100644 { 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 +468,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; } @@ -492,7 +498,7 @@ index 9f36a8de8e..f61e55bcfa 100644 /*! \todo FIXME-- unimplemented */ diff --git a/tests/availability-mcodes-regressions/.gitignore b/tests/availability-mcodes-regressions/.gitignore new file mode 100644 -index 0000000000..425d52b6e7 +index 0000000..425d52b --- /dev/null +++ b/tests/availability-mcodes-regressions/.gitignore @@ -0,0 +1,2 @@ @@ -500,7 +506,7 @@ index 0000000000..425d52b6e7 +!/base.ini diff --git a/tests/availability-mcodes-regressions/README b/tests/availability-mcodes-regressions/README new file mode 100644 -index 0000000000..3be13a3d4a +index 0000000..3be13a3 --- /dev/null +++ b/tests/availability-mcodes-regressions/README @@ -0,0 +1,9 @@ @@ -515,7 +521,7 @@ index 0000000000..3be13a3d4a +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 +index 0000000..14417ee --- /dev/null +++ b/tests/availability-mcodes-regressions/checkresult @@ -0,0 +1,5 @@ @@ -526,7 +532,7 @@ index 0000000000..14417ee80d +done diff --git a/tests/availability-mcodes-regressions/step.ngc b/tests/availability-mcodes-regressions/step.ngc new file mode 100644 -index 0000000000..a9bcd9e28d +index 0000000..a9bcd9e --- /dev/null +++ b/tests/availability-mcodes-regressions/step.ngc @@ -0,0 +1,6 @@ @@ -538,7 +544,7 @@ index 0000000000..a9bcd9e28d +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 +index 0000000..1cf2f53 --- /dev/null +++ b/tests/availability-mcodes-regressions/test-ui.py @@ -0,0 +1,74 @@ @@ -618,7 +624,7 @@ index 0000000000..1cf2f53b74 +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 +index 0000000..bcbcb6c --- /dev/null +++ b/tests/availability-mcodes-regressions/test.ini.in @@ -0,0 +1,9 @@ @@ -633,7 +639,7 @@ index 0000000000..bcbcb6c01d +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 +index 0000000..5ed42c8 --- /dev/null +++ b/tests/availability-mcodes-regressions/test.sh @@ -0,0 +1,6 @@ @@ -645,7 +651,7 @@ index 0000000000..5ed42c86b5 +done diff --git a/tests/availability-mcodes/.gitignore b/tests/availability-mcodes/.gitignore new file mode 100644 -index 0000000000..425d52b6e7 +index 0000000..425d52b --- /dev/null +++ b/tests/availability-mcodes/.gitignore @@ -0,0 +1,2 @@ @@ -653,14 +659,15 @@ index 0000000000..425d52b6e7 +!/base.ini diff --git a/tests/availability-mcodes/README b/tests/availability-mcodes/README new file mode 100644 -index 0000000000..a8a62f3415 +index 0000000..1f02b91 --- /dev/null +++ b/tests/availability-mcodes/README -@@ -0,0 +1,9 @@ +@@ -0,0 +1,10 @@ +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. + +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 @@ -668,7 +675,7 @@ index 0000000000..a8a62f3415 +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 +index 0000000..1e0aa79 --- /dev/null +++ b/tests/availability-mcodes/checkresult @@ -0,0 +1,4 @@ @@ -678,7 +685,7 @@ index 0000000000..1e0aa79240 +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 +index 0000000..563a89b --- /dev/null +++ b/tests/availability-mcodes/core_sim.hal @@ -0,0 +1 @@ @@ -686,7 +693,7 @@ index 0000000000..563a89b098 \ 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 +index 0000000..ca47f56 --- /dev/null +++ b/tests/availability-mcodes/homing.ngc @@ -0,0 +1,4 @@ @@ -696,7 +703,7 @@ index 0000000000..ca47f56f70 +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 +index 0000000..12b5b7a --- /dev/null +++ b/tests/availability-mcodes/no-force.ini.in @@ -0,0 +1,6 @@ @@ -708,7 +715,7 @@ index 0000000000..12b5b7a829 +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 +index 0000000..a180055 --- /dev/null +++ b/tests/availability-mcodes/ordered.ngc @@ -0,0 +1,6 @@ @@ -720,10 +727,10 @@ index 0000000000..a18005598f +M2 diff --git a/tests/availability-mcodes/test-ui.py b/tests/availability-mcodes/test-ui.py new file mode 100755 -index 0000000000..6b827943b9 +index 0000000..801530b --- /dev/null +++ b/tests/availability-mcodes/test-ui.py -@@ -0,0 +1,142 @@ +@@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +import os +import time @@ -824,14 +831,16 @@ index 0000000000..6b827943b9 +wait(lambda: not hal.get_value('joint.1.availability-request'), 'MDI M55') +pin('joint.1.availability-ack', 0); done() +c.mode(linuxcnc.MODE_AUTO); done() -+# Abort must terminate AUTO at the barrier, both before ACK and during homing. -+for during_home in (False, True): ++# Abort must terminate AUTO at the barrier, both before ACK and during homing; ++# Machine Off cancels acquisition homing the same way. ++for during_home, cancel in ((False, c.abort), (True, c.abort), ++ (True, lambda: c.state(linuxcnc.STATE_OFF))): + run('homing.ngc') + wait(lambda: hal.get_value('joint.2.availability-request'), 'abort AUTO request') + if during_home: + pin('joint.2.availability-ack', 1) + wait(lambda: abs(hal.get_value('joint.2.vel-cmd')) > .1, 'AUTO homing motion') -+ c.abort() ++ cancel() + wait(lambda: not hal.get_value('joint.2.availability-request'), 'AUTO abort output') + pin('joint.2.availability-ack', 0) + done(); idle() @@ -862,13 +871,40 @@ index 0000000000..6b827943b9 + 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 +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 +index 0000000..800b1b7 --- /dev/null +++ b/tests/availability-mcodes/test.ini @@ -0,0 +1 @@ @@ -876,7 +912,7 @@ index 0000000000..800b1b7d98 \ 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 +index 0000000..882b151 --- /dev/null +++ b/tests/availability-mcodes/test.sh @@ -0,0 +1,5 @@ @@ -887,7 +923,7 @@ index 0000000000..882b151895 +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 +index 0000000..8a28c6f --- /dev/null +++ b/tests/availability-mcodes/timeout.ngc @@ -0,0 +1,4 @@ @@ -897,7 +933,7 @@ index 0000000000..8a28c6f402 +M2 diff --git a/tests/availability-mcodes/tool.tbl b/tests/availability-mcodes/tool.tbl new file mode 120000 -index 0000000000..37d2571593 +index 0000000..37d2571 --- /dev/null +++ b/tests/availability-mcodes/tool.tbl @@ -0,0 +1 @@ @@ -905,7 +941,7 @@ index 0000000000..37d2571593 \ 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 +index 0000000..e572890 --- /dev/null +++ b/tests/availability-mcodes/unhomed.ngc @@ -0,0 +1,4 @@ @@ -915,7 +951,7 @@ index 0000000000..e5728900ed +M2 diff --git a/tests/interp/availability-mcodes/README b/tests/interp/availability-mcodes/README new file mode 100644 -index 0000000000..6054ffdd70 +index 0000000..6054ffd --- /dev/null +++ b/tests/interp/availability-mcodes/README @@ -0,0 +1,6 @@ @@ -927,7 +963,7 @@ index 0000000000..6054ffdd70 +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 +index 0000000..da0115c --- /dev/null +++ b/tests/interp/availability-mcodes/bad-joint.ngc @@ -0,0 +1,2 @@ @@ -935,7 +971,7 @@ index 0000000000..da0115cfed +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 +index 0000000..a851ea0 --- /dev/null +++ b/tests/interp/availability-mcodes/double-selector.ngc @@ -0,0 +1,2 @@ @@ -943,7 +979,7 @@ index 0000000000..a851ea0278 +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 +index 0000000..554485e --- /dev/null +++ b/tests/interp/availability-mcodes/execute-status.cc @@ -0,0 +1,26 @@ @@ -975,7 +1011,7 @@ index 0000000000..554485e05a +} 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 +index 0000000..145e482 --- /dev/null +++ b/tests/interp/availability-mcodes/execute-status.py @@ -0,0 +1,30 @@ @@ -1011,10 +1047,10 @@ index 0000000000..145e48201c + 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 +index 0000000..e69de29 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 +index 0000000..e5488fb --- /dev/null +++ b/tests/interp/availability-mcodes/fractional-joint.ngc @@ -0,0 +1,2 @@ @@ -1022,7 +1058,7 @@ index 0000000000..e5488fbd9a +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 +index 0000000..26ff05c --- /dev/null +++ b/tests/interp/availability-mcodes/fractional-spindle.ngc @@ -0,0 +1,2 @@ @@ -1030,7 +1066,7 @@ index 0000000000..26ff05c8a0 +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 +index 0000000..3b2f3fb --- /dev/null +++ b/tests/interp/availability-mcodes/group-spindle.ngc @@ -0,0 +1,2 @@ @@ -1038,7 +1074,7 @@ index 0000000000..3b2f3fbbe7 +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 +index 0000000..584fa3b --- /dev/null +++ b/tests/interp/availability-mcodes/huge-spindle.ngc @@ -0,0 +1,2 @@ @@ -1046,7 +1082,7 @@ index 0000000000..584fa3b719 +M2 diff --git a/tests/interp/availability-mcodes/legacy54.ngc b/tests/interp/availability-mcodes/legacy54.ngc new file mode 100644 -index 0000000000..6947d8a6fb +index 0000000..6947d8a --- /dev/null +++ b/tests/interp/availability-mcodes/legacy54.ngc @@ -0,0 +1,5 @@ @@ -1057,7 +1093,7 @@ index 0000000000..6947d8a6fb +M2 diff --git a/tests/interp/availability-mcodes/legacy55.ngc b/tests/interp/availability-mcodes/legacy55.ngc new file mode 100644 -index 0000000000..c48d1b9de1 +index 0000000..c48d1b9 --- /dev/null +++ b/tests/interp/availability-mcodes/legacy55.ngc @@ -0,0 +1,5 @@ @@ -1068,7 +1104,7 @@ index 0000000000..c48d1b9de1 +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 +index 0000000..96cb26c --- /dev/null +++ b/tests/interp/availability-mcodes/missing-selector.ngc @@ -0,0 +1,2 @@ @@ -1076,7 +1112,7 @@ index 0000000000..96cb26cf60 +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 +index 0000000..1a45e38 --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-feed.ngc @@ -0,0 +1,2 @@ @@ -1084,7 +1120,7 @@ index 0000000000..1a45e38e18 +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 +index 0000000..dd567c4 --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-modal.ngc @@ -0,0 +1,2 @@ @@ -1092,7 +1128,7 @@ index 0000000000..dd567c47f0 +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 +index 0000000..a52d2d4 --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-motion.ngc @@ -0,0 +1,2 @@ @@ -1100,7 +1136,7 @@ index 0000000000..a52d2d4fd1 +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 +index 0000000..1054e7e --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-parameter.ngc @@ -0,0 +1,2 @@ @@ -1108,7 +1144,7 @@ index 0000000000..1054e7e0aa +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 +index 0000000..1d22b22 --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-polar.ngc @@ -0,0 +1,2 @@ @@ -1116,7 +1152,7 @@ index 0000000000..1d22b22856 +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 +index 0000000..1cf09ae --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-speed.ngc @@ -0,0 +1,2 @@ @@ -1124,7 +1160,7 @@ index 0000000000..1cf09ae478 +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 +index 0000000..8fd4be9 --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-stop.ngc @@ -0,0 +1,2 @@ @@ -1132,7 +1168,7 @@ index 0000000000..8fd4be9598 +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 +index 0000000..6fc9e05 --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-tool.ngc @@ -0,0 +1,2 @@ @@ -1140,7 +1176,7 @@ index 0000000000..6fc9e05d67 +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 +index 0000000..37e7a2e --- /dev/null +++ b/tests/interp/availability-mcodes/mixed-word.ngc @@ -0,0 +1,2 @@ @@ -1148,7 +1184,7 @@ index 0000000000..37e7a2e4cb +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 +index 0000000..5153e91 --- /dev/null +++ b/tests/interp/availability-mcodes/negative-fractional-spindle.ngc @@ -0,0 +1,2 @@ @@ -1156,7 +1192,7 @@ index 0000000000..5153e911bc +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 +index 0000000..dea8ef7 --- /dev/null +++ b/tests/interp/availability-mcodes/negative-joint.ngc @@ -0,0 +1,2 @@ @@ -1164,7 +1200,7 @@ index 0000000000..dea8ef76e6 +M2 diff --git a/tests/interp/availability-mcodes/remap.ini b/tests/interp/availability-mcodes/remap.ini new file mode 100644 -index 0000000000..3a6b2030f2 +index 0000000..3a6b203 --- /dev/null +++ b/tests/interp/availability-mcodes/remap.ini @@ -0,0 +1,5 @@ @@ -1175,7 +1211,7 @@ index 0000000000..3a6b2030f2 +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 +index 0000000..2412206 --- /dev/null +++ b/tests/interp/availability-mcodes/remapped.ngc @@ -0,0 +1,3 @@ @@ -1184,7 +1220,7 @@ index 0000000000..2412206345 +M2 diff --git a/tests/interp/availability-mcodes/test.ini b/tests/interp/availability-mcodes/test.ini new file mode 100644 -index 0000000000..03afbfaa99 +index 0000000..03afbfa --- /dev/null +++ b/tests/interp/availability-mcodes/test.ini @@ -0,0 +1,2 @@ @@ -1192,7 +1228,7 @@ index 0000000000..03afbfaa99 +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 +index 0000000..c61548a --- /dev/null +++ b/tests/interp/availability-mcodes/test.sh @@ -0,0 +1,80 @@ @@ -1278,7 +1314,7 @@ index 0000000000..c61548a3fd +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 +index 0000000..d697df4 --- /dev/null +++ b/tests/interp/availability-mcodes/valid-joint.ngc @@ -0,0 +1,3 @@ @@ -1287,7 +1323,7 @@ index 0000000000..d697df4d37 +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 +index 0000000..10632c2 --- /dev/null +++ b/tests/interp/availability-mcodes/valid-spindle.ngc @@ -0,0 +1,3 @@ diff --git a/linuxcnc-patches/pending-pre2/0019-motion-allow-concurrent-individual-joint-homing.patch b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch similarity index 76% rename from linuxcnc-patches/pending-pre2/0019-motion-allow-concurrent-individual-joint-homing.patch rename to linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch index f6603e4..e5dfd77 100644 --- a/linuxcnc-patches/pending-pre2/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -3,19 +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 +-- + src/emc/motion/homing.c | 121 ++++++++-------- + src/emc/motion/homing.h | 3 + + src/hal/components/homecomp.comp | 14 +- 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(-) + 11 files changed, 462 insertions(+), 78 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 @@ -24,10 +36,10 @@ Subject: [PATCH] motion: allow concurrent individual joint homing create mode 100644 tests/homing-concurrent/tool.tbl diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index a18acd066f..f4fd73b31b 100644 +index 56264d2..9a37b35 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) +@@ -1746,8 +1746,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) joint_num); return; } @@ -47,10 +59,10 @@ index a18acd066f..f4fd73b31b 100644 } if (!GET_MOTION_ENABLE_FLAG()) { diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 722c58545d..a3e7a3b776 100644 +index 8a544ee..26b5b1d 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2625,18 +2625,13 @@ static void update_status(void) +@@ -2711,18 +2711,13 @@ static void update_status(void) } #endif joint_status->flag = joint->flag; @@ -77,7 +89,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..c63be34 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 +100,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 +146,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 +160,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 +180,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 +189,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 +198,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 +206,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 +221,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 +241,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 +252,16 @@ 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; +@@ -1512,15 +1498,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 +277,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 +1522,7 @@ static int base_1joint_state_machine(int joint_num) } immediate_state = 1; break; @@ -232,7 +285,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 +1537,43 @@ static int base_1joint_state_machine(int joint_num) return homing_flag; } // base_1joint_state_machine() @@ -291,7 +344,7 @@ index 13c5e6b513..2611ee8f0e 100644 } // base_do_homing() /*********************************************************************** -@@ -1461,6 +1458,7 @@ int get_home_sequence(int jno) { return base_get_home_sequence(jno); +@@ -1606,6 +1611,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 +352,7 @@ 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); +@@ -1664,6 +1670,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,79 +361,81 @@ 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 b6a51c4..dc52d99 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); +@@ -96,6 +96,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 diff --git a/src/hal/components/homecomp.comp b/src/hal/components/homecomp.comp -index 79c4691787..74025d5e07 100644 +index 9096469..e728e11 100644 --- a/src/hal/components/homecomp.comp +++ b/src/hal/components/homecomp.comp -@@ -258,34 +258,23 @@ void write_homing_out_pins(int njoints) +@@ -240,6 +240,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 +344,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,13 +358,10 @@ 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(); } +@@ -375,6 +373,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;} +@@ -417,6 +416,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/tests/homing-concurrent/checkresult b/tests/homing-concurrent/checkresult new file mode 100755 -index 0000000000..9c14eb33b3 +index 0000000..9c14eb3 --- /dev/null +++ b/tests/homing-concurrent/checkresult @@ -0,0 +1,3 @@ @@ -389,7 +444,7 @@ index 0000000000..9c14eb33b3 +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 +index 0000000..2eeb379 --- /dev/null +++ b/tests/homing-concurrent/homing.hal @@ -0,0 +1,14 @@ @@ -409,7 +464,7 @@ index 0000000000..2eeb379e69 +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 +index 0000000..6f64d30 --- /dev/null +++ b/tests/homing-concurrent/test-ui.py @@ -0,0 +1,217 @@ @@ -433,18 +488,18 @@ index 0000000000..e0c65cab6d +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.newpin("is-unlocked-%d" % joint, hal.HAL_BOOL, hal.HAL_OUT) ++component.newpin("joint-0-home-switch", hal.HAL_BOOL, 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.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-0-home-switch", hal.HAL_BIT) ++hal.new_sig("homing-concurrent-test-joint-0-home-switch", hal.HAL_BOOL) +hal.connect( + "homing-concurrent-test.joint-0-home-switch", + "homing-concurrent-test-joint-0-home-switch", @@ -632,7 +687,7 @@ index 0000000000..e0c65cab6d +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 +index 0000000..49d5777 --- /dev/null +++ b/tests/homing-concurrent/test.ini @@ -0,0 +1,133 @@ @@ -771,7 +826,7 @@ index 0000000000..49d5777ad0 +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 +index 0000000..3e0b516 --- /dev/null +++ b/tests/homing-concurrent/test.sh @@ -0,0 +1,4 @@ @@ -781,4 +836,4 @@ index 0000000000..3e0b51699c +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 +index 0000000..e69de29 diff --git a/linuxcnc-patches/pending-pre2/0020-feat-motion-add-native-lathe-power-jogging.patch b/linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch similarity index 89% rename from linuxcnc-patches/pending-pre2/0020-feat-motion-add-native-lathe-power-jogging.patch rename to linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch index ab7b2df..167beed 100644 --- a/linuxcnc-patches/pending-pre2/0020-feat-motion-add-native-lathe-power-jogging.patch +++ b/linuxcnc-patches/0020-feat-motion-add-native-lathe-power-jogging.patch @@ -3,6 +3,9 @@ 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 ++++ src/Makefile | 1 + @@ -10,10 +13,10 @@ Subject: [PATCH] feat(motion): add native lathe power jogging 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 +++++ @@ -25,7 +28,7 @@ Subject: [PATCH] feat(motion): add native lathe power jogging 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 +++++++++ + src/emc/usr_intf/halui_power_feed.hh | 63 ++++++++ tests/power-jog/.gitignore | 3 + tests/power-jog/checkresult | 4 + tests/power-jog/core_sim.hal | 11 ++ @@ -33,7 +36,7 @@ Subject: [PATCH] feat(motion): add native lathe power jogging 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(-) + 29 files changed, 796 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 @@ -46,7 +49,7 @@ Subject: [PATCH] feat(motion): add native lathe power jogging 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 +88,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 +100,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 +112,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 +129,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 +216,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 +224,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 +232,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 +272,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 +283,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 +306,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 9a37b35..373f426 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 +317,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 +329,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) +@@ -946,6 +959,22 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) joint->min_ferror = emcmotCommand->minFerror; break; @@ -348,10 +353,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 26b5b1d..0b54c9f 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1900,7 +1900,14 @@ static void get_pos_cmds(long period) +@@ -1982,7 +1982,14 @@ static void get_pos_cmds(long period) break; case EMCMOT_MOTION_TELEOP: @@ -368,10 +373,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 +384,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 51b58d1..6d99597 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 +395,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 +407,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 05ee23d..092beca 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 +427,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,7 +438,7 @@ 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..2303950 --- /dev/null +++ b/src/emc/motion/power_jog.c @@ -0,0 +1,128 @@ @@ -568,7 +572,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 +614,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 f70a5e0..b2b729a 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 +627,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 +636,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 +653,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 f2679d9..915aa58 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -75,6 +75,7 @@ struct PM_CARTESIAN; @@ -660,7 +664,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); +@@ -341,6 +342,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 +673,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 c03bfc3..05a29fe 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 +695,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 01e2b62..154c362 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1310,6 +1310,7 @@ static int emcTaskPlan(void) +@@ -1364,6 +1364,7 @@ static int emcTaskPlan(void) case EMC_JOINT_HOME_TYPE: case EMC_JOINT_UNHOME_TYPE: case EMC_JOG_CONT_TYPE: @@ -702,7 +706,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) +@@ -2265,6 +2266,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; @@ -717,10 +721,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 6dc8665..58c9c7c 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) +@@ -889,6 +889,18 @@ int emcJogCont(int nr, double vel, int jjogmode) return usrmotWriteEmcmotCommand(&emcmotCommand); } @@ -740,18 +744,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 +814,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 +832,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 +846,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 +866,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,14 +875,14 @@ 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..ad9e6e0 --- /dev/null +++ b/src/emc/usr_intf/halui_power_feed.hh -@@ -0,0 +1,69 @@ +@@ -0,0 +1,63 @@ +#pragma once + +#include "hal.h" @@ -887,49 +891,43 @@ index 0000000000..c29dd2bdb9 +/* 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,12 +935,12 @@ 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); ++ command.spindle = spindle; + 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; @@ -950,7 +948,7 @@ index 0000000000..c29dd2bdb9 +}; diff --git a/tests/power-jog/.gitignore b/tests/power-jog/.gitignore new file mode 100644 -index 0000000000..d070f21698 +index 0000000..d070f21 --- /dev/null +++ b/tests/power-jog/.gitignore @@ -0,0 +1,3 @@ @@ -959,7 +957,7 @@ index 0000000000..d070f21698 +sim.var* diff --git a/tests/power-jog/checkresult b/tests/power-jog/checkresult new file mode 100755 -index 0000000000..305bdc4180 +index 0000000..305bdc4 --- /dev/null +++ b/tests/power-jog/checkresult @@ -0,0 +1,4 @@ @@ -969,7 +967,7 @@ index 0000000000..305bdc4180 +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 +index 0000000..80225af --- /dev/null +++ b/tests/power-jog/core_sim.hal @@ -0,0 +1,11 @@ @@ -986,7 +984,7 @@ index 0000000000..80225af5a7 +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 +index 0000000..cc11940 --- /dev/null +++ b/tests/power-jog/test-ui.py @@ -0,0 +1,199 @@ @@ -1191,7 +1189,7 @@ index 0000000000..cc119402ba +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 +index 0000000..98afc6f --- /dev/null +++ b/tests/power-jog/test.ini @@ -0,0 +1,69 @@ @@ -1266,7 +1264,7 @@ index 0000000000..98afc6f1b2 +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 +index 0000000..4397029 --- /dev/null +++ b/tests/power-jog/test.sh @@ -0,0 +1,7 @@ @@ -1279,7 +1277,7 @@ index 0000000000..4397029735 +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 +index 0000000..68840ea --- /dev/null +++ b/tests/power-jog/tool.tbl @@ -0,0 +1 @@ diff --git a/linuxcnc-patches/pending-pre2/0021-hal-support-cross-compiling-external-components.patch b/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch similarity index 95% rename from linuxcnc-patches/pending-pre2/0021-hal-support-cross-compiling-external-components.patch rename to linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch index 82765d4..52e6ae4 100644 --- a/linuxcnc-patches/pending-pre2/0021-hal-support-cross-compiling-external-components.patch +++ b/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch @@ -6,19 +6,19 @@ 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 +++++++++++-- + src/hal/utils/halcompile.g | 130 ++++++++++++-- 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(-) + 7 files changed, 383 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 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,7 +63,7 @@ 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..fd55cf3 100644 --- a/src/Makefile.modinc.in +++ b/src/Makefile.modinc.in @@ -65,46 +65,87 @@ BUILDSYS = @BUILD_SYS@ @@ -173,14 +173,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) + $(Q)$(CC) -shared -Wl,-Bsymbolic $(LDFLAGS) -Wl,--version-script,$*.ver -o $@ $^ -lm $(EXTRA_LDFLAGS) @@ -130,4 +171,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 +192,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 +202,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 +305,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 +324,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 +339,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 +371,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) @@ -391,7 +394,7 @@ index fcce8c6329..e8db9fcd42 100644 diff --git a/tests/halcompile/cross-tools/.gitignore b/tests/halcompile/cross-tools/.gitignore new file mode 100644 -index 0000000000..b6e162464d +index 0000000..b6e1624 --- /dev/null +++ b/tests/halcompile/cross-tools/.gitignore @@ -0,0 +1,2 @@ @@ -399,7 +402,7 @@ index 0000000000..b6e162464d +with space.*/ diff --git a/tests/halcompile/cross-tools/checkresult b/tests/halcompile/cross-tools/checkresult new file mode 100755 -index 0000000000..367210b0f7 +index 0000000..367210b --- /dev/null +++ b/tests/halcompile/cross-tools/checkresult @@ -0,0 +1,4 @@ @@ -409,19 +412,19 @@ index 0000000000..367210b0f7 +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 +index 0000000..8265a4f --- /dev/null +++ b/tests/halcompile/cross-tools/cross_tools.comp @@ -0,0 +1,6 @@ +component cross_tools; -+pin out bit ready; ++pin out bool ready; +function _; +license "GPL"; +;; -+ready = 1; ++ready_set(1); diff --git a/tests/halcompile/cross-tools/test.sh b/tests/halcompile/cross-tools/test.sh new file mode 100755 -index 0000000000..13c1671450 +index 0000000..13c1671 --- /dev/null +++ b/tests/halcompile/cross-tools/test.sh @@ -0,0 +1,170 @@ diff --git a/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch b/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch new file mode 100644 index 0000000..c76d26b --- /dev/null +++ b/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch @@ -0,0 +1,607 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +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 | 98 +++++++++++++++ + src/hal/hal_period_stats.h | 118 ++++++++++++++++++ + src/hal/hal_priv.h | 7 +- + tests/halmodule/halquery/expected | 16 +++ + tests/save.0/expected | 1 + + .../arithmetic.c | 109 ++++++++++++++++ + 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 ++ + 12 files changed, 424 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 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. + + `tmax` is a read/write parameter so the user can set it to 0 to get rid of the first time initialization on the function's execution time. + ++[[sec:hal-thread-parameters]] ++== HAL Thread Parameters ++ ++(((HAL Thread Parameters))) ++Each realtime thread measures the interval between the starts of consecutive ++cycles and publishes the results as parameters named after the thread, for ++example `servo-thread.period-max`. ++All times are in nanoseconds. ++ ++[horizontal] ++`.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. ++ + [[sec:hal-logic-components]] + == Basic Logic Components + +diff --git a/src/hal/hal_lib.c b/src/hal/hal_lib.c +index 0839355..2820c07 100644 +--- a/src/hal/hal_lib.c ++++ b/src/hal/hal_lib.c +@@ -2093,6 +2093,72 @@ int hal_export_funct(const char *name, void (*funct) (void *, long), + return 0; + } + ++/* 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", ++ thread->name); ++ return 1; ++ } ++ ++ 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 param '%s.%s'\n", ++ thread->name, period_stat_names[i]); ++ return retval; ++ } ++ } ++ 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 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"); +@@ -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; ++ int recorded_sample; + + thread = arg; + while (1) { +@@ -3210,6 +3283,8 @@ static void thread_task(void *arg) + funct_entry = SHMPTR(funct_entry->links.next); + } + rtapi_task_self_resync(); ++ /* 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); +@@ -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 = 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 */ +@@ -3254,6 +3337,20 @@ static void thread_task(void *arg) + hal_set_si32(thread->maxtime, runtime); + } + 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 { ++ /* intervals while threads are stopped are not measured */ ++ thread->period_stats.previous_start_ns = 0; + } + /* wait until next period */ + rtapi_wait(); +@@ -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->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 0000000..f38db05 +--- /dev/null ++++ b/src/hal/hal_period_stats.h +@@ -0,0 +1,118 @@ ++#ifndef HAL_PERIOD_STATS_H ++#define HAL_PERIOD_STATS_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; ++ ++/* 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) ++{ ++ 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 void hal_period_stats_saturating_increment(rtapi_sint *value) ++{ ++ 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 (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; ++ 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 >= (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]); ++ } ++ stats->previous_start_ns = start_ns; ++ return recorded; ++} ++ ++/* 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) ++{ ++ rtapi_sint *value = stats->value; ++ ++ 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 c465dcc..5196348 100644 +--- a/src/hal/hal_priv.h ++++ b/src/hal/hal_priv.h +@@ -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 0x00000015 /* version code */ ++#define HAL_VER 0x00000016 /* version code */ + #define HAL_SIZE (2*256*4096) + + /* 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 6b849eb..cfbf203 100644 +--- a/tests/save.0/expected ++++ b/tests/save.0/expected +@@ -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 0x0000000000000001 +diff --git a/tests/thread-period-stats-arithmetic/arithmetic.c b/tests/thread-period-stats-arithmetic/arithmetic.c +new file mode 100644 +index 0000000..1c0b04e +--- /dev/null ++++ b/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/tests/thread-period-stats-arithmetic/expected b/tests/thread-period-stats-arithmetic/expected +new file mode 100644 +index 0000000..e69de29 +diff --git a/tests/thread-period-stats-arithmetic/test.sh b/tests/thread-period-stats-arithmetic/test.sh +new file mode 100644 +index 0000000..09d59c2 +--- /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 -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/tests/thread-period-stats/README b/tests/thread-period-stats/README +new file mode 100644 +index 0000000..dd01bec +--- /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 0000000..753ff32 +--- /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] != "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/tests/thread-period-stats/test.hal b/tests/thread-period-stats/test.hal +new file mode 100644 +index 0000000..452dd58 +--- /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 diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 1225343..3dabd98 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 @@ -17,20 +17,6 @@ they are materialized into LinuxCNC as a linear Git history with exactly one commit per patch. Changing the baseline requires rebasing and validating the complete series. -## Migration to v2.10.0-pre2 (in progress) - -This branch moves the series from the previous base (`888cb941fbf23ee32fc8e15ca180997d99a39117`) to the -`v2.10.0-pre2` tag. - -- Patches in this directory have been ported and apply to the new base. -- Patches still waiting to be ported are kept unchanged under - [`pending-pre2/`](./pending-pre2). They apply only to the previous base and - the tooling ignores them. -- A patch leaves `pending-pre2/` when its port is accepted. It keeps its number - and filename. - -Remove this section and the directory once `pending-pre2/` is empty. - ## Continuous integration Changes under `linuxcnc-patches/` trigger the @@ -510,6 +496,12 @@ 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, +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 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. Coordinated and teleop motion are permitted only when inverse kinematics leaves every unavailable joint at its held command position. Commands requiring an @@ -570,6 +562,13 @@ rejected. 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 diff --git a/linuxcnc-patches/pending-pre2/0023-hal-expose-native-thread-period-statistics.patch b/linuxcnc-patches/pending-pre2/0023-hal-expose-native-thread-period-statistics.patch deleted file mode 100644 index accd479..0000000 --- a/linuxcnc-patches/pending-pre2/0023-hal-expose-native-thread-period-statistics.patch +++ /dev/null @@ -1,510 +0,0 @@ -From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 -From: Dariusz Majnert -Date: Tue, 22 Sep 2026 21:15:00 +0200 -Subject: [PATCH] hal: expose native thread period statistics - ---- - 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(-) - 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 ---- 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. - - `tmax` is a read/write parameter so the user can set it to 0 to get rid of the first time initialization on the function's execution time. - -+[[sec:hal-thread-parameters]] -+== HAL Thread Parameters -+ -+(((HAL Thread Parameters))) -+Each realtime thread measures the interval between the starts of consecutive -+cycles and publishes the results as parameters named after the thread, for -+example `servo-thread.period-max`. -+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. -+ -+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. -+ - [[sec:hal-logic-components]] - == Basic Logic Components - -diff --git a/src/hal/hal_lib.c b/src/hal/hal_lib.c -index 653fa53f0c..c10dd268ea 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 - - #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) { -+ 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; -+ } -+ 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)) { -+ rtapi_print_msg(RTAPI_MSG_ERR, -+ "HAL: ERROR: fail to create period count '%s.%s'\n", -+ new->name, stat_name); -+ return -EINVAL; -+ } -+ } -+ if (hal_param_bit_newf(HAL_RW, &new->period_stats_reset, -+ new->comp_id, "%s.stats-reset", new->name)) { -+ rtapi_print_msg(RTAPI_MSG_ERR, -+ "HAL: ERROR: fail to create period reset for thread '%s'\n", -+ new->name); -+ return -EINVAL; -+ } - 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) - hal_funct_entry_t *funct_root, *funct_entry; - long long int start_time, end_time; - long long int thread_start_time; -+ int recorded_sample; - - thread = arg; - while (1) { -@@ -3173,6 +3237,7 @@ static void thread_task(void *arg) - funct_entry = SHMPTR(funct_entry->links.next); - } - rtapi_task_self_resync(); -+ thread->previous_period_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) - 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); - /* 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); - } -+ if (recorded_sample) { -+ unsigned long long execution_ns = end_time - thread_start_time; -+ hal_period_stats_record_execution(thread, execution_ns); -+ } -+ } else { -+ thread->previous_period_start_ns = 0; - } - /* wait until next period */ - rtapi_wait(); -@@ -3570,6 +3642,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; -diff --git a/src/hal/hal_period_stats.h b/src/hal/hal_period_stats.h -new file mode 100644 -index 0000000000..51daf69621 ---- /dev/null -+++ b/src/hal/hal_period_stats.h -@@ -0,0 +1,89 @@ -+#ifndef HAL_PERIOD_STATS_H -+#define HAL_PERIOD_STATS_H -+ -+#include -+#include "hal.h" -+#include "hal_priv.h" -+ -+static inline void hal_period_stats_clear(hal_thread_t *thread) -+{ -+ 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; -+} -+ -+static inline int hal_period_stats_record_start(hal_thread_t *thread, -+ long long start_ns) -+{ -+ unsigned long long actual_period, jitter, average; -+ 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++; -+ 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; -+ } -+ 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++; -+ } -+ thread->previous_period_start_ns = start_ns; -+ return recorded; -+} -+ -+static inline void hal_period_stats_record_execution(hal_thread_t *thread, -+ unsigned long long execution_ns) -+{ -+ unsigned long long average; -+ -+ 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; -+} -+ -+#endif -diff --git a/src/hal/hal_priv.h b/src/hal/hal_priv.h -index 708eb9511d..9edf398358 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 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 */ - -@@ -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 */ -diff --git a/tests/save.0/expected b/tests/save.0/expected -index 1ad2895953..d0e14360e9 100644 ---- a/tests/save.0/expected -+++ b/tests/save.0/expected -@@ -11,6 +11,7 @@ newsig unlinked bit - 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 From 8102677ab95cc2863b9ee271193d3c530ef79cea Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 12 Nov 2026 14:43:46 +0100 Subject: [PATCH 13/45] feat(linuxcnc): add patch 0024 for the MDI remap abort crash After an E-stop, machine off, mode change or interpreter re-init while an MDI remap or O-word call was waiting, task kept the state that resumes the call and later resumed a call the interpreter had already dropped: milltask crashed for a Python remap and an NGC remap's MDI command hung. The bug is in plain v2.10.0-pre2. Every interpreter reset now clears that state; tests/remap/mdi-remap-abort covers both remap kinds and all four triggers. Verified on the full stack: clean -Werror build, 348/348 regression tests (5 skipped). --- ...te-whenever-the-interpreter-is-reset.patch | 423 ++++++++++++++++++ ...e-command-an-operator-error-rejects.patch} | 0 linuxcnc-patches/README.md | 20 +- 3 files changed, 442 insertions(+), 1 deletion(-) create mode 100644 linuxcnc-patches/0024-task-drop-interrupted-MDI-call-state-whenever-the-interpreter-is-reset.patch rename linuxcnc-patches/{0024-task-identify-the-command-an-operator-error-rejects.patch => 0026-task-identify-the-command-an-operator-error-rejects.patch} (100%) 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 0000000..3567527 --- /dev/null +++ b/linuxcnc-patches/0024-task-drop-interrupted-MDI-call-state-whenever-the-interpreter-is-reset.patch @@ -0,0 +1,423 @@ +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(). An +EMC_TASK_PLAN_INIT re-initializes the interpreter without any of it. 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, and before +emcTaskPlanInit() for EMC_TASK_PLAN_INIT. 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, interpreter re-init and a mode +change, and checks that milltask survives and MDI works afterwards. +--- + src/emc/task/emctask.cc | 4 + + src/emc/task/emctaskmain.cc | 5 +- + src/emc/task/task.hh | 1 + + tests/remap/mdi-remap-abort/README | 12 +++ + tests/remap/mdi-remap-abort/checkresult | 2 + + tests/remap/mdi-remap-abort/m400.ngc | 5 + + tests/remap/mdi-remap-abort/remap.py | 9 ++ + tests/remap/mdi-remap-abort/test-ui.py | 138 ++++++++++++++++++++++++ + tests/remap/mdi-remap-abort/test.ini | 101 +++++++++++++++++ + tests/remap/mdi-remap-abort/test.sh | 2 + + tests/remap/mdi-remap-abort/toplevel.py | 1 + + 11 files changed, 279 insertions(+), 1 deletion(-) + create mode 100644 tests/remap/mdi-remap-abort/README + create mode 100755 tests/remap/mdi-remap-abort/checkresult + create mode 100644 tests/remap/mdi-remap-abort/m400.ngc + create mode 100644 tests/remap/mdi-remap-abort/remap.py + create mode 100755 tests/remap/mdi-remap-abort/test-ui.py + create mode 100644 tests/remap/mdi-remap-abort/test.ini + create mode 100755 tests/remap/mdi-remap-abort/test.sh + create mode 100644 tests/remap/mdi-remap-abort/toplevel.py + +diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc +index 5a1e60e..67edc9b 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 154c362..72e16f1 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -776,7 +776,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; + +@@ -3097,6 +3097,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + break; + + case EMC_TASK_PLAN_INIT_TYPE: ++ // re-initializing the interpreter drops any call an interrupted MDI ++ // command is still inside of ++ mdi_execute_abort(); + retval = emcTaskPlanInit(); + if (retval > INTERP_MIN_ERROR) { + retval = -1; +diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh +index 223886e..1a7a999 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/tests/remap/mdi-remap-abort/README b/tests/remap/mdi-remap-abort/README +new file mode 100644 +index 0000000..4d3f7c0 +--- /dev/null ++++ b/tests/remap/mdi-remap-abort/README +@@ -0,0 +1,12 @@ ++Interrupt an MDI command whose remap is mid-execution with an E-stop, a ++machine off, an interpreter re-init (EMC_TASK_PLAN_INIT) and a mode change ++to AUTO and back, instead of an operator abort, 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. +diff --git a/tests/remap/mdi-remap-abort/checkresult b/tests/remap/mdi-remap-abort/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/remap/mdi-remap-abort/m400.ngc b/tests/remap/mdi-remap-abort/m400.ngc +new file mode 100644 +index 0000000..b841fc7 +--- /dev/null ++++ b/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/tests/remap/mdi-remap-abort/remap.py b/tests/remap/mdi-remap-abort/remap.py +new file mode 100644 +index 0000000..b616b52 +--- /dev/null ++++ b/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/tests/remap/mdi-remap-abort/test-ui.py b/tests/remap/mdi-remap-abort/test-ui.py +new file mode 100755 +index 0000000..b67b7c7 +--- /dev/null ++++ b/tests/remap/mdi-remap-abort/test-ui.py +@@ -0,0 +1,138 @@ ++#!/usr/bin/env python3 ++# ++# Interrupt an MDI command whose remap is mid-execution in every way that ++# resets the interpreter without an operator abort (E-stop, machine off, ++# interpreter re-init, mode change), 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 plan_init(): ++ 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)) ++ interrupt() ++ check_mdi_works(name) ++ print("%s: ok" % name) ++ ++ ++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 interpreter re-init" % code, code, 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/tests/remap/mdi-remap-abort/test.ini b/tests/remap/mdi-remap-abort/test.ini +new file mode 100644 +index 0000000..7a70763 +--- /dev/null ++++ b/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/tests/remap/mdi-remap-abort/test.sh b/tests/remap/mdi-remap-abort/test.sh +new file mode 100755 +index 0000000..a16f6fa +--- /dev/null ++++ b/tests/remap/mdi-remap-abort/test.sh +@@ -0,0 +1,2 @@ ++#!/bin/bash ++exec linuxcnc -r test.ini +diff --git a/tests/remap/mdi-remap-abort/toplevel.py b/tests/remap/mdi-remap-abort/toplevel.py +new file mode 100644 +index 0000000..0dc38fa +--- /dev/null ++++ b/tests/remap/mdi-remap-abort/toplevel.py +@@ -0,0 +1 @@ ++import remap 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 100% 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 diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 3dabd98..8ca6106 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -644,7 +644,25 @@ 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, a drop out of the ON state and an `EMC_TASK_PLAN_INIT` reset +or re-initialise 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, +and `EMC_TASK_PLAN_INIT` runs it before re-initialising the interpreter. +`tests/remap/mdi-remap-abort` interrupts a waiting NGC and Python remap with +each of these and checks that MDI still works. The bug is present in plain +v2.10.0-pre2; the fix touches only upstream code paths. + +### 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 From d994ba03da55b9d03ff72a91ecf55c16c6eadcb9 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 12 Nov 2026 15:32:14 +0100 Subject: [PATCH 14/45] feat(linuxcnc): resumable Stop waits for spindle at-speed on Resume Patch 0004: - Resume, Run and Single Step from STOPPED wait in STARTING until every spindle that Stop switched off reports at-speed again before motion continues. A stale at-speed from before the restore does not count; a spindle whose at-speed never reads false (unconnected or tied true) does not hold Resume. - While Stop waits for motion to come to rest, task issues only commands that add to the motion queue. An M5, S word or M9 read behind a thread now runs after Resume instead of being undone by Resume's restore. Patch 0011 splits tests/resumable-stop into four tests sharing one driver (general, threading, g76-stop, g76-step) with faster programs: about 2.5 minutes each instead of one 11-minute test. The patch-test workflow now uses four shards and spreads them one per shard. Verified on the full stack: clean -Werror build, 351/351 regression tests (5 skipped), headless build with a test subset; 0004 builds on its own. --- .github/workflows/linuxcnc-patches.yml | 11 +- linuxcnc-patches/0004-resumable-stop.patch | 592 ++++++++++++++-- .../0007-native-automatic-tool-wear.patch | 22 +- ...reading-stop-clear-and-pass-stepping.patch | 76 +-- ...-single-step-during-active-execution.patch | 632 ++++++++++++++++-- ...-own-transactional-tool-CRUD-in-task.patch | 18 +- ...-publish-modal-CSS-maximum-in-status.patch | 8 +- ...0016-motion-joint-target-preparation.patch | 8 +- ...ntime-joint-and-spindle-availability.patch | 106 +-- ...w-concurrent-individual-joint-homing.patch | 6 +- ...otion-add-native-lathe-power-jogging.patch | 18 +- ...te-whenever-the-interpreter-is-reset.patch | 6 +- linuxcnc-patches/README.md | 41 +- 13 files changed, 1277 insertions(+), 267 deletions(-) diff --git a/.github/workflows/linuxcnc-patches.yml b/.github/workflows/linuxcnc-patches.yml index 6ee3366..1cf6b18 100644 --- a/.github/workflows/linuxcnc-patches.yml +++ b/.github/workflows/linuxcnc-patches.yml @@ -33,6 +33,8 @@ jobs: label: 2 - shard: 2 label: 3 + - shard: 3 + label: 4 steps: - name: Check out repository @@ -89,14 +91,19 @@ jobs: run: | set -euo pipefail + # tests/resumable-stop/* are the longest tests (about 2.5 minutes + # each); spread them one per shard. Everything else is hashed + # across all shards. shard_tests=() + resumable_index=0 while IFS= read -r -d '' test_path; do if [[ "${test_path}" == tests/resumable-stop/* ]]; then - test_shard=0 + test_shard=$((resumable_index % SHARD_COUNT)) + resumable_index=$((resumable_index + 1)) else checksum="$(printf '%s' "${test_path}" | cksum)" checksum="${checksum%% *}" - test_shard=$((1 + checksum % (SHARD_COUNT - 1))) + test_shard=$((checksum % SHARD_COUNT)) fi if (( test_shard == SHARD_INDEX )); then shard_tests+=("${test_path}") diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 254488d..3af031b 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -24,22 +24,26 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: docs/src/gui/halui.adoc | 3 +- docs/src/man/man1/halui.1.adoc | 5 +- src/emc/motion-logger/motion-logger.c | 4 + - src/emc/motion/command.c | 38 +- - src/emc/motion/control.c | 13 + + 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/motion/motion.h | 7 + src/emc/nml_intf/emc.cc | 24 + - src/emc/nml_intf/emc.hh | 10 + + src/emc/nml_intf/emc.hh | 14 + src/emc/nml_intf/emc_nml.hh | 22 + src/emc/nml_intf/emcops.cc | 4 + - src/emc/task/emctaskmain.cc | 358 ++++- - src/emc/task/taskintf.cc | 40 +- + src/emc/task/emctaskmain.cc | 422 ++++- + src/emc/task/taskintf.cc | 67 +- src/emc/tp/tp.c | 133 +- src/emc/tp/tp_types.h | 12 + src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + src/emc/usr_intf/halui.cc | 9 +- - tests/resumable-stop/README | 37 + + tests/resumable-stop/README | 51 + tests/resumable-stop/after-abort.ngc | 4 + + tests/resumable-stop/after-tap-m5.ngc | 7 + + tests/resumable-stop/after-thread-m5.ngc | 7 + + tests/resumable-stop/after-thread-m9.ngc | 8 + + tests/resumable-stop/after-thread-s.ngc | 7 + tests/resumable-stop/checkresult | 4 + tests/resumable-stop/core_sim.hal | 42 + tests/resumable-stop/css.ngc | 6 + @@ -54,22 +58,27 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/orient.ngc | 6 + tests/resumable-stop/pause.ngc | 7 + tests/resumable-stop/rapid-then-feed.ngc | 7 + + tests/resumable-stop/resume-atspeed.ngc | 7 + tests/resumable-stop/single-step.ngc | 10 + tests/resumable-stop/speed-change.ngc | 9 + tests/resumable-stop/spindle-state.ngc | 10 + tests/resumable-stop/tap.ngc | 7 + - tests/resumable-stop/test-ui.py | 1259 +++++++++++++++++ + tests/resumable-stop/test-ui.py | 1492 +++++++++++++++++ tests/resumable-stop/test.ini | 98 ++ tests/resumable-stop/test.ngc | 9 + - tests/resumable-stop/test.sh | 72 + + tests/resumable-stop/test.sh | 74 + tests/resumable-stop/thread-chain.ngc | 8 + tests/resumable-stop/thread-g95-thread.ngc | 9 + tests/resumable-stop/thread-then-steps.ngc | 10 + tests/resumable-stop/thread.ngc | 7 + tests/resumable-stop/tool.tbl | 1 + - 47 files changed, 2352 insertions(+), 24 deletions(-) + 52 files changed, 2750 insertions(+), 25 deletions(-) create mode 100644 tests/resumable-stop/README create mode 100644 tests/resumable-stop/after-abort.ngc + create mode 100644 tests/resumable-stop/after-tap-m5.ngc + create mode 100644 tests/resumable-stop/after-thread-m5.ngc + create mode 100644 tests/resumable-stop/after-thread-m9.ngc + create mode 100644 tests/resumable-stop/after-thread-s.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 @@ -84,6 +93,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: 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/resume-atspeed.ngc create mode 100644 tests/resumable-stop/single-step.ngc create mode 100644 tests/resumable-stop/speed-change.ngc create mode 100644 tests/resumable-stop/spindle-state.ngc @@ -174,7 +184,7 @@ index 36b77e5..24d0fea 100644 log_print("RESUME\n"); break; diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index e2ecb07..4c0b914 100644 +index e2ecb07..35cf0db 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -536,6 +536,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) @@ -222,20 +232,28 @@ index e2ecb07..4c0b914 100644 break; case EMCMOT_STEP: -@@ -1800,7 +1822,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]); - } -- emcmotStatus->atspeed_next_feed = emcmotCommand->wait_for_spindle_at_speed; ++ 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 +1865,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -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 @@ -253,10 +271,25 @@ index e2ecb07..4c0b914 100644 case EMCMOT_SPINDLE_ORIENT: diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 17fb96b..7a85db9 100644 +index 17fb96b..ccd0f34 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2071,6 +2071,19 @@ static void output_to_hal(void) +@@ -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); } @@ -289,7 +322,7 @@ index 30ce42a..067711a 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 b98bfc0..eb11553 100644 +index b98bfc0..1915616 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -81,6 +81,7 @@ to another. @@ -308,7 +341,18 @@ index b98bfc0..eb11553 100644 EMCMOT_REVERSE, /* run reverse motion */ EMCMOT_FORWARD, /* run reverse motion */ EMCMOT_RESUME, /* resume motion */ -@@ -645,6 +647,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 */ @@ -415,7 +459,7 @@ index ec54d4e..25e5f5a 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 c2f4d1b..6c61f5a 100644 +index c2f4d1b..f28481b 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -93,6 +93,7 @@ struct PM_CARTESIAN; @@ -456,6 +500,17 @@ index c2f4d1b..6c61f5a 100644 extern int emcTrajReverse(); extern int emcTrajForward(); extern int emcTrajStep(); +@@ -436,6 +446,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 3d8c617..0d4ab6c 100644 --- a/src/emc/nml_intf/emc_nml.hh @@ -561,10 +616,10 @@ index ed6a962..a6b2345 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a3b5256..564e4a1 100644 +index a3b5256..124eaf2 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -124,6 +124,37 @@ static int emcTaskEager = 0; +@@ -124,6 +124,40 @@ 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 @@ -578,6 +633,9 @@ index a3b5256..564e4a1 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 { @@ -602,7 +660,7 @@ index a3b5256..564e4a1 100644 // delay counter static double taskExecDelayTimeout = 0.0; -@@ -414,6 +445,10 @@ static double homingIssueTime = 0.0; // etime() when issued, for the start-t +@@ -414,6 +448,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 @@ -613,7 +671,7 @@ index a3b5256..564e4a1 100644 // 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 +557,9 @@ extern int emcTaskMopup(); +@@ -522,6 +560,9 @@ extern int emcTaskMopup(); void readahead_reading(void) { @@ -623,7 +681,7 @@ index a3b5256..564e4a1 100644 int readRetval; int execRetval; -@@ -737,6 +775,9 @@ static void mdi_execute_hook(void) +@@ -737,6 +778,9 @@ static void mdi_execute_hook(void) void readahead_waiting(void) { @@ -633,10 +691,50 @@ index a3b5256..564e4a1 100644 // now handle call logic // check for subsystems done if (interp_list.len() == 0 && -@@ -781,6 +822,197 @@ static bool allow_while_idle_type() { +@@ -781,6 +825,256 @@ 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) { @@ -707,11 +805,14 @@ index a3b5256..564e4a1 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); ++ 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; + } + if (stop_spindles[s].orienting) { + emcSpindleOrient(s, stop_spindles[s].orientation, @@ -812,6 +913,22 @@ index a3b5256..564e4a1 100644 + } + } + } ++ /* ++ * 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; ++ } ++ } + if (stop_single_step) { + emcTrajStep(); + } else { @@ -831,7 +948,7 @@ index a3b5256..564e4a1 100644 /* emcTaskPlan() -@@ -809,6 +1041,29 @@ static int emcTaskPlan(void) +@@ -809,6 +1103,29 @@ static int emcTaskPlan(void) return retval; } @@ -861,7 +978,7 @@ index a3b5256..564e4a1 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1734,6 +1989,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1734,6 +2051,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; @@ -869,7 +986,7 @@ index a3b5256..564e4a1 100644 if (homingPriorMode != EMC_TRAJ_MODE::FREE) { emcTrajSetMode(EMC_TRAJ_MODE::FREE); } -@@ -1937,6 +2193,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1937,6 +2255,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcTrajPause(); break; @@ -881,7 +998,7 @@ index a3b5256..564e4a1 100644 case EMC_TRAJ_RESUME_TYPE: emcStatus->task.task_paused = 0; retval = emcTrajResume(); -@@ -2039,6 +2300,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2039,6 +2362,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE: wait_spindle_orient_complete_msg = reinterpret_cast(cmd); @@ -893,7 +1010,7 @@ index a3b5256..564e4a1 100644 taskExecDelayTimeout = etime() + wait_spindle_orient_complete_msg->timeout; break; -@@ -2099,6 +2365,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2099,6 +2427,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_ORIENT_TYPE: spindle_orient_msg = reinterpret_cast(cmd); @@ -908,7 +1025,7 @@ index a3b5256..564e4a1 100644 retval = emcSpindleOrient(spindle_orient_msg->spindle, spindle_orient_msg->orientation, spindle_orient_msg->mode); break; -@@ -2191,7 +2465,52 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2191,7 +2527,52 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // task commands @@ -961,7 +1078,7 @@ index a3b5256..564e4a1 100644 // abort everything emcTaskAbort(); // KLUDGE call motion abort before state restore to make absolutely sure no -@@ -2215,6 +2534,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2215,6 +2596,9 @@ 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 @@ -971,7 +1088,7 @@ index a3b5256..564e4a1 100644 if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { // leaving auto or mdi mode for manual -@@ -2259,6 +2581,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2259,6 +2643,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_SET_STATE_TYPE: state_msg = reinterpret_cast(cmd); @@ -981,7 +1098,7 @@ index a3b5256..564e4a1 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2484,11 +2809,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2484,11 +2871,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -994,7 +1111,7 @@ index a3b5256..564e4a1 100644 retval = 0; break; -@@ -2701,6 +3023,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3085,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -1002,7 +1119,7 @@ index a3b5256..564e4a1 100644 /*! \todo FIXME-- duplicate code for abort, also near end of main, when aborting on subordinate errors, -@@ -2746,7 +3069,9 @@ static int emcTaskExecute(void) +@@ -2746,7 +3131,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -1013,7 +1130,16 @@ index a3b5256..564e4a1 100644 if (NULL == emcTaskCommand) { // need a new command emcTaskCommand = interp_list.get(); -@@ -3040,6 +3365,18 @@ static int emcTaskExecute(void) +@@ -2767,7 +3154,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 +3427,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -1032,7 +1158,7 @@ index a3b5256..564e4a1 100644 // check if delay has passed emcStatus->task.delayLeft = taskExecDelayTimeout - etime(); if (etime() >= taskExecDelayTimeout) { -@@ -3626,6 +3963,7 @@ int main(int argc, char *argv[]) +@@ -3626,6 +4025,7 @@ int main(int argc, char *argv[]) prev_traj_enabled = emcStatus->motion.traj.enabled; // synchronize subordinate states if (emcStatus->io.aux.estop) { @@ -1040,7 +1166,7 @@ index a3b5256..564e4a1 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3707,6 +4045,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4107,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -1048,7 +1174,7 @@ index a3b5256..564e4a1 100644 // abort everything emcTaskAbort(); emcIoAbort(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); -@@ -3742,6 +4081,12 @@ int main(int argc, char *argv[]) +@@ -3742,6 +4143,12 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -1061,7 +1187,7 @@ index a3b5256..564e4a1 100644 // update task-specific status emcTaskUpdate(&emcStatus->task); -@@ -3762,6 +4107,9 @@ int main(int argc, char *argv[]) +@@ -3762,6 +4169,9 @@ int main(int argc, char *argv[]) emcStatus->io.status == RCS_STATUS::ERROR) { emcStatus->status = RCS_STATUS::ERROR; emcStatus->task.status = RCS_STATUS::ERROR; @@ -1072,7 +1198,7 @@ index a3b5256..564e4a1 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 4215d22..7db2314 100644 +index 4215d22..3f66a0b 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc @@ -1497,6 +1497,13 @@ int emcTrajPause() @@ -1097,7 +1223,7 @@ index 4215d22..7db2314 100644 stat->scale = emcmotStatus.feed_scale; stat->rapid_scale = emcmotStatus.rapid_scale; -@@ -2065,25 +2073,42 @@ int emcSpindleOrient(int spindle, double orientation, int mode) +@@ -2065,25 +2073,69 @@ int emcSpindleOrient(int spindle, double orientation, int mode) } @@ -1143,10 +1269,37 @@ index 4215d22..7db2314 100644 - 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 +2162,9 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ +@@ -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; @@ -1468,10 +1621,10 @@ index 1d0cb6e..65b890a 100644 counts = new_halui_data.mv_counts; diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README new file mode 100644 -index 0000000..e5da45f +index 0000000..29da7fe --- /dev/null +++ b/tests/resumable-stop/README -@@ -0,0 +1,37 @@ +@@ -0,0 +1,51 @@ +Verify resumable Stop preserves an active AUTO program and resumes or +single-steps it. + @@ -1507,6 +1660,20 @@ index 0000000..e5da45f +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 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. diff --git a/tests/resumable-stop/after-abort.ngc b/tests/resumable-stop/after-abort.ngc @@ -1519,15 +1686,68 @@ index 0000000..df711f6 +F600 +G1 X6 +M2 +diff --git a/tests/resumable-stop/after-tap-m5.ngc b/tests/resumable-stop/after-tap-m5.ngc +new file mode 100644 +index 0000000..f8fa1b5 +--- /dev/null ++++ b/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 F60 ++M2 +diff --git a/tests/resumable-stop/after-thread-m5.ngc b/tests/resumable-stop/after-thread-m5.ngc +new file mode 100644 +index 0000000..db6cb3d +--- /dev/null ++++ b/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 F60 ++M2 +diff --git a/tests/resumable-stop/after-thread-m9.ngc b/tests/resumable-stop/after-thread-m9.ngc +new file mode 100644 +index 0000000..30b558d +--- /dev/null ++++ b/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 F60 ++M2 +diff --git a/tests/resumable-stop/after-thread-s.ngc b/tests/resumable-stop/after-thread-s.ngc +new file mode 100644 +index 0000000..336d6be +--- /dev/null ++++ b/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 F60 ++M2 diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult new file mode 100755 -index 0000000..c40d14c +index 0000000..5586b64 --- /dev/null +++ b/tests/resumable-stop/checkresult @@ -0,0 +1,4 @@ +#!/bin/sh +set -e -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 29 ++test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 31 +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 @@ -1724,6 +1944,19 @@ index 0000000..c562a57 +G1 X90 +M5 +M2 +diff --git a/tests/resumable-stop/resume-atspeed.ngc b/tests/resumable-stop/resume-atspeed.ngc +new file mode 100644 +index 0000000..cf66123 +--- /dev/null ++++ b/tests/resumable-stop/resume-atspeed.ngc +@@ -0,0 +1,7 @@ ++G21 G90 ++G0 X0 ++F60 ++S300 M3 ++G1 X4 ++M5 ++M2 diff --git a/tests/resumable-stop/single-step.ngc b/tests/resumable-stop/single-step.ngc new file mode 100644 index 0000000..8955e51 @@ -1786,10 +2019,10 @@ index 0000000..3060ac4 +M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py new file mode 100755 -index 0000000..aa7c6a3 +index 0000000..0b39992 --- /dev/null +++ b/tests/resumable-stop/test-ui.py -@@ -0,0 +1,1259 @@ +@@ -0,0 +1,1492 @@ +#!/usr/bin/env python3 + +import math @@ -1877,8 +2110,10 @@ index 0000000..aa7c6a3 + fail("rejected program Stop changed Stop state") + + -+def resume_and_wait_for_x_motion(stopped_x, on_poll=None): ++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 @@ -1907,6 +2142,20 @@ index 0000000..aa7c6a3 + 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") + @@ -2044,11 +2293,26 @@ index 0000000..aa7c6a3 + 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 resume incorrectly waited for spindle at-speed", ++ "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) @@ -2368,7 +2632,9 @@ index 0000000..aa7c6a3 + 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]) ++ 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() + @@ -2517,8 +2783,24 @@ index 0000000..aa7c6a3 + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE -+ and s.exec_state != linuxcnc.EXEC_WAITING_FOR_DELAY ++ 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", + ) @@ -2535,6 +2817,188 @@ index 0000000..aa7c6a3 + 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_multi_spindle_stop_resume_test(): + open_auto_program("multi-spindle.ngc") + c.spindle(linuxcnc.SPINDLE_FORWARD, 120.0, 0) @@ -2871,7 +3335,7 @@ index 0000000..aa7c6a3 + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_IDLE ++ lambda: s.stop_state != linuxcnc.STOP_STOPPED + and hal.get_value("spindle.0.speed-out") > 0.0, + "Resume did not restore the spindle", + ) @@ -3030,6 +3494,8 @@ index 0000000..aa7c6a3 + "orientation": run_spindle_orientation_stop_test, + "dwell": run_dwell_stop_resume_test, + "dwell-atspeed": run_dwell_atspeed_barrier_test, ++ "command-after-sync": run_command_after_sync_motion_test, ++ "resume-atspeed": run_resume_atspeed_wait_test, + "multi-spindle": run_multi_spindle_stop_resume_test, + "css": run_css_stop_resume_test, + "homing": run_homing_stop_resume_test, @@ -3170,10 +3636,10 @@ index 0000000..416044b +M2 diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh new file mode 100755 -index 0000000..6c37e51 +index 0000000..c70a720 --- /dev/null +++ b/tests/resumable-stop/test.sh -@@ -0,0 +1,72 @@ +@@ -0,0 +1,74 @@ +#!/bin/bash -e + +set -o pipefail @@ -3199,6 +3665,8 @@ index 0000000..6c37e51 + orientation + dwell + dwell-atspeed ++ command-after-sync ++ resume-atspeed + multi-spindle + css + homing diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index bd0552b..8cc2cbb 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -748,7 +748,7 @@ index 25e5f5a..d8d1d9d 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 6c61f5a..9435447 100644 +index f28481b..4c8ebac 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -430,9 +430,18 @@ extern int emcToolPrepare(int tool); @@ -1604,10 +1604,10 @@ index 7620a30..55fb417 100644 // 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 564e4a1..df94f0c 100644 +index 124eaf2..d2eec9f 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -610,6 +610,9 @@ interpret_again: +@@ -613,6 +613,9 @@ interpret_again: emcStatus->task.interpState = EMC_TASK_INTERP::WAITING; interp_list.clear(); @@ -1617,7 +1617,7 @@ index 564e4a1..df94f0c 100644 emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, "interpreter error"); } else if (execRetval == -1 -@@ -1854,6 +1857,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1916,6 +1919,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) break; case EMC_TOOL_SET_NUMBER_TYPE: @@ -1629,7 +1629,7 @@ index 564e4a1..df94f0c 100644 return EMC_TASK_EXEC::WAITING_FOR_IO; break; -@@ -1931,6 +1939,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) +@@ -1993,6 +2001,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) } // issues command immediately @@ -1642,7 +1642,7 @@ index 564e4a1..df94f0c 100644 static int emcTaskIssueCommand(NMLmsg * cmd) { int retval = 0; -@@ -2434,9 +2448,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2496,9 +2510,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcToolPrepare(tool_prepare_msg->tool); break; @@ -1657,7 +1657,7 @@ index 564e4a1..df94f0c 100644 case EMC_TOOL_UNLOAD_TYPE: retval = emcToolUnload(); -@@ -2452,6 +2470,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2514,6 +2532,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, @@ -1666,7 +1666,7 @@ index 564e4a1..df94f0c 100644 emc_tool_set_offset_msg->diameter, emc_tool_set_offset_msg->frontangle, emc_tool_set_offset_msg->backangle, -@@ -2461,6 +2481,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2523,6 +2543,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); @@ -1677,7 +1677,7 @@ index 564e4a1..df94f0c 100644 break; // task commands -@@ -3050,6 +3074,7 @@ static int emcTaskExecute(void) +@@ -3112,6 +3136,7 @@ static int emcTaskExecute(void) // clear out pending command emcTaskCommand = NULL; interp_list.clear(); @@ -1685,7 +1685,7 @@ index 564e4a1..df94f0c 100644 emcAbortCleanup(EMC_ABORT::TASK_EXEC_ERROR); emcStatus->task.currentLine = 0; -@@ -3616,7 +3641,8 @@ static int emctask_startup() +@@ -3678,7 +3703,8 @@ static int emctask_startup() } // initialize the subsystems @@ -1695,7 +1695,7 @@ index 564e4a1..df94f0c 100644 if (emcIoInit() != 0) { rcs_print_error("can't initialize IO\n"); return -1; -@@ -4066,6 +4092,7 @@ int main(int argc, char *argv[]) +@@ -4128,6 +4154,7 @@ int main(int argc, char *argv[]) // clear out the pending command emcTaskCommand = NULL; interp_list.clear(); 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 38139b2..dc74f83 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -91,7 +91,7 @@ index 950dc5c..f13ec12 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 4c0b914..dfceb2a 100644 +index 35cf0db..a8e8ae3 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -545,6 +545,9 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) @@ -176,10 +176,10 @@ index 4c0b914..dfceb2a 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 7a85db9..499824d 100644 +index ccd0f34..e347bf1 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2075,10 +2075,13 @@ 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_sync_run while a position-synchronized run @@ -195,7 +195,7 @@ index 7a85db9..499824d 100644 !emcmotInternal->coord_tp.stop_sync_run && fabs(emcmotStatus->current_vel) < TP_VEL_EPSILON) { emcmotStatus->stopped = 1; -@@ -2306,10 +2309,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 */ @@ -221,7 +221,7 @@ index 7a85db9..499824d 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 eb11553..019e6d1 100644 +index 1915616..ad391e1 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -278,6 +278,8 @@ extern "C" { @@ -297,7 +297,7 @@ index d8d1d9d..ded71c3 100644 /* diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index 9435447..8e943ba 100644 +index 4c8ebac..6b3f9d9 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -145,6 +145,7 @@ struct PM_CARTESIAN; @@ -703,10 +703,10 @@ index 55fb417..90cc136 100644 } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index df94f0c..fe2a371 100644 +index d2eec9f..e0156ee 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -501,6 +501,22 @@ static int programStartLine = 0; // which line to run program from +@@ -504,6 +504,22 @@ static int programStartLine = 0; // which line to run program from int stepping = 0; int steppingWait = 0; static int steppedLine = 0; @@ -729,7 +729,7 @@ index df94f0c..fe2a371 100644 // Variables to handle MDI call interrupts // Depth of call level before interrupted MDI call -@@ -831,8 +847,7 @@ static void emcTaskResumeInterpreter() +@@ -874,8 +890,7 @@ static void emcTaskResumeInterpreter() emcStatus->task.interpState = interpResumeState; } emcStatus->motion.traj.single_stepping = 0; @@ -739,7 +739,7 @@ index df94f0c..fe2a371 100644 } static void emcTaskStepInterpreter() -@@ -1473,6 +1488,10 @@ static int emcTaskPlan(void) +@@ -1535,6 +1550,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 @@ -750,7 +750,7 @@ index df94f0c..fe2a371 100644 break; // otherwise we can't handle it -@@ -1625,6 +1644,10 @@ static int emcTaskPlan(void) +@@ -1687,6 +1706,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 @@ -761,7 +761,7 @@ index df94f0c..fe2a371 100644 break; // otherwise we can't handle it -@@ -1882,6 +1905,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1944,6 +1967,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; @@ -773,7 +773,7 @@ index df94f0c..fe2a371 100644 case EMC_TRAJ_DELAY_TYPE: return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2187,7 +2215,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2249,7 +2277,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajLinearMoveMsg->type, emcTrajLinearMoveMsg->vel, emcTrajLinearMoveMsg->ini_maxvel, emcTrajLinearMoveMsg->acc, emcTrajLinearMoveMsg->ini_maxjerk, emcTrajLinearMoveMsg->vlimit_scale, @@ -784,7 +784,7 @@ index df94f0c..fe2a371 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2560,6 +2590,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2622,6 +2652,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } else { // we can honour the modeswitch if (mode_msg->mode != emcStatus->task.mode) { emcTaskStopClear(); @@ -793,7 +793,7 @@ index df94f0c..fe2a371 100644 } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { -@@ -2593,8 +2625,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2655,8 +2687,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; @@ -803,7 +803,7 @@ index df94f0c..fe2a371 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2607,6 +2638,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2669,6 +2700,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) state_msg = reinterpret_cast(cmd); if (state_msg->state != EMC_TASK_STATE::ON) { emcTaskStopClear(); @@ -812,7 +812,7 @@ index df94f0c..fe2a371 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2691,8 +2724,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2753,8 +2786,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_EXECUTE_TYPE: emcStatus->motion.traj.single_stepping = 0; @@ -822,7 +822,7 @@ index df94f0c..fe2a371 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")); -@@ -2787,8 +2819,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2849,8 +2881,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -832,7 +832,7 @@ index df94f0c..fe2a371 100644 if (!taskplanopen && emcStatus->task.file[0] != 0) { emcTaskPlanOpen(emcStatus->task.file); } -@@ -2856,6 +2887,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2918,6 +2949,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -843,7 +843,7 @@ index df94f0c..fe2a371 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: os_msg = reinterpret_cast(cmd); emcTaskPlanSetOptionalStop(os_msg->state); -@@ -2964,6 +2999,7 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3026,6 +3061,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: @@ -851,7 +851,7 @@ index df94f0c..fe2a371 100644 case EMC_TASK_PLAN_EXECUTE_TYPE: case EMC_TASK_PLAN_OPTIONAL_STOP_TYPE: return EMC_TASK_EXEC::DONE; -@@ -3016,11 +3052,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3078,11 +3114,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) #define STEPPING_CHECK() \ if (stepping) { \ if (! steppingWait) { \ @@ -873,7 +873,7 @@ index df94f0c..fe2a371 100644 break; \ } \ } \ -@@ -3082,8 +3125,7 @@ static int emcTaskExecute(void) +@@ -3144,8 +3187,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; @@ -883,7 +883,7 @@ index df94f0c..fe2a371 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -3105,6 +3147,7 @@ static int emcTaskExecute(void) +@@ -3167,6 +3209,7 @@ static int emcTaskExecute(void) if (NULL != emcTaskCommand) { emcTaskEager = 1; emcStatus->task.currentLine = interp_list.get_line_number(); @@ -891,7 +891,7 @@ index df94f0c..fe2a371 100644 // 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. -@@ -4101,8 +4144,7 @@ int main(int argc, char *argv[]) +@@ -4163,8 +4206,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; @@ -919,7 +919,7 @@ index d8c619c..79dbeb6 100644 #endif - diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index 7db2314..533265a 100644 +index 3f66a0b..3328659 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc @@ -1576,7 +1576,8 @@ int emcTrajSetTermCond(int cond, double tolerance) @@ -1371,11 +1371,11 @@ index e30cc2f..6afd929 100644 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 e5da45f..3a037f8 100644 +index 29da7fe..8750b87 100644 --- a/tests/resumable-stop/README +++ b/tests/resumable-stop/README -@@ -35,3 +35,19 @@ 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. +@@ -49,3 +49,19 @@ barrier, and queued-g33 drops and restores at-speed after Resume as a + spindle would while spinning up. 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 @@ -1395,14 +1395,14 @@ index e5da45f..3a037f8 100644 +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/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -index c40d14c..efeaf20 100755 +index 5586b64..631b3a4 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 29 -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 37 +-test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 31 ++test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 39 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 @@ -1490,7 +1490,7 @@ index 0000000..b0eb997 +M5 +M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index aa7c6a3..a4fb758 100755 +index 0b39992..d29f03f 100755 --- a/tests/resumable-stop/test-ui.py +++ b/tests/resumable-stop/test-ui.py @@ -2,6 +2,7 @@ @@ -1537,7 +1537,7 @@ index aa7c6a3..a4fb758 100755 def wait_complete(message, timeout=10.0): -@@ -447,6 +466,41 @@ def run_threading_stop_resume_test(): +@@ -478,6 +497,41 @@ def run_threading_stop_resume_test(): ) @@ -1579,7 +1579,7 @@ index aa7c6a3..a4fb758 100755 def run_fperrev_stop_resume_test(): open_auto_program("fperrev.ngc") c.auto(linuxcnc.AUTO_RUN, 0) -@@ -511,9 +565,9 @@ def run_g76_stop_resume_test(): +@@ -542,9 +596,9 @@ def run_g76_stop_resume_test(): if s.position[2] > -4.90: fail("G76 stopped before its active threading TC completed") @@ -1591,7 +1591,7 @@ index aa7c6a3..a4fb758 100755 % s.position[0] ) -@@ -532,6 +586,264 @@ def run_g76_stop_resume_test(): +@@ -563,6 +617,264 @@ def run_g76_stop_resume_test(): assert_outputs_stopped_after_program() @@ -1856,7 +1856,7 @@ index aa7c6a3..a4fb758 100755 def run_queued_threading_stop_resume_test(): hal.set_p("spindle.0.at-speed", "false") open_auto_program("thread.ngc") -@@ -1232,8 +1544,16 @@ SCENARIOS = { +@@ -1463,8 +1775,16 @@ SCENARIOS = { "abort-empty": run_abort_from_empty_stopped_queue_test, "queued-g33": run_queued_threading_stop_resume_test, "g33": run_threading_stop_resume_test, @@ -1886,7 +1886,7 @@ index a422788..96b5a38 100644 MAX_LINEAR_VELOCITY = 50 MAX_LINEAR_JERK = 5000 diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh -index 6c37e51..d7b218d 100755 +index c70a720..4b7d7c2 100755 --- a/tests/resumable-stop/test.sh +++ b/tests/resumable-stop/test.sh @@ -7,6 +7,11 @@ if nm -D -u "$EMC2_HOME/rtlib/motmod.so" | grep -q '[[:space:]]tpStop$'; then @@ -1913,7 +1913,7 @@ index 6c37e51..d7b218d 100755 rigid-tap orientation dwell -@@ -33,6 +41,11 @@ scenarios=( +@@ -35,6 +43,11 @@ scenarios=( step-resume-stopping g95-between-g33 spindle-state 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 1c6db6c..96a1086 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 @@ -11,21 +11,64 @@ 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 | 6 ++ - tests/resumable-stop/checkresult | 2 +- - tests/resumable-stop/inflight-step.ngc | 7 +++ - tests/resumable-stop/test-ui.py | 80 ++++++++++++++++++++++++++ - tests/resumable-stop/test.sh | 2 + - 10 files changed, 205 insertions(+), 52 deletions(-) + 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 | 27 +++++++ + tests/resumable-stop/after-tap-m5.ngc | 2 +- + tests/resumable-stop/after-thread-m5.ngc | 2 +- + tests/resumable-stop/after-thread-m9.ngc | 2 +- + tests/resumable-stop/after-thread-s.ngc | 2 +- + tests/resumable-stop/check-result.sh | 15 ++++ + tests/resumable-stop/checkresult | 4 - + tests/resumable-stop/css.ngc | 2 +- + tests/resumable-stop/g76-step/checkresult | 2 + + tests/resumable-stop/g76-step/scenarios | 6 ++ + tests/resumable-stop/g76-step/test.sh | 3 + + tests/resumable-stop/g76-stop/checkresult | 2 + + tests/resumable-stop/g76-stop/scenarios | 5 ++ + tests/resumable-stop/g76-stop/test.sh | 3 + + tests/resumable-stop/general/checkresult | 2 + + tests/resumable-stop/general/scenarios | 21 ++++++ + tests/resumable-stop/general/test.sh | 3 + + tests/resumable-stop/inflight-step.ngc | 7 ++ + tests/resumable-stop/multi-spindle.ngc | 2 +- + tests/resumable-stop/orient.ngc | 2 +- + tests/resumable-stop/rapid-then-feed.ngc | 2 +- + tests/resumable-stop/run-scenarios.sh | 61 +++++++++++++++ + tests/resumable-stop/tap.ngc | 6 +- + tests/resumable-stop/test-ui.py | 80 ++++++++++++++++++++ + tests/resumable-stop/test.ngc | 2 +- + tests/resumable-stop/test.sh | 87 ---------------------- + tests/resumable-stop/thread-g95-thread.ngc | 2 +- + tests/resumable-stop/thread-then-steps.ngc | 4 +- + tests/resumable-stop/thread.ngc | 6 +- + tests/resumable-stop/threading/checkresult | 2 + + tests/resumable-stop/threading/scenarios | 9 +++ + tests/resumable-stop/threading/test.sh | 3 + + 37 files changed, 378 insertions(+), 160 deletions(-) + create mode 100755 tests/resumable-stop/check-result.sh + delete mode 100755 tests/resumable-stop/checkresult + create mode 100755 tests/resumable-stop/g76-step/checkresult + create mode 100644 tests/resumable-stop/g76-step/scenarios + create mode 100755 tests/resumable-stop/g76-step/test.sh + create mode 100755 tests/resumable-stop/g76-stop/checkresult + create mode 100644 tests/resumable-stop/g76-stop/scenarios + create mode 100755 tests/resumable-stop/g76-stop/test.sh + create mode 100755 tests/resumable-stop/general/checkresult + create mode 100644 tests/resumable-stop/general/scenarios + create mode 100755 tests/resumable-stop/general/test.sh create mode 100644 tests/resumable-stop/inflight-step.ngc + create mode 100755 tests/resumable-stop/run-scenarios.sh + delete mode 100755 tests/resumable-stop/test.sh + create mode 100755 tests/resumable-stop/threading/checkresult + create mode 100644 tests/resumable-stop/threading/scenarios + create mode 100755 tests/resumable-stop/threading/test.sh diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index dfceb2a..8dc79dd 100644 +index a8e8ae3..ead94cb 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -1381,26 +1381,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) @@ -66,10 +109,10 @@ index dfceb2a..8dc79dd 100644 break; diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 499824d..aafe3a5 100644 +index e347bf1..75a9f1c 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2311,14 +2311,15 @@ static void update_status(void) +@@ -2319,14 +2319,15 @@ static void update_status(void) if (emcmotStatus->stepping) { TP_STRUCT *tp = &emcmotInternal->coord_tp; @@ -90,10 +133,10 @@ index 499824d..aafe3a5 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index fe2a371..0b20d68 100644 +index e0156ee..a16de26 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -501,6 +501,7 @@ static int programStartLine = 0; // which line to run program from +@@ -504,6 +504,7 @@ static int programStartLine = 0; // which line to run program from int stepping = 0; int steppingWait = 0; static int steppedLine = 0; @@ -101,7 +144,7 @@ index fe2a371..0b20d68 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 -@@ -516,6 +517,7 @@ void emcTaskResetSteppingState() +@@ -519,6 +520,7 @@ void emcTaskResetSteppingState() steppedLine = 0; currentPassGroup = 0; steppedPassGroup = 0; @@ -109,7 +152,7 @@ index fe2a371..0b20d68 100644 } // Variables to handle MDI call interrupts -@@ -861,6 +863,22 @@ static void emcTaskStepInterpreter() +@@ -904,6 +906,22 @@ static void emcTaskStepInterpreter() emcStatus->task.task_paused = 1; } @@ -132,7 +175,7 @@ index fe2a371..0b20d68 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1485,13 +1503,7 @@ static int emcTaskPlan(void) +@@ -1547,13 +1565,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -147,7 +190,7 @@ index fe2a371..0b20d68 100644 break; // otherwise we can't handle it -@@ -1565,17 +1577,9 @@ static int emcTaskPlan(void) +@@ -1627,17 +1639,9 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -166,7 +209,7 @@ index fe2a371..0b20d68 100644 break; // otherwise we can't handle it -@@ -1641,13 +1645,7 @@ static int emcTaskPlan(void) +@@ -1703,13 +1707,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -181,7 +224,7 @@ index fe2a371..0b20d68 100644 break; // otherwise we can't handle it -@@ -4022,6 +4020,10 @@ int main(int argc, char *argv[]) +@@ -4084,6 +4082,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); @@ -401,10 +444,38 @@ index 2963bcc..819f508 100644 } TP_STRUCT; diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -index 3a037f8..17c6a5b 100644 +index 8750b87..84de887 100644 --- a/tests/resumable-stop/README +++ b/tests/resumable-stop/README -@@ -47,6 +47,12 @@ step. It also starts G76 in normal AUTO_RUN, stops after the first pass with +@@ -1,6 +1,27 @@ + 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 run in parallel under ci/test-sharded.sh: ++ ++ 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 +@@ -61,6 +82,12 @@ 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. @@ -417,16 +488,194 @@ index 3a037f8..17c6a5b 100644 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/after-tap-m5.ngc b/tests/resumable-stop/after-tap-m5.ngc +index f8fa1b5..c6a6868 100644 +--- a/tests/resumable-stop/after-tap-m5.ngc ++++ b/tests/resumable-stop/after-tap-m5.ngc +@@ -3,5 +3,5 @@ G0 X0 Z0 + S300 M3 + G33.1 Z-5 K1 + M5 +-G1 X5 F60 ++G1 X5 F300 + M2 +diff --git a/tests/resumable-stop/after-thread-m5.ngc b/tests/resumable-stop/after-thread-m5.ngc +index db6cb3d..e96d6e6 100644 +--- a/tests/resumable-stop/after-thread-m5.ngc ++++ b/tests/resumable-stop/after-thread-m5.ngc +@@ -3,5 +3,5 @@ G0 X0 Z0 + S300 M3 + G33 Z-10 K1 + M5 +-G1 X5 F60 ++G1 X5 F300 + M2 +diff --git a/tests/resumable-stop/after-thread-m9.ngc b/tests/resumable-stop/after-thread-m9.ngc +index 30b558d..cfbf687 100644 +--- a/tests/resumable-stop/after-thread-m9.ngc ++++ b/tests/resumable-stop/after-thread-m9.ngc +@@ -4,5 +4,5 @@ M8 + S300 M3 + G33 Z-10 K1 + M9 +-G1 X5 F60 ++G1 X5 F300 + M2 +diff --git a/tests/resumable-stop/after-thread-s.ngc b/tests/resumable-stop/after-thread-s.ngc +index 336d6be..6e468d1 100644 +--- a/tests/resumable-stop/after-thread-s.ngc ++++ b/tests/resumable-stop/after-thread-s.ngc +@@ -3,5 +3,5 @@ G0 X0 Z0 + S300 M3 + G33 Z-10 K1 + S500 +-G1 X5 F60 ++G1 X5 F300 + M2 +diff --git a/tests/resumable-stop/check-result.sh b/tests/resumable-stop/check-result.sh +new file mode 100755 +index 0000000..7e07466 +--- /dev/null ++++ b/tests/resumable-stop/check-result.sh +@@ -0,0 +1,15 @@ ++#!/bin/sh ++# Shared checkresult for the tests/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/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -index efeaf20..631b3a4 100755 +deleted file mode 100755 +index 631b3a4..0000000 --- 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 37 -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 39 - grep -q '^resumable stop scenarios complete$' "$1" ++++ /dev/null +@@ -1,4 +0,0 @@ +-#!/bin/sh +-set -e +-test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 39 +-grep -q '^resumable stop scenarios complete$' "$1" +diff --git a/tests/resumable-stop/css.ngc b/tests/resumable-stop/css.ngc +index 382aaff..8a70da2 100644 +--- a/tests/resumable-stop/css.ngc ++++ b/tests/resumable-stop/css.ngc +@@ -1,6 +1,6 @@ + G21 G18 G90 + G0 X20 Z0 + G96 D1000 S60 M3 +-G1 X10 F60 ++G1 X10 F150 + M5 + M2 +diff --git a/tests/resumable-stop/g76-step/checkresult b/tests/resumable-stop/g76-step/checkresult +new file mode 100755 +index 0000000..0562404 +--- /dev/null ++++ b/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/tests/resumable-stop/g76-step/scenarios b/tests/resumable-stop/g76-step/scenarios +new file mode 100644 +index 0000000..df2a2ab +--- /dev/null ++++ b/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/tests/resumable-stop/g76-step/test.sh b/tests/resumable-stop/g76-step/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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/tests/resumable-stop/g76-stop/checkresult b/tests/resumable-stop/g76-stop/checkresult +new file mode 100755 +index 0000000..92d147c +--- /dev/null ++++ b/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/tests/resumable-stop/g76-stop/scenarios b/tests/resumable-stop/g76-stop/scenarios +new file mode 100644 +index 0000000..e39cc37 +--- /dev/null ++++ b/tests/resumable-stop/g76-stop/scenarios +@@ -0,0 +1,5 @@ ++g76-handoff-stress ++g76 ++g76-tapered ++g76-waiting-index ++fperrev +diff --git a/tests/resumable-stop/g76-stop/test.sh b/tests/resumable-stop/g76-stop/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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/tests/resumable-stop/general/checkresult b/tests/resumable-stop/general/checkresult +new file mode 100755 +index 0000000..55e9bbe +--- /dev/null ++++ b/tests/resumable-stop/general/checkresult +@@ -0,0 +1,2 @@ ++#!/bin/sh ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 21 +diff --git a/tests/resumable-stop/general/scenarios b/tests/resumable-stop/general/scenarios +new file mode 100644 +index 0000000..620d7df +--- /dev/null ++++ b/tests/resumable-stop/general/scenarios +@@ -0,0 +1,21 @@ ++idle-rejected ++ordinary ++trapezoidal:ordinary ++single-step ++trapezoidal:single-step ++inflight-single-step ++rapid-no-atspeed ++paused-resume ++paused-run ++abort-empty ++orientation ++dwell ++dwell-atspeed ++multi-spindle ++css ++homing ++homing-interrupted ++speed-change-atspeed ++queued-feed-atspeed ++spindle-state ++resume-atspeed +diff --git a/tests/resumable-stop/general/test.sh b/tests/resumable-stop/general/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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/tests/resumable-stop/inflight-step.ngc b/tests/resumable-stop/inflight-step.ngc new file mode 100644 index 0000000..1f72544 @@ -440,11 +689,126 @@ index 0000000..1f72544 +G1 X30 +G1 X40 +M2 +diff --git a/tests/resumable-stop/multi-spindle.ngc b/tests/resumable-stop/multi-spindle.ngc +index ba2e66f..3811387 100644 +--- a/tests/resumable-stop/multi-spindle.ngc ++++ b/tests/resumable-stop/multi-spindle.ngc +@@ -1,4 +1,4 @@ + G21 G90 + G0 X0 +-G1 X10 F60 ++G1 X10 F150 + M2 +diff --git a/tests/resumable-stop/orient.ngc b/tests/resumable-stop/orient.ngc +index bb08db3..6927a71 100644 +--- a/tests/resumable-stop/orient.ngc ++++ b/tests/resumable-stop/orient.ngc +@@ -2,5 +2,5 @@ G21 G90 + G0 X0 + M19 R90 P1 Q30 + M19 R180 P0 Q1 +-G1 X20 F60 ++G1 X20 F600 + M2 +diff --git a/tests/resumable-stop/rapid-then-feed.ngc b/tests/resumable-stop/rapid-then-feed.ngc +index c562a57..531480c 100644 +--- a/tests/resumable-stop/rapid-then-feed.ngc ++++ b/tests/resumable-stop/rapid-then-feed.ngc +@@ -2,6 +2,6 @@ G21 G90 + F60 + S300 M3 + G0 X80 +-G1 X90 ++G1 X90 F300 + M5 + M2 +diff --git a/tests/resumable-stop/run-scenarios.sh b/tests/resumable-stop/run-scenarios.sh +new file mode 100755 +index 0000000..f572282 +--- /dev/null ++++ b/tests/resumable-stop/run-scenarios.sh +@@ -0,0 +1,61 @@ ++#!/bin/bash -e ++# Shared driver for the tests/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 "$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/tests/resumable-stop/tap.ngc b/tests/resumable-stop/tap.ngc +index 3060ac4..2182f18 100644 +--- a/tests/resumable-stop/tap.ngc ++++ b/tests/resumable-stop/tap.ngc +@@ -1,7 +1,7 @@ + G21 G90 + G0 X0 Z0 +-S6 M3 +-G33.1 Z-5 K10 +-G1 X10 F60 ++S60 M3 ++G33.1 Z-5 K1 ++G1 X10 F600 + M5 + M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index a4fb758..a8aa2ef 100755 +index d29f03f..27f097d 100755 --- a/tests/resumable-stop/test-ui.py +++ b/tests/resumable-stop/test-ui.py -@@ -245,6 +245,42 @@ def run_stop_single_step_test(): +@@ -261,6 +261,42 @@ def run_stop_single_step_test(): wait_for_program_complete(20.0) assert_outputs_stopped_after_program() @@ -487,7 +851,7 @@ index a4fb758..a8aa2ef 100755 def run_rapid_resume_without_at_speed_test(): hal.set_p("spindle.0.at-speed", "false") -@@ -759,6 +795,48 @@ def run_tapered_g76_single_step_test(): +@@ -790,6 +826,48 @@ def run_tapered_g76_single_step_test(): "tapered-drive G76", ) @@ -536,7 +900,7 @@ index a4fb758..a8aa2ef 100755 def run_g76_exit_taper_stop_test(program, expected_clear_x, label): open_auto_program(program) -@@ -1538,6 +1616,7 @@ SCENARIOS = { +@@ -1769,6 +1847,7 @@ SCENARIOS = { "idle-rejected": run_idle_program_stop_rejected_test, "ordinary": run_ordinary_stop_resume_test, "single-step": run_stop_single_step_test, @@ -544,7 +908,7 @@ index a4fb758..a8aa2ef 100755 "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), -@@ -1551,6 +1630,7 @@ SCENARIOS = { +@@ -1782,6 +1861,7 @@ SCENARIOS = { "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, @@ -552,23 +916,181 @@ index a4fb758..a8aa2ef 100755 "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, +diff --git a/tests/resumable-stop/test.ngc b/tests/resumable-stop/test.ngc +index 416044b..c44a2cd 100644 +--- a/tests/resumable-stop/test.ngc ++++ b/tests/resumable-stop/test.ngc +@@ -1,6 +1,6 @@ + G21 G90 + G0 X0 +-F60 ++F150 + S300 M3 + M8 + G1 X10 diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh -index d7b218d..832cb0f 100755 +deleted file mode 100755 +index 4b7d7c2..0000000 --- a/tests/resumable-stop/test.sh -+++ b/tests/resumable-stop/test.sh -@@ -16,6 +16,7 @@ scenarios=( - idle-rejected - ordinary - single-step -+ inflight-single-step - rapid-no-atspeed - paused-resume - paused-run -@@ -43,6 +44,7 @@ scenarios=( - spindle-state - g76-single-step - g76-tapered-single-step -+ g76-inflight-single-step - g76-exit-taper - g76-tapered-exit-taper - g76-handoff-stress ++++ /dev/null +@@ -1,87 +0,0 @@ +-#!/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 +- +-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 +- 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 +- dwell-atspeed +- command-after-sync +- resume-atspeed +- multi-spindle +- css +- homing +- homing-interrupted +- speed-change-atspeed +- queued-feed-atspeed +- g33-chain +- step-resume-stopping +- g95-between-g33 +- spindle-state +- g76-single-step +- g76-tapered-single-step +- g76-exit-taper +- g76-tapered-exit-taper +- g76-handoff-stress +-) +- +-# test.ini selects the jerk-limited planner. Repeat the scenarios whose +-# unsynchronized motion is most planner dependent, and g33-chain (which ends +-# in a blend arc only with this planner), with the default trapezoidal planner. +-trapezoidal_scenarios=( +- ordinary +- single-step +- fperrev +- g33-chain +-) +- +-scenario_log=$(mktemp) +-trapezoidal_ini=test-trapezoidal.ini +-trap 'rm -f "$scenario_log" "$trapezoidal_ini"' EXIT +-sed 's/^PLANNER_TYPE = 1$/PLANNER_TYPE = 0/' test.ini > "$trapezoidal_ini" +-grep -q '^PLANNER_TYPE = 0$' "$trapezoidal_ini" +- +-run_scenario() { +- local ini=$1 scenario=$2 +- echo "Running resumable-stop scenario: $scenario ($ini)" +- : > "$scenario_log" +- 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 +-} +- +-for scenario in "${scenarios[@]}"; do +- run_scenario test.ini "$scenario" +-done +-for scenario in "${trapezoidal_scenarios[@]}"; do +- run_scenario "$trapezoidal_ini" "$scenario" +-done +-echo "resumable stop scenarios complete" +diff --git a/tests/resumable-stop/thread-g95-thread.ngc b/tests/resumable-stop/thread-g95-thread.ngc +index d6630aa..2bc7489 100644 +--- a/tests/resumable-stop/thread-g95-thread.ngc ++++ b/tests/resumable-stop/thread-g95-thread.ngc +@@ -4,6 +4,6 @@ S60 M3 + G33 Z-2 K1 + G95 G1 X1 F0.5 + G33 Z-4 K1 +-G94 G1 X10 F60 ++G94 G1 X10 F600 + M5 + M2 +diff --git a/tests/resumable-stop/thread-then-steps.ngc b/tests/resumable-stop/thread-then-steps.ngc +index e744543..44aa11e 100644 +--- a/tests/resumable-stop/thread-then-steps.ngc ++++ b/tests/resumable-stop/thread-then-steps.ngc +@@ -1,7 +1,7 @@ + G21 G90 + G0 X0 Z0 +-S6 M3 +-G33 Z-5 K10 ++S60 M3 ++G33 Z-5 K1 + G1 X5 F600 + M8 + G1 X10 +diff --git a/tests/resumable-stop/thread.ngc b/tests/resumable-stop/thread.ngc +index 5976979..c3ec6d0 100644 +--- a/tests/resumable-stop/thread.ngc ++++ b/tests/resumable-stop/thread.ngc +@@ -1,7 +1,7 @@ + G21 G90 + G0 X0 Z0 +-S6 M3 +-G33 Z-5 K10 +-G1 X10 F60 ++S60 M3 ++G33 Z-5 K1 ++G1 X10 F600 + M5 + M2 +diff --git a/tests/resumable-stop/threading/checkresult b/tests/resumable-stop/threading/checkresult +new file mode 100755 +index 0000000..0201d4f +--- /dev/null ++++ b/tests/resumable-stop/threading/checkresult +@@ -0,0 +1,2 @@ ++#!/bin/sh ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 9 +diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios +new file mode 100644 +index 0000000..0f41046 +--- /dev/null ++++ b/tests/resumable-stop/threading/scenarios +@@ -0,0 +1,9 @@ ++rigid-tap ++g33 ++queued-g33 ++g33-chain ++trapezoidal:g33-chain ++step-resume-stopping ++g95-between-g33 ++g33-no-following-rapid ++command-after-sync +diff --git a/tests/resumable-stop/threading/test.sh b/tests/resumable-stop/threading/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch b/linuxcnc-patches/0012-emc-own-transactional-tool-CRUD-in-task.patch index e6f6405..313e579 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 @@ -99,7 +99,7 @@ index ded71c3..ce4110e 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 8e943ba..8a8f0d1 100644 +index 6b3f9d9..d445ee8 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -28,6 +28,7 @@ class EMC_TRAJ_STAT; @@ -184,10 +184,10 @@ index cf8bc14..b40c76d 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 0b20d68..dc34e1a 100644 +index a16de26..f8ffe7c 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1182,7 +1182,18 @@ static int emcTaskPlan(void) +@@ -1244,7 +1244,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -207,7 +207,7 @@ index 0b20d68..dc34e1a 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO emcTaskQueueCommand(std::make_unique(*static_cast(emcCommand))); -@@ -1311,6 +1322,18 @@ static int emcTaskPlan(void) +@@ -1373,6 +1384,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -226,7 +226,7 @@ index 0b20d68..dc34e1a 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO -@@ -1436,6 +1459,18 @@ static int emcTaskPlan(void) +@@ -1498,6 +1521,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -245,7 +245,7 @@ index 0b20d68..dc34e1a 100644 // otherwise we can't handle it default: -@@ -1771,6 +1806,18 @@ static int emcTaskPlan(void) +@@ -1833,6 +1868,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -264,7 +264,7 @@ index 0b20d68..dc34e1a 100644 // otherwise we can't handle it default: -@@ -1874,6 +1921,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1936,6 +1983,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) case EMC_TOOL_LOAD_TOOL_TABLE_TYPE: case EMC_TOOL_SET_OFFSET_TYPE: @@ -273,7 +273,7 @@ index 0b20d68..dc34e1a 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2506,6 +2555,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2568,6 +2617,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emc_tool_set_offset_msg->orientation); break; @@ -288,7 +288,7 @@ index 0b20d68..dc34e1a 100644 case EMC_TOOL_SET_NUMBER_TYPE: emc_tool_set_number_msg = reinterpret_cast(cmd); retval = emcToolSetNumber(emc_tool_set_number_msg->tool); -@@ -2980,6 +3037,8 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3042,6 +3099,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: 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 1b61696..88ea0c9 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 @@ -40,10 +40,10 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index dc34e1a..ba88a24 100644 +index f8ffe7c..7923ce4 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -970,7 +970,7 @@ static void emcTaskStopProgress() +@@ -1016,7 +1016,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 +53,10 @@ index dc34e1a..ba88a24 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 533265a..4ea2592 100644 +index 3328659..aa63ab4 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -2157,7 +2157,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; diff --git a/linuxcnc-patches/0016-motion-joint-target-preparation.patch b/linuxcnc-patches/0016-motion-joint-target-preparation.patch index ee84e84..852e19c 100644 --- a/linuxcnc-patches/0016-motion-joint-target-preparation.patch +++ b/linuxcnc-patches/0016-motion-joint-target-preparation.patch @@ -38,10 +38,10 @@ index 4cc5503..e814320 100644 } diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index aafe3a5..fad2241 100644 +index 75a9f1c..f22ab9b 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1249,9 +1249,83 @@ static void handle_jjogwheels(void) +@@ -1257,9 +1257,83 @@ static void handle_jjogwheels(void) first_pass = 0; } @@ -126,7 +126,7 @@ index aafe3a5..fad2241 100644 emcmot_joint_t *joint; double positions[EMCMOT_MAX_JOINTS]; double vel_lim; -@@ -1436,40 +1510,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 +179,7 @@ index aafe3a5..fad2241 100644 /* there is data in the interpolators */ /* run interpolation */ for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1517,39 +1572,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 */ diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index 0eaa6e5..b772475 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -477,7 +477,7 @@ index e814320..029af60 100644 if (!motion_enable_flag) { 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 8dc79dd..56264d2 100644 +index ead94cb..3734dae 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -80,6 +80,16 @@ extern int motion_num_spindles; @@ -994,7 +994,7 @@ index 8dc79dd..56264d2 100644 for (n = s0; n<=s1; n++){ if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) -@@ -1916,8 +2266,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1923,8 +2273,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1008,7 +1008,7 @@ index 8dc79dd..56264d2 100644 if (n > emcmotConfig->numSpindles){ rtapi_print_msg(RTAPI_MSG_ERR, "spindle number <%d> too high in M19",n); break; -@@ -1967,6 +2321,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1974,6 +2328,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1019,7 +1019,7 @@ index 8dc79dd..56264d2 100644 for (n = s0; n<=s1; n++){ if (emcmotStatus->spindle_status[n].speed > 0) { emcmotStatus->spindle_status[n].speed += emcmotStatus->spindle_status[n].increment; -@@ -1991,6 +2349,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1998,6 +2356,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1030,7 +1030,7 @@ index 8dc79dd..56264d2 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; -@@ -2037,8 +2399,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -2044,8 +2406,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1045,7 +1045,7 @@ index 8dc79dd..56264d2 100644 } break; diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index fad2241..8a544ee 100644 +index f22ab9b..8d4c3e8 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c @@ -45,6 +45,9 @@ static int switchkins_type = 0; @@ -1102,7 +1102,7 @@ index fad2241..8a544ee 100644 /* 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. */ -@@ -510,8 +525,29 @@ static void process_inputs(void) +@@ -518,8 +533,29 @@ static void process_inputs(void) joint_data = &(emcmot_hal_data->joint[joint_num]); /* point to joint data */ joint = &joints[joint_num]; @@ -1133,7 +1133,7 @@ index fad2241..8a544ee 100644 continue; } /* copy data from HAL to joint structure */ -@@ -559,25 +595,7 @@ static void process_inputs(void) +@@ -567,25 +603,7 @@ static void process_inputs(void) SET_JOINT_FERROR_FLAG(joint, 0); } @@ -1160,7 +1160,7 @@ index fad2241..8a544ee 100644 } // a fault was signalled during a spindle-orient in progress -@@ -621,6 +639,391 @@ static void process_inputs(void) +@@ -629,6 +647,391 @@ static void process_inputs(void) } } @@ -1552,7 +1552,7 @@ index fad2241..8a544ee 100644 static void joint_jog_abort_all(bool immediate) { int jNum; -@@ -683,7 +1086,7 @@ static void do_forward_kins(void) +@@ -691,7 +1094,7 @@ static void do_forward_kins(void) at the traj rate */ double joint_pos[EMCMOT_MAX_JOINTS] = {0,}; @@ -1561,7 +1561,7 @@ index fad2241..8a544ee 100644 emcmot_joint_t *joint; /* copy joint position feedback to local array */ -@@ -865,7 +1268,9 @@ static void check_for_faults(void) +@@ -873,7 +1276,9 @@ static void check_for_faults(void) } /* check for spindle ampfifier errors */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1572,7 +1572,7 @@ index fad2241..8a544ee 100644 reportError(_("spindle %d amplifier fault"), spindle_num); emcmotInternal->enabling = 0; } -@@ -937,6 +1342,7 @@ static void set_operating_mode(void) +@@ -945,6 +1350,7 @@ static void set_operating_mode(void) /* check for disabling */ if (!emcmotInternal->enabling && GET_MOTION_ENABLE_FLAG()) { @@ -1580,7 +1580,7 @@ index fad2241..8a544ee 100644 /* clear out the motion emcmotInternal->coord_tp and interpolators */ tpClear(&emcmotInternal->coord_tp); for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -991,8 +1397,9 @@ static void set_operating_mode(void) +@@ -999,8 +1405,9 @@ static void set_operating_mode(void) } } SET_MOTION_ENABLE_FLAG(1); @@ -1592,7 +1592,7 @@ index fad2241..8a544ee 100644 } /* check for entering teleop mode */ -@@ -1020,7 +1427,7 @@ static void set_operating_mode(void) +@@ -1028,7 +1435,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); @@ -1601,7 +1601,7 @@ index fad2241..8a544ee 100644 kinematicsForward(positions, &emcmotStatus->carte_pos_cmd, &fflags, &iflags); // entering teleop (INPOS), remove ext offsets -@@ -1064,7 +1471,7 @@ static void set_operating_mode(void) +@@ -1072,7 +1479,7 @@ static void set_operating_mode(void) emcmotStatus->overrideLimitMask = 0; SET_MOTION_COORD_FLAG(1); SET_MOTION_TELEOP_FLAG(0); @@ -1610,7 +1610,7 @@ index fad2241..8a544ee 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1084,7 +1491,7 @@ static void set_operating_mode(void) +@@ -1092,7 +1499,7 @@ static void set_operating_mode(void) } SET_MOTION_COORD_FLAG(0); SET_MOTION_TELEOP_FLAG(0); @@ -1619,7 +1619,7 @@ index fad2241..8a544ee 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1119,10 +1526,17 @@ static void handle_jjogwheels(void) +@@ -1127,10 +1534,17 @@ static void handle_jjogwheels(void) /* point to joint data */ joint_data = &(emcmot_hal_data->joint[joint_num]); joint = &joints[joint_num]; @@ -1641,7 +1641,7 @@ index fad2241..8a544ee 100644 // disallow accel bogus fractions rtapi_real jjog_accel_fraction = hal_get_real(joint_data->jjog_accel_fraction); -@@ -1137,6 +1551,7 @@ static void handle_jjogwheels(void) +@@ -1145,6 +1559,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; @@ -1649,7 +1649,7 @@ index fad2241..8a544ee 100644 /* initialization complete */ if ( first_pass ) { continue; -@@ -1268,6 +1683,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, +@@ -1276,6 +1691,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, reportError(_("kinematicsInverse gave non-finite joint location on joint %d"), n); return -1; } @@ -1666,7 +1666,7 @@ index fad2241..8a544ee 100644 cubics[n] = joints[n].cubic; if (cubicNeedNextPoint(&cubics[n]) && cubicAddPoint(&cubics[n], positions[n]) != 0) { -@@ -1357,7 +1782,10 @@ static void get_pos_cmds(long period) +@@ -1365,7 +1790,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]; @@ -1678,7 +1678,7 @@ index fad2241..8a544ee 100644 /* if joint is not active, skip it */ continue; } -@@ -1513,8 +1941,7 @@ static void get_pos_cmds(long period) +@@ -1521,8 +1949,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1688,7 +1688,7 @@ index fad2241..8a544ee 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1575,8 +2002,7 @@ static void get_pos_cmds(long period) +@@ -1583,8 +2010,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1698,7 +1698,7 @@ index fad2241..8a544ee 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1587,6 +2013,8 @@ static void get_pos_cmds(long period) +@@ -1595,6 +2021,8 @@ static void get_pos_cmds(long period) &joint->vel_cmd, &joint->acc_cmd, &joint->jerk_cmd); } @@ -1707,7 +1707,7 @@ index fad2241..8a544ee 100644 /* END OF OUTPUT KINS */ -@@ -1603,10 +2031,13 @@ static void get_pos_cmds(long period) +@@ -1611,10 +2039,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 */ @@ -1722,7 +1722,7 @@ index fad2241..8a544ee 100644 /* save old command */ joint->pos_cmd = joint->pos_fb; /* set joint velocity and acceleration to zero */ -@@ -1994,8 +2425,6 @@ static void output_to_hal(void) +@@ -2002,8 +2433,6 @@ static void output_to_hal(void) double inch_mult; emcmot_joint_t *joint; joint_hal_t *joint_data; @@ -1731,7 +1731,7 @@ index fad2241..8a544ee 100644 /* output machine info to HAL for scoping, etc */ hal_set_bool(emcmot_hal_data->motion_enabled, GET_MOTION_ENABLE_FLAG()); -@@ -2037,6 +2466,9 @@ static void output_to_hal(void) +@@ -2045,6 +2474,9 @@ static void output_to_hal(void) for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ double speed; @@ -1741,7 +1741,7 @@ index fad2241..8a544ee 100644 if(emcmotStatus->spindle_status[spindle_num].css_factor) { double denom = fabs(emcmotStatus->spindle_status[spindle_num].xoffset - emcmotStatus->carte_pos_cmd.tran.x); -@@ -2071,14 +2503,22 @@ static void output_to_hal(void) +@@ -2079,14 +2511,22 @@ static void output_to_hal(void) } } @@ -1768,7 +1768,7 @@ index fad2241..8a544ee 100644 // What is this for? Docs don't say hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps, emcmotStatus->spindle_status[spindle_num].speed / 60.); -@@ -2139,6 +2579,13 @@ static void output_to_hal(void) +@@ -2147,6 +2587,13 @@ static void output_to_hal(void) /* two way handshaking for the spindle encoder */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1782,7 +1782,7 @@ index fad2241..8a544ee 100644 if(emcmotStatus->spindle_status[spindle_num].spindle_index_enable && !old_motion_index[spindle_num]) { hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable, 1); -@@ -2181,7 +2628,14 @@ static void output_to_hal(void) +@@ -2189,7 +2636,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); @@ -1891,7 +1891,7 @@ index 067711a..51b58d1 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 019e6d1..05ee23d 100644 +index ad391e1..1153fc5 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -180,6 +180,10 @@ extern "C" { @@ -1985,7 +1985,7 @@ index 019e6d1..05ee23d 100644 double pos_cmd; /* commanded joint position */ double pos_fb; /* position feedback, comp removed */ -@@ -560,6 +614,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; @@ -1993,7 +1993,7 @@ index 019e6d1..05ee23d 100644 } spindle_status_t; typedef struct { -@@ -786,6 +841,9 @@ typedef struct emcmot_internal_t { +@@ -790,6 +845,9 @@ typedef struct emcmot_internal_t { int enabling; /* starts up disabled */ int coordinating; /* starts up in free mode */ int teleoperating; /* starts up in free mode */ @@ -2086,7 +2086,7 @@ index ce4110e..f70a5e0 100644 /* diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index 8a8f0d1..f2679d9 100644 +index d445ee8..81ab9e6 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -74,6 +74,7 @@ struct PM_CARTESIAN; @@ -2116,7 +2116,7 @@ index 8a8f0d1..f2679d9 100644 extern int emcJointSetMaxJerk(int joint, double jerk); -@@ -469,6 +475,11 @@ extern int emcSpindleBrakeRelease(int spindle); +@@ -473,6 +479,11 @@ extern int emcSpindleBrakeRelease(int spindle); extern int emcSpindleBrakeEngage(int spindle); extern int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles); @@ -2230,10 +2230,10 @@ index 90cc136..5a1e60e 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index ba88a24..01e2b62 100644 +index 7923ce4..170f044 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -169,6 +169,61 @@ volatile int done; +@@ -172,6 +172,61 @@ volatile int done; static int emctask_shutdown(void); extern void backtrace(int signo); int _task = 1; // control preview behaviour when remapping @@ -2295,7 +2295,7 @@ index ba88a24..01e2b62 100644 static int joints = 0; uint64_t task_beat = 0; // Task's main loop heartbeat counter -@@ -180,8 +235,13 @@ extern void setup_signal_handlers(); // backtrace, gdb-in-new-window supportx +@@ -183,8 +238,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++) { @@ -2311,7 +2311,7 @@ index ba88a24..01e2b62 100644 } return 1; } -@@ -879,6 +939,13 @@ static bool emcTaskArmSingleStep() +@@ -922,6 +982,13 @@ static bool emcTaskArmSingleStep() return true; } @@ -2325,7 +2325,7 @@ index ba88a24..01e2b62 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1081,6 +1148,31 @@ static int emcTaskPlan(void) +@@ -1143,6 +1210,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2357,7 +2357,7 @@ index ba88a24..01e2b62 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -@@ -1100,6 +1192,36 @@ static int emcTaskPlan(void) +@@ -1162,6 +1254,36 @@ static int emcTaskPlan(void) return 0; } @@ -2394,7 +2394,7 @@ index ba88a24..01e2b62 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1612,9 +1734,7 @@ static int emcTaskPlan(void) +@@ -1674,9 +1796,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2405,7 +2405,7 @@ index ba88a24..01e2b62 100644 break; // otherwise we can't handle it -@@ -1877,6 +1997,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1939,6 +2059,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: @@ -2414,7 +2414,7 @@ index ba88a24..01e2b62 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2112,6 +2234,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2174,6 +2296,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2439,7 +2439,7 @@ index ba88a24..01e2b62 100644 case EMC_JOG_CONT_TYPE: jog_cont_msg = reinterpret_cast(cmd); retval = emcJogCont(jog_cont_msg->joint_or_axis, -@@ -2479,6 +2619,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2541,6 +2681,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcSpindleOff(spindle_off_msg->spindle, spindle_off_msg->wait_for_spindle_at_speed); break; @@ -2466,7 +2466,7 @@ index ba88a24..01e2b62 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -2936,7 +3096,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2998,7 +3158,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2481,7 +2481,7 @@ index ba88a24..01e2b62 100644 if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -3051,6 +3218,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3113,6 +3280,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2493,7 +2493,7 @@ index ba88a24..01e2b62 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -3133,6 +3305,12 @@ static int emcTaskExecute(void) +@@ -3195,6 +3367,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2506,7 +2506,7 @@ index ba88a24..01e2b62 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3251,11 +3429,49 @@ static int emcTaskExecute(void) +@@ -3313,11 +3491,49 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: @@ -2556,7 +2556,7 @@ index ba88a24..01e2b62 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } -@@ -3470,7 +3686,9 @@ static int emcTaskExecute(void) +@@ -3532,7 +3748,9 @@ static int emcTaskExecute(void) "coordinated motion until every joint is homed")); emcStatus->task.execState = EMC_TASK_EXEC::ERROR; } else if (success) { @@ -2580,7 +2580,7 @@ index 79dbeb6..223886e 100644 int emcTaskSetState(EMC_TASK_STATE state); int emcTaskPlanInit(); diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index 4ea2592..6dc8665 100644 +index aa63ab4..6e10ffb 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc @@ -1035,6 +1035,10 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) @@ -2668,7 +2668,7 @@ index 4ea2592..6dc8665 100644 return (r1 == 0 && r2 == 0 && r3 == 0) ? 0 : -1; } -@@ -2168,10 +2201,42 @@ int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles){ +@@ -2195,10 +2228,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; @@ -2711,7 +2711,7 @@ index 4ea2592..6dc8665 100644 int emcMotionUpdate(EMC_MOTION_STAT * stat) { int r1, r2, r3, r4; -@@ -2261,6 +2326,18 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) +@@ -2288,6 +2353,18 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) // FIXME-AJ: joints not axes for (joint = 0; joint < stat->traj.joints; joint++) { @@ -2730,7 +2730,7 @@ index 4ea2592..6dc8665 100644 if (stat->joint[joint].status == RCS_STATUS::ERROR) { error = 1; break; -@@ -2270,6 +2347,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) +@@ -2297,6 +2374,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) break; } } 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 e5dfd77..ad4c7b9 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -36,7 +36,7 @@ so the new concurrency checks never refuse it. create mode 100644 tests/homing-concurrent/tool.tbl diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index 56264d2..9a37b35 100644 +index 3734dae..3472aa9 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -1746,8 +1746,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) @@ -59,10 +59,10 @@ index 56264d2..9a37b35 100644 } if (!GET_MOTION_ENABLE_FLAG()) { diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 8a544ee..26b5b1d 100644 +index 8d4c3e8..e26daea 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2711,18 +2711,13 @@ static void update_status(void) +@@ -2719,18 +2719,13 @@ static void update_status(void) } #endif joint_status->flag = joint->flag; 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 167beed..c1fc4af 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 @@ -306,7 +306,7 @@ index 5d61f0b..f1ce1d7 100644 #ifdef __cplusplus diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index 9a37b35..373f426 100644 +index 3472aa9..d9f17ac 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -157,6 +157,19 @@ STATIC int spindle_range_is_available(int first, int last) @@ -353,10 +353,10 @@ index 9a37b35..373f426 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 26b5b1d..0b54c9f 100644 +index e26daea..2bc4061 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1982,7 +1982,14 @@ static void get_pos_cmds(long period) +@@ -1990,7 +1990,14 @@ static void get_pos_cmds(long period) break; case EMCMOT_MOTION_TELEOP: @@ -416,7 +416,7 @@ index 51b58d1..6d99597 100644 sp_scurve_cleanup(); /* free shared memory */ diff --git a/src/emc/motion/motion.h b/src/emc/motion/motion.h -index 05ee23d..092beca 100644 +index 1153fc5..3b6d1d1 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -184,6 +184,7 @@ extern "C" { @@ -653,7 +653,7 @@ index f70a5e0..b2b729a 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 f2679d9..915aa58 100644 +index 81ab9e6..003be39 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -75,6 +75,7 @@ struct PM_CARTESIAN; @@ -695,10 +695,10 @@ index c03bfc3..05a29fe 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 01e2b62..154c362 100644 +index 170f044..b69eb5a 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1364,6 +1364,7 @@ static int emcTaskPlan(void) +@@ -1426,6 +1426,7 @@ static int emcTaskPlan(void) case EMC_JOINT_HOME_TYPE: case EMC_JOINT_UNHOME_TYPE: case EMC_JOG_CONT_TYPE: @@ -706,7 +706,7 @@ index 01e2b62..154c362 100644 case EMC_JOG_INCR_TYPE: case EMC_JOG_ABS_TYPE: case EMC_JOG_STOP_TYPE: -@@ -2265,6 +2266,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2327,6 +2328,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; @@ -721,7 +721,7 @@ index 01e2b62..154c362 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 6dc8665..58c9c7c 100644 +index 6e10ffb..0e26533 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc @@ -889,6 +889,18 @@ int emcJogCont(int nr, double vel, int jjogmode) 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 index 3567527..3b12ee5 100644 --- 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 @@ -69,10 +69,10 @@ index 5a1e60e..67edc9b 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 154c362..72e16f1 100644 +index b69eb5a..6941bbd 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -776,7 +776,7 @@ interpret_again: +@@ -779,7 +779,7 @@ interpret_again: } // if interp len is less than max } @@ -81,7 +81,7 @@ index 154c362..72e16f1 100644 { int queued_mdi_commands; -@@ -3097,6 +3097,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3159,6 +3159,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_INIT_TYPE: diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 8ca6106..9bcc0f5 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -195,10 +195,22 @@ The command is exposed as Python `command.program_stop()`, protobuf reported as `EMC_TASK_STOP_STATE` (`IDLE`, `STOPPING`, `STOPPED`, `STARTING`) through Python `stop_state` and the task-status protobuf. -Spindle and coolant are restored without adding a task-level spindle-at-speed -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. +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. + +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 @@ -206,13 +218,15 @@ 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 `tests/resumable-stop` LinuxCNC regression runs 25 scenarios with the -jerk-limited planner and repeats four of them with the trapezoidal planner. -They cover Stop/Resume and Stop/Single-Step preserving the queued program, -spindle and coolant handling, the at-speed cases above, `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. +The `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 37 scenarios with the +jerk-limited planner and four re-runs 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, 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` @@ -366,9 +380,8 @@ 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 35 scenarios plus four trapezoidal re-runs -on v2.10.0-pre2. During an +later blocks queued and during an active G76 cut with later passes queued; +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. From 45c6e9bfa33455979afec3b87e3da5b6d22879f2 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Tue, 17 Nov 2026 23:34:04 +0100 Subject: [PATCH 15/45] fix(native): refuse HAL writes outside an owned S32/U32 item's range LinuxCNC 2.10 HAL stores integers in 64 bits only, so a pin or parameter that a remote component declares S32/U32 is a HAL_SINT/HAL_UINT item listed as S64/U64. HalService.Write accepted any 64-bit value for it and echoed it back, while the owning client reads it through hal_get_{s,u}i32_clamped and silently saw the clamped value. Main rejected such writes as mistyped. The adapter now records owned items declared S32/U32 (by HAL name, matched against the owning component id and HAL's alias old name) and refuses a write that does not fit the declared range, written to the item directly or to a signal an owned narrow pin is linked to. The refusal goes through the existing "missing, mistyped, or not writable" path, so HalService.Write answers FAILED_PRECONDITION as on main and a batch applies nothing. to_hal(), read_owned() and the new fits_declared() move to hal/value_codec.hpp and get a unit test (widening, signedness refusal, range check, clamped owner reads). The live HAL test covers rejected out-of-range S64/U64 writes, batch atomicity and the in-range 32-bit limits reaching the owner unchanged. --- native/server/CMakeLists.txt | 19 ++ .../include/linuxcnc_grpc/hal/adapter.hpp | 11 +- native/server/src/hal/adapter.cc | 192 ++++++++++-------- native/server/src/hal/value_codec.hpp | 121 +++++++++++ native/server/tests/grpc_live_hal.cc | 100 +++++++++ native/server/tests/hal_value_codec_tests.cc | 156 ++++++++++++++ 6 files changed, 516 insertions(+), 83 deletions(-) create mode 100644 native/server/src/hal/value_codec.hpp create mode 100644 native/server/tests/hal_value_codec_tests.cc diff --git a/native/server/CMakeLists.txt b/native/server/CMakeLists.txt index 462edc0..aaacd2b 100644 --- a/native/server/CMakeLists.txt +++ b/native/server/CMakeLists.txt @@ -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/include/linuxcnc_grpc/hal/adapter.hpp b/native/server/include/linuxcnc_grpc/hal/adapter.hpp index 0385197..0963ff3 100644 --- a/native/server/include/linuxcnc_grpc/hal/adapter.hpp +++ b/native/server/include/linuxcnc_grpc/hal/adapter.hpp @@ -113,8 +113,10 @@ class HalAdapterError final : public std::runtime_error { * 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; read() clamps a value outside the 32-bit - * range to the nearest 32-bit limit. + * 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: @@ -152,6 +154,11 @@ class LinuxCncHalComponent final { * 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 diff --git a/native/server/src/hal/adapter.cc b/native/server/src/hal/adapter.cc index 4a0d360..fe8f39e 100644 --- a/native/server/src/hal/adapter.cc +++ b/native/server/src/hal/adapter.cc @@ -23,6 +23,7 @@ #include #include "hal/query.hpp" +#include "hal/value_codec.hpp" namespace linuxcnc::server { namespace { @@ -153,51 +154,69 @@ HalAdapterValue from_hal(hal_type_t type, const hal_query_value_u& value) { } } -// 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. -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; +using hal_codec::fits_declared; +using hal_codec::read_owned; +using hal_codec::to_hal; + +// 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); } - return std::nullopt; -} + + 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 && + !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_; +}; // 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. @@ -270,11 +289,16 @@ struct PreparedWrite { // 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. +// 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 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); @@ -290,6 +314,8 @@ std::optional prepare_unlocked( 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. @@ -299,6 +325,28 @@ std::optional prepare_unlocked( 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; } @@ -382,34 +430,6 @@ int create_param(int component_id, hal_pdir_t direction, HalAdapterType type, return -EINVAL; } -// 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 (set from outside, or by a linked 64-bit writer) is clamped. -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; -} - bool write_owned(HalAdapterType type, const hal_refs_u& ref, const HalAdapterValue& value) { if (!same_type(type, value)) return false; @@ -506,18 +526,20 @@ 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(); } @@ -539,11 +561,16 @@ struct LinuxCncHalComponent::Impl { 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") + @@ -574,6 +601,8 @@ struct LinuxCncHalAdapter::Impl { 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; @@ -966,7 +995,7 @@ bool LinuxCncHalAdapter::write(const HalAdapterReference& reference, HalAdapterValue* written) { bool applied = false; run_locked([&] { - const auto prepared = prepare_unlocked(reference, value); + const auto prepared = prepare_unlocked(reference, value, *impl_->narrow); if (!prepared || !apply_unlocked(*prepared)) return; if (written) *written = read_back_unlocked(reference); applied = true; @@ -984,7 +1013,7 @@ std::size_t LinuxCncHalAdapter::write_many( for (const auto& [reference, value] : updates) { if (stop_token.stop_requested()) throw HalAdapterError("HAL write cancelled", -ECANCELED); - auto item = prepare_unlocked(reference, value); + auto item = prepare_unlocked(reference, value, *impl_->narrow); if (!item) return; prepared.push_back(*item); } @@ -1058,6 +1087,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/value_codec.hpp b/native/server/src/hal/value_codec.hpp new file mode 100644 index 0000000..22010a4 --- /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/tests/grpc_live_hal.cc b/native/server/tests/grpc_live_hal.cc index 44ead4d..8311712 100644 --- a/native/server/tests/grpc_live_hal.cc +++ b/native/server/tests/grpc_live_hal.cc @@ -292,6 +292,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 +388,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 +506,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"); } 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 0000000..9f73c19 --- /dev/null +++ b/native/server/tests/hal_value_codec_tests.cc @@ -0,0 +1,156 @@ +#include + +#include +#include +#include +#include +#include +#include + +#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{})); +} + +} // namespace + +int main() { + check_to_hal(); + check_fits_declared(); + check_read_owned(); + return 0; +} From 513868bae84ac55d82e2b8886dd90e308bd91af1 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Tue, 17 Nov 2026 23:34:06 +0100 Subject: [PATCH 16/45] test(native): sample 64-bit integer scope pins and pin CreateSignal S32 The live scope check selected a pin by HAL_TYPE_S32/U32, which HAL 2.10 no longer reports, so it always fell back to a bit/float pin and never sampled an integer channel. It now configures an S64/U64 pin on channel 0 and a bit/float pin on channel 1, and checks both channels are enabled in the first telemetry frame. Also pin the documented CreateSignal behaviour: a signal requested as S32 or U32 is created and reported as S64 or U64. --- native/server/tests/grpc_live_hal.cc | 50 ++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 7 deletions(-) diff --git a/native/server/tests/grpc_live_hal.cc b/native/server/tests/grpc_live_hal.cc index 8311712..e706961 100644 --- a/native/server/tests/grpc_live_hal.cc +++ b/native/server/tests/grpc_live_hal.cc @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -207,6 +208,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); @@ -683,16 +704,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(); @@ -703,7 +727,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()); @@ -730,6 +760,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()); From 367154d8f037f98a32d38fcb74870e13a763cb69 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 00:47:30 +0100 Subject: [PATCH 17/45] fix(linuxcnc): address final pre2 review findings Patch 0004: Pause while Resume is pending (STARTING, or a Resume latched during STOPPING) cancels it like a second Stop instead of being overridden when the spindle reaches speed. A spindle restored at commanded speed 0 no longer holds Resume forever. Patch 0007: a failed tool-table save after a random-changer M6 is reported as an operator error instead of being overwritten with DONE. Patch 0012: a table that fails to load (at startup or on reload of the configured file) blocks every save until a table loads, so one bad line can no longer lead to the file being overwritten with a partial table. CRLF, whitespace-only and comment-only lines count as blank. Startup reports the load failure. Patches 0017/0018: the acquisition home of M54 is not issued while the program is stopped or paused; it starts after Resume. Motion times out an acknowledged home that never starts, and task restores the trajectory mode once Abort has cancelled the acquisition. Patch 0019: an individual home is refused while another joint homes if either joint uses HOME_IS_SHARED or HOME_IGNORE_LIMITS (shared switch or limit chain could latch a wrong home). Homing modules export get_home_is_exclusive(). Patch 0024: EMC_TASK_PLAN_INIT drops MDI state only when an interrupted call exists, so a reset during a plain MDI move no longer reports IDLE while moving. The test now checks that queued MDI commands are dropped. New or extended tests: resumable-stop (pause-starting, pause-latched-resume, resume-s0), tool-line-length-save, tool-table-load, availability-mcodes, homing-concurrent, remap/mdi-remap-abort. Verified locally: -Werror build; full regression suite 343/352 with the 9 failures environmental (GUI tests on a --disable-gui build, pyvcp picking up another install) plus one link failure fixed in this commit and rerun. --- linuxcnc-patches/0004-resumable-stop.patch | 76 ++- .../0007-native-automatic-tool-wear.patch | 254 ++++++++-- ...reading-stop-clear-and-pass-stepping.patch | 32 +- ...-single-step-during-active-execution.patch | 277 ++++++++--- ...-own-transactional-tool-CRUD-in-task.patch | 466 ++++++++++++++++-- ...-publish-modal-CSS-maximum-in-status.patch | 4 +- ...ntime-joint-and-spindle-availability.patch | 159 ++++-- .../0018-availability-mcodes.patch | 67 ++- ...w-concurrent-individual-joint-homing.patch | 245 ++++++--- ...otion-add-native-lathe-power-jogging.patch | 12 +- ...te-whenever-the-interpreter-is-reset.patch | 85 +++- linuxcnc-patches/README.md | 47 +- 12 files changed, 1409 insertions(+), 315 deletions(-) diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 3af031b..42300df 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -32,7 +32,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: src/emc/nml_intf/emc.hh | 14 + src/emc/nml_intf/emc_nml.hh | 22 + src/emc/nml_intf/emcops.cc | 4 + - src/emc/task/emctaskmain.cc | 422 ++++- + src/emc/task/emctaskmain.cc | 439 ++++- src/emc/task/taskintf.cc | 67 +- src/emc/tp/tp.c | 133 +- src/emc/tp/tp_types.h | 12 + @@ -72,7 +72,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/thread-then-steps.ngc | 10 + tests/resumable-stop/thread.ngc | 7 + tests/resumable-stop/tool.tbl | 1 + - 52 files changed, 2750 insertions(+), 25 deletions(-) + 52 files changed, 2767 insertions(+), 25 deletions(-) create mode 100644 tests/resumable-stop/README create mode 100644 tests/resumable-stop/after-abort.ngc create mode 100644 tests/resumable-stop/after-tap-m5.ngc @@ -616,7 +616,7 @@ index ed6a962..a6b2345 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a3b5256..124eaf2 100644 +index a3b5256..0e54734 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -124,6 +124,40 @@ static int emcTaskEager = 0; @@ -691,7 +691,7 @@ index a3b5256..124eaf2 100644 // now handle call logic // check for subsystems done if (interp_list.len() == 0 && -@@ -781,6 +825,256 @@ static bool allow_while_idle_type() { +@@ -781,6 +825,275 @@ static bool allow_while_idle_type() { return 0; } @@ -791,6 +791,22 @@ index a3b5256..124eaf2 100644 + } +} + ++/* ++ * A second Stop, or a Pause, while Resume is pending cancels it: a Resume ++ * latched during STOPPING is dropped, and 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_resume_latched = false; ++ 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; @@ -808,11 +824,14 @@ index a3b5256..124eaf2 100644 + stop_spindles[s].restore_wait_at_speed = false; + if (stop_spindles[s].running) { + 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) == 0; ++ EMCMOT_SPINDLE_AT_SPEED_PRESERVE) == 0 && ++ stop_spindles[s].speed != 0.0; + } + if (stop_spindles[s].orienting) { + emcSpindleOrient(s, stop_spindles[s].orientation, @@ -948,7 +967,7 @@ index a3b5256..124eaf2 100644 /* emcTaskPlan() -@@ -809,6 +1103,29 @@ static int emcTaskPlan(void) +@@ -809,6 +1122,29 @@ static int emcTaskPlan(void) return retval; } @@ -978,7 +997,7 @@ index a3b5256..124eaf2 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1734,6 +2051,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1734,6 +2070,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; @@ -986,7 +1005,7 @@ index a3b5256..124eaf2 100644 if (homingPriorMode != EMC_TRAJ_MODE::FREE) { emcTrajSetMode(EMC_TRAJ_MODE::FREE); } -@@ -1937,6 +2255,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1937,6 +2274,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcTrajPause(); break; @@ -998,7 +1017,7 @@ index a3b5256..124eaf2 100644 case EMC_TRAJ_RESUME_TYPE: emcStatus->task.task_paused = 0; retval = emcTrajResume(); -@@ -2039,6 +2362,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2039,6 +2381,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE: wait_spindle_orient_complete_msg = reinterpret_cast(cmd); @@ -1010,7 +1029,7 @@ index a3b5256..124eaf2 100644 taskExecDelayTimeout = etime() + wait_spindle_orient_complete_msg->timeout; break; -@@ -2099,6 +2427,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2099,6 +2446,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_ORIENT_TYPE: spindle_orient_msg = reinterpret_cast(cmd); @@ -1025,7 +1044,7 @@ index a3b5256..124eaf2 100644 retval = emcSpindleOrient(spindle_orient_msg->spindle, spindle_orient_msg->orientation, spindle_orient_msg->mode); break; -@@ -2191,7 +2527,52 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2191,7 +2546,49 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // task commands @@ -1060,10 +1079,7 @@ index a3b5256..124eaf2 100644 + retval = emcTrajStop(); + break; + 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: @@ -1078,7 +1094,7 @@ index a3b5256..124eaf2 100644 // abort everything emcTaskAbort(); // KLUDGE call motion abort before state restore to make absolutely sure no -@@ -2215,6 +2596,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2215,6 +2612,9 @@ 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 @@ -1088,7 +1104,7 @@ index a3b5256..124eaf2 100644 if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { // leaving auto or mdi mode for manual -@@ -2259,6 +2643,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2259,6 +2659,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_SET_STATE_TYPE: state_msg = reinterpret_cast(cmd); @@ -1098,7 +1114,15 @@ index a3b5256..124eaf2 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2484,11 +2871,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2451,6 +2854,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 +2888,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -1111,7 +1135,7 @@ index a3b5256..124eaf2 100644 retval = 0; break; -@@ -2701,6 +3085,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3102,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -1119,7 +1143,7 @@ index a3b5256..124eaf2 100644 /*! \todo FIXME-- duplicate code for abort, also near end of main, when aborting on subordinate errors, -@@ -2746,7 +3131,9 @@ static int emcTaskExecute(void) +@@ -2746,7 +3148,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -1130,7 +1154,7 @@ index a3b5256..124eaf2 100644 if (NULL == emcTaskCommand) { // need a new command emcTaskCommand = interp_list.get(); -@@ -2767,7 +3154,7 @@ static int emcTaskExecute(void) +@@ -2767,7 +3171,7 @@ static int emcTaskExecute(void) emcStatus->task.execState = emcTaskCheckPreconditions(emcTaskCommand.get()); } } @@ -1139,7 +1163,7 @@ index a3b5256..124eaf2 100644 // have an outstanding command // This is the one emcTaskIssueCommand() call site followed by // emcTaskCheckPostconditions(), i.e. the only one whose commands -@@ -3040,6 +3427,18 @@ static int emcTaskExecute(void) +@@ -3040,6 +3444,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -1158,7 +1182,7 @@ index a3b5256..124eaf2 100644 // check if delay has passed emcStatus->task.delayLeft = taskExecDelayTimeout - etime(); if (etime() >= taskExecDelayTimeout) { -@@ -3626,6 +4025,7 @@ int main(int argc, char *argv[]) +@@ -3626,6 +4042,7 @@ int main(int argc, char *argv[]) prev_traj_enabled = emcStatus->motion.traj.enabled; // synchronize subordinate states if (emcStatus->io.aux.estop) { @@ -1166,7 +1190,7 @@ index a3b5256..124eaf2 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3707,6 +4107,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4124,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -1174,7 +1198,7 @@ index a3b5256..124eaf2 100644 // abort everything emcTaskAbort(); emcIoAbort(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); -@@ -3742,6 +4143,12 @@ int main(int argc, char *argv[]) +@@ -3742,6 +4160,12 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -1187,7 +1211,7 @@ index a3b5256..124eaf2 100644 // update task-specific status emcTaskUpdate(&emcStatus->task); -@@ -3762,6 +4169,9 @@ int main(int argc, char *argv[]) +@@ -3762,6 +4186,9 @@ int main(int argc, char *argv[]) emcStatus->io.status == RCS_STATUS::ERROR) { emcStatus->status = RCS_STATUS::ERROR; emcStatus->task.status = RCS_STATUS::ERROR; diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index 8cc2cbb..5bcf737 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -89,8 +89,8 @@ Fixes from review of the port: src/emc/task/emccanon.cc | 61 ++- src/emc/task/emctask.cc | 4 + src/emc/task/emctaskmain.cc | 31 +- - src/emc/task/taskclass.cc | 79 +++- - src/emc/task/taskclass.hh | 5 +- + 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 ++-- @@ -131,12 +131,13 @@ Fixes from review of the port: tests/t0/random-with-t0/expected-gcode-output | 2 +- .../random-without-t0/expected-gcode-output | 2 +- tests/tlo/test-ui.py | 7 +- - tests/tool-line-length-save/.gitignore | 3 + + tests/tool-line-length-save/.gitignore | 4 + tests/tool-line-length-save/checkresult | 2 + tests/tool-line-length-save/lathe.ini | 85 +++++ - tests/tool-line-length-save/make-table.py | 9 + + tests/tool-line-length-save/make-table.py | 13 + + tests/tool-line-length-save/random-ui.py | 62 +++ tests/tool-line-length-save/test-ui.py | 86 +++++ - tests/tool-line-length-save/test.sh | 4 + + tests/tool-line-length-save/test.sh | 12 + tests/tool-wear-abort/.gitignore | 3 + tests/tool-wear-abort/change-move.ngc | 5 + tests/tool-wear-abort/change-then-end.ngc | 3 + @@ -185,7 +186,7 @@ Fixes from review of the port: tests/tooldb/db-line-length/test-ui.py | 18 + tests/tooldb/db-line-length/test.ini | 5 + tests/tooldb/db-line-length/test.sh | 14 + - 128 files changed, 2806 insertions(+), 283 deletions(-) + 129 files changed, 2906 insertions(+), 294 deletions(-) create mode 100644 tests/interp/tool-line-length/expected create mode 100644 tests/interp/tool-line-length/missing-t2.ngc create mode 100644 tests/interp/tool-line-length/missing-t3.ngc @@ -208,6 +209,7 @@ Fixes from review of the port: create mode 100755 tests/tool-line-length-save/checkresult create mode 100644 tests/tool-line-length-save/lathe.ini create mode 100755 tests/tool-line-length-save/make-table.py + create mode 100755 tests/tool-line-length-save/random-ui.py create mode 100755 tests/tool-line-length-save/test-ui.py create mode 100755 tests/tool-line-length-save/test.sh create mode 100644 tests/tool-wear-abort/.gitignore @@ -1604,7 +1606,7 @@ index 7620a30..55fb417 100644 // 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 124eaf2..d2eec9f 100644 +index 0e54734..4f046a8 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -613,6 +613,9 @@ interpret_again: @@ -1617,7 +1619,7 @@ index 124eaf2..d2eec9f 100644 emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, "interpreter error"); } else if (execRetval == -1 -@@ -1916,6 +1919,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1935,6 +1938,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) break; case EMC_TOOL_SET_NUMBER_TYPE: @@ -1629,7 +1631,7 @@ index 124eaf2..d2eec9f 100644 return EMC_TASK_EXEC::WAITING_FOR_IO; break; -@@ -1993,6 +2001,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) +@@ -2012,6 +2020,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) } // issues command immediately @@ -1642,7 +1644,7 @@ index 124eaf2..d2eec9f 100644 static int emcTaskIssueCommand(NMLmsg * cmd) { int retval = 0; -@@ -2496,9 +2510,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2515,9 +2529,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcToolPrepare(tool_prepare_msg->tool); break; @@ -1657,7 +1659,7 @@ index 124eaf2..d2eec9f 100644 case EMC_TOOL_UNLOAD_TYPE: retval = emcToolUnload(); -@@ -2514,6 +2532,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2533,6 +2551,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, @@ -1666,7 +1668,7 @@ index 124eaf2..d2eec9f 100644 emc_tool_set_offset_msg->diameter, emc_tool_set_offset_msg->frontangle, emc_tool_set_offset_msg->backangle, -@@ -2523,6 +2543,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2542,6 +2562,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); @@ -1677,7 +1679,7 @@ index 124eaf2..d2eec9f 100644 break; // task commands -@@ -3112,6 +3136,7 @@ static int emcTaskExecute(void) +@@ -3129,6 +3153,7 @@ static int emcTaskExecute(void) // clear out pending command emcTaskCommand = NULL; interp_list.clear(); @@ -1685,7 +1687,7 @@ index 124eaf2..d2eec9f 100644 emcAbortCleanup(EMC_ABORT::TASK_EXEC_ERROR); emcStatus->task.currentLine = 0; -@@ -3678,7 +3703,8 @@ static int emctask_startup() +@@ -3695,7 +3720,8 @@ static int emctask_startup() } // initialize the subsystems @@ -1695,7 +1697,7 @@ index 124eaf2..d2eec9f 100644 if (emcIoInit() != 0) { rcs_print_error("can't initialize IO\n"); return -1; -@@ -4128,6 +4154,7 @@ int main(int argc, char *argv[]) +@@ -4145,6 +4171,7 @@ int main(int argc, char *argv[]) // clear out the pending command emcTaskCommand = NULL; interp_list.clear(); @@ -1704,7 +1706,7 @@ index 124eaf2..d2eec9f 100644 emcAbortCleanup(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index 6694667..6ba96b9 100644 +index 6694667..72b698b4 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc @@ -114,12 +114,44 @@ int emcToolPrepare(int tool) { return task_methods->emcToolPrepare(tool); } @@ -1756,7 +1758,77 @@ index 6694667..6ba96b9 100644 int emcTaskOnce(const char * /*filename*/, EMC_IO_STAT &emcioStatus) { task_methods = new Task(emcioStatus); -@@ -392,6 +424,8 @@ int Task::emcIoAbort(EMC_ABORT /*reason*/)//EMC_TOOL_ABORT_TYPE +@@ -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"); @@ -1765,7 +1837,7 @@ index 6694667..6ba96b9 100644 emcioStatus.coolant.mist = 0; emcioStatus.coolant.flood = 0; hal_set_bool(iocontrol_data->coolant_mist, 0); /* coolant mist output pin */ -@@ -512,7 +546,7 @@ int Task::emcToolLoad()//EMC_TOOL_LOAD_TYPE +@@ -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) { @@ -1774,7 +1846,7 @@ index 6694667..6ba96b9 100644 } // it's not necessary to load the tool already in the spindle -@@ -522,10 +556,12 @@ int Task::emcToolLoad()//EMC_TOOL_LOAD_TYPE +@@ -522,10 +564,12 @@ int Task::emcToolLoad()//EMC_TOOL_LOAD_TYPE } if (!random_toolchanger && (emcioStatus.tool.pocketPrepped > 0) && (emcioStatus.tool.toolInSpindle == tdata.toolno) ) { @@ -1789,7 +1861,7 @@ index 6694667..6ba96b9 100644 //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 +589,10 @@ int Task::emcToolLoadToolTable(const char *file)//EMC_TOOL_LOAD_TOOL_TABLE_TYPE +@@ -553,8 +597,10 @@ int Task::emcToolLoadToolTable(const char *file)//EMC_TOOL_LOAD_TOOL_TABLE_TYPE return 0; } @@ -1802,7 +1874,7 @@ index 6694667..6ba96b9 100644 { int o; -@@ -574,8 +612,12 @@ 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; } @@ -1815,7 +1887,7 @@ index 6694667..6ba96b9 100644 tdata.diameter = d; tdata.frontangle = f; tdata.backangle = b; -@@ -583,17 +625,24 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, double di +@@ -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; } @@ -1844,11 +1916,35 @@ index 6694667..6ba96b9 100644 } return 0; -@@ -674,6 +723,10 @@ int Task::read_tool_inputs(void) +@@ -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 -+ // the new tool's offset takes effect with the tool +- 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; + } @@ -1856,7 +1952,7 @@ index 6694667..6ba96b9 100644 } return 0; diff --git a/src/emc/task/taskclass.hh b/src/emc/task/taskclass.hh -index 6f4aff7..75572ea 100644 +index 6f4aff7..509f11f 100644 --- a/src/emc/task/taskclass.hh +++ b/src/emc/task/taskclass.hh @@ -67,8 +67,9 @@ public: @@ -1871,6 +1967,15 @@ index 6f4aff7..75572ea 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 @@ -3187,13 +3292,14 @@ index 42fe939..2814fe0 100755 - diff --git a/tests/tool-line-length-save/.gitignore b/tests/tool-line-length-save/.gitignore new file mode 100644 -index 0000000..f7b4787 +index 0000000..abf8040 --- /dev/null +++ b/tests/tool-line-length-save/.gitignore -@@ -0,0 +1,3 @@ +@@ -0,0 +1,4 @@ +sim.var +sim.var.bak +tool.tbl ++random.ini diff --git a/tests/tool-line-length-save/checkresult b/tests/tool-line-length-save/checkresult new file mode 100755 index 0000000..24dc9aa @@ -3295,19 +3401,91 @@ index 0000000..01a896f +HOME_SEQUENCE = 0 diff --git a/tests/tool-line-length-save/make-table.py b/tests/tool-line-length-save/make-table.py new file mode 100755 -index 0000000..3e2f0be +index 0000000..624f03b --- /dev/null +++ b/tests/tool-line-length-save/make-table.py -@@ -0,0 +1,9 @@ +@@ -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. ++# 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/tests/tool-line-length-save/random-ui.py b/tests/tool-line-length-save/random-ui.py +new file mode 100755 +index 0000000..35b3c18 +--- /dev/null ++++ b/tests/tool-line-length-save/random-ui.py +@@ -0,0 +1,62 @@ ++#!/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("*** all checks passed") ++sys.exit(0) diff --git a/tests/tool-line-length-save/test-ui.py b/tests/tool-line-length-save/test-ui.py new file mode 100755 index 0000000..9840cd3 @@ -3402,14 +3580,22 @@ index 0000000..9840cd3 +sys.exit(0) diff --git a/tests/tool-line-length-save/test.sh b/tests/tool-line-length-save/test.sh new file mode 100755 -index 0000000..3744834 +index 0000000..74234fb --- /dev/null +++ b/tests/tool-line-length-save/test.sh -@@ -0,0 +1,4 @@ +@@ -0,0 +1,12 @@ +#!/bin/bash ++set -e +python3 make-table.py > tool.tbl +rm -f sim.var -+exec linuxcnc -r 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 ++sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./random-ui.py#' \ ++ -e 's#^RANDOM_TOOLCHANGER = 0$#RANDOM_TOOLCHANGER = 1#' lathe.ini > random.ini ++linuxcnc -r random.ini diff --git a/tests/tool-wear-abort/.gitignore b/tests/tool-wear-abort/.gitignore new file mode 100644 index 0000000..f7b4787 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 dc74f83..31b014b 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -703,7 +703,7 @@ index 55fb417..90cc136 100644 } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index d2eec9f..e0156ee 100644 +index 4f046a8..1154fd8 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -504,6 +504,22 @@ static int programStartLine = 0; // which line to run program from @@ -739,7 +739,7 @@ index d2eec9f..e0156ee 100644 } static void emcTaskStepInterpreter() -@@ -1535,6 +1550,10 @@ static int emcTaskPlan(void) +@@ -1554,6 +1569,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 @@ -750,7 +750,7 @@ index d2eec9f..e0156ee 100644 break; // otherwise we can't handle it -@@ -1687,6 +1706,10 @@ static int emcTaskPlan(void) +@@ -1706,6 +1725,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 @@ -761,7 +761,7 @@ index d2eec9f..e0156ee 100644 break; // otherwise we can't handle it -@@ -1944,6 +1967,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1963,6 +1986,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; @@ -773,7 +773,7 @@ index d2eec9f..e0156ee 100644 case EMC_TRAJ_DELAY_TYPE: return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2249,7 +2277,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2268,7 +2296,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajLinearMoveMsg->type, emcTrajLinearMoveMsg->vel, emcTrajLinearMoveMsg->ini_maxvel, emcTrajLinearMoveMsg->acc, emcTrajLinearMoveMsg->ini_maxjerk, emcTrajLinearMoveMsg->vlimit_scale, @@ -784,7 +784,7 @@ index d2eec9f..e0156ee 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2622,6 +2652,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2638,6 +2668,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } else { // we can honour the modeswitch if (mode_msg->mode != emcStatus->task.mode) { emcTaskStopClear(); @@ -793,7 +793,7 @@ index d2eec9f..e0156ee 100644 } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { -@@ -2655,8 +2687,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2671,8 +2703,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; @@ -803,7 +803,7 @@ index d2eec9f..e0156ee 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2669,6 +2700,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2685,6 +2716,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) state_msg = reinterpret_cast(cmd); if (state_msg->state != EMC_TASK_STATE::ON) { emcTaskStopClear(); @@ -812,7 +812,7 @@ index d2eec9f..e0156ee 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2753,8 +2786,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2769,8 +2802,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_EXECUTE_TYPE: emcStatus->motion.traj.single_stepping = 0; @@ -822,7 +822,7 @@ index d2eec9f..e0156ee 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")); -@@ -2849,8 +2881,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2865,8 +2897,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -832,7 +832,7 @@ index d2eec9f..e0156ee 100644 if (!taskplanopen && emcStatus->task.file[0] != 0) { emcTaskPlanOpen(emcStatus->task.file); } -@@ -2918,6 +2949,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2935,6 +2966,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -843,7 +843,7 @@ index d2eec9f..e0156ee 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: os_msg = reinterpret_cast(cmd); emcTaskPlanSetOptionalStop(os_msg->state); -@@ -3026,6 +3061,7 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3043,6 +3078,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: @@ -851,7 +851,7 @@ index d2eec9f..e0156ee 100644 case EMC_TASK_PLAN_EXECUTE_TYPE: case EMC_TASK_PLAN_OPTIONAL_STOP_TYPE: return EMC_TASK_EXEC::DONE; -@@ -3078,11 +3114,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3095,11 +3131,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) #define STEPPING_CHECK() \ if (stepping) { \ if (! steppingWait) { \ @@ -873,7 +873,7 @@ index d2eec9f..e0156ee 100644 break; \ } \ } \ -@@ -3144,8 +3187,7 @@ static int emcTaskExecute(void) +@@ -3161,8 +3204,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; @@ -883,7 +883,7 @@ index d2eec9f..e0156ee 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -3167,6 +3209,7 @@ static int emcTaskExecute(void) +@@ -3184,6 +3226,7 @@ static int emcTaskExecute(void) if (NULL != emcTaskCommand) { emcTaskEager = 1; emcStatus->task.currentLine = interp_list.get_line_number(); @@ -891,7 +891,7 @@ index d2eec9f..e0156ee 100644 // 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. -@@ -4163,8 +4206,7 @@ int main(int argc, char *argv[]) +@@ -4180,8 +4223,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; 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 96a1086..e0e20fd 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 @@ -11,44 +11,45 @@ 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 | 27 +++++++ - tests/resumable-stop/after-tap-m5.ngc | 2 +- - tests/resumable-stop/after-thread-m5.ngc | 2 +- - tests/resumable-stop/after-thread-m9.ngc | 2 +- - tests/resumable-stop/after-thread-s.ngc | 2 +- - tests/resumable-stop/check-result.sh | 15 ++++ - tests/resumable-stop/checkresult | 4 - - tests/resumable-stop/css.ngc | 2 +- - tests/resumable-stop/g76-step/checkresult | 2 + - tests/resumable-stop/g76-step/scenarios | 6 ++ - tests/resumable-stop/g76-step/test.sh | 3 + - tests/resumable-stop/g76-stop/checkresult | 2 + - tests/resumable-stop/g76-stop/scenarios | 5 ++ - tests/resumable-stop/g76-stop/test.sh | 3 + - tests/resumable-stop/general/checkresult | 2 + - tests/resumable-stop/general/scenarios | 21 ++++++ - tests/resumable-stop/general/test.sh | 3 + - tests/resumable-stop/inflight-step.ngc | 7 ++ - tests/resumable-stop/multi-spindle.ngc | 2 +- - tests/resumable-stop/orient.ngc | 2 +- - tests/resumable-stop/rapid-then-feed.ngc | 2 +- - tests/resumable-stop/run-scenarios.sh | 61 +++++++++++++++ - tests/resumable-stop/tap.ngc | 6 +- - tests/resumable-stop/test-ui.py | 80 ++++++++++++++++++++ - tests/resumable-stop/test.ngc | 2 +- - tests/resumable-stop/test.sh | 87 ---------------------- - tests/resumable-stop/thread-g95-thread.ngc | 2 +- - tests/resumable-stop/thread-then-steps.ngc | 4 +- - tests/resumable-stop/thread.ngc | 6 +- - tests/resumable-stop/threading/checkresult | 2 + - tests/resumable-stop/threading/scenarios | 9 +++ - tests/resumable-stop/threading/test.sh | 3 + - 37 files changed, 378 insertions(+), 160 deletions(-) + 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 | 33 ++++ + tests/resumable-stop/after-tap-m5.ngc | 2 +- + tests/resumable-stop/after-thread-m5.ngc | 2 +- + tests/resumable-stop/after-thread-m9.ngc | 2 +- + tests/resumable-stop/after-thread-s.ngc | 2 +- + tests/resumable-stop/check-result.sh | 15 ++ + tests/resumable-stop/checkresult | 4 - + tests/resumable-stop/css.ngc | 2 +- + tests/resumable-stop/g76-step/checkresult | 2 + + tests/resumable-stop/g76-step/scenarios | 6 + + tests/resumable-stop/g76-step/test.sh | 3 + + tests/resumable-stop/g76-stop/checkresult | 2 + + tests/resumable-stop/g76-stop/scenarios | 5 + + tests/resumable-stop/g76-stop/test.sh | 3 + + tests/resumable-stop/general/checkresult | 2 + + tests/resumable-stop/general/scenarios | 23 +++ + tests/resumable-stop/general/test.sh | 3 + + tests/resumable-stop/inflight-step.ngc | 7 + + tests/resumable-stop/multi-spindle.ngc | 2 +- + tests/resumable-stop/orient.ngc | 2 +- + tests/resumable-stop/rapid-then-feed.ngc | 2 +- + tests/resumable-stop/resume-s0.ngc | 7 + + tests/resumable-stop/run-scenarios.sh | 61 +++++++ + tests/resumable-stop/tap.ngc | 6 +- + tests/resumable-stop/test-ui.py | 200 +++++++++++++++++++++ + tests/resumable-stop/test.ngc | 2 +- + tests/resumable-stop/test.sh | 87 --------- + tests/resumable-stop/thread-g95-thread.ngc | 2 +- + tests/resumable-stop/thread-then-steps.ngc | 4 +- + tests/resumable-stop/thread.ngc | 6 +- + tests/resumable-stop/threading/checkresult | 2 + + tests/resumable-stop/threading/scenarios | 10 ++ + tests/resumable-stop/threading/test.sh | 3 + + 38 files changed, 514 insertions(+), 160 deletions(-) create mode 100755 tests/resumable-stop/check-result.sh delete mode 100755 tests/resumable-stop/checkresult create mode 100755 tests/resumable-stop/g76-step/checkresult @@ -61,6 +62,7 @@ feature and its program. create mode 100644 tests/resumable-stop/general/scenarios create mode 100755 tests/resumable-stop/general/test.sh create mode 100644 tests/resumable-stop/inflight-step.ngc + create mode 100644 tests/resumable-stop/resume-s0.ngc create mode 100755 tests/resumable-stop/run-scenarios.sh delete mode 100755 tests/resumable-stop/test.sh create mode 100755 tests/resumable-stop/threading/checkresult @@ -133,7 +135,7 @@ index e347bf1..75a9f1c 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index e0156ee..a16de26 100644 +index 1154fd8..2a3c750 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -504,6 +504,7 @@ static int programStartLine = 0; // which line to run program from @@ -175,7 +177,7 @@ index e0156ee..a16de26 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1547,13 +1565,7 @@ static int emcTaskPlan(void) +@@ -1566,13 +1584,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -190,7 +192,7 @@ index e0156ee..a16de26 100644 break; // otherwise we can't handle it -@@ -1627,17 +1639,9 @@ static int emcTaskPlan(void) +@@ -1646,17 +1658,9 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -209,7 +211,7 @@ index e0156ee..a16de26 100644 break; // otherwise we can't handle it -@@ -1703,13 +1707,7 @@ static int emcTaskPlan(void) +@@ -1722,13 +1726,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -224,7 +226,7 @@ index e0156ee..a16de26 100644 break; // otherwise we can't handle it -@@ -4084,6 +4082,10 @@ int main(int argc, char *argv[]) +@@ -4101,6 +4099,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); @@ -444,7 +446,7 @@ index 2963bcc..819f508 100644 } TP_STRUCT; diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -index 8750b87..84de887 100644 +index 8750b87..6274c79 100644 --- a/tests/resumable-stop/README +++ b/tests/resumable-stop/README @@ -1,6 +1,27 @@ @@ -475,7 +477,20 @@ index 8750b87..84de887 100644 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 -@@ -61,6 +82,12 @@ step. It also starts G76 in normal AUTO_RUN, stops after the first pass with +@@ -47,6 +68,12 @@ 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 +@@ -61,6 +88,12 @@ 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. @@ -634,18 +649,18 @@ index 0000000..713f576 +exec bash ../run-scenarios.sh scenarios diff --git a/tests/resumable-stop/general/checkresult b/tests/resumable-stop/general/checkresult new file mode 100755 -index 0000000..55e9bbe +index 0000000..dea9811 --- /dev/null +++ b/tests/resumable-stop/general/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 21 ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 23 diff --git a/tests/resumable-stop/general/scenarios b/tests/resumable-stop/general/scenarios new file mode 100644 -index 0000000..620d7df +index 0000000..d2ee92d --- /dev/null +++ b/tests/resumable-stop/general/scenarios -@@ -0,0 +1,21 @@ +@@ -0,0 +1,23 @@ +idle-rejected +ordinary +trapezoidal:ordinary @@ -667,6 +682,8 @@ index 0000000..620d7df +queued-feed-atspeed +spindle-state +resume-atspeed ++pause-starting ++resume-s0 diff --git a/tests/resumable-stop/general/test.sh b/tests/resumable-stop/general/test.sh new file mode 100755 index 0000000..713f576 @@ -722,6 +739,19 @@ index c562a57..531480c 100644 +G1 X90 F300 M5 M2 +diff --git a/tests/resumable-stop/resume-s0.ngc b/tests/resumable-stop/resume-s0.ngc +new file mode 100644 +index 0000000..69d6ce7 +--- /dev/null ++++ b/tests/resumable-stop/resume-s0.ngc +@@ -0,0 +1,7 @@ ++G21 G90 ++G0 X0 ++F60 ++S0 M3 ++G1 X4 ++M5 ++M2 diff --git a/tests/resumable-stop/run-scenarios.sh b/tests/resumable-stop/run-scenarios.sh new file mode 100755 index 0000000..f572282 @@ -805,7 +835,7 @@ index 3060ac4..2182f18 100644 M5 M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index d29f03f..27f097d 100755 +index d29f03f..add6ef4 100755 --- a/tests/resumable-stop/test-ui.py +++ b/tests/resumable-stop/test-ui.py @@ -261,6 +261,42 @@ def run_stop_single_step_test(): @@ -900,7 +930,131 @@ index d29f03f..27f097d 100755 def run_g76_exit_taper_stop_test(program, expected_clear_x, label): open_auto_program(program) -@@ -1769,6 +1847,7 @@ SCENARIOS = { +@@ -1286,6 +1364,123 @@ def run_resume_atspeed_wait_test(): + 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_pause_after_latched_resume_test(): ++ # Resume during STOPPING is latched until Stop completes; a Pause after ++ # it cancels the latched Resume, so the program stays STOPPED. ++ 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.auto(linuxcnc.AUTO_RESUME) ++ c.auto(linuxcnc.AUTO_PAUSE) ++ s.poll() ++ if s.stop_state != linuxcnc.STOP_STOPPING: ++ fail("G33 finished before Resume and Pause were sent") ++ ++ wait_for( ++ lambda: s.stop_state == linuxcnc.STOP_STOPPED ++ and math.isclose(s.position[2], -5.0, abs_tol=0.01), ++ lambda: "Pause after latched Resume did not leave the program " ++ "STOPPED: X=%.3f Z=%.3f stop=%d" ++ % (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("Pause after latched Resume: program left STOPPED") ++ if hal.get_value("spindle.0.on"): ++ fail("Pause after latched Resume: spindle on while STOPPED") ++ if abs(s.position[0]) > 0.001: ++ fail("Pause after latched Resume: feed after G33 moved") ++ ++ 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) +@@ -1769,6 +1964,7 @@ SCENARIOS = { "idle-rejected": run_idle_program_stop_rejected_test, "ordinary": run_ordinary_stop_resume_test, "single-step": run_stop_single_step_test, @@ -908,7 +1062,7 @@ index d29f03f..27f097d 100755 "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), -@@ -1782,6 +1861,7 @@ SCENARIOS = { +@@ -1782,6 +1978,7 @@ SCENARIOS = { "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, @@ -916,6 +1070,16 @@ index d29f03f..27f097d 100755 "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, +@@ -1791,6 +1988,9 @@ SCENARIOS = { + "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, ++ "pause-latched-resume": run_pause_after_latched_resume_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, diff --git a/tests/resumable-stop/test.ngc b/tests/resumable-stop/test.ngc index 416044b..c44a2cd 100644 --- a/tests/resumable-stop/test.ngc @@ -1064,18 +1228,18 @@ index 5976979..c3ec6d0 100644 M2 diff --git a/tests/resumable-stop/threading/checkresult b/tests/resumable-stop/threading/checkresult new file mode 100755 -index 0000000..0201d4f +index 0000000..3b2acd1 --- /dev/null +++ b/tests/resumable-stop/threading/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 9 ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 10 diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios new file mode 100644 -index 0000000..0f41046 +index 0000000..c248aa5 --- /dev/null +++ b/tests/resumable-stop/threading/scenarios -@@ -0,0 +1,9 @@ +@@ -0,0 +1,10 @@ +rigid-tap +g33 +queued-g33 @@ -1085,6 +1249,7 @@ index 0000000..0f41046 +g95-between-g33 +g33-no-following-rapid +command-after-sync ++pause-latched-resume diff --git a/tests/resumable-stop/threading/test.sh b/tests/resumable-stop/threading/test.sh new file mode 100755 index 0000000..713f576 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 313e579..7c6b314 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 @@ -24,19 +24,33 @@ tests/tooldb tests, which need a db program, are skipped. --- 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 | 238 ++++++++++++++++-- + src/emc/nml_intf/emc_nml.hh | 44 +++ + src/emc/task/emctaskmain.cc | 61 +++- + src/emc/task/taskclass.cc | 256 +++++++++++++++-- src/emc/task/taskclass.hh | 5 +- - src/emc/tooldata/tooldata.hh | 14 ++ - src/emc/tooldata/tooldata_common.cc | 237 ++++++++++------- - src/emc/tooldata/tooldata_mmap.cc | 102 +++++++- + src/emc/tooldata/tooldata.hh | 14 + + src/emc/tooldata/tooldata_common.cc | 260 ++++++++++++------ + src/emc/tooldata/tooldata_mmap.cc | 102 ++++++- src/emc/tooldata/tooldata_nml.cc | 16 ++ - .../reload-tool/non-random/test-ui.py | 14 ++ + tests/tool-table-load/.gitignore | 4 + + tests/tool-table-load/checkresult | 2 + + tests/tool-table-load/common.py | 76 +++++ + tests/tool-table-load/crlf-ui.py | 27 ++ + tests/tool-table-load/garbage-ui.py | 56 ++++ + tests/tool-table-load/test.ini | 84 ++++++ + tests/tool-table-load/test.sh | 16 ++ + .../reload-tool/non-random/test-ui.py | 14 + .../toolchanger/reload-tool/random/test-ui.py | 3 +- tests/tooldb/db-g10-offset/skip | 3 + tests/tooldb/db-line-length/skip | 3 + - 14 files changed, 659 insertions(+), 119 deletions(-) + 21 files changed, 960 insertions(+), 124 deletions(-) + create mode 100644 tests/tool-table-load/.gitignore + create mode 100755 tests/tool-table-load/checkresult + create mode 100644 tests/tool-table-load/common.py + create mode 100755 tests/tool-table-load/crlf-ui.py + create mode 100755 tests/tool-table-load/garbage-ui.py + create mode 100644 tests/tool-table-load/test.ini + create mode 100755 tests/tool-table-load/test.sh create mode 100644 tests/tooldb/db-g10-offset/skip create mode 100644 tests/tooldb/db-line-length/skip @@ -184,10 +198,10 @@ index cf8bc14..b40c76d 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a16de26..f8ffe7c 100644 +index 2a3c750..ae1462b 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1244,7 +1244,18 @@ static int emcTaskPlan(void) +@@ -1263,7 +1263,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -207,7 +221,7 @@ index a16de26..f8ffe7c 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO emcTaskQueueCommand(std::make_unique(*static_cast(emcCommand))); -@@ -1373,6 +1384,18 @@ static int emcTaskPlan(void) +@@ -1392,6 +1403,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -226,7 +240,7 @@ index a16de26..f8ffe7c 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO -@@ -1498,6 +1521,18 @@ static int emcTaskPlan(void) +@@ -1517,6 +1540,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -245,7 +259,7 @@ index a16de26..f8ffe7c 100644 // otherwise we can't handle it default: -@@ -1833,6 +1868,18 @@ static int emcTaskPlan(void) +@@ -1852,6 +1887,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -264,7 +278,7 @@ index a16de26..f8ffe7c 100644 // otherwise we can't handle it default: -@@ -1936,6 +1983,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1955,6 +2002,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) case EMC_TOOL_LOAD_TOOL_TABLE_TYPE: case EMC_TOOL_SET_OFFSET_TYPE: @@ -273,7 +287,7 @@ index a16de26..f8ffe7c 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2568,6 +2617,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2587,6 +2636,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emc_tool_set_offset_msg->orientation); break; @@ -288,7 +302,7 @@ index a16de26..f8ffe7c 100644 case EMC_TOOL_SET_NUMBER_TYPE: emc_tool_set_number_msg = reinterpret_cast(cmd); retval = emcToolSetNumber(emc_tool_set_number_msg->tool); -@@ -3042,6 +3099,8 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3059,6 +3116,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: @@ -298,10 +312,18 @@ index a16de26..f8ffe7c 100644 case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index 6ba96b9..27c32fe 100644 +index 72b698b4..07b68b2 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc -@@ -26,6 +26,7 @@ +@@ -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" @@ -309,7 +331,7 @@ index 6ba96b9..27c32fe 100644 using namespace linuxcnc; -@@ -122,6 +123,8 @@ int emcToolSetOffset(int pocket, int toolno, const EmcPose& offset, +@@ -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); } @@ -318,7 +340,7 @@ index 6ba96b9..27c32fe 100644 // 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 +208,10 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : +@@ -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()); @@ -338,7 +360,7 @@ index 6ba96b9..27c32fe 100644 } } -@@ -226,14 +224,6 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : +@@ -226,14 +225,6 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : #endif //} tooldata_init(random_toolchanger); @@ -353,7 +375,7 @@ index 6ba96b9..27c32fe 100644 emcioStatus.status = RCS_STATUS::DONE;//TODO?? emcioStatus.tool.pocketPrepped = -1; -@@ -246,7 +236,7 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : +@@ -246,7 +237,7 @@ Task::Task(EMC_IO_STAT & emcioStatus_in) : } } @@ -362,18 +384,25 @@ index 6ba96b9..27c32fe 100644 rcs_print_error("can't load tool table.\n"); } -@@ -409,6 +399,10 @@ void Task::reload_tool_number(int toolno) { +@@ -417,7 +408,16 @@ 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 && 0 != tooldata_load(tooltable_filename)) { ++ // the machine starts without the table, and the file is not saved ++ // over until a table loads ++ emcOperatorError("can't load tool table %s: no tools until it is " ++ "corrected and reloaded", tooltable_filename); ++ } reload_tool_number(emcioStatus.tool.toolInSpindle); -@@ -581,10 +575,28 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE + if (0 != iniTool(emc_inifile)) { +@@ -589,10 +589,38 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE return 0; } @@ -381,6 +410,13 @@ index 6ba96b9..27c32fe 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 @@ -396,6 +432,9 @@ index 6ba96b9..27c32fe 100644 + (emcioStatus.tool.toolInSpindle > 0 && + find_tool(loaded, loaded_last, emcioStatus.tool.toolInSpindle, + random_toolchanger) < 0)) { ++ // the table in memory stays, but the file it is saved to now holds ++ // something else: it is not saved over until a table loads ++ if (same_file(file, tooltable_filename)) tooldata_set_refused_lines(true); + return -1; + } + if (tooldata_replace(loaded, loaded_last)) return -1; @@ -403,7 +442,7 @@ index 6ba96b9..27c32fe 100644 reload_tool_number(emcioStatus.tool.toolInSpindle); return 0; } -@@ -626,9 +638,10 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -634,9 +662,10 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, UNEXPECTED_MSG; } bool stored = (0 == tooldata_save(tooltable_filename)); @@ -415,7 +454,7 @@ index 6ba96b9..27c32fe 100644 int pno = idx; // for random_toolchanger if (!random_toolchanger) { pno = tdata.pocketno; } if (tooldata_db_notify(TOOL_OFFSET,toolno,pno,tdata)) { -@@ -648,6 +661,191 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -656,6 +685,191 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, return 0; } @@ -608,7 +647,7 @@ index 6ba96b9..27c32fe 100644 { int idx; diff --git a/src/emc/task/taskclass.hh b/src/emc/task/taskclass.hh -index 75572ea..0a065c5 100644 +index 509f11f..d9afc98 100644 --- a/src/emc/task/taskclass.hh +++ b/src/emc/task/taskclass.hh @@ -75,6 +75,8 @@ public: @@ -631,7 +670,7 @@ index 75572ea..0a065c5 100644 }; diff --git a/src/emc/tooldata/tooldata.hh b/src/emc/tooldata/tooldata.hh -index db3e6b7..226f4bf 100644 +index db3e6b7..0b28e0e 100644 --- a/src/emc/tooldata/tooldata.hh +++ b/src/emc/tooldata/tooldata.hh @@ -58,6 +58,8 @@ void tooldata_reset(void); @@ -653,8 +692,8 @@ index db3e6b7..226f4bf 100644 + CANON_TOOL_TABLE *table, + int *last_index, + bool *refused_lines); -+// the published table was loaded with refused lines: saves are refused -+// until a table without them is loaded ++// the published table was loaded with refused lines, or the table file ++// did not load: saves are refused until a table without them is loaded +void tooldata_set_refused_lines(bool refused); int tooldata_save(const char *filename); @@ -665,7 +704,7 @@ index db3e6b7..226f4bf 100644 //---------------------------------------------------------- //mmap specific diff --git a/src/emc/tooldata/tooldata_common.cc b/src/emc/tooldata/tooldata_common.cc -index ceefe9b..2dcf5e5 100644 +index ceefe9b..a0ca625 100644 --- a/src/emc/tooldata/tooldata_common.cc +++ b/src/emc/tooldata/tooldata_common.cc @@ -24,7 +24,12 @@ @@ -707,7 +746,31 @@ index ceefe9b..2dcf5e5 100644 void tooldata_init(bool random_toolchanger) { -@@ -206,7 +230,7 @@ int tooldata_read_entry(const char *input_line) +@@ -92,12 +116,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 +237,7 @@ int tooldata_read_entry(const char *input_line) if (valid) { CANON_TOOL_TABLE tdata = tooldata_entry_init(); // verify no prior tool in pocket @@ -716,7 +779,7 @@ index ceefe9b..2dcf5e5 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__); -@@ -233,7 +257,7 @@ int tooldata_read_entry(const char *input_line) +@@ -233,7 +264,7 @@ int tooldata_read_entry(const char *input_line) ); } } @@ -725,15 +788,15 @@ index ceefe9b..2dcf5e5 100644 UNEXPECTED_MSG; } } else { -@@ -323,31 +347,27 @@ int tooldata_format_toolline (int idx, +@@ -323,31 +354,27 @@ 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 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) @@ -771,7 +834,7 @@ index ceefe9b..2dcf5e5 100644 // open tool table file if (NULL == (fp = fopen(filename, "r"))) { -@@ -356,16 +376,17 @@ int tooldata_load(const char *filename) +@@ -356,16 +383,17 @@ int tooldata_load(const char *filename) return -1; } @@ -794,7 +857,7 @@ index ceefe9b..2dcf5e5 100644 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 -@@ -383,7 +404,7 @@ int tooldata_load(const char *filename) +@@ -383,7 +411,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); @@ -803,7 +866,7 @@ index ceefe9b..2dcf5e5 100644 continue; } strcpy(orig_line, input_line); -@@ -391,37 +412,66 @@ int tooldata_load(const char *filename) +@@ -391,37 +419,74 @@ 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) { @@ -858,7 +921,15 @@ index ceefe9b..2dcf5e5 100644 + int last_index = 0; + bool refused_lines = false; + if (tooldata_load_snapshot(filename, staged, &last_index, &refused_lines) || -+ tooldata_replace(staged, last_index)) return -1; ++ 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); ++ } ++ return -1; ++ } + tooldata_set_refused_lines(refused_lines); return 0; } // tooldata_load() @@ -879,7 +950,7 @@ index ceefe9b..2dcf5e5 100644 if (db_mode == DB_ACTIVE && idx != 0 ) { return 0; } -@@ -433,63 +483,82 @@ static int write_tool_line(std::string &table,int idx) +@@ -433,63 +498,82 @@ static int write_tool_line(std::string &table,int idx) tdata,theline)) { return -1; } @@ -922,7 +993,7 @@ index ceefe9b..2dcf5e5 100644 + last_index >= CANON_POCKETS_MAX || db_mode == DB_ACTIVE) return -1; + 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", ++ "would be lost; correct them and reload the tool table\n", + filename); + return -1; } @@ -1253,6 +1324,313 @@ index f333925..a7ee61e 100644 + memcpy(the_table, table, CANON_POCKETS_MAX * sizeof(*table)); + return 0; +} +diff --git a/tests/tool-table-load/.gitignore b/tests/tool-table-load/.gitignore +new file mode 100644 +index 0000000..76e1adf +--- /dev/null ++++ b/tests/tool-table-load/.gitignore +@@ -0,0 +1,4 @@ ++sim.var ++sim.var.bak ++tool.tbl ++run.ini +diff --git a/tests/tool-table-load/checkresult b/tests/tool-table-load/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/tool-table-load/common.py b/tests/tool-table-load/common.py +new file mode 100644 +index 0000000..69f291e +--- /dev/null ++++ b/tests/tool-table-load/common.py +@@ -0,0 +1,76 @@ ++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 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() +diff --git a/tests/tool-table-load/crlf-ui.py b/tests/tool-table-load/crlf-ui.py +new file mode 100755 +index 0000000..f2c8011 +--- /dev/null ++++ b/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/tests/tool-table-load/garbage-ui.py b/tests/tool-table-load/garbage-ui.py +new file mode 100755 +index 0000000..89099f9 +--- /dev/null ++++ b/tests/tool-table-load/garbage-ui.py +@@ -0,0 +1,56 @@ ++#!/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, the machine has no tools, and the file is ++not saved over. A table loaded later lifts that; a reload of the file that ++fails keeps the table in memory but again keeps the file from being saved ++over.""" ++ ++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())) ++before = table() ++ ++print("*** a G10 edit finds no tool and does not touch the file") ++mdi("g10 l1 p1 z5") ++if table() != before: ++ fail("the table file was rewritten:\n" + table()) ++ ++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") ++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() ++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/tests/tool-table-load/test.ini b/tests/tool-table-load/test.ini +new file mode 100644 +index 0000000..9338ce7 +--- /dev/null ++++ b/tests/tool-table-load/test.ini +@@ -0,0 +1,84 @@ ++# A metric lathe whose tool table is written by test.sh for each run. ++ ++[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/tests/tool-table-load/test.sh b/tests/tool-table-load/test.sh +new file mode 100755 +index 0000000..6819e71 +--- /dev/null ++++ b/tests/tool-table-load/test.sh +@@ -0,0 +1,16 @@ ++#!/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 ++sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./crlf-ui.py#' test.ini > run.ini ++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 ++sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./garbage-ui.py#' test.ini > run.ini ++linuxcnc -r run.ini diff --git a/tests/toolchanger/reload-tool/non-random/test-ui.py b/tests/toolchanger/reload-tool/non-random/test-ui.py index fca46c3..445e5ee 100755 --- a/tests/toolchanger/reload-tool/non-random/test-ui.py 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 88ea0c9..2c326b1 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 @@ -40,10 +40,10 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index f8ffe7c..7923ce4 100644 +index ae1462b..f3bcb8e 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1016,7 +1016,7 @@ static void emcTaskStopProgress() +@@ -1035,7 +1035,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]; diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index b772475..4495e51 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -40,7 +40,7 @@ other motion-logger tests. src/emc/motion-logger/motion-logger.c | 22 + src/emc/motion/axis.c | 2 +- src/emc/motion/command.c | 374 +++++++++++- - src/emc/motion/control.c | 550 ++++++++++++++++-- + src/emc/motion/control.c | 559 ++++++++++++++++-- src/emc/motion/mot_priv.h | 21 + src/emc/motion/motion.c | 16 + src/emc/motion/motion.h | 60 +- @@ -49,7 +49,7 @@ other motion-logger tests. 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 | 230 +++++++- + src/emc/task/emctaskmain.cc | 269 ++++++++- src/emc/task/task.hh | 1 + src/emc/task/taskintf.cc | 94 ++- src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + @@ -95,7 +95,7 @@ other motion-logger tests. tests/runtime-availability/test.ini.in | 3 + tests/runtime-availability/test.sh | 5 + tests/runtime-availability/tool.tbl | 0 - 64 files changed, 2806 insertions(+), 83 deletions(-) + 64 files changed, 2846 insertions(+), 91 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 @@ -1045,7 +1045,7 @@ index ead94cb..3734dae 100644 } break; diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index f22ab9b..8d4c3e8 100644 +index f22ab9b..ff24751 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c @@ -45,6 +45,9 @@ static int switchkins_type = 0; @@ -1160,7 +1160,7 @@ index f22ab9b..8d4c3e8 100644 } // a fault was signalled during a spindle-orient in progress -@@ -629,6 +647,391 @@ static void process_inputs(void) +@@ -629,6 +647,400 @@ static void process_inputs(void) } } @@ -1375,6 +1375,7 @@ index f22ab9b..8d4c3e8 100644 + * which also owns the FREE dip and mode restoration. */ + a->state = EMCMOT_AVAILABILITY_HOMING; + 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); @@ -1388,11 +1389,19 @@ index f22ab9b..8d4c3e8 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(). */ @@ -1552,7 +1561,7 @@ index f22ab9b..8d4c3e8 100644 static void joint_jog_abort_all(bool immediate) { int jNum; -@@ -691,7 +1094,7 @@ static void do_forward_kins(void) +@@ -691,7 +1103,7 @@ static void do_forward_kins(void) at the traj rate */ double joint_pos[EMCMOT_MAX_JOINTS] = {0,}; @@ -1561,7 +1570,7 @@ index f22ab9b..8d4c3e8 100644 emcmot_joint_t *joint; /* copy joint position feedback to local array */ -@@ -873,7 +1276,9 @@ static void check_for_faults(void) +@@ -873,7 +1285,9 @@ static void check_for_faults(void) } /* check for spindle ampfifier errors */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1572,7 +1581,7 @@ index f22ab9b..8d4c3e8 100644 reportError(_("spindle %d amplifier fault"), spindle_num); emcmotInternal->enabling = 0; } -@@ -945,6 +1350,7 @@ static void set_operating_mode(void) +@@ -945,6 +1359,7 @@ static void set_operating_mode(void) /* check for disabling */ if (!emcmotInternal->enabling && GET_MOTION_ENABLE_FLAG()) { @@ -1580,7 +1589,7 @@ index f22ab9b..8d4c3e8 100644 /* clear out the motion emcmotInternal->coord_tp and interpolators */ tpClear(&emcmotInternal->coord_tp); for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -999,8 +1405,9 @@ static void set_operating_mode(void) +@@ -999,8 +1414,9 @@ static void set_operating_mode(void) } } SET_MOTION_ENABLE_FLAG(1); @@ -1592,7 +1601,7 @@ index f22ab9b..8d4c3e8 100644 } /* check for entering teleop mode */ -@@ -1028,7 +1435,7 @@ static void set_operating_mode(void) +@@ -1028,7 +1444,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); @@ -1601,7 +1610,7 @@ index f22ab9b..8d4c3e8 100644 kinematicsForward(positions, &emcmotStatus->carte_pos_cmd, &fflags, &iflags); // entering teleop (INPOS), remove ext offsets -@@ -1072,7 +1479,7 @@ static void set_operating_mode(void) +@@ -1072,7 +1488,7 @@ static void set_operating_mode(void) emcmotStatus->overrideLimitMask = 0; SET_MOTION_COORD_FLAG(1); SET_MOTION_TELEOP_FLAG(0); @@ -1610,7 +1619,7 @@ index f22ab9b..8d4c3e8 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1092,7 +1499,7 @@ static void set_operating_mode(void) +@@ -1092,7 +1508,7 @@ static void set_operating_mode(void) } SET_MOTION_COORD_FLAG(0); SET_MOTION_TELEOP_FLAG(0); @@ -1619,7 +1628,7 @@ index f22ab9b..8d4c3e8 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1127,10 +1534,17 @@ static void handle_jjogwheels(void) +@@ -1127,10 +1543,17 @@ static void handle_jjogwheels(void) /* point to joint data */ joint_data = &(emcmot_hal_data->joint[joint_num]); joint = &joints[joint_num]; @@ -1641,7 +1650,7 @@ index f22ab9b..8d4c3e8 100644 // disallow accel bogus fractions rtapi_real jjog_accel_fraction = hal_get_real(joint_data->jjog_accel_fraction); -@@ -1145,6 +1559,7 @@ static void handle_jjogwheels(void) +@@ -1145,6 +1568,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; @@ -1649,7 +1658,7 @@ index f22ab9b..8d4c3e8 100644 /* initialization complete */ if ( first_pass ) { continue; -@@ -1276,6 +1691,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, +@@ -1276,6 +1700,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, reportError(_("kinematicsInverse gave non-finite joint location on joint %d"), n); return -1; } @@ -1666,7 +1675,7 @@ index f22ab9b..8d4c3e8 100644 cubics[n] = joints[n].cubic; if (cubicNeedNextPoint(&cubics[n]) && cubicAddPoint(&cubics[n], positions[n]) != 0) { -@@ -1365,7 +1790,10 @@ static void get_pos_cmds(long period) +@@ -1365,7 +1799,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]; @@ -1678,7 +1687,7 @@ index f22ab9b..8d4c3e8 100644 /* if joint is not active, skip it */ continue; } -@@ -1521,8 +1949,7 @@ static void get_pos_cmds(long period) +@@ -1521,8 +1958,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1688,7 +1697,7 @@ index f22ab9b..8d4c3e8 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1583,8 +2010,7 @@ static void get_pos_cmds(long period) +@@ -1583,8 +2019,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1698,7 +1707,7 @@ index f22ab9b..8d4c3e8 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1595,6 +2021,8 @@ static void get_pos_cmds(long period) +@@ -1595,6 +2030,8 @@ static void get_pos_cmds(long period) &joint->vel_cmd, &joint->acc_cmd, &joint->jerk_cmd); } @@ -1707,7 +1716,7 @@ index f22ab9b..8d4c3e8 100644 /* END OF OUTPUT KINS */ -@@ -1611,10 +2039,13 @@ static void get_pos_cmds(long period) +@@ -1611,10 +2048,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 */ @@ -1722,7 +1731,7 @@ index f22ab9b..8d4c3e8 100644 /* save old command */ joint->pos_cmd = joint->pos_fb; /* set joint velocity and acceleration to zero */ -@@ -2002,8 +2433,6 @@ static void output_to_hal(void) +@@ -2002,8 +2442,6 @@ static void output_to_hal(void) double inch_mult; emcmot_joint_t *joint; joint_hal_t *joint_data; @@ -1731,7 +1740,7 @@ index f22ab9b..8d4c3e8 100644 /* output machine info to HAL for scoping, etc */ hal_set_bool(emcmot_hal_data->motion_enabled, GET_MOTION_ENABLE_FLAG()); -@@ -2045,6 +2474,9 @@ static void output_to_hal(void) +@@ -2045,6 +2483,9 @@ static void output_to_hal(void) for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ double speed; @@ -1741,7 +1750,7 @@ index f22ab9b..8d4c3e8 100644 if(emcmotStatus->spindle_status[spindle_num].css_factor) { double denom = fabs(emcmotStatus->spindle_status[spindle_num].xoffset - emcmotStatus->carte_pos_cmd.tran.x); -@@ -2079,14 +2511,22 @@ static void output_to_hal(void) +@@ -2079,14 +2520,22 @@ static void output_to_hal(void) } } @@ -1768,7 +1777,7 @@ index f22ab9b..8d4c3e8 100644 // What is this for? Docs don't say hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps, emcmotStatus->spindle_status[spindle_num].speed / 60.); -@@ -2147,6 +2587,13 @@ static void output_to_hal(void) +@@ -2147,6 +2596,13 @@ static void output_to_hal(void) /* two way handshaking for the spindle encoder */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1782,7 +1791,7 @@ index f22ab9b..8d4c3e8 100644 if(emcmotStatus->spindle_status[spindle_num].spindle_index_enable && !old_motion_index[spindle_num]) { hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable, 1); -@@ -2189,7 +2636,14 @@ static void output_to_hal(void) +@@ -2189,7 +2645,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); @@ -2230,7 +2239,7 @@ index 90cc136..5a1e60e 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 7923ce4..170f044 100644 +index f3bcb8e..c465732 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -172,6 +172,61 @@ volatile int done; @@ -2311,7 +2320,38 @@ index 7923ce4..170f044 100644 } return 1; } -@@ -922,6 +982,13 @@ static bool emcTaskArmSingleStep() +@@ -452,6 +512,10 @@ static EMC_TRAJ_MODE homingPriorMode = EMC_TRAJ_MODE::FREE; // mode to restore o + // 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 +@@ -463,6 +527,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; +@@ -922,6 +999,13 @@ static bool emcTaskArmSingleStep() return true; } @@ -2325,7 +2365,7 @@ index 7923ce4..170f044 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1143,6 +1210,31 @@ static int emcTaskPlan(void) +@@ -1162,6 +1246,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2357,7 +2397,7 @@ index 7923ce4..170f044 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -@@ -1162,6 +1254,36 @@ static int emcTaskPlan(void) +@@ -1181,6 +1290,36 @@ static int emcTaskPlan(void) return 0; } @@ -2394,7 +2434,7 @@ index 7923ce4..170f044 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1674,9 +1796,7 @@ static int emcTaskPlan(void) +@@ -1693,9 +1832,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2405,7 +2445,7 @@ index 7923ce4..170f044 100644 break; // otherwise we can't handle it -@@ -1939,6 +2059,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1958,6 +2095,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: @@ -2414,7 +2454,26 @@ index 7923ce4..170f044 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2174,6 +2296,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2164,6 +2303,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + emcTrajSetMode(EMC_TRAJ_MODE::FREE); + } + homingWaitJoint = target_joint; ++ homingRestoreAfterAvailability = false; + homingStarted = false; + homingIssueTime = etime(); + homingWaiting = true; +@@ -2177,9 +2317,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; +@@ -2193,6 +2331,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2439,7 +2498,7 @@ index 7923ce4..170f044 100644 case EMC_JOG_CONT_TYPE: jog_cont_msg = reinterpret_cast(cmd); retval = emcJogCont(jog_cont_msg->joint_or_axis, -@@ -2541,6 +2681,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2560,6 +2716,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcSpindleOff(spindle_off_msg->spindle, spindle_off_msg->wait_for_spindle_at_speed); break; @@ -2466,7 +2525,7 @@ index 7923ce4..170f044 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -2998,7 +3158,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3015,7 +3191,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2481,7 +2540,7 @@ index 7923ce4..170f044 100644 if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -3113,6 +3280,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3130,6 +3313,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2493,7 +2552,7 @@ index 7923ce4..170f044 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -3195,6 +3367,12 @@ static int emcTaskExecute(void) +@@ -3212,6 +3400,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2506,7 +2565,7 @@ index 7923ce4..170f044 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3313,11 +3491,49 @@ static int emcTaskExecute(void) +@@ -3330,11 +3524,59 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: @@ -2517,6 +2576,11 @@ index 7923ce4..170f044 100644 + !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; @@ -2532,6 +2596,11 @@ index 7923ce4..170f044 100644 + 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; @@ -2556,7 +2625,21 @@ index 7923ce4..170f044 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } -@@ -3532,7 +3748,9 @@ static int emcTaskExecute(void) +@@ -3479,11 +3721,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? +@@ -3549,7 +3788,9 @@ static int emcTaskExecute(void) "coordinated motion until every joint is homed")); emcStatus->task.execState = EMC_TASK_EXEC::ERROR; } else if (success) { diff --git a/linuxcnc-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index 83d6945..bad297d 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -14,8 +14,8 @@ homing ends as it does during G28.2. 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_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 + @@ -28,17 +28,17 @@ homing ends as it does during G28.2. tests/availability-mcodes-regressions/README | 9 + .../checkresult | 5 + .../availability-mcodes-regressions/step.ngc | 6 + - .../test-ui.py | 74 ++++++++ + .../test-ui.py | 74 +++++++ .../test.ini.in | 9 + tests/availability-mcodes-regressions/test.sh | 6 + tests/availability-mcodes/.gitignore | 2 + - tests/availability-mcodes/README | 10 + + tests/availability-mcodes/README | 12 + 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 | 171 ++++++++++++++++++ + tests/availability-mcodes/test-ui.py | 205 ++++++++++++++++++ tests/availability-mcodes/test.ini | 1 + tests/availability-mcodes/test.sh | 5 + tests/availability-mcodes/timeout.ngc | 4 + @@ -47,7 +47,7 @@ homing ends as it does during G28.2. 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.cc | 29 +++ .../availability-mcodes/execute-status.py | 30 +++ tests/interp/availability-mcodes/expected | 0 .../availability-mcodes/fractional-joint.ngc | 2 + @@ -71,10 +71,10 @@ homing ends as it does during G28.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 ++++++++ + tests/interp/availability-mcodes/test.sh | 80 +++++++ .../availability-mcodes/valid-joint.ngc | 3 + .../availability-mcodes/valid-spindle.ngc | 3 + - 65 files changed, 664 insertions(+), 7 deletions(-) + 65 files changed, 703 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 @@ -659,15 +659,17 @@ index 0000000..425d52b +!/base.ini diff --git a/tests/availability-mcodes/README b/tests/availability-mcodes/README new file mode 100644 -index 0000000..1f02b91 +index 0000000..bbb8ad6 --- /dev/null +++ b/tests/availability-mcodes/README -@@ -0,0 +1,10 @@ +@@ -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 @@ -727,10 +729,10 @@ index 0000000..a180055 +M2 diff --git a/tests/availability-mcodes/test-ui.py b/tests/availability-mcodes/test-ui.py new file mode 100755 -index 0000000..801530b +index 0000000..0f3d8df --- /dev/null +++ b/tests/availability-mcodes/test-ui.py -@@ -0,0 +1,171 @@ +@@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +import os +import time @@ -898,6 +900,40 @@ index 0000000..801530b +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 ACK completes the ++# handshake, 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_STOPPED, 'Stop before ACK') ++ else: ++ wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED, 'Pause before ACK') ++ pin('joint.2.availability-ack', 1) ++ 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' @@ -979,15 +1015,18 @@ index 0000000..a851ea0 +M2 diff --git a/tests/interp/availability-mcodes/execute-status.cc b/tests/interp/availability-mcodes/execute-status.cc new file mode 100644 -index 0000000..554485e +index 0000000..f2f707c --- /dev/null +++ b/tests/interp/availability-mcodes/execute-status.cc -@@ -0,0 +1,26 @@ +@@ -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); 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 ad4c7b9..5275e82 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -16,18 +16,18 @@ 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/command.c | 23 ++- src/emc/motion/control.c | 19 +-- - src/emc/motion/homing.c | 121 ++++++++-------- - src/emc/motion/homing.h | 3 + - src/hal/components/homecomp.comp | 14 +- + src/emc/motion/homing.c | 131 +++++++++------- + src/emc/motion/homing.h | 7 + + src/hal/components/homecomp.comp | 17 +- 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/homing.hal | 16 ++ + tests/homing-concurrent/test-ui.py | 235 ++++++++++++++++++++++++++++ + tests/homing-concurrent/test.ini | 170 ++++++++++++++++++++ tests/homing-concurrent/test.sh | 4 + tests/homing-concurrent/tool.tbl | 0 - 11 files changed, 462 insertions(+), 78 deletions(-) + 11 files changed, 547 insertions(+), 78 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 @@ -36,10 +36,10 @@ so the new concurrency checks never refuse it. create mode 100644 tests/homing-concurrent/tool.tbl diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index 3734dae..3472aa9 100644 +index 3734dae..35eee04 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -1746,8 +1746,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1746,10 +1746,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) joint_num); return; } @@ -57,12 +57,25 @@ index 3734dae..3472aa9 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 8d4c3e8..e26daea 100644 +index ff24751..ca7d5cd 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2719,18 +2719,13 @@ static void update_status(void) +@@ -2728,18 +2728,13 @@ static void update_status(void) } #endif joint_status->flag = joint->flag; @@ -89,7 +102,7 @@ index 8d4c3e8..e26daea 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 a2b6c9b..c63be34 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) @@ -252,7 +265,22 @@ index a2b6c9b..c63be34 100644 static int base_get_home_sequence(int jno) { return H[jno].home_sequence; } -@@ -1512,15 +1498,21 @@ static int base_1joint_state_machine(int joint_num) +@@ -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; @@ -277,7 +305,7 @@ index a2b6c9b..c63be34 100644 H[i].homing = 0; H[i].homed = 0; H[i].joint_in_sequence = 0; -@@ -1530,6 +1522,7 @@ static int base_1joint_state_machine(int joint_num) +@@ -1530,6 +1530,7 @@ static int base_1joint_state_machine(int joint_num) } immediate_state = 1; break; @@ -285,7 +313,7 @@ index a2b6c9b..c63be34 100644 default: /* should never get here */ -@@ -1544,31 +1537,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() @@ -344,7 +372,15 @@ index a2b6c9b..c63be34 100644 } // base_do_homing() /*********************************************************************** -@@ -1606,6 +1611,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(); } @@ -352,7 +388,15 @@ index a2b6c9b..c63be34 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); } -@@ -1664,6 +1670,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); @@ -361,7 +405,7 @@ index a2b6c9b..c63be34 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 b6a51c4..dc52d99 100644 +index b6a51c4..4d518b9 100644 --- a/src/emc/motion/homing.h +++ b/src/emc/motion/homing.h @@ -96,6 +96,9 @@ bool get_allhomed(void); @@ -374,11 +418,30 @@ index b6a51c4..dc52d99 100644 // per-joint information: int get_home_sequence(int jno); //return s +@@ -109,6 +112,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 9096469..e728e11 100644 +index 9096469..ea04e05 100644 --- a/src/hal/components/homecomp.comp +++ b/src/hal/components/homecomp.comp -@@ -240,6 +240,7 @@ int get_home_sequence(int jno) { (void)jno; return 0; } +@@ -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; } @@ -386,7 +449,7 @@ index 9096469..e728e11 100644 bool get_index_enable(int jno) { (void)jno; return 0; } void read_homing_in_pins(int njoints) { rd(njoints); } -@@ -343,12 +344,12 @@ void write_homing_out_pins(int njoints) +@@ -343,12 +345,12 @@ void write_homing_out_pins(int njoints) bool do_homing(void) { @@ -401,7 +464,7 @@ index 9096469..e728e11 100644 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,13 +358,10 @@ bool do_homing(void) +@@ -357,17 +359,15 @@ bool do_homing(void) H[jno].homing = 0; H[jno].home_state = HOME_IDLE; } else { @@ -417,7 +480,12 @@ index 9096469..e728e11 100644 } bool get_allhomed(void) { return base_get_allhomed(); } -@@ -375,6 +373,7 @@ int get_home_sequence(int jno) { return base_get_home_sequence(jn + 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(); } @@ -425,7 +493,15 @@ index 9096469..e728e11 100644 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 +416,7 @@ EXPORT_SYMBOL(get_home_sequence); +@@ -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); @@ -444,12 +520,12 @@ index 0000000..9c14eb3 +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 0000000..2eeb379 +index 0000000..5d4eaa3 --- /dev/null +++ b/tests/homing-concurrent/homing.hal -@@ -0,0 +1,14 @@ +@@ -0,0 +1,16 @@ +loadrt [KINS]KINEMATICS -+loadrt [EMCMOT]EMCMOT servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS unlock_joints_mask=31 ++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 @@ -459,15 +535,17 @@ index 0000000..2eeb379 +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/tests/homing-concurrent/test-ui.py b/tests/homing-concurrent/test-ui.py new file mode 100755 -index 0000000..6f64d30 +index 0000000..3a0aac0 --- /dev/null +++ b/tests/homing-concurrent/test-ui.py -@@ -0,0 +1,217 @@ +@@ -0,0 +1,235 @@ +#!/usr/bin/env python3 + +import time @@ -487,11 +565,11 @@ index 0000000..6f64d30 +status = linuxcnc.stat() +errors = linuxcnc.error_channel() +component = hal.component("homing-concurrent-test") -+for joint in range(5): ++for joint in range(7): + component.newpin("is-unlocked-%d" % joint, hal.HAL_BOOL, hal.HAL_OUT) -+component.newpin("joint-0-home-switch", hal.HAL_BOOL, hal.HAL_OUT) ++component.newpin("joint-5-home-switch", hal.HAL_BOOL, hal.HAL_OUT) +component.ready() -+for joint in range(5): ++for joint in range(7): + signal = "homing-concurrent-test-unlocked-%d" % joint + hal.new_sig(signal, hal.HAL_BOOL) + hal.connect( @@ -499,12 +577,12 @@ index 0000000..6f64d30 + signal, + ) + hal.connect("joint.%d.is-unlocked" % joint, signal) -+hal.new_sig("homing-concurrent-test-joint-0-home-switch", hal.HAL_BOOL) ++hal.new_sig("homing-concurrent-test-joint-5-home-switch", hal.HAL_BOOL) +hal.connect( -+ "homing-concurrent-test.joint-0-home-switch", -+ "homing-concurrent-test-joint-0-home-switch", ++ "homing-concurrent-test.joint-5-home-switch", ++ "homing-concurrent-test-joint-5-home-switch", +) -+hal.connect("joint.0.home-sw-in", "homing-concurrent-test-joint-0-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): @@ -625,24 +703,42 @@ index 0000000..6f64d30 +) +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") + ++# 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) @@ -672,7 +768,7 @@ index 0000000..6f64d30 +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: all(status.homed[:7]), "HOME ALL completion") +wait( + lambda: status.motion_mode == linuxcnc.TRAJ_MODE_TELEOP, + "automatic teleop transition", @@ -687,10 +783,10 @@ index 0000000..6f64d30 +print("concurrent homing regression passed") diff --git a/tests/homing-concurrent/test.ini b/tests/homing-concurrent/test.ini new file mode 100644 -index 0000000..49d5777 +index 0000000..ffae470 --- /dev/null +++ b/tests/homing-concurrent/test.ini -@@ -0,0 +1,133 @@ +@@ -0,0 +1,170 @@ +[EMC] +VERSION = 1.1 +MACHINE = homing-concurrent @@ -718,16 +814,16 @@ index 0000000..49d5777 +HALFILE = homing.hal + +[TRAJ] -+AXES = 5 -+COORDINATES = XYZUV ++AXES = 7 ++COORDINATES = XYZUVWA +LINEAR_UNITS = mm +ANGULAR_UNITS = degree +DEFAULT_LINEAR_VELOCITY = 10 +MAX_LINEAR_VELOCITY = 50 + +[KINS] -+KINEMATICS = trivkins coordinates=XYZUV -+JOINTS = 5 ++KINEMATICS = trivkins coordinates=XYZUVWA ++JOINTS = 7 + +[AXIS_X] +MIN_LIMIT = -100 @@ -759,12 +855,23 @@ index 0000000..49d5777 +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_IS_SHARED = 1 +HOME_SEQUENCE = 1 +MAX_VELOCITY = 50 +MAX_ACCELERATION = 500 @@ -824,6 +931,32 @@ index 0000000..49d5777 +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/tests/homing-concurrent/test.sh b/tests/homing-concurrent/test.sh new file mode 100755 index 0000000..3e0b516 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 c1fc4af..d18929d 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 @@ -306,7 +306,7 @@ index 5d61f0b..f1ce1d7 100644 #ifdef __cplusplus diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index 3472aa9..d9f17ac 100644 +index 35eee04..f434080 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -157,6 +157,19 @@ STATIC int spindle_range_is_available(int first, int last) @@ -353,10 +353,10 @@ index 3472aa9..d9f17ac 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 e26daea..2bc4061 100644 +index ca7d5cd..5a8ba71 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1990,7 +1990,14 @@ static void get_pos_cmds(long period) +@@ -1999,7 +1999,14 @@ static void get_pos_cmds(long period) break; case EMCMOT_MOTION_TELEOP: @@ -695,10 +695,10 @@ index c03bfc3..05a29fe 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 170f044..b69eb5a 100644 +index c465732..d06c467 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1426,6 +1426,7 @@ static int emcTaskPlan(void) +@@ -1462,6 +1462,7 @@ static int emcTaskPlan(void) case EMC_JOINT_HOME_TYPE: case EMC_JOINT_UNHOME_TYPE: case EMC_JOG_CONT_TYPE: @@ -706,7 +706,7 @@ index 170f044..b69eb5a 100644 case EMC_JOG_INCR_TYPE: case EMC_JOG_ABS_TYPE: case EMC_JOG_STOP_TYPE: -@@ -2327,6 +2328,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2362,6 +2363,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; 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 index 3b12ee5..a05ab1d 100644 --- 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 @@ -33,17 +33,17 @@ remap with each of E-stop, machine off, interpreter re-init and a mode change, and checks that milltask survives and MDI works afterwards. --- src/emc/task/emctask.cc | 4 + - src/emc/task/emctaskmain.cc | 5 +- + src/emc/task/emctaskmain.cc | 7 +- src/emc/task/task.hh | 1 + - tests/remap/mdi-remap-abort/README | 12 +++ + tests/remap/mdi-remap-abort/README | 17 +++ tests/remap/mdi-remap-abort/checkresult | 2 + tests/remap/mdi-remap-abort/m400.ngc | 5 + tests/remap/mdi-remap-abort/remap.py | 9 ++ - tests/remap/mdi-remap-abort/test-ui.py | 138 ++++++++++++++++++++++++ - tests/remap/mdi-remap-abort/test.ini | 101 +++++++++++++++++ + tests/remap/mdi-remap-abort/test-ui.py | 186 ++++++++++++++++++++++++ + tests/remap/mdi-remap-abort/test.ini | 101 +++++++++++++ tests/remap/mdi-remap-abort/test.sh | 2 + tests/remap/mdi-remap-abort/toplevel.py | 1 + - 11 files changed, 279 insertions(+), 1 deletion(-) + 11 files changed, 334 insertions(+), 1 deletion(-) create mode 100644 tests/remap/mdi-remap-abort/README create mode 100755 tests/remap/mdi-remap-abort/checkresult create mode 100644 tests/remap/mdi-remap-abort/m400.ngc @@ -69,10 +69,10 @@ index 5a1e60e..67edc9b 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index b69eb5a..6941bbd 100644 +index d06c467..05d8783 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -779,7 +779,7 @@ interpret_again: +@@ -796,7 +796,7 @@ interpret_again: } // if interp len is less than max } @@ -81,13 +81,15 @@ index b69eb5a..6941bbd 100644 { int queued_mdi_commands; -@@ -3159,6 +3159,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3192,6 +3192,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_INIT_TYPE: + // re-initializing the interpreter drops any call an interrupted MDI -+ // command is still inside of -+ mdi_execute_abort(); ++ // command is still inside of; an ordinary MDI move keeps running and ++ // keeps its interpreter state ++ if (mdi_execute_wait || mdi_execute_next || mdi_execute_level >= 0) ++ mdi_execute_abort(); retval = emcTaskPlanInit(); if (retval > INTERP_MIN_ERROR) { retval = -1; @@ -105,10 +107,10 @@ index 223886e..1a7a999 100644 int emcTaskSetState(EMC_TASK_STATE state); diff --git a/tests/remap/mdi-remap-abort/README b/tests/remap/mdi-remap-abort/README new file mode 100644 -index 0000000..4d3f7c0 +index 0000000..213678e9 --- /dev/null +++ b/tests/remap/mdi-remap-abort/README -@@ -0,0 +1,12 @@ +@@ -0,0 +1,17 @@ +Interrupt an MDI command whose remap is mid-execution with an E-stop, a +machine off, an interpreter re-init (EMC_TASK_PLAN_INIT) and a mode change +to AUTO and back, instead of an operator abort, then bring the machine back @@ -121,6 +123,11 @@ index 0000000..4d3f7c0 + +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. Finally, an interpreter re-init during ++an ordinary MDI G1 move, with no interrupted call, must leave the move ++running and the interpreter state non-idle until the move ends. diff --git a/tests/remap/mdi-remap-abort/checkresult b/tests/remap/mdi-remap-abort/checkresult new file mode 100755 index 0000000..24dc9aa @@ -157,10 +164,10 @@ index 0000000..b616b52 + yield INTERP_EXECUTE_FINISH diff --git a/tests/remap/mdi-remap-abort/test-ui.py b/tests/remap/mdi-remap-abort/test-ui.py new file mode 100755 -index 0000000..b67b7c7 +index 0000000..b88dda9 --- /dev/null +++ b/tests/remap/mdi-remap-abort/test-ui.py -@@ -0,0 +1,138 @@ +@@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +# +# Interrupt an MDI command whose remap is mid-execution in every way that @@ -280,9 +287,55 @@ index 0000000..b67b7c7 + 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() ++ set_mode(linuxcnc.MODE_MDI) ++ time.sleep(0.5) ++ s.poll() ++ if s.queued_mdi_commands != 0: ++ fail("%s: %d queued MDI commands survived" ++ % (name, s.queued_mdi_commands)) ++ 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) ++ print("%s: ok" % name, flush=True) ++ ++ ++def plain_move_reset(): ++ # Re-initializing the interpreter during an ordinary MDI move, with no ++ # interrupted call, leaves the move running and the MDI command active ++ # until the move ends. ++ set_mode(linuxcnc.MODE_MDI) ++ end = target[0] + 4.0 ++ c.mdi("G1 X%.1f F120" % end) ++ wait_for(lambda: s.current_vel > 0.0, "plain MDI move to start") ++ # task stays busy until the move ends, so do not wait for completion ++ c.reset_interpreter() ++ serial = c.serial ++ wait_for(lambda: s.echo_serial_number >= serial, ++ "interpreter re-init to be received") ++ if abs(s.position[0] - end) < 0.5: ++ fail("plain MDI move ended before the interpreter re-init") ++ start = time.time() ++ while abs(s.position[0] - end) > 1e-6: ++ if time.time() - start > 10.0: ++ fail("plain MDI move did not end after the interpreter re-init " ++ "(X=%.4f interp_state=%d)" % (s.position[0], s.interp_state)) ++ if s.interp_state == linuxcnc.INTERP_IDLE: ++ fail("interpreter re-init during a plain MDI move reported " ++ "IDLE while moving (X=%.4f)" % s.position[0]) ++ time.sleep(0.02) ++ s.poll() ++ wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE ++ and s.exec_state == linuxcnc.EXEC_DONE, ++ "plain MDI move to finish after interpreter re-init") ++ target[0] = end ++ check_mdi_works("plain move interpreter re-init") ++ print("plain move interpreter re-init: ok") + + +wait_for(lambda: s.task_state == linuxcnc.STATE_ESTOP, "task to start") @@ -296,6 +349,8 @@ index 0000000..b67b7c7 + scenario("%s interpreter re-init" % code, code, plan_init) + scenario("%s mode change" % code, code, mode_auto) + ++plain_move_reset() ++ +print("all scenarios passed") +set_state(linuxcnc.STATE_ESTOP) +sys.exit(0) diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 9bcc0f5..4d4076d 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -206,6 +206,10 @@ 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. +Pause while Resume is pending (in `STARTING`, or a Resume latched during +`STOPPING`) cancels it like a second Stop: 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 @@ -220,11 +224,11 @@ spindle-state bookkeeping of later spindle commands untouched. The `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 37 scenarios with the +run in parallel. With patches 0009 and 0011 they hold 40 scenarios with the jerk-limited planner and four re-runs 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, commands queued behind a thread, `G33` threading including a chain of +signal, Pause while Resume is pending, 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. @@ -296,7 +300,12 @@ 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. The G-code preview applies the same geometry-plus-wear offset +back in memory. 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. +`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 @@ -404,6 +413,14 @@ 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. CRLF line endings, whitespace-only lines and comment-only lines count as +blank. `tests/tool-table-load` 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 LinuxCNC restart and remap under the same process lock used by all mmap @@ -513,7 +530,12 @@ 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, 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 failed acquisition homing +accepted and stays `STOPPING` until homing ends. Stop or Pause before the +hardware acknowledgment of an unhomed joint does not hold `STOPPING`: the +acknowledgment completes the handshake and the acquisition home 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. Coordinated and teleop motion are permitted only when inverse kinematics leaves @@ -571,7 +593,13 @@ 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. @@ -670,9 +698,12 @@ 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, -and `EMC_TASK_PLAN_INIT` runs it before re-initialising the interpreter. -`tests/remap/mdi-remap-abort` interrupts a waiting NGC and Python remap with -each of these and checks that MDI still works. The bug is present in plain +and `EMC_TASK_PLAN_INIT` runs it before re-initialising the interpreter when an +interrupted call exists; an ordinary MDI move keeps running and keeps its +interpreter state. `tests/remap/mdi-remap-abort` interrupts a waiting NGC and +Python remap with each of these, checks that an MDI command queued behind it +never runs and that MDI still works, and resets the interpreter during a plain +MDI move. The bug is present in plain v2.10.0-pre2; the fix touches only upstream code paths. ### 0026 — Identify the command an operator error rejects From fff12b079d0613cffeb10d5c29ca34c20f6586b6 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 10:47:11 +0100 Subject: [PATCH 18/45] fix(linuxcnc): address high-severity findings from review round 2 Patch 0004: a second Stop during STOPPING cancels a latched Resume, so the outputs are not restored and the program stays STOPPED. Patch 0011: Pause during an in-flight Single Step drops the step target and pauses normally instead of letting the block or G76 pass finish. Patch 0012: a nonrandom pocket number is only a label, so tables that load at startup also reload. A refused reload tells the operator why and blocks saves only when the file differs from the table in use. On a random changer a reload is refused unless pocket 0 holds the spindle tool. Tests: resumable-stop stop-latched-resume and pause-inflight-step, tool-table-load reload runs, tool-line-length-save random reload. Verified locally: full regression suite 344/352; the 8 failures are the GUI tests on this --disable-gui build and pyvcp loading another install. --- linuxcnc-patches/0004-resumable-stop.patch | 33 +-- .../0007-native-automatic-tool-wear.patch | 8 +- ...reading-stop-clear-and-pass-stepping.patch | 24 +- ...-single-step-during-active-execution.patch | 133 +++++++---- ...-own-transactional-tool-CRUD-in-task.patch | 208 ++++++++++++++---- ...-publish-modal-CSS-maximum-in-status.patch | 2 +- ...ntime-joint-and-spindle-availability.patch | 42 ++-- ...w-concurrent-individual-joint-homing.patch | 4 +- ...otion-add-native-lathe-power-jogging.patch | 4 +- ...te-whenever-the-interpreter-is-reset.patch | 4 +- linuxcnc-patches/README.md | 20 +- 11 files changed, 336 insertions(+), 146 deletions(-) diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 42300df..ca72a10 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -32,7 +32,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: src/emc/nml_intf/emc.hh | 14 + src/emc/nml_intf/emc_nml.hh | 22 + src/emc/nml_intf/emcops.cc | 4 + - src/emc/task/emctaskmain.cc | 439 ++++- + src/emc/task/emctaskmain.cc | 440 ++++- src/emc/task/taskintf.cc | 67 +- src/emc/tp/tp.c | 133 +- src/emc/tp/tp_types.h | 12 + @@ -72,7 +72,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/thread-then-steps.ngc | 10 + tests/resumable-stop/thread.ngc | 7 + tests/resumable-stop/tool.tbl | 1 + - 52 files changed, 2767 insertions(+), 25 deletions(-) + 52 files changed, 2768 insertions(+), 25 deletions(-) create mode 100644 tests/resumable-stop/README create mode 100644 tests/resumable-stop/after-abort.ngc create mode 100644 tests/resumable-stop/after-tap-m5.ngc @@ -616,7 +616,7 @@ index ed6a962..a6b2345 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a3b5256..0e54734 100644 +index a3b5256..15aac38 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -124,6 +124,40 @@ static int emcTaskEager = 0; @@ -1044,7 +1044,7 @@ index a3b5256..0e54734 100644 retval = emcSpindleOrient(spindle_orient_msg->spindle, spindle_orient_msg->orientation, spindle_orient_msg->mode); break; -@@ -2191,7 +2546,49 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2191,7 +2546,50 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // task commands @@ -1078,6 +1078,7 @@ index a3b5256..0e54734 100644 + emcStatus->task.task_paused = 1; + retval = emcTrajStop(); + break; ++ case EMC_TASK_STOP_STATE::STOPPING: + case EMC_TASK_STOP_STATE::STARTING: + emcTaskStopCancelResume(); + retval = 0; @@ -1094,7 +1095,7 @@ index a3b5256..0e54734 100644 // abort everything emcTaskAbort(); // KLUDGE call motion abort before state restore to make absolutely sure no -@@ -2215,6 +2612,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2215,6 +2613,9 @@ 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 @@ -1104,7 +1105,7 @@ index a3b5256..0e54734 100644 if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { // leaving auto or mdi mode for manual -@@ -2259,6 +2659,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2259,6 +2660,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_SET_STATE_TYPE: state_msg = reinterpret_cast(cmd); @@ -1114,7 +1115,7 @@ index a3b5256..0e54734 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2451,6 +2854,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2451,6 +2855,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_PAUSE_TYPE: @@ -1122,7 +1123,7 @@ index a3b5256..0e54734 100644 emcTrajPause(); if (emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED) { interpResumeState = emcStatus->task.interpState; -@@ -2484,11 +2888,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2484,11 +2889,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -1135,7 +1136,7 @@ index a3b5256..0e54734 100644 retval = 0; break; -@@ -2701,6 +3102,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3103,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -1143,7 +1144,7 @@ index a3b5256..0e54734 100644 /*! \todo FIXME-- duplicate code for abort, also near end of main, when aborting on subordinate errors, -@@ -2746,7 +3148,9 @@ static int emcTaskExecute(void) +@@ -2746,7 +3149,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -1154,7 +1155,7 @@ index a3b5256..0e54734 100644 if (NULL == emcTaskCommand) { // need a new command emcTaskCommand = interp_list.get(); -@@ -2767,7 +3171,7 @@ static int emcTaskExecute(void) +@@ -2767,7 +3172,7 @@ static int emcTaskExecute(void) emcStatus->task.execState = emcTaskCheckPreconditions(emcTaskCommand.get()); } } @@ -1163,7 +1164,7 @@ index a3b5256..0e54734 100644 // have an outstanding command // This is the one emcTaskIssueCommand() call site followed by // emcTaskCheckPostconditions(), i.e. the only one whose commands -@@ -3040,6 +3444,18 @@ static int emcTaskExecute(void) +@@ -3040,6 +3445,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -1182,7 +1183,7 @@ index a3b5256..0e54734 100644 // check if delay has passed emcStatus->task.delayLeft = taskExecDelayTimeout - etime(); if (etime() >= taskExecDelayTimeout) { -@@ -3626,6 +4042,7 @@ int main(int argc, char *argv[]) +@@ -3626,6 +4043,7 @@ int main(int argc, char *argv[]) prev_traj_enabled = emcStatus->motion.traj.enabled; // synchronize subordinate states if (emcStatus->io.aux.estop) { @@ -1190,7 +1191,7 @@ index a3b5256..0e54734 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3707,6 +4124,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4125,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -1198,7 +1199,7 @@ index a3b5256..0e54734 100644 // abort everything emcTaskAbort(); emcIoAbort(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); -@@ -3742,6 +4160,12 @@ int main(int argc, char *argv[]) +@@ -3742,6 +4161,12 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -1211,7 +1212,7 @@ index a3b5256..0e54734 100644 // update task-specific status emcTaskUpdate(&emcStatus->task); -@@ -3762,6 +4186,9 @@ int main(int argc, char *argv[]) +@@ -3762,6 +4187,9 @@ int main(int argc, char *argv[]) emcStatus->io.status == RCS_STATUS::ERROR) { emcStatus->status = RCS_STATUS::ERROR; emcStatus->task.status = RCS_STATUS::ERROR; diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index 5bcf737..fbc9868 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -1606,7 +1606,7 @@ index 7620a30..55fb417 100644 // 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 0e54734..4f046a8 100644 +index 15aac38..6025a96 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -613,6 +613,9 @@ interpret_again: @@ -1679,7 +1679,7 @@ index 0e54734..4f046a8 100644 break; // task commands -@@ -3129,6 +3153,7 @@ static int emcTaskExecute(void) +@@ -3130,6 +3154,7 @@ static int emcTaskExecute(void) // clear out pending command emcTaskCommand = NULL; interp_list.clear(); @@ -1687,7 +1687,7 @@ index 0e54734..4f046a8 100644 emcAbortCleanup(EMC_ABORT::TASK_EXEC_ERROR); emcStatus->task.currentLine = 0; -@@ -3695,7 +3720,8 @@ static int emctask_startup() +@@ -3696,7 +3721,8 @@ static int emctask_startup() } // initialize the subsystems @@ -1697,7 +1697,7 @@ index 0e54734..4f046a8 100644 if (emcIoInit() != 0) { rcs_print_error("can't initialize IO\n"); return -1; -@@ -4145,6 +4171,7 @@ int main(int argc, char *argv[]) +@@ -4146,6 +4172,7 @@ int main(int argc, char *argv[]) // clear out the pending command emcTaskCommand = NULL; interp_list.clear(); 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 31b014b..5d89115 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -703,7 +703,7 @@ index 55fb417..90cc136 100644 } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 4f046a8..1154fd8 100644 +index 6025a96..e2a7209 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -504,6 +504,22 @@ static int programStartLine = 0; // which line to run program from @@ -784,7 +784,7 @@ index 4f046a8..1154fd8 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2638,6 +2668,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2639,6 +2669,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } else { // we can honour the modeswitch if (mode_msg->mode != emcStatus->task.mode) { emcTaskStopClear(); @@ -793,7 +793,7 @@ index 4f046a8..1154fd8 100644 } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { -@@ -2671,8 +2703,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2672,8 +2704,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; @@ -803,7 +803,7 @@ index 4f046a8..1154fd8 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2685,6 +2716,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2686,6 +2717,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) state_msg = reinterpret_cast(cmd); if (state_msg->state != EMC_TASK_STATE::ON) { emcTaskStopClear(); @@ -812,7 +812,7 @@ index 4f046a8..1154fd8 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2769,8 +2802,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2770,8 +2803,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_EXECUTE_TYPE: emcStatus->motion.traj.single_stepping = 0; @@ -822,7 +822,7 @@ index 4f046a8..1154fd8 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")); -@@ -2865,8 +2897,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2866,8 +2898,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -832,7 +832,7 @@ index 4f046a8..1154fd8 100644 if (!taskplanopen && emcStatus->task.file[0] != 0) { emcTaskPlanOpen(emcStatus->task.file); } -@@ -2935,6 +2966,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2936,6 +2967,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -843,7 +843,7 @@ index 4f046a8..1154fd8 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: os_msg = reinterpret_cast(cmd); emcTaskPlanSetOptionalStop(os_msg->state); -@@ -3043,6 +3078,7 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3044,6 +3079,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: @@ -851,7 +851,7 @@ index 4f046a8..1154fd8 100644 case EMC_TASK_PLAN_EXECUTE_TYPE: case EMC_TASK_PLAN_OPTIONAL_STOP_TYPE: return EMC_TASK_EXEC::DONE; -@@ -3095,11 +3131,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3096,11 +3132,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) #define STEPPING_CHECK() \ if (stepping) { \ if (! steppingWait) { \ @@ -873,7 +873,7 @@ index 4f046a8..1154fd8 100644 break; \ } \ } \ -@@ -3161,8 +3204,7 @@ static int emcTaskExecute(void) +@@ -3162,8 +3205,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; @@ -883,7 +883,7 @@ index 4f046a8..1154fd8 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -3184,6 +3226,7 @@ static int emcTaskExecute(void) +@@ -3185,6 +3227,7 @@ static int emcTaskExecute(void) if (NULL != emcTaskCommand) { emcTaskEager = 1; emcStatus->task.currentLine = interp_list.get_line_number(); @@ -891,7 +891,7 @@ index 4f046a8..1154fd8 100644 // 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. -@@ -4180,8 +4223,7 @@ int main(int argc, char *argv[]) +@@ -4181,8 +4224,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; 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 e0e20fd..84d9ef2 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 @@ -11,12 +11,12 @@ 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/command.c | 24 ++- src/emc/motion/control.c | 9 +- - src/emc/task/emctaskmain.cc | 48 ++--- - src/emc/tp/tp.c | 80 +++++++-- + src/emc/task/emctaskmain.cc | 48 +++-- + src/emc/tp/tp.c | 80 +++++-- src/emc/tp/tp_types.h | 6 +- - tests/resumable-stop/README | 33 ++++ + tests/resumable-stop/README | 33 +++ tests/resumable-stop/after-tap-m5.ngc | 2 +- tests/resumable-stop/after-thread-m5.ngc | 2 +- tests/resumable-stop/after-thread-m9.ngc | 2 +- @@ -31,25 +31,25 @@ feature and its program. tests/resumable-stop/g76-stop/scenarios | 5 + tests/resumable-stop/g76-stop/test.sh | 3 + tests/resumable-stop/general/checkresult | 2 + - tests/resumable-stop/general/scenarios | 23 +++ + tests/resumable-stop/general/scenarios | 24 +++ tests/resumable-stop/general/test.sh | 3 + tests/resumable-stop/inflight-step.ngc | 7 + tests/resumable-stop/multi-spindle.ngc | 2 +- tests/resumable-stop/orient.ngc | 2 +- tests/resumable-stop/rapid-then-feed.ngc | 2 +- tests/resumable-stop/resume-s0.ngc | 7 + - tests/resumable-stop/run-scenarios.sh | 61 +++++++ + tests/resumable-stop/run-scenarios.sh | 61 ++++++ tests/resumable-stop/tap.ngc | 6 +- - tests/resumable-stop/test-ui.py | 200 +++++++++++++++++++++ + tests/resumable-stop/test-ui.py | 237 +++++++++++++++++++++ tests/resumable-stop/test.ngc | 2 +- - tests/resumable-stop/test.sh | 87 --------- + tests/resumable-stop/test.sh | 87 -------- tests/resumable-stop/thread-g95-thread.ngc | 2 +- tests/resumable-stop/thread-then-steps.ngc | 4 +- tests/resumable-stop/thread.ngc | 6 +- tests/resumable-stop/threading/checkresult | 2 + - tests/resumable-stop/threading/scenarios | 10 ++ + tests/resumable-stop/threading/scenarios | 11 + tests/resumable-stop/threading/test.sh | 3 + - 38 files changed, 514 insertions(+), 160 deletions(-) + 38 files changed, 560 insertions(+), 160 deletions(-) create mode 100755 tests/resumable-stop/check-result.sh delete mode 100755 tests/resumable-stop/checkresult create mode 100755 tests/resumable-stop/g76-step/checkresult @@ -70,10 +70,24 @@ feature and its program. create mode 100755 tests/resumable-stop/threading/test.sh diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index a8e8ae3..ead94cb 100644 +index a8e8ae3..ff48890 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -1381,26 +1381,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1334,6 +1334,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 +1388,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_STEP: @@ -135,7 +149,7 @@ index e347bf1..75a9f1c 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 1154fd8..2a3c750 100644 +index e2a7209..f69fcbb 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -504,6 +504,7 @@ static int programStartLine = 0; // which line to run program from @@ -226,7 +240,7 @@ index 1154fd8..2a3c750 100644 break; // otherwise we can't handle it -@@ -4101,6 +4099,10 @@ int main(int argc, char *argv[]) +@@ -4102,6 +4100,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); @@ -649,18 +663,18 @@ index 0000000..713f576 +exec bash ../run-scenarios.sh scenarios diff --git a/tests/resumable-stop/general/checkresult b/tests/resumable-stop/general/checkresult new file mode 100755 -index 0000000..dea9811 +index 0000000..362de54 --- /dev/null +++ b/tests/resumable-stop/general/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 23 ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 24 diff --git a/tests/resumable-stop/general/scenarios b/tests/resumable-stop/general/scenarios new file mode 100644 -index 0000000..d2ee92d +index 0000000..d8e2870 --- /dev/null +++ b/tests/resumable-stop/general/scenarios -@@ -0,0 +1,23 @@ +@@ -0,0 +1,24 @@ +idle-rejected +ordinary +trapezoidal:ordinary @@ -684,6 +698,7 @@ index 0000000..d2ee92d +resume-atspeed +pause-starting +resume-s0 ++pause-inflight-step diff --git a/tests/resumable-stop/general/test.sh b/tests/resumable-stop/general/test.sh new file mode 100755 index 0000000..713f576 @@ -835,10 +850,10 @@ index 3060ac4..2182f18 100644 M5 M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index d29f03f..add6ef4 100755 +index d29f03f..9d8a771 100755 --- a/tests/resumable-stop/test-ui.py +++ b/tests/resumable-stop/test-ui.py -@@ -261,6 +261,42 @@ def run_stop_single_step_test(): +@@ -261,6 +261,74 @@ def run_stop_single_step_test(): wait_for_program_complete(20.0) assert_outputs_stopped_after_program() @@ -877,11 +892,43 @@ index d29f03f..add6ef4 100755 + + 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") -@@ -790,6 +826,48 @@ def run_tapered_g76_single_step_test(): +@@ -790,6 +858,48 @@ def run_tapered_g76_single_step_test(): "tapered-drive G76", ) @@ -930,7 +977,7 @@ index d29f03f..add6ef4 100755 def run_g76_exit_taper_stop_test(program, expected_clear_x, label): open_auto_program(program) -@@ -1286,6 +1364,123 @@ def run_resume_atspeed_wait_test(): +@@ -1286,6 +1396,124 @@ def run_resume_atspeed_wait_test(): fail("Abort while waiting: the feed moved") @@ -972,9 +1019,10 @@ index d29f03f..add6ef4 100755 + assert_outputs_stopped_after_program() + + -+def run_pause_after_latched_resume_test(): -+ # Resume during STOPPING is latched until Stop completes; a Pause after -+ # it cancels the latched Resume, so the program stays STOPPED. ++def run_cancel_latched_resume_test(label, cancel): ++ # Resume during STOPPING is latched until Stop completes; a Pause or a ++ # second Stop after it cancels the latched Resume, so the program stays ++ # STOPPED. + open_auto_program("thread-then-steps.ngc") + c.auto(linuxcnc.AUTO_RUN, 0) + wait_for( @@ -991,27 +1039,27 @@ index d29f03f..add6ef4 100755 + timeout=1.0, + ) + c.auto(linuxcnc.AUTO_RESUME) -+ c.auto(linuxcnc.AUTO_PAUSE) ++ cancel() + s.poll() + if s.stop_state != linuxcnc.STOP_STOPPING: -+ fail("G33 finished before Resume and Pause were sent") ++ fail("G33 finished before Resume and %s were sent" % label) + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED + and math.isclose(s.position[2], -5.0, abs_tol=0.01), -+ lambda: "Pause after latched Resume did not leave the program " ++ lambda: "%s after latched Resume did not leave the program " + "STOPPED: X=%.3f Z=%.3f stop=%d" -+ % (s.position[0], s.position[2], s.stop_state), ++ % (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("Pause after latched Resume: program left STOPPED") ++ fail("%s after latched Resume: program left STOPPED" % label) + if hal.get_value("spindle.0.on"): -+ fail("Pause after latched Resume: spindle on while STOPPED") ++ fail("%s after latched Resume: spindle on while STOPPED" % label) + if abs(s.position[0]) > 0.001: -+ fail("Pause after latched Resume: feed after G33 moved") ++ fail("%s after latched Resume: feed after G33 moved" % label) + + c.auto(linuxcnc.AUTO_RESUME) + wait_for( @@ -1054,7 +1102,7 @@ index d29f03f..add6ef4 100755 def run_multi_spindle_stop_resume_test(): open_auto_program("multi-spindle.ngc") c.spindle(linuxcnc.SPINDLE_FORWARD, 120.0, 0) -@@ -1769,6 +1964,7 @@ SCENARIOS = { +@@ -1769,6 +1997,7 @@ SCENARIOS = { "idle-rejected": run_idle_program_stop_rejected_test, "ordinary": run_ordinary_stop_resume_test, "single-step": run_stop_single_step_test, @@ -1062,7 +1110,7 @@ index d29f03f..add6ef4 100755 "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), -@@ -1782,6 +1978,7 @@ SCENARIOS = { +@@ -1782,6 +2011,7 @@ SCENARIOS = { "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, @@ -1070,12 +1118,16 @@ index d29f03f..add6ef4 100755 "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, -@@ -1791,6 +1988,9 @@ SCENARIOS = { +@@ -1791,6 +2021,13 @@ SCENARIOS = { "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, -+ "pause-latched-resume": run_pause_after_latched_resume_test, ++ "pause-latched-resume": lambda: run_cancel_latched_resume_test( ++ "Pause", lambda: c.auto(linuxcnc.AUTO_PAUSE)), ++ "stop-latched-resume": lambda: run_cancel_latched_resume_test( ++ "Stop", c.program_stop), ++ "pause-inflight-step": run_pause_inflight_single_step_test, + "resume-s0": run_resume_zero_speed_test, "multi-spindle": run_multi_spindle_stop_resume_test, "css": run_css_stop_resume_test, @@ -1228,18 +1280,18 @@ index 5976979..c3ec6d0 100644 M2 diff --git a/tests/resumable-stop/threading/checkresult b/tests/resumable-stop/threading/checkresult new file mode 100755 -index 0000000..3b2acd1 +index 0000000..664eed8 --- /dev/null +++ b/tests/resumable-stop/threading/checkresult @@ -0,0 +1,2 @@ +#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 10 ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 11 diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios new file mode 100644 -index 0000000..c248aa5 +index 0000000..a4410d4 --- /dev/null +++ b/tests/resumable-stop/threading/scenarios -@@ -0,0 +1,10 @@ +@@ -0,0 +1,11 @@ +rigid-tap +g33 +queued-g33 @@ -1250,6 +1302,7 @@ index 0000000..c248aa5 +g33-no-following-rapid +command-after-sync +pause-latched-resume ++stop-latched-resume diff --git a/tests/resumable-stop/threading/test.sh b/tests/resumable-stop/threading/test.sh new file mode 100755 index 0000000..713f576 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 7c6b314..284317a 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 @@ -26,29 +26,32 @@ tests/tooldb tests, which need a db program, are skipped. 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 | 256 +++++++++++++++-- + src/emc/task/taskclass.cc | 280 ++++++++++++++++-- src/emc/task/taskclass.hh | 5 +- - src/emc/tooldata/tooldata.hh | 14 + - src/emc/tooldata/tooldata_common.cc | 260 ++++++++++++------ + src/emc/tooldata/tooldata.hh | 18 ++ + src/emc/tooldata/tooldata_common.cc | 274 +++++++++++------ src/emc/tooldata/tooldata_mmap.cc | 102 ++++++- - src/emc/tooldata/tooldata_nml.cc | 16 ++ + src/emc/tooldata/tooldata_nml.cc | 16 + + tests/tool-line-length-save/random-ui.py | 31 ++ tests/tool-table-load/.gitignore | 4 + tests/tool-table-load/checkresult | 2 + tests/tool-table-load/common.py | 76 +++++ tests/tool-table-load/crlf-ui.py | 27 ++ tests/tool-table-load/garbage-ui.py | 56 ++++ + tests/tool-table-load/reload-ui.py | 26 ++ tests/tool-table-load/test.ini | 84 ++++++ - tests/tool-table-load/test.sh | 16 ++ + tests/tool-table-load/test.sh | 29 ++ .../reload-tool/non-random/test-ui.py | 14 + .../toolchanger/reload-tool/random/test-ui.py | 3 +- tests/tooldb/db-g10-offset/skip | 3 + tests/tooldb/db-line-length/skip | 3 + - 21 files changed, 960 insertions(+), 124 deletions(-) + 23 files changed, 1073 insertions(+), 123 deletions(-) create mode 100644 tests/tool-table-load/.gitignore create mode 100755 tests/tool-table-load/checkresult create mode 100644 tests/tool-table-load/common.py create mode 100755 tests/tool-table-load/crlf-ui.py create mode 100755 tests/tool-table-load/garbage-ui.py + create mode 100755 tests/tool-table-load/reload-ui.py create mode 100644 tests/tool-table-load/test.ini create mode 100755 tests/tool-table-load/test.sh create mode 100644 tests/tooldb/db-g10-offset/skip @@ -198,7 +201,7 @@ index cf8bc14..b40c76d 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 2a3c750..ae1462b 100644 +index f69fcbb..269facc 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1263,7 +1263,18 @@ static int emcTaskPlan(void) @@ -302,7 +305,7 @@ index 2a3c750..ae1462b 100644 case EMC_TOOL_SET_NUMBER_TYPE: emc_tool_set_number_msg = reinterpret_cast(cmd); retval = emcToolSetNumber(emc_tool_set_number_msg->tool); -@@ -3059,6 +3116,8 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3060,6 +3117,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: @@ -312,7 +315,7 @@ index 2a3c750..ae1462b 100644 case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index 72b698b4..07b68b2 100644 +index 72b698b4..6594e3d 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc @@ -17,6 +17,7 @@ @@ -402,7 +405,7 @@ index 72b698b4..07b68b2 100644 reload_tool_number(emcioStatus.tool.toolInSpindle); if (0 != iniTool(emc_inifile)) { -@@ -589,10 +589,38 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE +@@ -589,10 +589,60 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE return 0; } @@ -427,14 +430,36 @@ index 72b698b4..07b68b2 100644 + CANON_TOOL_TABLE loaded[CANON_POCKETS_MAX]; + int loaded_last = 0; + bool refused_lines = false; -+ if (tooldata_load_snapshot(file, loaded, &loaded_last, &refused_lines) || -+ !valid_table(loaded, loaded_last, random_toolchanger) || -+ (emcioStatus.tool.toolInSpindle > 0 && -+ find_tool(loaded, loaded_last, emcioStatus.tool.toolInSpindle, -+ random_toolchanger) < 0)) { -+ // the table in memory stays, but the file it is saved to now holds -+ // something else: it is not saved over until a table loads -+ if (same_file(file, tooltable_filename)) tooldata_set_refused_lines(true); ++ 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 file now holds something else, ++ // it is not saved over until a table 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 (!unchanged && same_file(file, tooltable_filename)) { ++ 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; @@ -442,7 +467,7 @@ index 72b698b4..07b68b2 100644 reload_tool_number(emcioStatus.tool.toolInSpindle); return 0; } -@@ -634,9 +662,10 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -634,9 +684,10 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, UNEXPECTED_MSG; } bool stored = (0 == tooldata_save(tooltable_filename)); @@ -454,7 +479,7 @@ index 72b698b4..07b68b2 100644 int pno = idx; // for random_toolchanger if (!random_toolchanger) { pno = tdata.pocketno; } if (tooldata_db_notify(TOOL_OFFSET,toolno,pno,tdata)) { -@@ -656,6 +685,191 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -656,6 +707,193 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, return 0; } @@ -497,7 +522,9 @@ index 72b698b4..07b68b2 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; @@ -670,7 +697,7 @@ index 509f11f..d9afc98 100644 }; diff --git a/src/emc/tooldata/tooldata.hh b/src/emc/tooldata/tooldata.hh -index db3e6b7..0b28e0e 100644 +index db3e6b7..d4829ff 100644 --- a/src/emc/tooldata/tooldata.hh +++ b/src/emc/tooldata/tooldata.hh @@ -58,6 +58,8 @@ void tooldata_reset(void); @@ -682,7 +709,7 @@ index db3e6b7..0b28e0e 100644 // ignore_zero_values:1 for file writes // :0 for use with tooldata_db_notify() -@@ -76,8 +78,20 @@ void tooldata_set_db(tooldb_t mode); +@@ -76,8 +78,24 @@ void tooldata_set_db(tooldb_t mode); //---------------------------------------------------------- int tooldata_load(const char *filename); @@ -695,6 +722,10 @@ index db3e6b7..0b28e0e 100644 +// the published table was loaded with refused lines, or the table file +// did not load: saves are refused until a table without them is loaded +void tooldata_set_refused_lines(bool refused); ++ ++// 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, @@ -704,7 +735,7 @@ index db3e6b7..0b28e0e 100644 //---------------------------------------------------------- //mmap specific diff --git a/src/emc/tooldata/tooldata_common.cc b/src/emc/tooldata/tooldata_common.cc -index ceefe9b..a0ca625 100644 +index ceefe9b..93626f8 100644 --- a/src/emc/tooldata/tooldata_common.cc +++ b/src/emc/tooldata/tooldata_common.cc @@ -24,7 +24,12 @@ @@ -950,7 +981,7 @@ index ceefe9b..a0ca625 100644 if (db_mode == DB_ACTIVE && idx != 0 ) { return 0; } -@@ -433,63 +498,82 @@ static int write_tool_line(std::string &table,int idx) +@@ -433,63 +498,98 @@ static int write_tool_line(std::string &table,int idx) tdata,theline)) { return -1; } @@ -961,9 +992,8 @@ index ceefe9b..a0ca625 100644 } // 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; @@ -989,15 +1019,19 @@ index ceefe9b..a0ca625 100644 - filename); - return -1; - } -+ if (!filename || !filename[0] || !table || last_index < 0 || -+ last_index >= CANON_POCKETS_MAX || db_mode == DB_ACTIVE) return -1; -+ 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; ++ 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; ++} + - // 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; @@ -1009,6 +1043,18 @@ index ceefe9b..a0ca625 100644 - for (idx = start_idx; idx < CANON_POCKETS_MAX; idx++) { - if (write_tool_line(table,idx)) {return -1;} - } ++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; ++ 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; ++ } + // a tool whose line is too long fails the write, and the file stays as + // it was: the table goes to a temporary file renamed over it only when + // every line has been written @@ -1324,6 +1370,47 @@ index f333925..a7ee61e 100644 + memcpy(the_table, table, CANON_POCKETS_MAX * sizeof(*table)); + return 0; +} +diff --git a/tests/tool-line-length-save/random-ui.py b/tests/tool-line-length-save/random-ui.py +index 35b3c18..4b2e267 100755 +--- a/tests/tool-line-length-save/random-ui.py ++++ b/tests/tool-line-length-save/random-ui.py +@@ -58,5 +58,36 @@ if s.tool_table[0].id != 1: + 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/tests/tool-table-load/.gitignore b/tests/tool-table-load/.gitignore new file mode 100644 index 0000000..76e1adf @@ -1519,6 +1606,38 @@ index 0000000..89099f9 +print(table()) +print("*** all checks passed") +sys.exit(0) +diff --git a/tests/tool-table-load/reload-ui.py b/tests/tool-table-load/reload-ui.py +new file mode 100755 +index 0000000..5e073f5 +--- /dev/null ++++ b/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/tests/tool-table-load/test.ini b/tests/tool-table-load/test.ini new file mode 100644 index 0000000..9338ce7 @@ -1611,10 +1730,10 @@ index 0000000..9338ce7 +HOME_SEQUENCE = 0 diff --git a/tests/tool-table-load/test.sh b/tests/tool-table-load/test.sh new file mode 100755 -index 0000000..6819e71 +index 0000000..c629639 --- /dev/null +++ b/tests/tool-table-load/test.sh -@@ -0,0 +1,16 @@ +@@ -0,0 +1,29 @@ +#!/bin/bash +set -e + @@ -1631,6 +1750,19 @@ index 0000000..6819e71 +rm -f sim.var +sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./garbage-ui.py#' test.ini > run.ini +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 ++sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./reload-ui.py#' test.ini > run.ini ++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 diff --git a/tests/toolchanger/reload-tool/non-random/test-ui.py b/tests/toolchanger/reload-tool/non-random/test-ui.py index fca46c3..445e5ee 100755 --- a/tests/toolchanger/reload-tool/non-random/test-ui.py 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 2c326b1..3e870b7 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 @@ -40,7 +40,7 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index ae1462b..f3bcb8e 100644 +index 269facc..7a81049 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1035,7 +1035,7 @@ static void emcTaskStopProgress() diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index 4495e51..31935be 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -477,7 +477,7 @@ index e814320..029af60 100644 if (!motion_enable_flag) { 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 ead94cb..3734dae 100644 +index ff48890..e24a9d2 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -80,6 +80,16 @@ extern int motion_num_spindles; @@ -712,7 +712,7 @@ index ead94cb..3734dae 100644 tpSetSpindleSync(&emcmotInternal->coord_tp, emcmotCommand->spindle, emcmotCommand->spindlesync, emcmotCommand->flags); break; -@@ -1501,6 +1637,7 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1508,6 +1644,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; @@ -720,7 +720,7 @@ index ead94cb..3734dae 100644 if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { emcmotInternal->teleoperating = 0; emcmotInternal->coordinating = 0; -@@ -1513,10 +1650,16 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1520,10 +1657,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"); @@ -738,7 +738,7 @@ index ead94cb..3734dae 100644 if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { emcmotInternal->teleoperating = 0; emcmotInternal->coordinating = 0; -@@ -1533,6 +1676,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1540,6 +1683,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (joint == 0) { break; } @@ -752,7 +752,7 @@ index ead94cb..3734dae 100644 SET_JOINT_ACTIVE_FLAG(joint, 1); break; -@@ -1545,6 +1695,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1552,6 +1702,13 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (joint == 0) { break; } @@ -766,7 +766,7 @@ index ead94cb..3734dae 100644 SET_JOINT_ACTIVE_FLAG(joint, 0); break; -@@ -1556,6 +1713,14 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1563,6 +1720,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); @@ -781,7 +781,7 @@ index ead94cb..3734dae 100644 /* 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 -@@ -1588,6 +1753,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1595,6 +1760,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (!GET_MOTION_ENABLE_FLAG()) { break; } @@ -794,7 +794,7 @@ index ead94cb..3734dae 100644 // Negative joint_num specifies homeall do_home_joint(joint_num); -@@ -1604,6 +1775,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1611,6 +1782,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) return; } @@ -821,7 +821,7 @@ index ead94cb..3734dae 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'. -@@ -1622,6 +1813,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1629,6 +1820,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; @@ -982,7 +982,7 @@ index ead94cb..3734dae 100644 case EMCMOT_CLEAR_PROBE_FLAGS: rtapi_print_msg(RTAPI_MSG_DBG, "CLEAR_PROBE_FLAGS"); emcmotStatus->probing = 0; -@@ -1818,6 +2163,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1825,6 +2170,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -994,7 +994,7 @@ index ead94cb..3734dae 100644 for (n = s0; n<=s1; n++){ if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) -@@ -1923,8 +2273,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1930,8 +2280,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1008,7 +1008,7 @@ index ead94cb..3734dae 100644 if (n > emcmotConfig->numSpindles){ rtapi_print_msg(RTAPI_MSG_ERR, "spindle number <%d> too high in M19",n); break; -@@ -1974,6 +2328,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1981,6 +2335,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1019,7 +1019,7 @@ index ead94cb..3734dae 100644 for (n = s0; n<=s1; n++){ if (emcmotStatus->spindle_status[n].speed > 0) { emcmotStatus->spindle_status[n].speed += emcmotStatus->spindle_status[n].increment; -@@ -1998,6 +2356,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -2005,6 +2363,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1030,7 +1030,7 @@ index ead94cb..3734dae 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; -@@ -2044,8 +2406,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -2051,8 +2413,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -2239,7 +2239,7 @@ index 90cc136..5a1e60e 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index f3bcb8e..c465732 100644 +index 7a81049..79a8355 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -172,6 +172,61 @@ volatile int done; @@ -2525,7 +2525,7 @@ index f3bcb8e..c465732 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -3015,7 +3191,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3016,7 +3192,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2540,7 +2540,7 @@ index f3bcb8e..c465732 100644 if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -3130,6 +3313,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3131,6 +3314,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2552,7 +2552,7 @@ index f3bcb8e..c465732 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -3212,6 +3400,12 @@ static int emcTaskExecute(void) +@@ -3213,6 +3401,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2565,7 +2565,7 @@ index f3bcb8e..c465732 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3330,11 +3524,59 @@ static int emcTaskExecute(void) +@@ -3331,11 +3525,59 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: @@ -2625,7 +2625,7 @@ index f3bcb8e..c465732 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } -@@ -3479,11 +3721,8 @@ static int emcTaskExecute(void) +@@ -3480,11 +3722,8 @@ static int emcTaskExecute(void) emcTaskEager = 1; homingWaiting = false; // Nothing physically moved, so it's safe to restore the @@ -2639,7 +2639,7 @@ index f3bcb8e..c465732 100644 break; } // It ran and has now stopped; did it reach the expected end state? -@@ -3549,7 +3788,9 @@ static int emcTaskExecute(void) +@@ -3550,7 +3789,9 @@ static int emcTaskExecute(void) "coordinated motion until every joint is homed")); emcStatus->task.execState = EMC_TASK_EXEC::ERROR; } else if (success) { 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 5275e82..d1da8aa 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -36,10 +36,10 @@ so the new concurrency checks never refuse it. create mode 100644 tests/homing-concurrent/tool.tbl diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index 3734dae..35eee04 100644 +index e24a9d2..dd99fd8 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -1746,10 +1746,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1753,10 +1753,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) joint_num); return; } 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 d18929d..9da60cf 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 @@ -306,7 +306,7 @@ index 5d61f0b..f1ce1d7 100644 #ifdef __cplusplus diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index 35eee04..f434080 100644 +index dd99fd8..00ae21c 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -157,6 +157,19 @@ STATIC int spindle_range_is_available(int first, int last) @@ -695,7 +695,7 @@ index c03bfc3..05a29fe 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index c465732..d06c467 100644 +index 79a8355..f0d4ab8 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1462,6 +1462,7 @@ static int emcTaskPlan(void) 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 index a05ab1d..1b6b4d4 100644 --- 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 @@ -69,7 +69,7 @@ index 5a1e60e..67edc9b 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index d06c467..05d8783 100644 +index f0d4ab8..7726feb 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -796,7 +796,7 @@ interpret_again: @@ -81,7 +81,7 @@ index d06c467..05d8783 100644 { int queued_mdi_commands; -@@ -3192,6 +3192,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3193,6 +3193,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_INIT_TYPE: diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 4d4076d..7605588 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -206,9 +206,9 @@ 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. -Pause while Resume is pending (in `STARTING`, or a Resume latched during -`STOPPING`) cancels it like a second Stop: the program returns to `STOPPED` -with the restored outputs off. A spindle restored at commanded speed 0 does not +A second Stop or a Pause while Resume is pending (in `STARTING`, or a Resume +latched during `STOPPING`) cancels it: the program stays in or 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 @@ -224,11 +224,11 @@ spindle-state bookkeeping of later spindle commands untouched. The `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 40 scenarios with the +run in parallel. With patches 0009 and 0011 they hold 42 scenarios with the jerk-limited planner and four re-runs 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 of a spindle restored at S0, commands queued behind a thread, `G33` threading including a chain of +signal, Stop and Pause while Resume is pending, Pause during an in-flight Step, 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. @@ -386,8 +386,8 @@ before stopping at an exact boundary. 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. +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. 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; they are part of the resumable-stop tests described under patch 0004. During an @@ -418,7 +418,11 @@ 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. CRLF line endings, whitespace-only lines and comment-only lines count as +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. `tests/tool-table-load` covers this. Tool-table reload now preserves the live table when opening, parsing, or From 8d37e816f0f2054c72877c845440c5b3c64d0f5a Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 11:47:03 +0100 Subject: [PATCH 19/45] fix(native): keep task-queued command results with their command LinuxCNC task reports one result, for the command it read last. A later command written while a tool or availability command was still queued therefore took over that command's failure: the queued command resolved Completed and the next one Rejected. Hold later normal-priority writes until a task-queued command resolves or its time limit passes. Abort, stop, pause, E-stop and machine off go first, and Resume, Step and spindle off pass the hold. A queued command whose result was overtaken now fails with an unknown outcome instead of completing. --- .../linuxcnc_grpc/command_coordinator.hpp | 25 +- .../linuxcnc/command_completion_tracker.hpp | 34 +- .../linuxcnc_grpc/linuxcnc/nml_adapter.hpp | 109 +++++ native/server/src/command_coordinator.cc | 64 ++- .../linuxcnc/command_completion_tracker.cc | 22 +- native/server/src/linuxcnc/nml_adapter.cc | 54 +-- native/server/tests/grpc_live_integration.cc | 1 + native/server/tests/grpc_live_support.cc | 162 +++++++ native/server/tests/grpc_live_support.hpp | 5 + native/server/tests/native_edge_tests.cc | 401 ++++++++++++++++++ 10 files changed, 824 insertions(+), 53 deletions(-) diff --git a/native/server/include/linuxcnc_grpc/command_coordinator.hpp b/native/server/include/linuxcnc_grpc/command_coordinator.hpp index 9a3dc4b..edbdd54 100644 --- a/native/server/include/linuxcnc_grpc/command_coordinator.hpp +++ b/native/server/include/linuxcnc_grpc/command_coordinator.hpp @@ -31,6 +31,13 @@ enum class CommandPriority { Safety, }; +// 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 { Submitted, QueueFull, @@ -58,6 +65,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 @@ -126,7 +138,10 @@ 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); + // 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 +151,14 @@ class CommandCoordinator { CommandAction action; ContextCommandAction context_action; std::shared_ptr state; + bool bypass_hold = false; }; void run(); + // 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 +170,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/linuxcnc/command_completion_tracker.hpp b/native/server/include/linuxcnc_grpc/linuxcnc/command_completion_tracker.hpp index bdc918e..d36e85c 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 cfaac9f..b0048c5 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, @@ -258,6 +271,102 @@ 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. +// 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: + case NmlCommandKind::AbortTask: + routing.priority = CommandPriority::Safety; + break; + case NmlCommandKind::SetTaskState: + if (command.integer == kNmlTaskStateEstop || + command.integer == kNmlTaskStateOff) + routing.priority = CommandPriority::Safety; + 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 002c3bc..cfc10f8 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 { @@ -84,7 +85,7 @@ CommandSubmission CommandCoordinator::submit(CommandAction action, 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}); + queue.push_back(Item{sequence, std::move(action), {}, state, false}); lock.unlock(); condition_.notify_one(); return {CommandSubmitStatus::Submitted, CommandTicket(std::move(state))}; @@ -92,12 +93,13 @@ CommandSubmission CommandCoordinator::submit(CommandAction action, 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) { if (!action) throw std::invalid_argument("command action must not be empty"); auto state = std::make_shared(); std::unique_lock lock(mutex_); @@ -115,7 +117,8 @@ CommandSubmission CommandCoordinator::submit_with_context( context.stop_token = stop_token; action(context); }, - state}); + state, + hold_policy == CommandHoldPolicy::Bypass}); lock.unlock(); condition_.notify_one(); return {CommandSubmitStatus::Submitted, CommandTicket(std::move(state))}; @@ -136,18 +139,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 +206,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/linuxcnc/command_completion_tracker.cc b/native/server/src/linuxcnc/command_completion_tracker.cc index e594036..e2cb94e 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 62f6ec3..3dc0f2e 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 { @@ -537,12 +547,11 @@ 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::Safety; 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(); }; @@ -926,41 +935,16 @@ 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); #else (void)command; (void)stop_token; diff --git a/native/server/tests/grpc_live_integration.cc b/native/server/tests/grpc_live_integration.cc index 2d932c9..2257a31 100644 --- a/native/server/tests/grpc_live_integration.cc +++ b/native/server/tests/grpc_live_integration.cc @@ -384,6 +384,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 893a0b0..c208fa5 100644 --- a/native/server/tests/grpc_live_support.cc +++ b/native/server/tests/grpc_live_support.cc @@ -461,6 +461,168 @@ 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) { + ExecuteCommandRequest dwell; + dwell.mutable_mdi()->set_command("G4 P1"); + (void)execute_accepted(machine, std::move(dwell)); + 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. + create_live_tool(machine, kLiveTool, kLivePocket); + { + QueuedToolDelete overtaken(machine, kLiveTool); + 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"); + } + + // 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 queued command cannot finish while the program is paused, 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); + 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"); +} + 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 f6d464e..4c12f02 100644 --- a/native/server/tests/grpc_live_support.hpp +++ b/native/server/tests/grpc_live_support.hpp @@ -45,6 +45,11 @@ 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); std::string read_file(const std::string& path); diff --git a/native/server/tests/native_edge_tests.cc b/native/server/tests/native_edge_tests.cc index 05e50d9..a51d84d 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,389 @@ 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(); +} + +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::AbortTask, NmlCommandKind::Pause, + NmlCommandKind::StopProgram}) { + const auto routing = routed(kind); + require(routing.priority == CommandPriority::Safety, "stops are safety"); + require(!routing.task_queued, "stops do not start a hold"); + } + for (const auto state : + {detail::kNmlTaskStateEstop, detail::kNmlTaskStateOff}) { + require(routed(NmlCommandKind::SetTaskState, state).priority == + CommandPriority::Safety, + "E-stop and machine off are safety commands"); + } + 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) { + log.add(serial); + detail::track_written_command( + &tracker, context, serial, task_queued, timeout, + [this] { ++completed_callbacks; }, + [this] { ++failed_callbacks; }); + }, + {}, 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 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 command_validation_test() { NmlStatusSnapshot configuration; configuration.motion_stat.traj.joints = 3; @@ -930,6 +1318,19 @@ 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(); + nml_command_routing_test(); + queued_command_failure_attribution_test(); + queued_command_success_releases_hold_test(); + queued_command_superseded_by_safety_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(); command_validation_test(); nml_serial_wrap_test(); position_cursor_generation_and_replacement_test(); From 07d216cb105511d06388979781374c57b31f1c99 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 11:47:03 +0100 Subject: [PATCH 20/45] test(native): cover every owned S32/U32 write path Move NarrowItemRegistry to a header and unit-test add, remove, owner mismatch, aliases and re-creation. Extend the live HAL test with linked signals, pin and parameter aliases, parameters and component re-creation. --- native/server/src/hal/adapter.cc | 62 +------ .../server/src/hal/narrow_item_registry.hpp | 79 +++++++++ native/server/tests/grpc_live_hal.cc | 160 ++++++++++++++++++ native/server/tests/hal_value_codec_tests.cc | 132 +++++++++++++++ .../server/tests/run_grpc_live_integration.sh | 4 + 5 files changed, 376 insertions(+), 61 deletions(-) create mode 100644 native/server/src/hal/narrow_item_registry.hpp diff --git a/native/server/src/hal/adapter.cc b/native/server/src/hal/adapter.cc index fe8f39e..f35a4ed 100644 --- a/native/server/src/hal/adapter.cc +++ b/native/server/src/hal/adapter.cc @@ -22,6 +22,7 @@ #include #include +#include "hal/narrow_item_registry.hpp" #include "hal/query.hpp" #include "hal/value_codec.hpp" @@ -154,70 +155,9 @@ HalAdapterValue from_hal(hal_type_t type, const hal_query_value_u& value) { } } -using hal_codec::fits_declared; using hal_codec::read_owned; using hal_codec::to_hal; -// 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 && - !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_; -}; - // 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) { 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 0000000..35abebb --- /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/tests/grpc_live_hal.cc b/native/server/tests/grpc_live_hal.cc index e706961..bd493bd 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 @@ -35,6 +36,163 @@ 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; + 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"); + + 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; @@ -693,6 +851,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); diff --git a/native/server/tests/hal_value_codec_tests.cc b/native/server/tests/hal_value_codec_tests.cc index 9f73c19..8632406 100644 --- a/native/server/tests/hal_value_codec_tests.cc +++ b/native/server/tests/hal_value_codec_tests.cc @@ -3,10 +3,12 @@ #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" @@ -146,11 +148,141 @@ void check_read_owned() { 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/run_grpc_live_integration.sh b/native/server/tests/run_grpc_live_integration.sh index 5e0c329..12f8ba4 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 From 485e65925094adabe134f1428e20223d72319341 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 12:01:51 +0100 Subject: [PATCH 21/45] test(native): make command hold tests deterministic Record a simulated write only after the command is tracked, so a status published in response cannot be mistaken for an older one. Queue the live Resume case's tool delete after the pause, where Resume really has to pass the hold. --- native/server/tests/grpc_live_support.cc | 15 +++++++++------ native/server/tests/native_edge_tests.cc | 4 +++- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/native/server/tests/grpc_live_support.cc b/native/server/tests/grpc_live_support.cc index c208fa5..d942437 100644 --- a/native/server/tests/grpc_live_support.cc +++ b/native/server/tests/grpc_live_support.cc @@ -497,10 +497,12 @@ void create_live_tool(linuxcnc::v1::MachineService::Stub* machine, int tool_no, // is still unresolved when the caller sends its next command. class QueuedToolDelete { public: - QueuedToolDelete(linuxcnc::v1::MachineService::Stub* machine, int tool_no) { + 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); @@ -594,14 +596,15 @@ void verify_task_queued_command_ordering( mdi_mode.mutable_set_task_mode()->set_mode(linuxcnc::v1::TASK_MODE_MDI); (void)execute_completed(machine, std::move(mdi_mode)); - // A queued command cannot finish while the program is paused, so Resume has + // 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); - ExecuteCommandRequest pause; - pause.mutable_pause_program(); - (void)execute_accepted(machine, std::move(pause)); + 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(); diff --git a/native/server/tests/native_edge_tests.cc b/native/server/tests/native_edge_tests.cc index a51d84d..a0e64cc 100644 --- a/native/server/tests/native_edge_tests.cc +++ b/native/server/tests/native_edge_tests.cc @@ -485,11 +485,13 @@ class TrackedCommands { CommandPriority priority = CommandPriority::Normal) { return submitted(coordinator.submit_with_context( [this, serial, task_queued](CommandContext& context) { - log.add(serial); 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)); } From a73a04b5fd8e46ecbb7e72a63089a796682f8609 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 12:25:27 +0100 Subject: [PATCH 22/45] test(native): satisfy lint in the live HAL write checks --- native/server/tests/grpc_live_hal.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/native/server/tests/grpc_live_hal.cc b/native/server/tests/grpc_live_hal.cc index bd493bd..739feaf 100644 --- a/native/server/tests/grpc_live_hal.cc +++ b/native/server/tests/grpc_live_hal.cc @@ -73,6 +73,7 @@ void require_narrow(linuxcnc::v1::HalService::Stub* hal, 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()); } @@ -163,6 +164,7 @@ void verify_narrow_write_paths(linuxcnc::v1::HalService::Stub* hal) { 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); From 844ff61d12f3f38f7e67c177b5b9e415aead3a95 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 13:36:40 +0100 Subject: [PATCH 23/45] fix(linuxcnc): address medium findings from review round 2 Patch 0024: an interpreter re-init always drops MDI commands not read yet, and aborts only an interrupted call. A running command, including G38.n, M66, M6 and G28.2, keeps its state and finishes normally. Patch 0012: a refused tool update or delete reports why and fails only that command. A save is refused while the configured table file differs from what was last loaded or saved, follows symbolic links, and only loading that file lifts a save block. On a random changer the first table to load after a failed startup sets the spindle tool. Patch 0007: a G10 whose save fails reports an operator error and fails the command. Patch 0017: motion publishes the command number of the last home it started, so a home that finishes between two task status reads is not reported as "did not start". Verified locally: 346 of 354 regression tests passed; the 8 failures are GUI tests on a --disable-gui build. --- .../0007-native-automatic-tool-wear.patch | 53 +- ...-own-transactional-tool-CRUD-in-task.patch | 1137 ++++++++++++++--- ...-publish-modal-CSS-maximum-in-status.patch | 2 +- ...ntime-joint-and-spindle-availability.patch | 620 +++++++-- ...w-concurrent-individual-joint-homing.patch | 12 +- ...otion-add-native-lathe-power-jogging.patch | 24 +- ...te-whenever-the-interpreter-is-reset.patch | 244 +++- linuxcnc-patches/README.md | 30 +- 8 files changed, 1813 insertions(+), 309 deletions(-) diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index fbc9868..06a1724 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -131,12 +131,12 @@ Fixes from review of the port: tests/t0/random-with-t0/expected-gcode-output | 2 +- .../random-without-t0/expected-gcode-output | 2 +- tests/tlo/test-ui.py | 7 +- - tests/tool-line-length-save/.gitignore | 4 + + tests/tool-line-length-save/.gitignore | 5 + tests/tool-line-length-save/checkresult | 2 + tests/tool-line-length-save/lathe.ini | 85 +++++ tests/tool-line-length-save/make-table.py | 13 + tests/tool-line-length-save/random-ui.py | 62 +++ - tests/tool-line-length-save/test-ui.py | 86 +++++ + tests/tool-line-length-save/test-ui.py | 116 ++++++ tests/tool-line-length-save/test.sh | 12 + tests/tool-wear-abort/.gitignore | 3 + tests/tool-wear-abort/change-move.ngc | 5 + @@ -186,7 +186,7 @@ Fixes from review of the port: tests/tooldb/db-line-length/test-ui.py | 18 + tests/tooldb/db-line-length/test.ini | 5 + tests/tooldb/db-line-length/test.sh | 14 + - 129 files changed, 2906 insertions(+), 294 deletions(-) + 129 files changed, 2937 insertions(+), 294 deletions(-) create mode 100644 tests/interp/tool-line-length/expected create mode 100644 tests/interp/tool-line-length/missing-t2.ngc create mode 100644 tests/interp/tool-line-length/missing-t3.ngc @@ -1706,7 +1706,7 @@ index 15aac38..6025a96 100644 emcAbortCleanup(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); diff --git a/src/emc/task/taskclass.cc b/src/emc/task/taskclass.cc -index 6694667..72b698b4 100644 +index 6694667..0d076c8 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc @@ -114,12 +114,44 @@ int emcToolPrepare(int tool) { return task_methods->emcToolPrepare(tool); } @@ -1911,8 +1911,8 @@ index 6694667..72b698b4 100644 + if (tooldata_put(previous,idx) != IDX_OK) { UNEXPECTED_MSG; } -+ rcs_print_error("tool %d: offsets not stored, tool table unchanged\n", toolno); -+ emcioStatus.status = RCS_STATUS::ERROR; ++ emcOperatorError("tool %d: offsets not stored, tool table unchanged", toolno); ++ return -1; } return 0; @@ -3292,14 +3292,15 @@ index 42fe939..2814fe0 100755 - diff --git a/tests/tool-line-length-save/.gitignore b/tests/tool-line-length-save/.gitignore new file mode 100644 -index 0000000..abf8040 +index 0000000..ed7a35c --- /dev/null +++ b/tests/tool-line-length-save/.gitignore -@@ -0,0 +1,4 @@ +@@ -0,0 +1,5 @@ +sim.var +sim.var.bak +tool.tbl +random.ini ++g10.ngc diff --git a/tests/tool-line-length-save/checkresult b/tests/tool-line-length-save/checkresult new file mode 100755 index 0000000..24dc9aa @@ -3488,10 +3489,10 @@ index 0000000..35b3c18 +sys.exit(0) diff --git a/tests/tool-line-length-save/test-ui.py b/tests/tool-line-length-save/test-ui.py new file mode 100755 -index 0000000..9840cd3 +index 0000000..08ce5ff --- /dev/null +++ b/tests/tool-line-length-save/test-ui.py -@@ -0,0 +1,86 @@ +@@ -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 @@ -3542,6 +3543,19 @@ index 0000000..9840cd3 + 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) @@ -3556,13 +3570,30 @@ index 0000000..9840cd3 +print("*** a G10 edit is refused: file and memory unchanged") +before = table() +c.mdi("g10 l3 p1 x0.1") -+c.wait_complete() ++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") 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 284317a..de51de2 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 @@ -22,36 +22,60 @@ 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 | 280 ++++++++++++++++-- - src/emc/task/taskclass.hh | 5 +- - src/emc/tooldata/tooldata.hh | 18 ++ - src/emc/tooldata/tooldata_common.cc | 274 +++++++++++------ - src/emc/tooldata/tooldata_mmap.cc | 102 ++++++- + src/emc/nml_intf/emc_nml.hh | 44 ++ + src/emc/task/emctaskmain.cc | 71 +++- + src/emc/task/taskclass.cc | 369 ++++++++++++++++- + 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 + + tests/tool-crud-refusal/.gitignore | 5 + + tests/tool-crud-refusal/README | 7 + + tests/tool-crud-refusal/checkresult | 2 + + tests/tool-crud-refusal/program.ngc | 2 + + tests/tool-crud-refusal/test-ui.py | 83 ++++ + tests/tool-crud-refusal/test.sh | 12 + + tests/tool-crud-refusal/tool-cmd.cc | 50 +++ tests/tool-line-length-save/random-ui.py | 31 ++ - tests/tool-table-load/.gitignore | 4 + + tests/tool-table-load/.gitignore | 6 + tests/tool-table-load/checkresult | 2 + - tests/tool-table-load/common.py | 76 +++++ + tests/tool-table-load/common.py | 121 ++++++ tests/tool-table-load/crlf-ui.py | 27 ++ - tests/tool-table-load/garbage-ui.py | 56 ++++ + tests/tool-table-load/external-edit-ui.py | 74 ++++ + tests/tool-table-load/garbage-ui.py | 51 +++ + tests/tool-table-load/missing-ui.py | 52 +++ + tests/tool-table-load/other-table-ui.py | 33 ++ + tests/tool-table-load/random-start-ui.py | 36 ++ tests/tool-table-load/reload-ui.py | 26 ++ - tests/tool-table-load/test.ini | 84 ++++++ - tests/tool-table-load/test.sh | 29 ++ + tests/tool-table-load/symlink-ui.py | 55 +++ + tests/tool-table-load/test.ini | 84 ++++ + tests/tool-table-load/test.sh | 65 +++ .../reload-tool/non-random/test-ui.py | 14 + .../toolchanger/reload-tool/random/test-ui.py | 3 +- tests/tooldb/db-g10-offset/skip | 3 + tests/tooldb/db-line-length/skip | 3 + - 23 files changed, 1073 insertions(+), 123 deletions(-) + 35 files changed, 1773 insertions(+), 128 deletions(-) + create mode 100644 tests/tool-crud-refusal/.gitignore + create mode 100644 tests/tool-crud-refusal/README + create mode 100755 tests/tool-crud-refusal/checkresult + create mode 100644 tests/tool-crud-refusal/program.ngc + create mode 100755 tests/tool-crud-refusal/test-ui.py + create mode 100755 tests/tool-crud-refusal/test.sh + create mode 100644 tests/tool-crud-refusal/tool-cmd.cc create mode 100644 tests/tool-table-load/.gitignore create mode 100755 tests/tool-table-load/checkresult create mode 100644 tests/tool-table-load/common.py create mode 100755 tests/tool-table-load/crlf-ui.py + create mode 100755 tests/tool-table-load/external-edit-ui.py create mode 100755 tests/tool-table-load/garbage-ui.py + create mode 100755 tests/tool-table-load/missing-ui.py + create mode 100755 tests/tool-table-load/other-table-ui.py + create mode 100755 tests/tool-table-load/random-start-ui.py create mode 100755 tests/tool-table-load/reload-ui.py + create mode 100755 tests/tool-table-load/symlink-ui.py create mode 100644 tests/tool-table-load/test.ini create mode 100755 tests/tool-table-load/test.sh create mode 100644 tests/tooldb/db-g10-offset/skip @@ -201,7 +225,7 @@ index cf8bc14..b40c76d 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index f69fcbb..269facc 100644 +index f69fcbb..bb43b9c 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1263,7 +1263,18 @@ static int emcTaskPlan(void) @@ -314,8 +338,28 @@ index f69fcbb..269facc 100644 case EMC_TOOL_SET_NUMBER_TYPE: case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: +@@ -3244,10 +3303,18 @@ 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 ++ ? 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 72b698b4..6594e3d 100644 +index 0d076c8..3bac973 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc @@ -17,6 +17,7 @@ @@ -378,16 +422,44 @@ index 72b698b4..6594e3d 100644 emcioStatus.status = RCS_STATUS::DONE;//TODO?? emcioStatus.tool.pocketPrepped = -1; -@@ -246,7 +237,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"); ++ } } -@@ -417,7 +408,16 @@ 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 { @@ -396,16 +468,20 @@ index 72b698b4..6594e3d 100644 + rcs_print_error("can't initialize IO: [EMCIO]DB_PROGRAM is not supported\n"); + return -1; + } -+ if (tooltable_filename && 0 != tooldata_load(tooltable_filename)) { -+ // the machine starts without the table, and the file is not saved -+ // over until a table loads -+ emcOperatorError("can't load tool table %s: no tools until it is " -+ "corrected and reloaded", 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); if (0 != iniTool(emc_inifile)) { -@@ -589,10 +589,60 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE +@@ -589,10 +612,70 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE return 0; } @@ -448,26 +524,36 @@ index 72b698b4..6594e3d 100644 + problem = "pocket 0 does not hold the tool in the spindle"; + } + if (problem) { -+ // the table in memory stays. If the file now holds something else, -+ // it is not saved over until a table loads ++ // 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 (!unchanged && same_file(file, tooltable_filename)) { -+ tooldata_set_refused_lines(true); ++ 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; -+ tooldata_set_refused_lines(refused_lines); ++ // 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; } -@@ -634,9 +684,10 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -634,9 +717,10 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, UNEXPECTED_MSG; } bool stored = (0 == tooldata_save(tooltable_filename)); @@ -479,7 +565,7 @@ index 72b698b4..6594e3d 100644 int pno = idx; // for random_toolchanger if (!random_toolchanger) { pno = tdata.pocketno; } if (tooldata_db_notify(TOOL_OFFSET,toolno,pno,tdata)) { -@@ -656,6 +707,193 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -656,6 +740,247 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, return 0; } @@ -542,6 +628,22 @@ index 72b698b4..6594e3d 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( @@ -555,44 +657,69 @@ index 72b698b4..6594e3d 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 || + (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 -1; ++ 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) { @@ -605,7 +732,9 @@ index 72b698b4..6594e3d 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; @@ -631,41 +760,52 @@ index 72b698b4..6594e3d 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 || ++ 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 -1; ++ 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; +} @@ -674,7 +814,7 @@ index 72b698b4..6594e3d 100644 { int idx; diff --git a/src/emc/task/taskclass.hh b/src/emc/task/taskclass.hh -index 509f11f..d9afc98 100644 +index 509f11f..6077e19 100644 --- a/src/emc/task/taskclass.hh +++ b/src/emc/task/taskclass.hh @@ -75,6 +75,8 @@ public: @@ -686,18 +826,27 @@ index 509f11f..d9afc98 100644 int iocontrol_hal_init(void); void reload_tool_number(int toolno); -@@ -89,8 +91,7 @@ public: +@@ -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 db3e6b7..d4829ff 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); @@ -709,7 +858,7 @@ index db3e6b7..d4829ff 100644 // ignore_zero_values:1 for file writes // :0 for use with tooldata_db_notify() -@@ -76,8 +78,24 @@ void tooldata_set_db(tooldb_t mode); +@@ -76,8 +78,27 @@ void tooldata_set_db(tooldb_t mode); //---------------------------------------------------------- int tooldata_load(const char *filename); @@ -720,8 +869,11 @@ index db3e6b7..d4829ff 100644 + 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 a table without them is loaded ++// 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, @@ -735,10 +887,15 @@ index db3e6b7..d4829ff 100644 //---------------------------------------------------------- //mmap specific diff --git a/src/emc/tooldata/tooldata_common.cc b/src/emc/tooldata/tooldata_common.cc -index ceefe9b..93626f8 100644 +index ceefe9b..0695af8 100644 --- a/src/emc/tooldata/tooldata_common.cc +++ b/src/emc/tooldata/tooldata_common.cc -@@ -24,7 +24,12 @@ +@@ -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 @@ -751,7 +908,7 @@ index ceefe9b..93626f8 100644 #include "tooldata.hh" #define UNEXPECTED_MSG fprintf(stderr,"UNEXPECTED %s %d\n",__FILE__,__LINE__); -@@ -33,6 +38,25 @@ static bool is_random_toolchanger = 0; +@@ -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; @@ -777,7 +934,7 @@ index ceefe9b..93626f8 100644 void tooldata_init(bool random_toolchanger) { -@@ -92,12 +116,19 @@ 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; @@ -801,7 +958,7 @@ index ceefe9b..93626f8 100644 comment = strtok_r(NULL, "\n", &saveptr); token = strtok_r(buff, " ", &saveptr); -@@ -206,7 +237,7 @@ int tooldata_read_entry(const char *input_line) +@@ -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 @@ -810,7 +967,7 @@ index ceefe9b..93626f8 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__); -@@ -233,7 +264,7 @@ int tooldata_read_entry(const char *input_line) +@@ -233,7 +266,7 @@ int tooldata_read_entry(const char *input_line) ); } } @@ -819,7 +976,7 @@ index ceefe9b..93626f8 100644 UNEXPECTED_MSG; } } else { -@@ -323,31 +354,27 @@ int tooldata_format_toolline (int idx, +@@ -323,50 +356,130 @@ int tooldata_format_toolline (int idx, return 0; } // tooldata_format_toolline() @@ -832,42 +989,127 @@ index ceefe9b..93626f8 100644 -int tooldata_load(const char *filename) +void tooldata_set_refused_lines(bool refused) -+{ + { +- FILE *fp; +- char input_line[CANON_TOOL_ENTRY_LEN]; +- char orig_line[CANON_TOOL_ENTRY_LEN]; + table_has_refused_lines = refused; +} -+ -+int tooldata_load_snapshot(const char *filename, -+ CANON_TOOL_TABLE *staged, -+ int *last_index, -+ bool *refused_lines) - { - FILE *fp; - char input_line[CANON_TOOL_ENTRY_LEN]; - char orig_line[CANON_TOOL_ENTRY_LEN]; - 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 || !refused_lines || + db_mode == DB_ACTIVE) return -1; - // open tool table file - if (NULL == (fp = fopen(filename, "r"))) { -@@ -356,16 +383,17 @@ 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 @@ -884,11 +1126,13 @@ index ceefe9b..93626f8 100644 - 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 -@@ -383,7 +411,7 @@ 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); @@ -897,7 +1141,7 @@ index ceefe9b..93626f8 100644 continue; } strcpy(orig_line, input_line); -@@ -391,37 +419,74 @@ int tooldata_load(const char *filename) +@@ -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) { @@ -927,13 +1171,14 @@ index ceefe9b..93626f8 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; + *refused_lines = refused; ++ last_read_content = std::move(content); + return 0; +} // tooldata_load_snapshot() @@ -958,18 +1203,23 @@ index ceefe9b..93626f8 100644 + 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() -// 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) -+// Write idx's tool line from table, or from the table in memory if table -+// is NULL; -1 if it is too long to write or the write fails. -+static int write_tool_line(FILE* fp, int idx, const CANON_TOOL_TABLE *table) ++// 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 0;} @@ -981,12 +1231,12 @@ index ceefe9b..93626f8 100644 if (db_mode == DB_ACTIVE && idx != 0 ) { return 0; } -@@ -433,63 +498,98 @@ static int write_tool_line(std::string &table,int idx) +@@ -433,63 +588,114 @@ static int write_tool_line(std::string &table,int idx) tdata,theline)) { return -1; } - table += theline; -+ if (fprintf(fp,"%s",theline) < 0) return -1; ++ out->append(theline); } return 0; } // write_tool_line() @@ -1019,6 +1269,19 @@ index ceefe9b..93626f8 100644 - 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}; @@ -1032,17 +1295,10 @@ index ceefe9b..93626f8 100644 + return true; +} -- // 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;} -- } +- // 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) @@ -1053,45 +1309,61 @@ index ceefe9b..93626f8 100644 + 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; -+ } -+ // a tool whose line is too long fails the write, and the file stays as + 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 temporary = std::string(filename) + ".tmp.XXXXXX"; ++ 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; } - } ++ 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() - -- // 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; + } //tooldata_save() ++ +int tooldata_save(const char *filename) +{ + if (db_mode == DB_ACTIVE) { @@ -1109,20 +1381,14 @@ index ceefe9b..93626f8 100644 + if (!result && fsync(fileno(fp))) result = -1; + if (fclose(fp)) result = -1; + return result; - } -- 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)); ++ } + // 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; - } -- return 0; --} //tooldata_save() ++ return -1; ++ } + CANON_TOOL_TABLE table[CANON_POCKETS_MAX]; + int last_index = 0; + if (tooldata_snapshot(table, &last_index)) return -1; @@ -1370,6 +1636,209 @@ index f333925..a7ee61e 100644 + memcpy(the_table, table, CANON_POCKETS_MAX * sizeof(*table)); + return 0; +} +diff --git a/tests/tool-crud-refusal/.gitignore b/tests/tool-crud-refusal/.gitignore +new file mode 100644 +index 0000000..89772f7 +--- /dev/null ++++ b/tests/tool-crud-refusal/.gitignore +@@ -0,0 +1,5 @@ ++sim.var ++sim.var.bak ++tool.tbl ++run.ini ++tool-cmd +diff --git a/tests/tool-crud-refusal/README b/tests/tool-crud-refusal/README +new file mode 100644 +index 0000000..1535c26 +--- /dev/null ++++ b/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/tests/tool-crud-refusal/checkresult b/tests/tool-crud-refusal/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/tool-crud-refusal/program.ngc b/tests/tool-crud-refusal/program.ngc +new file mode 100644 +index 0000000..1f0eacc +--- /dev/null ++++ b/tests/tool-crud-refusal/program.ngc +@@ -0,0 +1,2 @@ ++G0 X1 ++M2 +diff --git a/tests/tool-crud-refusal/test-ui.py b/tests/tool-crud-refusal/test-ui.py +new file mode 100755 +index 0000000..8d6ef70 +--- /dev/null ++++ b/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/tests/tool-crud-refusal/test.sh b/tests/tool-crud-refusal/test.sh +new file mode 100755 +index 0000000..c9a8d42 +--- /dev/null ++++ b/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 ++cp ../tool-table-load/test.ini run.ini ++linuxcnc -r run.ini +diff --git a/tests/tool-crud-refusal/tool-cmd.cc b/tests/tool-crud-refusal/tool-cmd.cc +new file mode 100644 +index 0000000..226cf79 +--- /dev/null ++++ b/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/tests/tool-line-length-save/random-ui.py b/tests/tool-line-length-save/random-ui.py index 35b3c18..4b2e267 100755 --- a/tests/tool-line-length-save/random-ui.py @@ -1413,13 +1882,15 @@ index 35b3c18..4b2e267 100755 sys.exit(0) diff --git a/tests/tool-table-load/.gitignore b/tests/tool-table-load/.gitignore new file mode 100644 -index 0000000..76e1adf +index 0000000..ebe0144 --- /dev/null +++ b/tests/tool-table-load/.gitignore -@@ -0,0 +1,4 @@ +@@ -0,0 +1,6 @@ +sim.var +sim.var.bak +tool.tbl ++other.tbl ++linked/ +run.ini diff --git a/tests/tool-table-load/checkresult b/tests/tool-table-load/checkresult new file mode 100755 @@ -1431,14 +1902,17 @@ index 0000000..24dc9aa +exit 0 # test failure is indicated by test.sh exit value diff --git a/tests/tool-table-load/common.py b/tests/tool-table-load/common.py new file mode 100644 -index 0000000..69f291e +index 0000000..fe72033 --- /dev/null +++ b/tests/tool-table-load/common.py -@@ -0,0 +1,76 @@ +@@ -0,0 +1,121 @@ ++import hal +import linuxcnc +import linuxcnc_util + +import math ++import socket ++import subprocess +import sys +import time + @@ -1511,6 +1985,48 @@ index 0000000..69f291e +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/tests/tool-table-load/crlf-ui.py b/tests/tool-table-load/crlf-ui.py new file mode 100755 index 0000000..f2c8011 @@ -1544,18 +2060,99 @@ index 0000000..f2c8011 + fail("tools lost from the saved table") +print("*** all checks passed") +sys.exit(0) +diff --git a/tests/tool-table-load/external-edit-ui.py b/tests/tool-table-load/external-edit-ui.py +new file mode 100755 +index 0000000..ce064c0 +--- /dev/null ++++ b/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/tests/tool-table-load/garbage-ui.py b/tests/tool-table-load/garbage-ui.py new file mode 100755 -index 0000000..89099f9 +index 0000000..e390c5d --- /dev/null +++ b/tests/tool-table-load/garbage-ui.py -@@ -0,0 +1,56 @@ +@@ -0,0 +1,51 @@ +#!/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, the machine has no tools, and the file is -+not saved over. A table loaded later lifts that; a reload of the file that -+fails keeps the table in memory but again keeps the file from being saved -+over.""" ++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 * + @@ -1563,12 +2160,6 @@ index 0000000..89099f9 +wait_error("can't load tool table") +if tools(): + fail("tools %s loaded from a table that did not load" % sorted(tools())) -+before = table() -+ -+print("*** a G10 edit finds no tool and does not touch the file") -+mdi("g10 l1 p1 z5") -+if table() != before: -+ fail("the table file was rewritten:\n" + table()) + +print("*** with the line fixed and the table reloaded, saving works") +with open("tool.tbl", "w") as f: @@ -1606,6 +2197,145 @@ index 0000000..89099f9 +print(table()) +print("*** all checks passed") +sys.exit(0) +diff --git a/tests/tool-table-load/missing-ui.py b/tests/tool-table-load/missing-ui.py +new file mode 100755 +index 0000000..0f44290 +--- /dev/null ++++ b/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/tests/tool-table-load/other-table-ui.py b/tests/tool-table-load/other-table-ui.py +new file mode 100755 +index 0000000..af9ba05 +--- /dev/null ++++ b/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/tests/tool-table-load/random-start-ui.py b/tests/tool-table-load/random-start-ui.py +new file mode 100755 +index 0000000..3b860d3 +--- /dev/null ++++ b/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/tests/tool-table-load/reload-ui.py b/tests/tool-table-load/reload-ui.py new file mode 100755 index 0000000..5e073f5 @@ -1638,6 +2368,67 @@ index 0000000..5e073f5 +print(table()) +print("*** all checks passed") +sys.exit(0) +diff --git a/tests/tool-table-load/symlink-ui.py b/tests/tool-table-load/symlink-ui.py +new file mode 100755 +index 0000000..2e03fa7 +--- /dev/null ++++ b/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/tests/tool-table-load/test.ini b/tests/tool-table-load/test.ini new file mode 100644 index 0000000..9338ce7 @@ -1730,10 +2521,10 @@ index 0000000..9338ce7 +HOME_SEQUENCE = 0 diff --git a/tests/tool-table-load/test.sh b/tests/tool-table-load/test.sh new file mode 100755 -index 0000000..c629639 +index 0000000..db74c94 --- /dev/null +++ b/tests/tool-table-load/test.sh -@@ -0,0 +1,29 @@ +@@ -0,0 +1,65 @@ +#!/bin/bash +set -e + @@ -1763,6 +2554,42 @@ index 0000000..c629639 +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 ++ sed -e "s#^DISPLAY = ./test-ui.py\$#DISPLAY = ./$1#" \ ++ -e "s#^RANDOM_TOOLCHANGER = 0\$#RANDOM_TOOLCHANGER = $2#" test.ini > run.ini ++ 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/tests/toolchanger/reload-tool/non-random/test-ui.py b/tests/toolchanger/reload-tool/non-random/test-ui.py index fca46c3..445e5ee 100755 --- a/tests/toolchanger/reload-tool/non-random/test-ui.py 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 3e870b7..aa6fee0 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 @@ -40,7 +40,7 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 269facc..7a81049 100644 +index bb43b9c..ee88562 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1035,7 +1035,7 @@ static void emcTaskStopProgress() diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index 31935be..8529de7 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -31,7 +31,7 @@ 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 | 33 ++ + docs/src/config/ini-config.adoc | 33 + docs/src/config/python-interface.adoc | 26 + docs/src/man/man9/motion.9.adoc | 26 + src/emc/ini/inijoint.cc | 36 +- @@ -39,20 +39,27 @@ other motion-logger tests. 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 | 374 +++++++++++- - src/emc/motion/control.c | 559 ++++++++++++++++-- + src/emc/motion/command.c | 376 +++++++++++- + src/emc/motion/control.c | 568 ++++++++++++++++-- + src/emc/motion/homing.h | 4 +- src/emc/motion/mot_priv.h | 21 + - src/emc/motion/motion.c | 16 + - src/emc/motion/motion.h | 60 +- + 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 | 16 + 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 | 269 ++++++++- + src/emc/task/emctaskmain.cc | 295 ++++++++- src/emc/task/task.hh | 1 + - src/emc/task/taskintf.cc | 94 ++- + src/emc/task/taskintf.cc | 112 +++- src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + + tests/interp/g28.2/instant-home/README | 7 + + tests/interp/g28.2/instant-home/checkresult | 2 + + tests/interp/g28.2/instant-home/sim.tbl | 0 + tests/interp/g28.2/instant-home/test-ui.py | 80 +++ + tests/interp/g28.2/instant-home/test.ini | 103 ++++ + tests/interp/g28.2/instant-home/test.sh | 2 + .../expected.motion-logger | 17 +- .../basic/expected.builtin-startup.in | 16 +- .../mountaindew/expected.motion-logger | 11 +- @@ -62,7 +69,7 @@ other motion-logger tests. .../availability-fixture.h | 5 + tests/motion-target-preparation/test.py | 57 ++ .../.gitignore | 2 + - tests/runtime-availability-regressions/README | 20 + + tests/runtime-availability-regressions/README | 22 + .../runtime-availability-regressions/base.ini | 94 +++ .../checkresult | 5 + .../runtime-availability-regressions/core.hal | 17 + @@ -70,32 +77,39 @@ other motion-logger tests. .../extra.hal | 17 + .../extra.ini.in | 16 + .../fault.ini.in | 13 + - .../fixture.py | 75 +++ + .../fixture.py | 81 +++ .../joghome.ini.in | 6 + .../record_abort.ngc | 6 + .../sequence.ini.in | 6 + + .../slowtask.ini.in | 7 + .../runtime-availability-regressions/tail.hal | 30 + .../tail.ini.in | 7 + - .../test-ui.py | 192 ++++++ + .../test-ui.py | 198 ++++++ .../test.ini.in | 3 + - .../runtime-availability-regressions/test.sh | 34 ++ + .../runtime-availability-regressions/test.sh | 35 ++ .../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/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-ui.py | 297 +++++++++ tests/runtime-availability/test.ini.in | 3 + tests/runtime-availability/test.sh | 5 + tests/runtime-availability/tool.tbl | 0 - 64 files changed, 2846 insertions(+), 91 deletions(-) + 72 files changed, 3123 insertions(+), 103 deletions(-) + create mode 100644 tests/interp/g28.2/instant-home/README + create mode 100755 tests/interp/g28.2/instant-home/checkresult + create mode 100644 tests/interp/g28.2/instant-home/sim.tbl + create mode 100755 tests/interp/g28.2/instant-home/test-ui.py + create mode 100644 tests/interp/g28.2/instant-home/test.ini + create mode 100755 tests/interp/g28.2/instant-home/test.sh 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 @@ -111,6 +125,7 @@ other motion-logger tests. 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/slowtask.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 @@ -477,7 +492,7 @@ index e814320..029af60 100644 if (!motion_enable_flag) { 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 ff48890..e24a9d2 100644 +index ff48890..9d6fb2c 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -80,6 +80,16 @@ extern int motion_num_spindles; @@ -781,10 +796,11 @@ index ff48890..e24a9d2 100644 /* 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 -@@ -1595,6 +1760,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1595,9 +1760,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 = @@ -794,7 +810,11 @@ index ff48890..e24a9d2 100644 // Negative joint_num specifies homeall do_home_joint(joint_num); -@@ -1611,6 +1782,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) ++ emcmotInternal->home_started_command = emcmotCommand->commandNum; + break; + + case EMCMOT_JOINT_UNHOME: +@@ -1611,6 +1784,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) return; } @@ -821,7 +841,7 @@ index ff48890..e24a9d2 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'. -@@ -1629,6 +1820,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1629,6 +1822,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; @@ -982,7 +1002,7 @@ index ff48890..e24a9d2 100644 case EMCMOT_CLEAR_PROBE_FLAGS: rtapi_print_msg(RTAPI_MSG_DBG, "CLEAR_PROBE_FLAGS"); emcmotStatus->probing = 0; -@@ -1825,6 +2170,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1825,6 +2172,11 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -994,7 +1014,7 @@ index ff48890..e24a9d2 100644 for (n = s0; n<=s1; n++){ if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) -@@ -1930,8 +2280,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1930,8 +2282,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1008,7 +1028,7 @@ index ff48890..e24a9d2 100644 if (n > emcmotConfig->numSpindles){ rtapi_print_msg(RTAPI_MSG_ERR, "spindle number <%d> too high in M19",n); break; -@@ -1981,6 +2335,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1981,6 +2337,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1019,7 +1039,7 @@ index ff48890..e24a9d2 100644 for (n = s0; n<=s1; n++){ if (emcmotStatus->spindle_status[n].speed > 0) { emcmotStatus->spindle_status[n].speed += emcmotStatus->spindle_status[n].increment; -@@ -2005,6 +2363,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -2005,6 +2365,10 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1030,7 +1050,7 @@ index ff48890..e24a9d2 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; -@@ -2051,8 +2413,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -2051,8 +2415,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -1045,7 +1065,7 @@ index ff48890..e24a9d2 100644 } break; diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index f22ab9b..ff24751 100644 +index f22ab9b..31c4284 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c @@ -45,6 +45,9 @@ static int switchkins_type = 0; @@ -1075,7 +1095,7 @@ index f22ab9b..ff24751 100644 do_forward_kins(); process_probe_inputs(); check_for_faults(); -@@ -258,13 +264,22 @@ void emcmotController(void *arg, long period) +@@ -258,13 +264,28 @@ void emcmotController(void *arg, long period) if (!hal_get_bool(emcmot_hal_data->jog_inhibit)) { handle_jjogwheels(); } @@ -1094,15 +1114,22 @@ index f22ab9b..ff24751 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(); ++ } } + 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. */ -@@ -518,8 +533,29 @@ static void process_inputs(void) +@@ -518,8 +539,29 @@ static void process_inputs(void) joint_data = &(emcmot_hal_data->joint[joint_num]); /* point to joint data */ joint = &joints[joint_num]; @@ -1133,7 +1160,7 @@ index f22ab9b..ff24751 100644 continue; } /* copy data from HAL to joint structure */ -@@ -567,25 +603,7 @@ static void process_inputs(void) +@@ -567,25 +609,7 @@ static void process_inputs(void) SET_JOINT_FERROR_FLAG(joint, 0); } @@ -1160,7 +1187,7 @@ index f22ab9b..ff24751 100644 } // a fault was signalled during a spindle-orient in progress -@@ -629,6 +647,400 @@ static void process_inputs(void) +@@ -629,6 +653,401 @@ static void process_inputs(void) } } @@ -1308,6 +1335,7 @@ index f22ab9b..ff24751 100644 + 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 = @@ -1561,7 +1589,7 @@ index f22ab9b..ff24751 100644 static void joint_jog_abort_all(bool immediate) { int jNum; -@@ -691,7 +1103,7 @@ static void do_forward_kins(void) +@@ -691,7 +1110,7 @@ static void do_forward_kins(void) at the traj rate */ double joint_pos[EMCMOT_MAX_JOINTS] = {0,}; @@ -1570,7 +1598,7 @@ index f22ab9b..ff24751 100644 emcmot_joint_t *joint; /* copy joint position feedback to local array */ -@@ -873,7 +1285,9 @@ static void check_for_faults(void) +@@ -873,7 +1292,9 @@ static void check_for_faults(void) } /* check for spindle ampfifier errors */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1581,7 +1609,7 @@ index f22ab9b..ff24751 100644 reportError(_("spindle %d amplifier fault"), spindle_num); emcmotInternal->enabling = 0; } -@@ -945,6 +1359,7 @@ static void set_operating_mode(void) +@@ -945,6 +1366,7 @@ static void set_operating_mode(void) /* check for disabling */ if (!emcmotInternal->enabling && GET_MOTION_ENABLE_FLAG()) { @@ -1589,7 +1617,7 @@ index f22ab9b..ff24751 100644 /* clear out the motion emcmotInternal->coord_tp and interpolators */ tpClear(&emcmotInternal->coord_tp); for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -999,8 +1414,9 @@ static void set_operating_mode(void) +@@ -999,8 +1421,9 @@ static void set_operating_mode(void) } } SET_MOTION_ENABLE_FLAG(1); @@ -1601,7 +1629,7 @@ index f22ab9b..ff24751 100644 } /* check for entering teleop mode */ -@@ -1028,7 +1444,7 @@ static void set_operating_mode(void) +@@ -1028,7 +1451,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); @@ -1610,7 +1638,7 @@ index f22ab9b..ff24751 100644 kinematicsForward(positions, &emcmotStatus->carte_pos_cmd, &fflags, &iflags); // entering teleop (INPOS), remove ext offsets -@@ -1072,7 +1488,7 @@ static void set_operating_mode(void) +@@ -1072,7 +1495,7 @@ static void set_operating_mode(void) emcmotStatus->overrideLimitMask = 0; SET_MOTION_COORD_FLAG(1); SET_MOTION_TELEOP_FLAG(0); @@ -1619,7 +1647,7 @@ index f22ab9b..ff24751 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1092,7 +1508,7 @@ static void set_operating_mode(void) +@@ -1092,7 +1515,7 @@ static void set_operating_mode(void) } SET_MOTION_COORD_FLAG(0); SET_MOTION_TELEOP_FLAG(0); @@ -1628,7 +1656,7 @@ index f22ab9b..ff24751 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1127,10 +1543,17 @@ static void handle_jjogwheels(void) +@@ -1127,10 +1550,17 @@ static void handle_jjogwheels(void) /* point to joint data */ joint_data = &(emcmot_hal_data->joint[joint_num]); joint = &joints[joint_num]; @@ -1650,7 +1678,7 @@ index f22ab9b..ff24751 100644 // disallow accel bogus fractions rtapi_real jjog_accel_fraction = hal_get_real(joint_data->jjog_accel_fraction); -@@ -1145,6 +1568,7 @@ static void handle_jjogwheels(void) +@@ -1145,6 +1575,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; @@ -1658,7 +1686,7 @@ index f22ab9b..ff24751 100644 /* initialization complete */ if ( first_pass ) { continue; -@@ -1276,6 +1700,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, +@@ -1276,6 +1707,16 @@ static int prepare_joint_targets(const EmcPose *pose, double *positions, reportError(_("kinematicsInverse gave non-finite joint location on joint %d"), n); return -1; } @@ -1675,7 +1703,7 @@ index f22ab9b..ff24751 100644 cubics[n] = joints[n].cubic; if (cubicNeedNextPoint(&cubics[n]) && cubicAddPoint(&cubics[n], positions[n]) != 0) { -@@ -1365,7 +1799,10 @@ static void get_pos_cmds(long period) +@@ -1365,7 +1806,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]; @@ -1687,7 +1715,7 @@ index f22ab9b..ff24751 100644 /* if joint is not active, skip it */ continue; } -@@ -1521,8 +1958,7 @@ static void get_pos_cmds(long period) +@@ -1521,8 +1965,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1697,7 +1725,7 @@ index f22ab9b..ff24751 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1583,8 +2019,7 @@ static void get_pos_cmds(long period) +@@ -1583,8 +2026,7 @@ static void get_pos_cmds(long period) result = prepare_joint_targets(&emcmotStatus->carte_pos_cmd, positions, staged_cubics); if (result != 0) { @@ -1707,7 +1735,7 @@ index f22ab9b..ff24751 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1595,6 +2030,8 @@ static void get_pos_cmds(long period) +@@ -1595,6 +2037,8 @@ static void get_pos_cmds(long period) &joint->vel_cmd, &joint->acc_cmd, &joint->jerk_cmd); } @@ -1716,7 +1744,7 @@ index f22ab9b..ff24751 100644 /* END OF OUTPUT KINS */ -@@ -1611,10 +2048,13 @@ static void get_pos_cmds(long period) +@@ -1611,10 +2055,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 */ @@ -1731,7 +1759,7 @@ index f22ab9b..ff24751 100644 /* save old command */ joint->pos_cmd = joint->pos_fb; /* set joint velocity and acceleration to zero */ -@@ -2002,8 +2442,6 @@ static void output_to_hal(void) +@@ -2002,8 +2449,6 @@ static void output_to_hal(void) double inch_mult; emcmot_joint_t *joint; joint_hal_t *joint_data; @@ -1740,7 +1768,7 @@ index f22ab9b..ff24751 100644 /* output machine info to HAL for scoping, etc */ hal_set_bool(emcmot_hal_data->motion_enabled, GET_MOTION_ENABLE_FLAG()); -@@ -2045,6 +2483,9 @@ static void output_to_hal(void) +@@ -2045,6 +2490,9 @@ static void output_to_hal(void) for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ double speed; @@ -1750,7 +1778,7 @@ index f22ab9b..ff24751 100644 if(emcmotStatus->spindle_status[spindle_num].css_factor) { double denom = fabs(emcmotStatus->spindle_status[spindle_num].xoffset - emcmotStatus->carte_pos_cmd.tran.x); -@@ -2079,14 +2520,22 @@ static void output_to_hal(void) +@@ -2079,14 +2527,22 @@ static void output_to_hal(void) } } @@ -1777,7 +1805,7 @@ index f22ab9b..ff24751 100644 // What is this for? Docs don't say hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps, emcmotStatus->spindle_status[spindle_num].speed / 60.); -@@ -2147,6 +2596,13 @@ static void output_to_hal(void) +@@ -2147,6 +2603,13 @@ static void output_to_hal(void) /* two way handshaking for the spindle encoder */ for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ @@ -1791,7 +1819,7 @@ index f22ab9b..ff24751 100644 if(emcmotStatus->spindle_status[spindle_num].spindle_index_enable && !old_motion_index[spindle_num]) { hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable, 1); -@@ -2189,7 +2645,14 @@ static void output_to_hal(void) +@@ -2189,7 +2652,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); @@ -1807,6 +1835,21 @@ index f22ab9b..ff24751 100644 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 6e02b16..e5b8373 100644 --- a/src/emc/motion/mot_priv.h @@ -1852,7 +1895,7 @@ index 6e02b16..e5b8373 100644 + #endif /* MOT_PRIV_H */ diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c -index 067711a..51b58d1 100644 +index 067711a..8993290 100644 --- a/src/emc/motion/motion.c +++ b/src/emc/motion/motion.c @@ -739,6 +739,12 @@ static int export_spindle(int num, spindle_hal_t * addr){ @@ -1881,7 +1924,20 @@ index 067711a..51b58d1 100644 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)); -@@ -927,6 +939,8 @@ static int init_comm_buffers(void) +@@ -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; @@ -1890,7 +1946,7 @@ index 067711a..51b58d1 100644 } axis_init_all(); -@@ -946,6 +960,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; @@ -1900,7 +1956,7 @@ index 067711a..51b58d1 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 ad391e1..1153fc5 100644 +index ad391e1..bed4351 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -180,6 +180,10 @@ extern "C" { @@ -2002,13 +2058,26 @@ index ad391e1..1153fc5 100644 } spindle_status_t; typedef struct { -@@ -790,6 +845,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 */ @@ -2095,7 +2164,7 @@ index ce4110e..f70a5e0 100644 /* diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index d445ee8..81ab9e6 100644 +index d445ee8..ba2bd2f 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -74,6 +74,7 @@ struct PM_CARTESIAN; @@ -2114,7 +2183,19 @@ index d445ee8..81ab9e6 100644 #define EMC_SPINDLE_STAT_TYPE ((NMLTYPE) 1399) -@@ -344,6 +346,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); +@@ -332,6 +334,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); +@@ -344,6 +351,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); extern int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints); @@ -2125,7 +2206,7 @@ index d445ee8..81ab9e6 100644 extern int emcJointSetMaxJerk(int joint, double jerk); -@@ -473,6 +479,11 @@ extern int emcSpindleBrakeRelease(int spindle); +@@ -473,6 +484,11 @@ extern int emcSpindleBrakeRelease(int spindle); extern int emcSpindleBrakeEngage(int spindle); extern int emcSpindleUpdate(EMC_SPINDLE_STAT stat[], int num_spindles); @@ -2239,7 +2320,7 @@ index 90cc136..5a1e60e 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 7a81049..79a8355 100644 +index ee88562..b0ece8e 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -172,6 +172,61 @@ volatile int done; @@ -2320,7 +2401,28 @@ index 7a81049..79a8355 100644 } return 1; } -@@ -452,6 +512,10 @@ static EMC_TRAJ_MODE homingPriorMode = EMC_TRAJ_MODE::FREE; // mode to restore o +@@ -437,21 +497,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; @@ -2331,7 +2433,7 @@ index 7a81049..79a8355 100644 // 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 -@@ -463,6 +527,19 @@ static EMC_TASK_MODE homingPriorTaskMode = EMC_TASK_MODE::MANUAL; +@@ -463,6 +529,19 @@ static EMC_TASK_MODE homingPriorTaskMode = EMC_TASK_MODE::MANUAL; // an immediate home keeps its original pass-through behaviour. static bool issuingQueuedCommand = false; @@ -2351,7 +2453,7 @@ index 7a81049..79a8355 100644 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; -@@ -922,6 +999,13 @@ static bool emcTaskArmSingleStep() +@@ -922,6 +1001,13 @@ static bool emcTaskArmSingleStep() return true; } @@ -2365,7 +2467,7 @@ index 7a81049..79a8355 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1162,6 +1246,31 @@ static int emcTaskPlan(void) +@@ -1162,6 +1248,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2397,7 +2499,7 @@ index 7a81049..79a8355 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -@@ -1181,6 +1290,36 @@ static int emcTaskPlan(void) +@@ -1181,6 +1292,36 @@ static int emcTaskPlan(void) return 0; } @@ -2434,7 +2536,7 @@ index 7a81049..79a8355 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1693,9 +1832,7 @@ static int emcTaskPlan(void) +@@ -1693,9 +1834,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2445,7 +2547,7 @@ index 7a81049..79a8355 100644 break; // otherwise we can't handle it -@@ -1958,6 +2095,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1958,6 +2097,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: @@ -2454,7 +2556,7 @@ index 7a81049..79a8355 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2164,6 +2303,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2164,10 +2305,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajSetMode(EMC_TRAJ_MODE::FREE); } homingWaitJoint = target_joint; @@ -2462,7 +2564,12 @@ index 7a81049..79a8355 100644 homingStarted = false; homingIssueTime = etime(); homingWaiting = true; -@@ -2177,9 +2317,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) + 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 +@@ -2177,9 +2320,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // from it) stays stuck at FREE/MANUAL until the operator // manually cycles mode again. homingWaiting = false; @@ -2473,7 +2580,7 @@ index 7a81049..79a8355 100644 } } break; -@@ -2193,6 +2331,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2193,6 +2334,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2498,7 +2605,7 @@ index 7a81049..79a8355 100644 case EMC_JOG_CONT_TYPE: jog_cont_msg = reinterpret_cast(cmd); retval = emcJogCont(jog_cont_msg->joint_or_axis, -@@ -2560,6 +2716,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2560,6 +2719,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcSpindleOff(spindle_off_msg->spindle, spindle_off_msg->wait_for_spindle_at_speed); break; @@ -2525,7 +2632,7 @@ index 7a81049..79a8355 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -3016,7 +3192,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3016,7 +3195,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2540,7 +2647,7 @@ index 7a81049..79a8355 100644 if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -3131,6 +3314,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3131,6 +3317,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2552,7 +2659,7 @@ index 7a81049..79a8355 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -3213,6 +3401,12 @@ static int emcTaskExecute(void) +@@ -3213,6 +3404,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2565,7 +2672,7 @@ index 7a81049..79a8355 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3331,11 +3525,59 @@ static int emcTaskExecute(void) +@@ -3339,11 +3536,59 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: @@ -2625,7 +2732,30 @@ index 7a81049..79a8355 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } -@@ -3480,11 +3722,8 @@ static int emcTaskExecute(void) +@@ -3471,12 +3716,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; +@@ -3488,11 +3738,8 @@ static int emcTaskExecute(void) emcTaskEager = 1; homingWaiting = false; // Nothing physically moved, so it's safe to restore the @@ -2639,7 +2769,7 @@ index 7a81049..79a8355 100644 break; } // It ran and has now stopped; did it reach the expected end state? -@@ -3550,7 +3789,9 @@ static int emcTaskExecute(void) +@@ -3558,7 +3805,9 @@ static int emcTaskExecute(void) "coordinated motion until every joint is homed")); emcStatus->task.execState = EMC_TASK_EXEC::ERROR; } else if (success) { @@ -2663,10 +2793,41 @@ index 79dbeb6..223886e 100644 int emcTaskSetState(EMC_TASK_STATE state); int emcTaskPlanInit(); diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc -index aa63ab4..6e10ffb 100644 +index aa63ab4..27418ce 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -1035,6 +1035,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 @@ -2677,7 +2838,7 @@ index aa63ab4..6e10ffb 100644 // for // all -@@ -1060,6 +1064,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) +@@ -1060,6 +1079,33 @@ int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints) return 0; } @@ -2711,7 +2872,7 @@ index aa63ab4..6e10ffb 100644 // EMC_TRAJ functions int emcTrajSetJoints(int joints) -@@ -1918,9 +1949,11 @@ int emcMotionInit() +@@ -1918,9 +1964,11 @@ int emcMotionInit() int emcMotionHalt() { @@ -2724,7 +2885,7 @@ index aa63ab4..6e10ffb 100644 r1 = -1; for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { if (0 == emcJointHalt(t)) { -@@ -1933,7 +1966,7 @@ int emcMotionHalt() +@@ -1933,7 +1981,7 @@ int emcMotionHalt() r4 = emcPositionSave(); r5 = ini_hal_exit(); @@ -2733,7 +2894,7 @@ index aa63ab4..6e10ffb 100644 } int emcMotionAbort() -@@ -1943,6 +1976,8 @@ int emcMotionAbort() +@@ -1943,6 +1991,8 @@ int emcMotionAbort() int r3 = 0; int t; @@ -2742,7 +2903,7 @@ index aa63ab4..6e10ffb 100644 r1 = -1; for (t = 0; t < EMCMOT_MAX_JOINTS; t++) { if (0 == emcJogAbort(t)) { -@@ -1950,8 +1985,6 @@ int emcMotionAbort() +@@ -1950,8 +2000,6 @@ int emcMotionAbort() } } @@ -2751,7 +2912,7 @@ index aa63ab4..6e10ffb 100644 return (r1 == 0 && r2 == 0 && r3 == 0) ? 0 : -1; } -@@ -2195,10 +2228,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; @@ -2794,7 +2955,15 @@ index aa63ab4..6e10ffb 100644 int emcMotionUpdate(EMC_MOTION_STAT * stat) { int r1, r2, r3, r4; -@@ -2288,6 +2353,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++) { @@ -2813,7 +2982,7 @@ index aa63ab4..6e10ffb 100644 if (stat->joint[joint].status == RCS_STATUS::ERROR) { error = 1; break; -@@ -2297,6 +2374,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) +@@ -2297,6 +2390,15 @@ int emcMotionUpdate(EMC_MOTION_STAT * stat) break; } } @@ -2885,6 +3054,233 @@ index f5cc454..7733e39 100644 {"jog", (PyCFunction)jog, METH_VARARGS, "jog(JOG_CONTINUOUS, joint_flag, index, speed)\n" "jog(JOG_INCREMENT, joint_flag, index, speed, increment)\n" +diff --git a/tests/interp/g28.2/instant-home/README b/tests/interp/g28.2/instant-home/README +new file mode 100644 +index 0000000..277dcb5 +--- /dev/null ++++ b/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/tests/interp/g28.2/instant-home/checkresult b/tests/interp/g28.2/instant-home/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/interp/g28.2/instant-home/sim.tbl b/tests/interp/g28.2/instant-home/sim.tbl +new file mode 100644 +index 0000000..e69de29 +diff --git a/tests/interp/g28.2/instant-home/test-ui.py b/tests/interp/g28.2/instant-home/test-ui.py +new file mode 100755 +index 0000000..8643922 +--- /dev/null ++++ b/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/tests/interp/g28.2/instant-home/test.ini b/tests/interp/g28.2/instant-home/test.ini +new file mode 100644 +index 0000000..f1b2352 +--- /dev/null ++++ b/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/tests/interp/g28.2/instant-home/test.sh b/tests/interp/g28.2/instant-home/test.sh +new file mode 100755 +index 0000000..a16f6fa +--- /dev/null ++++ b/tests/interp/g28.2/instant-home/test.sh +@@ -0,0 +1,2 @@ ++#!/bin/bash ++exec linuxcnc -r test.ini 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 @@ -3392,10 +3788,10 @@ index 0000000..425d52b +!/base.ini diff --git a/tests/runtime-availability-regressions/README b/tests/runtime-availability-regressions/README new file mode 100644 -index 0000000..e1bde10 +index 0000000..2a46151 --- /dev/null +++ b/tests/runtime-availability-regressions/README -@@ -0,0 +1,20 @@ +@@ -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. @@ -3416,6 +3812,8 @@ index 0000000..e1bde10 +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/tests/runtime-availability-regressions/base.ini b/tests/runtime-availability-regressions/base.ini new file mode 100644 index 0000000..71f455a @@ -3626,10 +4024,10 @@ index 0000000..b39d68b +AVAILABILITY_CONTROL = 0 diff --git a/tests/runtime-availability-regressions/fixture.py b/tests/runtime-availability-regressions/fixture.py new file mode 100644 -index 0000000..ef0f630 +index 0000000..c4c8307 --- /dev/null +++ b/tests/runtime-availability-regressions/fixture.py -@@ -0,0 +1,75 @@ +@@ -0,0 +1,81 @@ +#!/usr/bin/env python3 +import os +import time @@ -3694,7 +4092,7 @@ index 0000000..ef0f630 +c.teleop_enable(0); done() +if case != 'fault': + acquire('joint.0') -+if case not in ('fault', 'joghome'): ++if case not in ('fault', 'joghome', 'slowtask'): + acquire('joint.1') +if case == 'joghome': + c.set_joint_availability(1, True) @@ -3703,6 +4101,12 @@ index 0000000..ef0f630 + 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/tests/runtime-availability-regressions/joghome.ini.in b/tests/runtime-availability-regressions/joghome.ini.in @@ -3741,6 +4145,19 @@ index 0000000..3786b15 + +[JOINT_1] +HOME_SEQUENCE = 1 +diff --git a/tests/runtime-availability-regressions/slowtask.ini.in b/tests/runtime-availability-regressions/slowtask.ini.in +new file mode 100644 +index 0000000..75125d8 +--- /dev/null ++++ b/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/tests/runtime-availability-regressions/tail.hal b/tests/runtime-availability-regressions/tail.hal new file mode 100644 index 0000000..c9eea9d @@ -3792,10 +4209,10 @@ index 0000000..cdf6f94 +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 0000000..468b03b +index 0000000..c23405a --- /dev/null +++ b/tests/runtime-availability-regressions/test-ui.py -@@ -0,0 +1,192 @@ +@@ -0,0 +1,198 @@ +#!/usr/bin/env python3 +from fixture import * +from pathlib import Path @@ -3985,6 +4402,12 @@ index 0000000..468b03b + settle() + assert not hal.get_value('flipflop.0.out'), 'amp-enable pulsed with amp-fault asserted' + ++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') @@ -3999,20 +4422,21 @@ index 0000000..67dab70 +BASE = base.ini diff --git a/tests/runtime-availability-regressions/test.sh b/tests/runtime-availability-regressions/test.sh new file mode 100755 -index 0000000..e2dc178 +index 0000000..80bc7dd --- /dev/null +++ b/tests/runtime-availability-regressions/test.sh -@@ -0,0 +1,34 @@ +@@ -0,0 +1,35 @@ +#!/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 ++for scenario in ${AVAILABILITY_REGRESSION_CASES:-fault wheel jointwheel tail amp power index jogstop joghome slowtask 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 ;; + extra) + # Unsupported ownership must fail configuration, before Machine On. + if linuxcnc -r extra.ini >extra.log 2>&1; then 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 d1da8aa..8f4d3f7 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -36,7 +36,7 @@ so the new concurrency checks never refuse it. create mode 100644 tests/homing-concurrent/tool.tbl diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index e24a9d2..dd99fd8 100644 +index 9d6fb2c..e8a68ce 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -1753,10 +1753,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) @@ -72,10 +72,10 @@ index e24a9d2..dd99fd8 100644 break; } diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index ff24751..ca7d5cd 100644 +index 31c4284..babce73 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2728,18 +2728,13 @@ static void update_status(void) +@@ -2735,18 +2735,13 @@ static void update_status(void) } #endif joint_status->flag = joint->flag; @@ -405,10 +405,10 @@ index a2b6c9b..9f36e71 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 b6a51c4..4d518b9 100644 +index af883eb..feea75c 100644 --- a/src/emc/motion/homing.h +++ b/src/emc/motion/homing.h -@@ -96,6 +96,9 @@ 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); @@ -418,7 +418,7 @@ index b6a51c4..4d518b9 100644 // per-joint information: int get_home_sequence(int jno); //return s -@@ -109,6 +112,10 @@ bool get_index_enable(int jno); +@@ -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); 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 9da60cf..9456469 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 @@ -306,7 +306,7 @@ index 5d61f0b..f1ce1d7 100644 #ifdef __cplusplus diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index dd99fd8..00ae21c 100644 +index e8a68ce..554c1b5 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -157,6 +157,19 @@ STATIC int spindle_range_is_available(int first, int last) @@ -353,10 +353,10 @@ index dd99fd8..00ae21c 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 ca7d5cd..5a8ba71 100644 +index babce73..cb1b2cb 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -1999,7 +1999,14 @@ static void get_pos_cmds(long period) +@@ -2006,7 +2006,14 @@ static void get_pos_cmds(long period) break; case EMCMOT_MOTION_TELEOP: @@ -384,7 +384,7 @@ index e5b8373..a0b6ea1 100644 #endif /* MOT_PRIV_H */ diff --git a/src/emc/motion/motion.c b/src/emc/motion/motion.c -index 51b58d1..6d99597 100644 +index 8993290..43efa8c 100644 --- a/src/emc/motion/motion.c +++ b/src/emc/motion/motion.c @@ -23,6 +23,7 @@ @@ -416,7 +416,7 @@ index 51b58d1..6d99597 100644 sp_scurve_cleanup(); /* free shared memory */ diff --git a/src/emc/motion/motion.h b/src/emc/motion/motion.h -index 1153fc5..3b6d1d1 100644 +index bed4351..51719c1 100644 --- a/src/emc/motion/motion.h +++ b/src/emc/motion/motion.h @@ -184,6 +184,7 @@ extern "C" { @@ -653,7 +653,7 @@ index f70a5e0..b2b729a 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 81ab9e6..003be39 100644 +index ba2bd2f..c33ee96 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -75,6 +75,7 @@ struct PM_CARTESIAN; @@ -664,7 +664,7 @@ index 81ab9e6..003be39 100644 #define EMC_JOINT_STAT_TYPE ((NMLTYPE) 198) #define EMC_AXIS_STAT_TYPE ((NMLTYPE) 199) -@@ -341,6 +342,7 @@ extern int emcJointOverrideLimits(int joint); +@@ -346,6 +347,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); @@ -695,10 +695,10 @@ index c03bfc3..05a29fe 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 79a8355..f0d4ab8 100644 +index b0ece8e..9097f40 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1462,6 +1462,7 @@ static int emcTaskPlan(void) +@@ -1464,6 +1464,7 @@ static int emcTaskPlan(void) case EMC_JOINT_HOME_TYPE: case EMC_JOINT_UNHOME_TYPE: case EMC_JOG_CONT_TYPE: @@ -706,7 +706,7 @@ index 79a8355..f0d4ab8 100644 case EMC_JOG_INCR_TYPE: case EMC_JOG_ABS_TYPE: case EMC_JOG_STOP_TYPE: -@@ -2362,6 +2363,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2365,6 +2366,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; @@ -721,10 +721,10 @@ index 79a8355..f0d4ab8 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 6e10ffb..0e26533 100644 +index 27418ce..98f2ca9 100644 --- a/src/emc/task/taskintf.cc +++ b/src/emc/task/taskintf.cc -@@ -889,6 +889,18 @@ int emcJogCont(int nr, double vel, int jjogmode) +@@ -904,6 +904,18 @@ int emcJogCont(int nr, double vel, int jjogmode) return usrmotWriteEmcmotCommand(&emcmotCommand); } 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 index 1b6b4d4..f41bdcb 100644 --- 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 @@ -32,18 +32,20 @@ tests/remap/mdi-remap-abort interrupts a waiting NGC and a waiting Python remap with each of E-stop, machine off, interpreter re-init and a mode change, and checks that milltask survives and MDI works afterwards. --- + src/emc/nml_intf/interpl.cc | 14 ++ + src/emc/nml_intf/interpl.hh | 2 + src/emc/task/emctask.cc | 4 + - src/emc/task/emctaskmain.cc | 7 +- + src/emc/task/emctaskmain.cc | 46 +++- src/emc/task/task.hh | 1 + - tests/remap/mdi-remap-abort/README | 17 +++ + tests/remap/mdi-remap-abort/README | 22 ++ tests/remap/mdi-remap-abort/checkresult | 2 + tests/remap/mdi-remap-abort/m400.ngc | 5 + - tests/remap/mdi-remap-abort/remap.py | 9 ++ - tests/remap/mdi-remap-abort/test-ui.py | 186 ++++++++++++++++++++++++ - tests/remap/mdi-remap-abort/test.ini | 101 +++++++++++++ + tests/remap/mdi-remap-abort/remap.py | 9 + + tests/remap/mdi-remap-abort/test-ui.py | 290 ++++++++++++++++++++++++ + tests/remap/mdi-remap-abort/test.ini | 101 +++++++++ tests/remap/mdi-remap-abort/test.sh | 2 + tests/remap/mdi-remap-abort/toplevel.py | 1 + - 11 files changed, 334 insertions(+), 1 deletion(-) + 13 files changed, 491 insertions(+), 8 deletions(-) create mode 100644 tests/remap/mdi-remap-abort/README create mode 100755 tests/remap/mdi-remap-abort/checkresult create mode 100644 tests/remap/mdi-remap-abort/m400.ngc @@ -53,6 +55,44 @@ change, and checks that milltask survives and MDI works afterwards. create mode 100755 tests/remap/mdi-remap-abort/test.sh create mode 100644 tests/remap/mdi-remap-abort/toplevel.py +diff --git a/src/emc/nml_intf/interpl.cc b/src/emc/nml_intf/interpl.cc +index 415f873..1c36637 100644 +--- a/src/emc/nml_intf/interpl.cc ++++ b/src/emc/nml_intf/interpl.cc +@@ -109,6 +109,20 @@ void NML_INTERP_LIST::clear() + pass_group = 0; + } + ++int NML_INTERP_LIST::remove_type(int type) ++{ ++ int removed = 0; ++ for (auto it = linked_list.begin(); it != linked_list.end();) { ++ if (it->command->_type == type) { ++ it = linked_list.erase(it); ++ removed++; ++ } else { ++ ++it; ++ } ++ } ++ return removed; ++} ++ + void NML_INTERP_LIST::print() + { + rcs_print("NML_INTERP_LIST::print(): list size=%lu\n", linked_list.size()); +diff --git a/src/emc/nml_intf/interpl.hh b/src/emc/nml_intf/interpl.hh +index 52c338e..86ae5ab 100644 +--- a/src/emc/nml_intf/interpl.hh ++++ b/src/emc/nml_intf/interpl.hh +@@ -42,6 +42,8 @@ public: + int append(std::unique_ptr&& command); + std::unique_ptr get(); + void clear(); ++ // removes every queued command of this type, returns how many ++ int remove_type(int type); + void print(); + int len(); + // the most recently appended command still on the list whose type is diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc index 5a1e60e..67edc9b 100644 --- a/src/emc/task/emctask.cc @@ -69,30 +109,83 @@ index 5a1e60e..67edc9b 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index f0d4ab8..7726feb 100644 +index 9097f40..7176809 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -796,7 +796,7 @@ interpret_again: +@@ -798,10 +798,18 @@ interpret_again: } // if interp len is less than max } -static void mdi_execute_abort(void) -+void mdi_execute_abort(void) ++static void mdi_execute_drop_queue(void) { - int queued_mdi_commands; +- int queued_mdi_commands; ++ int queued_mdi_commands = mdi_execute_queue.len(); ++ if (queued_mdi_commands > 0) { ++ rcs_print("mdi_execute_abort: dropping %d queued MDI commands\n", queued_mdi_commands); ++ } ++ mdi_execute_queue.clear(); ++ emcStatus->task.queuedMDIcommands = 0; ++} + ++void mdi_execute_abort(void) ++{ + // XXX: Reset needed? + if (mdi_execute_wait || mdi_execute_next) + emcTaskPlanReset(); +@@ -809,16 +817,22 @@ static void mdi_execute_abort(void) + mdi_execute_wait = 0; + mdi_execute_next = 0; + +- queued_mdi_commands = mdi_execute_queue.len(); +- if (queued_mdi_commands > 0) { +- rcs_print("mdi_execute_abort: dropping %d queued MDI commands\n", queued_mdi_commands); +- } +- mdi_execute_queue.clear(); +- emcStatus->task.queuedMDIcommands = 0; ++ mdi_execute_drop_queue(); + + emcStatus->task.interpState = EMC_TASK_INTERP::IDLE; + } -@@ -3193,6 +3193,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) ++// Drop every MDI command the interpreter has not read yet: the queue, and ++// what mdi_execute_hook() already moved from it towards execution. ++static void mdi_execute_drop_unread(void) ++{ ++ mdi_execute_drop_queue(); ++ interp_list.remove_type(EMC_TASK_PLAN_EXECUTE_TYPE); ++ if (emcTaskCommand && emcTaskCommand->_type == EMC_TASK_PLAN_EXECUTE_TYPE) { ++ emcTaskCommand = NULL; ++ } ++} ++ + static void mdi_execute_hook(void) + { + if (mdi_execute_wait && emcTaskPlanIsWait()) { +@@ -3196,7 +3210,23 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_INIT_TYPE: -+ // re-initializing the interpreter drops any call an interrupted MDI -+ // command is still inside of; an ordinary MDI move keeps running and -+ // keeps its interpreter state -+ if (mdi_execute_wait || mdi_execute_next || mdi_execute_level >= 0) ++ // MDI commands not read yet were written for the modal state this ++ // discards, so they never run. ++ mdi_execute_drop_unread(); ++ // Re-initializing the interpreter drops any call an interrupted MDI ++ // command is still inside of. A command already read keeps running and ++ // keeps its interpreter state, including one that returned ++ // INTERP_EXECUTE_FINISH outside a call (G38.n, M66, M6, G28.2). ++ if (mdi_execute_next || mdi_execute_level >= 0) { + mdi_execute_abort(); ++ emcStatus->task.command[0] = 0; ++ } retval = emcTaskPlanInit(); ++ // emcTaskPlanInit() clears the wait; mdi_execute_hook() needs it to see ++ // that command finish ++ if (mdi_execute_wait) { ++ emcTaskPlanSetWait(); ++ } if (retval > INTERP_MIN_ERROR) { retval = -1; + } diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh index 223886e..1a7a999 100644 --- a/src/emc/task/task.hh @@ -107,10 +200,10 @@ index 223886e..1a7a999 100644 int emcTaskSetState(EMC_TASK_STATE state); diff --git a/tests/remap/mdi-remap-abort/README b/tests/remap/mdi-remap-abort/README new file mode 100644 -index 0000000..213678e9 +index 0000000..cdb34f9 --- /dev/null +++ b/tests/remap/mdi-remap-abort/README -@@ -0,0 +1,17 @@ +@@ -0,0 +1,22 @@ +Interrupt an MDI command whose remap is mid-execution with an E-stop, a +machine off, an interpreter re-init (EMC_TASK_PLAN_INIT) and a mode change +to AUTO and back, instead of an operator abort, then bring the machine back @@ -128,6 +221,11 @@ index 0000000..213678e9 +dropped by each interrupt, never run. Finally, an interpreter re-init during +an ordinary MDI G1 move, with no interrupted call, must leave the move +running and the interpreter state non-idle until the move ends. ++ ++Commands queued behind an ordinary move are dropped by the re-init too: they ++were written for the modal state it discards. M66 and G38.3 return ++INTERP_EXECUTE_FINISH without entering a call, so a re-init while they run ++leaves them active (not IDLE, still the current command) until they finish. diff --git a/tests/remap/mdi-remap-abort/checkresult b/tests/remap/mdi-remap-abort/checkresult new file mode 100755 index 0000000..24dc9aa @@ -164,10 +262,10 @@ index 0000000..b616b52 + yield INTERP_EXECUTE_FINISH diff --git a/tests/remap/mdi-remap-abort/test-ui.py b/tests/remap/mdi-remap-abort/test-ui.py new file mode 100755 -index 0000000..b88dda9 +index 0000000..b6c86ff --- /dev/null +++ b/tests/remap/mdi-remap-abort/test-ui.py -@@ -0,0 +1,186 @@ +@@ -0,0 +1,290 @@ +#!/usr/bin/env python3 +# +# Interrupt an MDI command whose remap is mid-execution in every way that @@ -252,6 +350,14 @@ index 0000000..b88dda9 + c.wait_complete() + + ++def plan_init_received(): ++ # for a command that keeps task busy: wait_complete() would wait it out ++ c.reset_interpreter() ++ serial = c.serial ++ wait_for(lambda: s.echo_serial_number >= serial, ++ "interpreter re-init to be received") ++ ++ +def mode_auto(): + set_mode(linuxcnc.MODE_AUTO) + set_mode(linuxcnc.MODE_MDI) @@ -293,12 +399,16 @@ index 0000000..b88dda9 + wait_for(lambda: s.queued_mdi_commands == 1, + "%s: G0 X5 to be queued behind %s" % (name, code)) + interrupt() -+ set_mode(linuxcnc.MODE_MDI) -+ time.sleep(0.5) ++ # 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) @@ -338,6 +448,92 @@ index 0000000..b88dda9 + print("plain move interpreter re-init: ok") + + ++def queued_reset(name, during_move): ++ # A command is queued only while task is busy with an earlier one; the ++ # block below keeps its move on the interp list behind the dwell. What is ++ # queued was written for the modal state the re-init discards (here G91), ++ # so none of it may run after the re-init. Once the move is issued the ++ # first queued command is already task's pending command. ++ set_mode(linuxcnc.MODE_MDI) ++ end = target[0] + 4.0 ++ c.mdi("G91") ++ c.wait_complete() ++ c.mdi("G4 P0.5 G1 X4 F120") ++ wait_for(lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY, ++ "%s: dwell to start" % name) ++ c.mdi("G0 X1") ++ c.mdi("G0 X1") ++ wait_for(lambda: s.queued_mdi_commands == 2, ++ "%s: G0 X1 to be queued" % name) ++ if during_move: ++ wait_for(lambda: s.current_vel > 0.0 and s.queued_mdi_commands == 1, ++ "%s: move to start" % name) ++ plan_init_received() ++ s.poll() ++ if s.queued_mdi_commands != 0: ++ fail("%s: %d queued MDI commands survived" ++ % (name, s.queued_mdi_commands)) ++ start = time.time() ++ while abs(s.position[0] - end) > 1e-6: ++ if time.time() - start > 10.0: ++ fail("%s: move did not reach X%.1f (X=%.4f)" ++ % (name, end, s.position[0])) ++ if s.interp_state == linuxcnc.INTERP_IDLE: ++ fail("%s: IDLE while moving (X=%.4f)" % (name, s.position[0])) ++ time.sleep(0.02) ++ s.poll() ++ wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE ++ and s.exec_state == linuxcnc.EXEC_DONE, ++ "%s: move to finish" % name) ++ time.sleep(0.5) ++ s.poll() ++ if abs(s.position[0] - end) > 1e-6: ++ fail("%s: a dropped command ran (X=%.4f, expected %.4f)" ++ % (name, s.position[0], end)) ++ target[0] = end ++ check_mdi_works(name) ++ print("%s: ok" % name, flush=True) ++ ++ ++def execute_finish_reset(name, code, busy_for, end=None): ++ # These commands return INTERP_EXECUTE_FINISH without entering a call. A ++ # re-init leaves them running: still reported, not IDLE, and finished ++ # normally, with what was queued behind them dropped. ++ set_mode(linuxcnc.MODE_MDI) ++ c.mdi(code) ++ wait_for(lambda: s.interp_state != linuxcnc.INTERP_IDLE, ++ "%s: to start" % name) ++ time.sleep(0.2) ++ c.mdi("G0 X5") ++ wait_for(lambda: s.queued_mdi_commands == 1, ++ "%s: G0 X5 to be queued" % name) ++ plan_init_received() ++ s.poll() ++ if s.queued_mdi_commands != 0: ++ fail("%s: %d queued MDI commands survived" ++ % (name, s.queued_mdi_commands)) ++ start = time.time() ++ while time.time() - start < busy_for: ++ s.poll() ++ if s.interp_state == linuxcnc.INTERP_IDLE: ++ fail("%s: reported IDLE while running" % name) ++ if s.command != code: ++ fail("%s: active command is %r" % (name, s.command)) ++ time.sleep(0.02) ++ wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE ++ and s.exec_state == linuxcnc.EXEC_DONE, ++ "%s: to finish" % name) ++ wait_for(lambda: s.command == "", "%s: active command to clear" % name) ++ if end is not None: ++ target[0] = end ++ time.sleep(0.3) ++ s.poll() ++ if abs(s.position[0] - target[0]) > 1e-6: ++ fail("%s: X=%.4f, expected %.4f" % (name, s.position[0], target[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) @@ -350,6 +546,12 @@ index 0000000..b88dda9 + scenario("%s mode change" % code, code, mode_auto) + +plain_move_reset() ++queued_reset("queue re-init during dwell", False) ++queued_reset("queue re-init during move", True) ++execute_finish_reset("M66 interpreter re-init", "M66 P0 L3 Q2", 0.8) ++probe_end = target[0] + 3.0 ++execute_finish_reset("G38.3 interpreter re-init", ++ "G38.3 X%.1f F120" % probe_end, 0.5, probe_end) + +print("all scenarios passed") +set_state(linuxcnc.STATE_ESTOP) diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 7605588..3d796b5 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -300,7 +300,9 @@ 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. On a random toolchanger the table is saved after every M6 and +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 @@ -425,6 +427,18 @@ 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. `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 or delete tells the operator why and fails only that +command: spindle, coolant and an open program are unaffected. +`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 LinuxCNC restart and remap under the same process lock used by all mmap @@ -531,7 +545,10 @@ 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, +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 `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. Stop or Pause before the @@ -702,9 +719,12 @@ 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, -and `EMC_TASK_PLAN_INIT` runs it before re-initialising the interpreter when an -interrupted call exists; an ordinary MDI move keeps running and keeps its -interpreter state. `tests/remap/mdi-remap-abort` interrupts a waiting NGC and +and `EMC_TASK_PLAN_INIT` always drops MDI commands the interpreter has not read, +including one already moved towards execution, because they were written for +the modal state being discarded. It runs `mdi_execute_abort()` only when a call +is interrupted. A command already read keeps running and stays reported until it +ends, including one that returned `INTERP_EXECUTE_FINISH` outside a call +(`G38.n`, `M66`, `M6`, `G28.2`). `tests/remap/mdi-remap-abort` interrupts a waiting NGC and Python remap with each of these, checks that an MDI command queued behind it never runs and that MDI still works, and resets the interpreter during a plain MDI move. The bug is present in plain From 70c357966b489e8691d39f1d5bd2c579df883d1e Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 13:36:40 +0100 Subject: [PATCH 24/45] ci(linuxcnc): test patches on a headless build LinuxCNC's GUIs and GUI tools are out of scope for this repository, so document that, build the patch test job with the headless package profile and leave out their tests. halui stays in scope. Verified by running the workflow's install, build and test steps in clean Ubuntu 24.04 containers: all four shards passed. --- .github/workflows/linuxcnc-patches.yml | 24 ++++++++++++++++++++++-- AGENTS.md | 6 ++++++ README.md | 8 ++++++++ linuxcnc-patches/README.md | 7 ++++--- 4 files changed, 40 insertions(+), 5 deletions(-) diff --git a/.github/workflows/linuxcnc-patches.yml b/.github/workflows/linuxcnc-patches.yml index 1cf6b18..6cf1a2f 100644 --- a/.github/workflows/linuxcnc-patches.yml +++ b/.github/workflows/linuxcnc-patches.yml @@ -73,7 +73,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 @@ -81,7 +91,10 @@ 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 @@ -97,6 +110,13 @@ jobs: shard_tests=() resumable_index=0 while IFS= read -r -d '' test_path; do + # LinuxCNC's GUIs are out of scope for this repository. + case "${test_path}" in + tests/build/ui/* | tests/glcanon/* | tests/pyvcp/* | \ + tests/tooledit/* | tests/ui-smoke/*) + continue + ;; + esac if [[ "${test_path}" == tests/resumable-stop/* ]]; then test_shard=$((resumable_index % SHARD_COUNT)) resumable_index=$((resumable_index + 1)) diff --git a/AGENTS.md b/AGENTS.md index 8697ccc..a84376c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,11 @@ # LinuxCNC Ctrl Agent Guidance +## Project scope + +- LinuxCNC's own GUIs and GUI tools are out of scope (see `README.md`). Do not + report review findings against them, fix them, test them, or extend patches + for 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/README.md b/README.md index 7e54460..0d7af2c 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,14 @@ 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. + ## Repository layout - `proto/`: canonical versioned protobuf wire contract and its existing license. diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 3d796b5..7c50cf5 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -22,9 +22,10 @@ complete series. Changes under `linuxcnc-patches/` 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 LinuxCNC regression suite with failure output enabled, +leaving out the tests for LinuxCNC's GUIs and GUI tools, which are out of scope +for this repository (`tests/build/ui`, `tests/glcanon`, `tests/pyvcp`, +`tests/tooledit` and `tests/ui-smoke`). ## Applying the series From dc7e0abf20e2e4caba9065cd36afe0b55b9f211f Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 13:42:16 +0100 Subject: [PATCH 25/45] docs: define what is out of scope Older remote interfaces and tool database programs join LinuxCNC's GUIs as out of scope, and patch CI leaves out their tests. Out of scope means we do not review or fix these features; it does not mean patches remove them. --- .github/workflows/linuxcnc-patches.yml | 8 +++++--- AGENTS.md | 7 ++++--- README.md | 9 +++++++++ linuxcnc-patches/README.md | 8 +++++--- 4 files changed, 23 insertions(+), 9 deletions(-) diff --git a/.github/workflows/linuxcnc-patches.yml b/.github/workflows/linuxcnc-patches.yml index 6cf1a2f..99b9ff9 100644 --- a/.github/workflows/linuxcnc-patches.yml +++ b/.github/workflows/linuxcnc-patches.yml @@ -110,10 +110,12 @@ jobs: shard_tests=() resumable_index=0 while IFS= read -r -d '' test_path; do - # LinuxCNC's GUIs are out of scope for this repository. + # LinuxCNC features that are out of scope for this repository. case "${test_path}" in - tests/build/ui/* | tests/glcanon/* | tests/pyvcp/* | \ - tests/tooledit/* | tests/ui-smoke/*) + tests/build/ui/* | tests/glcanon/* | tests/halrmt/* | \ + tests/linuxcncrsh/* | tests/linuxcncrsh-tcp/* | \ + tests/pyvcp/* | tests/tooldb/* | tests/tooledit/* | \ + tests/ui-smoke/*) continue ;; esac diff --git a/AGENTS.md b/AGENTS.md index a84376c..b38f415 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,9 +2,10 @@ ## Project scope -- LinuxCNC's own GUIs and GUI tools are out of scope (see `README.md`). Do not - report review findings against them, fix them, test them, or extend patches - for them. `halui` is headless and stays in scope. +- LinuxCNC's own GUIs and GUI tools, its older remote interfaces and tool + database programs 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 diff --git a/README.md b/README.md index 0d7af2c..912d09a 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,15 @@ 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`) and tool +database programs (`[EMCIO]DB_PROGRAM`) are out of scope in the same way: +clients use this repository's gRPC APIs, and tool data lives in the file-backed +tool table. + +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/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 7c50cf5..cc9c876 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -23,9 +23,11 @@ Changes under `linuxcnc-patches/` 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 a headless LinuxCNC in run-in-place mode, and runs the LinuxCNC regression suite with failure output enabled, -leaving out the tests for LinuxCNC's GUIs and GUI tools, which are out of scope -for this repository (`tests/build/ui`, `tests/glcanon`, `tests/pyvcp`, -`tests/tooledit` and `tests/ui-smoke`). +leaving 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`). ## Applying the series From e4db04f360b16645fe44cca972603e9346c35ff7 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 13:55:33 +0100 Subject: [PATCH 26/45] test(linuxcnc): trim tool wear test fixtures Patch 0007 no longer carries tests for tool database programs, which are out of scope: its db-line-length test and its edits to upstream's db-g10-offset are gone. The tool wear and tool table tests generate their lathe configuration from one shared template instead of six copies. --- .../0007-native-automatic-tool-wear.patch | 1139 +++-------------- ...-own-transactional-tool-CRUD-in-task.patch | 120 +- 2 files changed, 200 insertions(+), 1059 deletions(-) diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index 06a1724..45b0ae5 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -131,62 +131,45 @@ Fixes from review of the port: tests/t0/random-with-t0/expected-gcode-output | 2 +- .../random-without-t0/expected-gcode-output | 2 +- tests/tlo/test-ui.py | 7 +- - tests/tool-line-length-save/.gitignore | 5 + + tests/tool-line-length-save/.gitignore | 6 + tests/tool-line-length-save/checkresult | 2 + - tests/tool-line-length-save/lathe.ini | 85 +++++ tests/tool-line-length-save/make-table.py | 13 + tests/tool-line-length-save/random-ui.py | 62 +++ tests/tool-line-length-save/test-ui.py | 116 ++++++ tests/tool-line-length-save/test.sh | 12 + - tests/tool-wear-abort/.gitignore | 3 + + tests/tool-wear-abort/.gitignore | 4 + tests/tool-wear-abort/change-move.ngc | 5 + tests/tool-wear-abort/change-then-end.ngc | 3 + tests/tool-wear-abort/checkresult | 2 + tests/tool-wear-abort/core_sim_handshake.hal | 18 + tests/tool-wear-abort/interp-error-m6.ngc | 7 + - tests/tool-wear-abort/lathe.ini | 85 +++++ tests/tool-wear-abort/move-origin.ngc | 5 + tests/tool-wear-abort/postgui.hal | 5 + tests/tool-wear-abort/readahead-g43.ngc | 6 + tests/tool-wear-abort/readahead-m61.ngc | 7 + tests/tool-wear-abort/test-ui.py | 359 ++++++++++++++++++ - tests/tool-wear-abort/test.sh | 6 + + tests/tool-wear-abort/test.sh | 7 + tests/tool-wear-abort/tool.tbl.original | 2 + - tests/tool-wear-restart/.gitignore | 3 + + tests/tool-wear-common/lathe.ini.in | 84 ++++ + tests/tool-wear-common/make-ini.sh | 18 + + tests/tool-wear-restart/.gitignore | 5 + tests/tool-wear-restart/checkresult | 2 + tests/tool-wear-restart/common.py | 72 ++++ - tests/tool-wear-restart/run1.ini | 85 +++++ tests/tool-wear-restart/run1.py | 10 + - tests/tool-wear-restart/run2.ini | 85 +++++ tests/tool-wear-restart/run2.py | 18 + - tests/tool-wear-restart/test.sh | 12 + + tests/tool-wear-restart/test.sh | 14 + tests/tool-wear-restart/tool.tbl.original | 2 + - tests/tool-wear-task/.gitignore | 3 + + tests/tool-wear-task/.gitignore | 4 + tests/tool-wear-task/checkresult | 2 + - tests/tool-wear-task/lathe.ini | 90 +++++ tests/tool-wear-task/remap.py | 15 + tests/tool-wear-task/test-ui.py | 297 +++++++++++++++ - tests/tool-wear-task/test.sh | 6 + + tests/tool-wear-task/test.sh | 10 + tests/tool-wear-task/tool.tbl.original | 2 + tests/tool-wear-task/toplevel.py | 1 + tests/toolchanger/m61/test-ui.py | 28 +- .../nonrandom/expected-gcode-output | 12 +- .../random/expected-gcode-output | 12 +- - tests/tooldb/db-g10-offset/README | 4 +- - tests/tooldb/db-g10-offset/db_test.py | 10 +- - tests/tooldb/db-g10-offset/dbtest_lib.py | 16 +- - tests/tooldb/db-g10-offset/test-ui.py | 15 + - tests/tooldb/db-g10-offset/verify-ui.py | 5 +- - tests/tooldb/db-line-length/.gitignore | 5 + - tests/tooldb/db-line-length/base.inc | 98 +++++ - tests/tooldb/db-line-length/checkresult | 2 + - tests/tooldb/db-line-length/db_long.py | 30 ++ - tests/tooldb/db-line-length/long-ui.py | 34 ++ - tests/tooldb/db-line-length/long.ini | 5 + - tests/tooldb/db-line-length/test-ui.py | 18 + - tests/tooldb/db-line-length/test.ini | 5 + - tests/tooldb/db-line-length/test.sh | 14 + - 129 files changed, 2937 insertions(+), 294 deletions(-) + 112 files changed, 2368 insertions(+), 286 deletions(-) create mode 100644 tests/interp/tool-line-length/expected create mode 100644 tests/interp/tool-line-length/missing-t2.ngc create mode 100644 tests/interp/tool-line-length/missing-t3.ngc @@ -207,7 +190,6 @@ Fixes from review of the port: create mode 100644 tests/interp/tool-wear/test.tbl create mode 100644 tests/tool-line-length-save/.gitignore create mode 100755 tests/tool-line-length-save/checkresult - create mode 100644 tests/tool-line-length-save/lathe.ini create mode 100755 tests/tool-line-length-save/make-table.py create mode 100755 tests/tool-line-length-save/random-ui.py create mode 100755 tests/tool-line-length-save/test-ui.py @@ -218,7 +200,6 @@ Fixes from review of the port: create mode 100755 tests/tool-wear-abort/checkresult create mode 100644 tests/tool-wear-abort/core_sim_handshake.hal create mode 100644 tests/tool-wear-abort/interp-error-m6.ngc - create mode 100644 tests/tool-wear-abort/lathe.ini create mode 100644 tests/tool-wear-abort/move-origin.ngc create mode 100644 tests/tool-wear-abort/postgui.hal create mode 100644 tests/tool-wear-abort/readahead-g43.ngc @@ -226,32 +207,22 @@ Fixes from review of the port: create mode 100755 tests/tool-wear-abort/test-ui.py create mode 100755 tests/tool-wear-abort/test.sh create mode 100644 tests/tool-wear-abort/tool.tbl.original + create mode 100644 tests/tool-wear-common/lathe.ini.in + create mode 100755 tests/tool-wear-common/make-ini.sh create mode 100644 tests/tool-wear-restart/.gitignore create mode 100755 tests/tool-wear-restart/checkresult create mode 100644 tests/tool-wear-restart/common.py - create mode 100644 tests/tool-wear-restart/run1.ini create mode 100755 tests/tool-wear-restart/run1.py - create mode 100644 tests/tool-wear-restart/run2.ini create mode 100755 tests/tool-wear-restart/run2.py create mode 100755 tests/tool-wear-restart/test.sh create mode 100644 tests/tool-wear-restart/tool.tbl.original create mode 100644 tests/tool-wear-task/.gitignore create mode 100755 tests/tool-wear-task/checkresult - create mode 100644 tests/tool-wear-task/lathe.ini create mode 100644 tests/tool-wear-task/remap.py create mode 100755 tests/tool-wear-task/test-ui.py create mode 100755 tests/tool-wear-task/test.sh create mode 100644 tests/tool-wear-task/tool.tbl.original create mode 100644 tests/tool-wear-task/toplevel.py - create mode 100644 tests/tooldb/db-line-length/.gitignore - create mode 100644 tests/tooldb/db-line-length/base.inc - create mode 100755 tests/tooldb/db-line-length/checkresult - create mode 100755 tests/tooldb/db-line-length/db_long.py - create mode 100755 tests/tooldb/db-line-length/long-ui.py - create mode 100644 tests/tooldb/db-line-length/long.ini - create mode 100755 tests/tooldb/db-line-length/test-ui.py - create mode 100644 tests/tooldb/db-line-length/test.ini - create mode 100755 tests/tooldb/db-line-length/test.sh diff --git a/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini b/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini index 37daf10..bbcdfc2 100644 @@ -3292,15 +3263,16 @@ index 42fe939..2814fe0 100755 - diff --git a/tests/tool-line-length-save/.gitignore b/tests/tool-line-length-save/.gitignore new file mode 100644 -index 0000000..ed7a35c +index 0000000..61ad1bd --- /dev/null +++ b/tests/tool-line-length-save/.gitignore -@@ -0,0 +1,5 @@ +@@ -0,0 +1,6 @@ +sim.var +sim.var.bak +tool.tbl +random.ini +g10.ngc ++lathe.ini diff --git a/tests/tool-line-length-save/checkresult b/tests/tool-line-length-save/checkresult new file mode 100755 index 0000000..24dc9aa @@ -3309,97 +3281,6 @@ index 0000000..24dc9aa @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value -diff --git a/tests/tool-line-length-save/lathe.ini b/tests/tool-line-length-save/lathe.ini -new file mode 100644 -index 0000000..01a896f ---- /dev/null -+++ b/tests/tool-line-length-save/lathe.ini -@@ -0,0 +1,85 @@ -+# A metric lathe whose tool table has a line too long to load (T3). -+# Saving the table would delete that line, so saves are refused. -+ -+[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/tests/tool-line-length-save/make-table.py b/tests/tool-line-length-save/make-table.py new file mode 100755 index 0000000..624f03b @@ -3611,7 +3492,7 @@ index 0000000..08ce5ff +sys.exit(0) diff --git a/tests/tool-line-length-save/test.sh b/tests/tool-line-length-save/test.sh new file mode 100755 -index 0000000..74234fb +index 0000000..346c022 --- /dev/null +++ b/tests/tool-line-length-save/test.sh @@ -0,0 +1,12 @@ @@ -3619,23 +3500,24 @@ index 0000000..74234fb +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 -+sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./random-ui.py#' \ -+ -e 's#^RANDOM_TOOLCHANGER = 0$#RANDOM_TOOLCHANGER = 1#' lathe.ini > random.ini ++../tool-wear-common/make-ini.sh random.ini ui=./random-ui.py random=1 +linuxcnc -r random.ini diff --git a/tests/tool-wear-abort/.gitignore b/tests/tool-wear-abort/.gitignore new file mode 100644 -index 0000000..f7b4787 +index 0000000..09798bf --- /dev/null +++ b/tests/tool-wear-abort/.gitignore -@@ -0,0 +1,3 @@ +@@ -0,0 +1,4 @@ +sim.var +sim.var.bak +tool.tbl ++lathe.ini diff --git a/tests/tool-wear-abort/change-move.ngc b/tests/tool-wear-abort/change-move.ngc new file mode 100644 index 0000000..df79eee @@ -3701,97 +3583,6 @@ index 0000000..ac36eff +G0 X1 +T2 M6 G1 X10 +M2 -diff --git a/tests/tool-wear-abort/lathe.ini b/tests/tool-wear-abort/lathe.ini -new file mode 100644 -index 0000000..128bace ---- /dev/null -+++ b/tests/tool-wear-abort/lathe.ini -@@ -0,0 +1,85 @@ -+# A metric lathe whose tool changer waits for the UI to complete the -+# prepare and change handshakes, so a tool change can be aborted while -+# it is pending. T1 and T2 differ in X and Z geometry and wear. -+ -+[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 = core_sim_handshake.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/tests/tool-wear-abort/move-origin.ngc b/tests/tool-wear-abort/move-origin.ngc new file mode 100644 index 0000000..1d66847 @@ -4206,15 +3997,16 @@ index 0000000..be0836e +sys.exit(0) diff --git a/tests/tool-wear-abort/test.sh b/tests/tool-wear-abort/test.sh new file mode 100755 -index 0000000..5a480e2 +index 0000000..c7ee908 --- /dev/null +++ b/tests/tool-wear-abort/test.sh -@@ -0,0 +1,6 @@ +@@ -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/tests/tool-wear-abort/tool.tbl.original b/tests/tool-wear-abort/tool.tbl.original new file mode 100644 @@ -4224,150 +4016,54 @@ index 0000000..1026231 @@ -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/tests/tool-wear-restart/.gitignore b/tests/tool-wear-restart/.gitignore -new file mode 100644 -index 0000000..f7b4787 ---- /dev/null -+++ b/tests/tool-wear-restart/.gitignore -@@ -0,0 +1,3 @@ -+sim.var -+sim.var.bak -+tool.tbl -diff --git a/tests/tool-wear-restart/checkresult b/tests/tool-wear-restart/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/tool-wear-restart/common.py b/tests/tool-wear-restart/common.py +diff --git a/tests/tool-wear-common/lathe.ini.in b/tests/tool-wear-common/lathe.ini.in new file mode 100644 -index 0000000..ed5a426 +index 0000000..b4d12ae --- /dev/null -+++ b/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) ++++ b/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 + -+def fail(msg): -+ print("ERROR: " + msg) -+ sys.exit(1) ++[DISPLAY] ++DISPLAY = ./test-ui.py ++LATHE = 1 + ++[RS274NGC] ++PARAMETER_FILE = sim.var + -+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)) ++[EMCMOT] ++EMCMOT = motmod ++COMM_TIMEOUT = 4.0 ++BASE_PERIOD = 0 ++SERVO_PERIOD = 1000000 + ++[TASK] ++TASK = milltask ++CYCLE_TIME = 0.001 + -+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() ++[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 + -+def mdi(cmd): -+ print("mdi: " + cmd) -+ c.mdi(cmd) -+ if c.wait_complete(10) == -1: -+ fail("timeout running '%s'" % cmd) -+ s.poll() ++[EMCIO] ++TOOL_TABLE = tool.tbl ++RANDOM_TOOLCHANGER = 0 + -+ -+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/tests/tool-wear-restart/run1.ini b/tests/tool-wear-restart/run1.ini -new file mode 100644 -index 0000000..06ce653 ---- /dev/null -+++ b/tests/tool-wear-restart/run1.ini -@@ -0,0 +1,85 @@ -+# A metric lathe with a random toolchanger, which keeps the tool in the -+# spindle (P0) across a restart; T1 and T2 carry X and Z wear. -+ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0 -+ -+[DISPLAY] -+DISPLAY = ./run1.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 = 1 -+ -+[KINS] -+KINEMATICS = trivkins -+JOINTS = 3 ++[KINS] ++KINEMATICS = trivkins ++JOINTS = 3 + +[AXIS_X] +MIN_LIMIT = -300.0 @@ -4410,113 +4106,143 @@ index 0000000..06ce653 +FERROR = 1.0 +MIN_FERROR = 0.25 +HOME_SEQUENCE = 0 -diff --git a/tests/tool-wear-restart/run1.py b/tests/tool-wear-restart/run1.py +diff --git a/tests/tool-wear-common/make-ini.sh b/tests/tool-wear-common/make-ini.sh new file mode 100755 -index 0000000..3523810 +index 0000000..2e1b1f2 --- /dev/null -+++ b/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/tests/tool-wear-restart/run2.ini b/tests/tool-wear-restart/run2.ini ++++ b/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/tests/tool-wear-restart/.gitignore b/tests/tool-wear-restart/.gitignore new file mode 100644 -index 0000000..859f7a3 +index 0000000..99ef76e --- /dev/null -+++ b/tests/tool-wear-restart/run2.ini -@@ -0,0 +1,85 @@ -+# A metric lathe with a random toolchanger, which keeps the tool in the -+# spindle (P0) across a restart; T1 and T2 carry X and Z wear. ++++ b/tests/tool-wear-restart/.gitignore +@@ -0,0 +1,5 @@ ++sim.var ++sim.var.bak ++tool.tbl ++run1.ini ++run2.ini +diff --git a/tests/tool-wear-restart/checkresult b/tests/tool-wear-restart/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/tool-wear-restart/common.py b/tests/tool-wear-restart/common.py +new file mode 100644 +index 0000000..ed5a426 +--- /dev/null ++++ b/tests/tool-wear-restart/common.py +@@ -0,0 +1,72 @@ ++# shared by run1.py and run2.py ++import linuxcnc ++import linuxcnc_util + -+[EMC] -+VERSION = 1.1 -+DEBUG = 0 ++import math ++import sys ++import time + -+[DISPLAY] -+DISPLAY = ./run2.py -+LATHE = 1 ++c = linuxcnc.command() ++e = linuxcnc.error_channel() ++s = linuxcnc.stat() ++l = linuxcnc_util.LinuxCNC(command=c, status=s, error=e) + -+[RS274NGC] -+PARAMETER_FILE = sim.var + ++def fail(msg): ++ print("ERROR: " + msg) ++ sys.exit(1) + -+[EMCMOT] -+EMCMOT = motmod -+COMM_TIMEOUT = 4.0 -+BASE_PERIOD = 0 -+SERVO_PERIOD = 1000000 + -+[TASK] -+TASK = milltask -+CYCLE_TIME = 0.001 ++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)) + -+[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 ++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() + -+[EMCIO] -+TOOL_TABLE = tool.tbl -+RANDOM_TOOLCHANGER = 1 + -+[KINS] -+KINEMATICS = trivkins -+JOINTS = 3 ++def mdi(cmd): ++ print("mdi: " + cmd) ++ c.mdi(cmd) ++ if c.wait_complete(10) == -1: ++ fail("timeout running '%s'" % cmd) ++ s.poll() + -+[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 ++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) + -+[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 ++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/tests/tool-wear-restart/run1.py b/tests/tool-wear-restart/run1.py +new file mode 100755 +index 0000000..3523810 +--- /dev/null ++++ b/tests/tool-wear-restart/run1.py +@@ -0,0 +1,10 @@ ++#!/usr/bin/env python3 ++from common import * + -+[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 ++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/tests/tool-wear-restart/run2.py b/tests/tool-wear-restart/run2.py new file mode 100755 index 0000000..5feff1a @@ -4543,21 +4269,23 @@ index 0000000..5feff1a +sys.exit(0) diff --git a/tests/tool-wear-restart/test.sh b/tests/tool-wear-restart/test.sh new file mode 100755 -index 0000000..54bcc33 +index 0000000..72a85fd --- /dev/null +++ b/tests/tool-wear-restart/test.sh -@@ -0,0 +1,12 @@ +@@ -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/tests/tool-wear-restart/tool.tbl.original b/tests/tool-wear-restart/tool.tbl.original new file mode 100644 @@ -4569,13 +4297,14 @@ index 0000000..1026231 +T2 P2 X-2.500000 Z+20.000000 WX-0.300000 WZ+0.150000 Q2 ;back tool diff --git a/tests/tool-wear-task/.gitignore b/tests/tool-wear-task/.gitignore new file mode 100644 -index 0000000..f7b4787 +index 0000000..09798bf --- /dev/null +++ b/tests/tool-wear-task/.gitignore -@@ -0,0 +1,3 @@ +@@ -0,0 +1,4 @@ +sim.var +sim.var.bak +tool.tbl ++lathe.ini diff --git a/tests/tool-wear-task/checkresult b/tests/tool-wear-task/checkresult new file mode 100755 index 0000000..24dc9aa @@ -4584,102 +4313,6 @@ index 0000000..24dc9aa @@ -0,0 +1,2 @@ +#!/bin/sh +exit 0 # test failure is indicated by test.sh exit value -diff --git a/tests/tool-wear-task/lathe.ini b/tests/tool-wear-task/lathe.ini -new file mode 100644 -index 0000000..e2dc531 ---- /dev/null -+++ b/tests/tool-wear-task/lathe.ini -@@ -0,0 +1,90 @@ -+# A metric lathe running through task, for native tool wear: the tool -+# table carries X and Z wear for a front tool (T1) and a back tool (T2). -+ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0 -+ -+[DISPLAY] -+DISPLAY = ./test-ui.py -+LATHE = 1 -+ -+[RS274NGC] -+PARAMETER_FILE = sim.var -+# M7 reads tool entries out of range through emccanon (remap.py) -+REMAP = M7 modalgroup=8 python=out_of_range_tools -+ -+[PYTHON] -+PATH_PREPEND = . -+TOPLEVEL = toplevel.py -+ -+[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/tests/tool-wear-task/remap.py b/tests/tool-wear-task/remap.py new file mode 100644 index 0000000..05e1a69 @@ -5006,15 +4639,19 @@ index 0000000..a6a6fd6 +sys.exit(0) diff --git a/tests/tool-wear-task/test.sh b/tests/tool-wear-task/test.sh new file mode 100755 -index 0000000..5a480e2 +index 0000000..f5f4988 --- /dev/null +++ b/tests/tool-wear-task/test.sh -@@ -0,0 +1,6 @@ +@@ -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/tests/tool-wear-task/tool.tbl.original b/tests/tool-wear-task/tool.tbl.original new file mode 100644 @@ -5243,395 +4880,3 @@ index 30edd89..59bed1c 100644 toolno = 99999.000000 tlo_z = -0.067000 -diff --git a/tests/tooldb/db-g10-offset/README b/tests/tooldb/db-g10-offset/README -index 095d3fb..face3c8 100644 ---- a/tests/tooldb/db-g10-offset/README -+++ b/tests/tooldb/db-g10-offset/README -@@ -1,5 +1,5 @@ --Verify that tool offsets set with G10 L1/L10/L11 are persisted when an --[EMCIO]DB_PROGRAM is configured. -+Verify that tool offsets set with G10 L1/L10/L11, and tool wear set with -+G10 L3, are persisted when an [EMCIO]DB_PROGRAM is configured. - - In db mode with a nonrandom toolchanger no tool table file is written, so the - db program must be notified of the new offsets ('p' command). Without that -diff --git a/tests/tooldb/db-g10-offset/db_test.py b/tests/tooldb/db-g10-offset/db_test.py -index ee22030..eaae357 100755 ---- a/tests/tooldb/db-g10-offset/db_test.py -+++ b/tests/tooldb/db-g10-offset/db_test.py -@@ -48,12 +48,18 @@ def toolno_of(toolline): - if item.startswith("T"): return int(item[1:]) - raise ValueError("no toolno in <%s>"%toolline) - -+def word(item): -+ # the letters of a tool-line item: one (Z) or two for wear (WZ) -+ letters = item.rstrip("+-.0123456789") -+ return letters, item[len(letters):] -+ - def merge(toolline,params): - # apply the letter parameters of params to toolline -- D = dict((item[0],item[1:]) for item in toolline.upper().split()) -+ D = dict(word(item) for item in toolline.upper().split()) - for item in params.upper().split(): - if item.startswith(";"): break -- D[item[0]] = item[1:] -+ letters, value = word(item) -+ D[letters] = value - letters = ["T","P"] + sorted(set(D) - set(["T","P"])) - return " ".join("%s%s"%(letter,D[letter]) for letter in letters) - -diff --git a/tests/tooldb/db-g10-offset/dbtest_lib.py b/tests/tooldb/db-g10-offset/dbtest_lib.py -index fbb6e18..b4221eb 100644 ---- a/tests/tooldb/db-g10-offset/dbtest_lib.py -+++ b/tests/tooldb/db-g10-offset/dbtest_lib.py -@@ -62,8 +62,19 @@ def tool_table_zoffset(s, idx): - return s.tool_table[idx].zoffset - - -+def tool_table_wzoffset(s, idx): -+ s.poll() -+ return s.tool_table[idx].wzoffset -+ -+ - def db_zoffset(toolno, timeout=0): - """Z offset recorded by the db program for toolno, or None.""" -+ return db_word(toolno, "Z", timeout) -+ -+ -+def db_word(toolno, word, timeout=0): -+ """Value of a tool-line word (Z, WZ, ...) recorded by the db program -+ for toolno, or None.""" - deadline = time.time() + timeout - while True: - try: -@@ -73,8 +84,9 @@ def db_zoffset(toolno, timeout=0): - if "T%d" % toolno not in items: - continue - for item in items: -- if item.startswith("Z"): -- return float(item[1:]) -+ letters = item.rstrip("+-.0123456789") -+ if letters == word: -+ return float(item[len(letters):]) - except IOError: - pass - if time.time() >= deadline: -diff --git a/tests/tooldb/db-g10-offset/test-ui.py b/tests/tooldb/db-g10-offset/test-ui.py -index 6d429fb..6499e6f 100755 ---- a/tests/tooldb/db-g10-offset/test-ui.py -+++ b/tests/tooldb/db-g10-offset/test-ui.py -@@ -8,6 +8,7 @@ - import sys - - from dbtest_lib import start_machine, check, fail, tool_table_zoffset, db_zoffset -+from dbtest_lib import tool_table_wzoffset, db_word - - (c, s) = start_machine() - -@@ -84,4 +85,18 @@ check("db zoffset for tool 5 after G10 L11", got, 1.75) - c.mdi("G10 L2 P1 Z0") - c.wait_complete() - -+# 5) G10 L3 sets stored wear; the db program gets it as a WZ word and the -+# geometry it already has is left alone. -+c.mdi("G10 L3 P1 Z-0.02") -+c.wait_complete() -+ -+check("tool 1 wzoffset after G10 L3", tool_table_wzoffset(s, 1), -0.02) -+check("tool 1 zoffset after G10 L3", tool_table_zoffset(s, 1), 0.5) -+ -+got = db_word(1, "WZ", timeout=5) -+if got is None: -+ fail("db program was not notified of the G10 L3 wear for tool 1") -+check("db wzoffset for tool 1 after G10 L3", got, -0.02) -+check("db zoffset for tool 1 after G10 L3", db_zoffset(1), 0.5) -+ - sys.exit(0) -diff --git a/tests/tooldb/db-g10-offset/verify-ui.py b/tests/tooldb/db-g10-offset/verify-ui.py -index f3c8f43..6585266 100755 ---- a/tests/tooldb/db-g10-offset/verify-ui.py -+++ b/tests/tooldb/db-g10-offset/verify-ui.py -@@ -5,7 +5,7 @@ - - import sys - --from dbtest_lib import start_machine, check, tool_table_zoffset -+from dbtest_lib import start_machine, check, tool_table_zoffset, tool_table_wzoffset - - (c, s) = start_machine() - -@@ -14,7 +14,8 @@ check("tool 2 zoffset after restart (G10 L1)", tool_table_zoffset(s, 2), -6.789) - check("tool 4 zoffset after restart (G10 L10)", tool_table_zoffset(s, 4), 1.5) - check("tool 5 zoffset after restart (G10 L11)", tool_table_zoffset(s, 5), 1.75) - --# tool 1 was never touched -+# tool 1 only had its wear set (G10 L3) - check("tool 1 zoffset after restart", tool_table_zoffset(s, 1), 0.5) -+check("tool 1 wzoffset after restart (G10 L3)", tool_table_wzoffset(s, 1), -0.02) - - sys.exit(0) -diff --git a/tests/tooldb/db-line-length/.gitignore b/tests/tooldb/db-line-length/.gitignore -new file mode 100644 -index 0000000..3a2d845 ---- /dev/null -+++ b/tests/tooldb/db-line-length/.gitignore -@@ -0,0 +1,5 @@ -+sim.var -+sim.var.bak -+long.inc -+long-run.ini -+db_spindle.tbl -diff --git a/tests/tooldb/db-line-length/base.inc b/tests/tooldb/db-line-length/base.inc -new file mode 100644 -index 0000000..9f95539 ---- /dev/null -+++ b/tests/tooldb/db-line-length/base.inc -@@ -0,0 +1,98 @@ -+[EMC] -+# The version string for this INI file. -+VERSION = 1.1 -+DEBUG = 0x0 -+ -+[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] -+# the library file provides the estop and toolchange loopbacks needed here -+HALFILE = LIB:core_sim.hal -+ -+[TRAJ] -+NO_FORCE_HOMING=1 -+COORDINATES = XYZ -+HOME = 0 0 0 -+LINEAR_UNITS = inch -+ANGULAR_UNITS = degree -+DEFAULT_LINEAR_VELOCITY = 1.2 -+MAX_LINEAR_ACCELERATION = 123.45 -+MAX_LINEAR_VELOCITY = 45.67 -+ -+[EMCIO] -+# no TOOL_TABLE: tool data is provided by the db program -+TOOL_CHANGE_QUILL_UP = 1 -+RANDOM_TOOLCHANGER = 0 -+DB_PROGRAM = ./db_long.py -+ -+[KINS] -+KINEMATICS = trivkins coordinates=XYZ -+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 = -40.0 -+MAX_LIMIT = 40.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 = -40.0 -+MAX_LIMIT = 40.0 -+FERROR = 0.050 -+MIN_FERROR = 0.010 -diff --git a/tests/tooldb/db-line-length/checkresult b/tests/tooldb/db-line-length/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/tests/tooldb/db-line-length/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh -+exit 0 # test failure is indicated by test.sh exit value -diff --git a/tests/tooldb/db-line-length/db_long.py b/tests/tooldb/db-line-length/db_long.py -new file mode 100755 -index 0000000..8e388f1 ---- /dev/null -+++ b/tests/tooldb/db-line-length/db_long.py -@@ -0,0 +1,30 @@ -+#!/usr/bin/env python3 -+# [EMCIO]DB_PROGRAM whose T1 line is exactly 510 characters (the longest -+# allowed), or 600 with the argument "long", which also adds a T3 line of -+# 5000 characters, longer than one pipe packet. The WZ word ends each long -+# line, so a reader that cut a line would cut that number. -+import sys -+ -+from tooldb import tooldb_callbacks, tooldb_tools, tooldb_loop -+ -+length = 600 if sys.argv[1:] == ["long"] else 510 -+ -+head = "T1 P1 X+1 Z+2 WX+0.5 D0." -+tail = " WZ-0.7555555555" -+t1 = head + "0" * (length - len(head) - len(tail)) + tail -+assert len(t1) == length -+ -+tools = {1: t1, 2: "T2 P2 Z+3 WZ-0.125"} -+if length == 600: -+ head3 = "T3 P3 Z+4 D0." -+ tools[3] = head3 + "0" * (5000 - len(head3) - len(tail)) + tail -+ -+def get_tool(tno): -+ return tools[tno] -+ -+def ignore(tno, params): -+ pass -+ -+tooldb_callbacks(get_tool, ignore, ignore, ignore) -+tooldb_tools(sorted(tools)) -+tooldb_loop() -diff --git a/tests/tooldb/db-line-length/long-ui.py b/tests/tooldb/db-line-length/long-ui.py -new file mode 100755 -index 0000000..86eb97f ---- /dev/null -+++ b/tests/tooldb/db-line-length/long-ui.py -@@ -0,0 +1,34 @@ -+#!/usr/bin/env python3 -+# A 600-character T1 line and a 5000-character T3 line (two pipe packets) -+# from the db program are refused, each read to its end: -+# T1 is not in the tool table (not with a number cut short), T2 after it is -+# loaded, and the db program is still in step for the next exchange. -+import sys -+sys.path.insert(0, "../db-g10-offset") -+from dbtest_lib import start_machine, check, fail -+ -+import linuxcnc -+ -+(c, s) = start_machine() -+s.poll() -+for t in s.tool_table[1:]: -+ if t.id == 1: -+ fail("T1 loaded from a 600-character line: wzoffset=%f" % t.wzoffset) -+ if t.id == 3: -+ fail("T3 loaded from a 5000-character line: wzoffset=%f" % t.wzoffset) -+print("ok: the 600- and 5000-character lines were refused") -+t2 = [t for t in s.tool_table[1:] if t.id == 2] -+if len(t2) != 1: -+ fail("T2, after the refused line, was not loaded") -+check("T2 wzoffset", t2[0].wzoffset, -0.125) -+ -+# a G10 notifies the db program and reads its reply: out of step, this -+# would read leftovers of the refused line instead -+c.mdi("G10 L1 P2 Z4") -+c.wait_complete() -+s.poll() -+if s.state != linuxcnc.RCS_DONE: -+ fail("G10 L1 after the refused line failed: state %d" % s.state) -+t2 = [t for t in s.tool_table[1:] if t.id == 2] -+check("T2 zoffset after G10 L1", t2[0].zoffset, 4.0) -+sys.exit(0) -diff --git a/tests/tooldb/db-line-length/long.ini b/tests/tooldb/db-line-length/long.ini -new file mode 100644 -index 0000000..bb7d822 ---- /dev/null -+++ b/tests/tooldb/db-line-length/long.ini -@@ -0,0 +1,5 @@ -+# a 600-character tool line from the db program is refused, not cut -+[DISPLAY] -+DISPLAY = ./long-ui.py -+ -+#INCLUDE base.inc -diff --git a/tests/tooldb/db-line-length/test-ui.py b/tests/tooldb/db-line-length/test-ui.py -new file mode 100755 -index 0000000..b9a3191 ---- /dev/null -+++ b/tests/tooldb/db-line-length/test-ui.py -@@ -0,0 +1,18 @@ -+#!/usr/bin/env python3 -+# The 510-character T1 line from the db program loads with every number. -+import sys -+sys.path.insert(0, "../db-g10-offset") -+from dbtest_lib import start_machine, check, fail -+ -+(c, s) = start_machine() -+s.poll() -+t1 = [t for t in s.tool_table[1:] if t.id == 1] -+if len(t1) != 1: -+ fail("T1 (a 510-character line) was not loaded") -+check("T1 xoffset", t1[0].xoffset, 1.0) -+check("T1 wzoffset at the end of the line", t1[0].wzoffset, -0.7555555555) -+t2 = [t for t in s.tool_table[1:] if t.id == 2] -+if len(t2) != 1: -+ fail("T2 was not loaded") -+check("T2 wzoffset", t2[0].wzoffset, -0.125) -+sys.exit(0) -diff --git a/tests/tooldb/db-line-length/test.ini b/tests/tooldb/db-line-length/test.ini -new file mode 100644 -index 0000000..6b56dc2 ---- /dev/null -+++ b/tests/tooldb/db-line-length/test.ini -@@ -0,0 +1,5 @@ -+# a 510-character tool line from the db program loads whole -+[DISPLAY] -+DISPLAY = ./test-ui.py -+ -+#INCLUDE base.inc -diff --git a/tests/tooldb/db-line-length/test.sh b/tests/tooldb/db-line-length/test.sh -new file mode 100755 -index 0000000..649e412 ---- /dev/null -+++ b/tests/tooldb/db-line-length/test.sh -@@ -0,0 +1,14 @@ -+#!/bin/bash -+set -x -+set -e -+ -+rm -f sim.var* -+ -+# run 1: the longest allowed line loads whole -+linuxcnc -r test.ini -+ -+# run 2: a longer line is refused (the db program is told to send one) -+sed -e 's#^DB_PROGRAM = ./db_long.py$#DB_PROGRAM = ./db_long.py long#' base.inc > long.inc -+sed -e 's#^\#INCLUDE base.inc#\#INCLUDE long.inc#' long.ini > long-run.ini -+linuxcnc -r long-run.ini -+rm -f long.inc long-run.ini 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 de51de2..e3212f6 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 @@ -51,13 +51,11 @@ tests/tooldb tests, which need a db program, are skipped. tests/tool-table-load/random-start-ui.py | 36 ++ tests/tool-table-load/reload-ui.py | 26 ++ tests/tool-table-load/symlink-ui.py | 55 +++ - tests/tool-table-load/test.ini | 84 ++++ - tests/tool-table-load/test.sh | 65 +++ + tests/tool-table-load/test.sh | 64 +++ .../reload-tool/non-random/test-ui.py | 14 + .../toolchanger/reload-tool/random/test-ui.py | 3 +- tests/tooldb/db-g10-offset/skip | 3 + - tests/tooldb/db-line-length/skip | 3 + - 35 files changed, 1773 insertions(+), 128 deletions(-) + 33 files changed, 1685 insertions(+), 128 deletions(-) create mode 100644 tests/tool-crud-refusal/.gitignore create mode 100644 tests/tool-crud-refusal/README create mode 100755 tests/tool-crud-refusal/checkresult @@ -76,10 +74,8 @@ tests/tooldb tests, which need a db program, are skipped. create mode 100755 tests/tool-table-load/random-start-ui.py create mode 100755 tests/tool-table-load/reload-ui.py create mode 100755 tests/tool-table-load/symlink-ui.py - create mode 100644 tests/tool-table-load/test.ini create mode 100755 tests/tool-table-load/test.sh create mode 100644 tests/tooldb/db-g10-offset/skip - create mode 100644 tests/tooldb/db-line-length/skip diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc index ded71c3..ce4110e 100644 @@ -2429,102 +2425,12 @@ index 0000000..2e03fa7 +print(real()) +print("*** all checks passed") +sys.exit(0) -diff --git a/tests/tool-table-load/test.ini b/tests/tool-table-load/test.ini -new file mode 100644 -index 0000000..9338ce7 ---- /dev/null -+++ b/tests/tool-table-load/test.ini -@@ -0,0 +1,84 @@ -+# A metric lathe whose tool table is written by test.sh for each run. -+ -+[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/tests/tool-table-load/test.sh b/tests/tool-table-load/test.sh new file mode 100755 -index 0000000..db74c94 +index 0000000..c7295bc --- /dev/null +++ b/tests/tool-table-load/test.sh -@@ -0,0 +1,65 @@ +@@ -0,0 +1,64 @@ +#!/bin/bash +set -e + @@ -2532,21 +2438,21 @@ index 0000000..db74c94 +# 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 -+sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./crlf-ui.py#' test.ini > run.ini ++../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 -+sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./garbage-ui.py#' test.ini > run.ini ++../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 -+sed -e 's#^DISPLAY = ./test-ui.py$#DISPLAY = ./reload-ui.py#' test.ini > run.ini ++../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 @@ -2558,8 +2464,7 @@ index 0000000..db74c94 +# the remaining runs choose their user interface and changer type +run_ui() { + rm -f sim.var -+ sed -e "s#^DISPLAY = ./test-ui.py\$#DISPLAY = ./$1#" \ -+ -e "s#^RANDOM_TOOLCHANGER = 0\$#RANDOM_TOOLCHANGER = $2#" test.ini > run.ini ++ ../tool-wear-common/make-ini.sh run.ini "ui=./$1" "random=$2" + linuxcnc -r run.ini +} + @@ -2642,12 +2547,3 @@ index 0000000..730d8c3 +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/tests/tooldb/db-line-length/skip b/tests/tooldb/db-line-length/skip -new file mode 100644 -index 0000000..730d8c3 ---- /dev/null -+++ b/tests/tooldb/db-line-length/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. From 7bb89f8691167cde8d379eb3e9390895bcd4b23c Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 14:02:17 +0100 Subject: [PATCH 27/45] test(linuxcnc): trim resumable Stop and availability fixtures Patch 0004 starts with the four resumable-stop test groups, so patch 0011 no longer replaces its single test script. availability-mcodes generates its configuration from the shared availability base. The final patched tree is unchanged apart from the generated fixture and a corrected test README. --- linuxcnc-patches/0004-resumable-stop.patch | 344 ++++++++++---- ...reading-stop-clear-and-pass-stepping.patch | 140 +++--- ...-single-step-during-active-execution.patch | 425 +++--------------- .../0018-availability-mcodes.patch | 21 +- 4 files changed, 399 insertions(+), 531 deletions(-) diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index ca72a10..70907d5 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -38,20 +38,29 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: src/emc/tp/tp_types.h | 12 + src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + src/emc/usr_intf/halui.cc | 9 +- - tests/resumable-stop/README | 51 + + tests/resumable-stop/README | 72 + tests/resumable-stop/after-abort.ngc | 4 + tests/resumable-stop/after-tap-m5.ngc | 7 + tests/resumable-stop/after-thread-m5.ngc | 7 + tests/resumable-stop/after-thread-m9.ngc | 8 + tests/resumable-stop/after-thread-s.ngc | 7 + - tests/resumable-stop/checkresult | 4 + + tests/resumable-stop/check-result.sh | 15 + tests/resumable-stop/core_sim.hal | 42 + tests/resumable-stop/css.ngc | 6 + tests/resumable-stop/dwell-atspeed.ngc | 7 + tests/resumable-stop/dwell.ngc | 5 + tests/resumable-stop/feed-atspeed.ngc | 7 + tests/resumable-stop/fperrev.ngc | 7 + + tests/resumable-stop/g76-step/checkresult | 2 + + tests/resumable-stop/g76-step/scenarios | 1 + + tests/resumable-stop/g76-step/test.sh | 3 + + tests/resumable-stop/g76-stop/checkresult | 2 + + tests/resumable-stop/g76-stop/scenarios | 2 + + tests/resumable-stop/g76-stop/test.sh | 3 + tests/resumable-stop/g76.ngc | 7 + + tests/resumable-stop/general/checkresult | 2 + + tests/resumable-stop/general/scenarios | 20 + + tests/resumable-stop/general/test.sh | 3 + tests/resumable-stop/homing-long.ngc | 6 + tests/resumable-stop/homing.ngc | 6 + tests/resumable-stop/multi-spindle.ngc | 4 + @@ -59,6 +68,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/pause.ngc | 7 + tests/resumable-stop/rapid-then-feed.ngc | 7 + tests/resumable-stop/resume-atspeed.ngc | 7 + + tests/resumable-stop/run-scenarios.sh | 51 + tests/resumable-stop/single-step.ngc | 10 + tests/resumable-stop/speed-change.ngc | 9 + tests/resumable-stop/spindle-state.ngc | 10 + @@ -66,27 +76,38 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/test-ui.py | 1492 +++++++++++++++++ tests/resumable-stop/test.ini | 98 ++ tests/resumable-stop/test.ngc | 9 + - tests/resumable-stop/test.sh | 74 + tests/resumable-stop/thread-chain.ngc | 8 + tests/resumable-stop/thread-g95-thread.ngc | 9 + tests/resumable-stop/thread-then-steps.ngc | 10 + tests/resumable-stop/thread.ngc | 7 + + tests/resumable-stop/threading/checkresult | 2 + + tests/resumable-stop/threading/scenarios | 8 + + tests/resumable-stop/threading/test.sh | 3 + tests/resumable-stop/tool.tbl | 1 + - 52 files changed, 2768 insertions(+), 25 deletions(-) + 64 files changed, 2828 insertions(+), 25 deletions(-) create mode 100644 tests/resumable-stop/README create mode 100644 tests/resumable-stop/after-abort.ngc create mode 100644 tests/resumable-stop/after-tap-m5.ngc create mode 100644 tests/resumable-stop/after-thread-m5.ngc create mode 100644 tests/resumable-stop/after-thread-m9.ngc create mode 100644 tests/resumable-stop/after-thread-s.ngc - create mode 100755 tests/resumable-stop/checkresult + create mode 100755 tests/resumable-stop/check-result.sh create mode 100644 tests/resumable-stop/core_sim.hal create mode 100644 tests/resumable-stop/css.ngc create mode 100644 tests/resumable-stop/dwell-atspeed.ngc create mode 100644 tests/resumable-stop/dwell.ngc create mode 100644 tests/resumable-stop/feed-atspeed.ngc create mode 100644 tests/resumable-stop/fperrev.ngc + create mode 100755 tests/resumable-stop/g76-step/checkresult + create mode 100644 tests/resumable-stop/g76-step/scenarios + create mode 100755 tests/resumable-stop/g76-step/test.sh + create mode 100755 tests/resumable-stop/g76-stop/checkresult + create mode 100644 tests/resumable-stop/g76-stop/scenarios + create mode 100755 tests/resumable-stop/g76-stop/test.sh create mode 100644 tests/resumable-stop/g76.ngc + create mode 100755 tests/resumable-stop/general/checkresult + create mode 100644 tests/resumable-stop/general/scenarios + create mode 100755 tests/resumable-stop/general/test.sh create mode 100644 tests/resumable-stop/homing-long.ngc create mode 100644 tests/resumable-stop/homing.ngc create mode 100644 tests/resumable-stop/multi-spindle.ngc @@ -94,6 +115,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: create mode 100644 tests/resumable-stop/pause.ngc create mode 100644 tests/resumable-stop/rapid-then-feed.ngc create mode 100644 tests/resumable-stop/resume-atspeed.ngc + create mode 100755 tests/resumable-stop/run-scenarios.sh create mode 100644 tests/resumable-stop/single-step.ngc create mode 100644 tests/resumable-stop/speed-change.ngc create mode 100644 tests/resumable-stop/spindle-state.ngc @@ -101,11 +123,13 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: 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-chain.ngc create mode 100644 tests/resumable-stop/thread-g95-thread.ngc create mode 100644 tests/resumable-stop/thread-then-steps.ngc create mode 100644 tests/resumable-stop/thread.ngc + create mode 100755 tests/resumable-stop/threading/checkresult + create mode 100644 tests/resumable-stop/threading/scenarios + create mode 100755 tests/resumable-stop/threading/test.sh create mode 100644 tests/resumable-stop/tool.tbl diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc @@ -1646,13 +1670,34 @@ index 1d0cb6e..65b890a 100644 counts = new_halui_data.mv_counts; diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README new file mode 100644 -index 0000000..29da7fe +index 0000000..137bc85 --- /dev/null +++ b/tests/resumable-stop/README -@@ -0,0 +1,51 @@ +@@ -0,0 +1,72 @@ +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 @@ -1764,16 +1809,27 @@ index 0000000..336d6be +S500 +G1 X5 F60 +M2 -diff --git a/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult +diff --git a/tests/resumable-stop/check-result.sh b/tests/resumable-stop/check-result.sh new file mode 100755 -index 0000000..5586b64 +index 0000000..7e07466 --- /dev/null -+++ b/tests/resumable-stop/checkresult -@@ -0,0 +1,4 @@ ++++ b/tests/resumable-stop/check-result.sh +@@ -0,0 +1,15 @@ +#!/bin/sh ++# Shared checkresult for the tests/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 -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 31 -+grep -q '^resumable stop scenarios complete$' "$1" ++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/tests/resumable-stop/core_sim.hal b/tests/resumable-stop/core_sim.hal new file mode 100644 index 0000000..bbc7166 @@ -1884,6 +1940,55 @@ index 0000000..92dbe87 +G1 X10 F1 +M5 +M2 +diff --git a/tests/resumable-stop/g76-step/checkresult b/tests/resumable-stop/g76-step/checkresult +new file mode 100755 +index 0000000..55a8859 +--- /dev/null ++++ b/tests/resumable-stop/g76-step/checkresult +@@ -0,0 +1,2 @@ ++#!/bin/sh ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 1 +diff --git a/tests/resumable-stop/g76-step/scenarios b/tests/resumable-stop/g76-step/scenarios +new file mode 100644 +index 0000000..f0a4053 +--- /dev/null ++++ b/tests/resumable-stop/g76-step/scenarios +@@ -0,0 +1 @@ ++trapezoidal:fperrev +diff --git a/tests/resumable-stop/g76-step/test.sh b/tests/resumable-stop/g76-step/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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/tests/resumable-stop/g76-stop/checkresult b/tests/resumable-stop/g76-stop/checkresult +new file mode 100755 +index 0000000..30bd373 +--- /dev/null ++++ b/tests/resumable-stop/g76-stop/checkresult +@@ -0,0 +1,2 @@ ++#!/bin/sh ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 2 +diff --git a/tests/resumable-stop/g76-stop/scenarios b/tests/resumable-stop/g76-stop/scenarios +new file mode 100644 +index 0000000..bea05471 +--- /dev/null ++++ b/tests/resumable-stop/g76-stop/scenarios +@@ -0,0 +1,2 @@ ++g76 ++fperrev +diff --git a/tests/resumable-stop/g76-stop/test.sh b/tests/resumable-stop/g76-stop/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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/tests/resumable-stop/g76.ngc b/tests/resumable-stop/g76.ngc new file mode 100644 index 0000000..1c6a3ea @@ -1897,6 +2002,49 @@ index 0000000..1c6a3ea +G1 X20 F600 +M5 +M2 +diff --git a/tests/resumable-stop/general/checkresult b/tests/resumable-stop/general/checkresult +new file mode 100755 +index 0000000..2d7e132 +--- /dev/null ++++ b/tests/resumable-stop/general/checkresult +@@ -0,0 +1,2 @@ ++#!/bin/sh ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 20 +diff --git a/tests/resumable-stop/general/scenarios b/tests/resumable-stop/general/scenarios +new file mode 100644 +index 0000000..f3792d2 +--- /dev/null ++++ b/tests/resumable-stop/general/scenarios +@@ -0,0 +1,20 @@ ++idle-rejected ++ordinary ++trapezoidal:ordinary ++single-step ++trapezoidal:single-step ++rapid-no-atspeed ++paused-resume ++paused-run ++abort-empty ++orientation ++dwell ++dwell-atspeed ++multi-spindle ++css ++homing ++homing-interrupted ++speed-change-atspeed ++queued-feed-atspeed ++spindle-state ++resume-atspeed +diff --git a/tests/resumable-stop/general/test.sh b/tests/resumable-stop/general/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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/tests/resumable-stop/homing-long.ngc b/tests/resumable-stop/homing-long.ngc new file mode 100644 index 0000000..2cc583c @@ -1982,6 +2130,63 @@ index 0000000..cf66123 +G1 X4 +M5 +M2 +diff --git a/tests/resumable-stop/run-scenarios.sh b/tests/resumable-stop/run-scenarios.sh +new file mode 100755 +index 0000000..c756dd3 +--- /dev/null ++++ b/tests/resumable-stop/run-scenarios.sh +@@ -0,0 +1,51 @@ ++#!/bin/bash -e ++# Shared driver for the tests/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) ++ ++[ $# -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 "$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/tests/resumable-stop/single-step.ngc b/tests/resumable-stop/single-step.ngc new file mode 100644 index 0000000..8955e51 @@ -3659,86 +3864,6 @@ index 0000000..416044b +M9 +M5 +M2 -diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh -new file mode 100755 -index 0000000..c70a720 ---- /dev/null -+++ b/tests/resumable-stop/test.sh -@@ -0,0 +1,74 @@ -+#!/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 -+ dwell-atspeed -+ command-after-sync -+ resume-atspeed -+ multi-spindle -+ css -+ homing -+ homing-interrupted -+ speed-change-atspeed -+ queued-feed-atspeed -+ g33-chain -+ step-resume-stopping -+ g95-between-g33 -+ spindle-state -+) -+ -+# test.ini selects the jerk-limited planner. Repeat the scenarios whose -+# unsynchronized motion is most planner dependent, and g33-chain (which ends -+# in a blend arc only with this planner), with the default trapezoidal planner. -+trapezoidal_scenarios=( -+ ordinary -+ single-step -+ fperrev -+ g33-chain -+) -+ -+scenario_log=$(mktemp) -+trapezoidal_ini=test-trapezoidal.ini -+trap 'rm -f "$scenario_log" "$trapezoidal_ini"' EXIT -+sed 's/^PLANNER_TYPE = 1$/PLANNER_TYPE = 0/' test.ini > "$trapezoidal_ini" -+grep -q '^PLANNER_TYPE = 0$' "$trapezoidal_ini" -+ -+run_scenario() { -+ local ini=$1 scenario=$2 -+ echo "Running resumable-stop scenario: $scenario ($ini)" -+ : > "$scenario_log" -+ 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 -+} -+ -+for scenario in "${scenarios[@]}"; do -+ run_scenario test.ini "$scenario" -+done -+for scenario in "${trapezoidal_scenarios[@]}"; do -+ run_scenario "$trapezoidal_ini" "$scenario" -+done -+echo "resumable stop scenarios complete" diff --git a/tests/resumable-stop/thread-chain.ngc b/tests/resumable-stop/thread-chain.ngc new file mode 100644 index 0000000..ca80839 @@ -3797,6 +3922,37 @@ index 0000000..5976979 +G1 X10 F60 +M5 +M2 +diff --git a/tests/resumable-stop/threading/checkresult b/tests/resumable-stop/threading/checkresult +new file mode 100755 +index 0000000..e619f41 +--- /dev/null ++++ b/tests/resumable-stop/threading/checkresult +@@ -0,0 +1,2 @@ ++#!/bin/sh ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 8 +diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios +new file mode 100644 +index 0000000..9fdbe0c +--- /dev/null ++++ b/tests/resumable-stop/threading/scenarios +@@ -0,0 +1,8 @@ ++rigid-tap ++g33 ++queued-g33 ++g33-chain ++trapezoidal:g33-chain ++step-resume-stopping ++g95-between-g33 ++command-after-sync +diff --git a/tests/resumable-stop/threading/test.sh b/tests/resumable-stop/threading/test.sh +new file mode 100755 +index 0000000..713f576 +--- /dev/null ++++ b/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/tests/resumable-stop/tool.tbl b/tests/resumable-stop/tool.tbl new file mode 100644 index 0000000..68840ea 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 5d89115..5bc7e30 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -44,18 +44,23 @@ that adds in-flight stepping. src/emc/tp/tp_types.h | 16 +- tests/interp/compile/use-rs274.cc | 5 + tests/resumable-stop/README | 16 + - tests/resumable-stop/checkresult | 2 +- .../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 + + tests/resumable-stop/g76-step/checkresult | 2 +- + tests/resumable-stop/g76-step/scenarios | 4 + + tests/resumable-stop/g76-stop/checkresult | 2 +- + tests/resumable-stop/g76-stop/scenarios | 3 + .../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/run-scenarios.sh | 10 + tests/resumable-stop/test-ui.py | 330 +++++++++++++++++- tests/resumable-stop/test.ini | 1 + - tests/resumable-stop/test.sh | 13 + - 35 files changed, 895 insertions(+), 57 deletions(-) + tests/resumable-stop/threading/checkresult | 2 +- + tests/resumable-stop/threading/scenarios | 1 + + 40 files changed, 902 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 @@ -1371,10 +1376,10 @@ index e30cc2f..6afd929 100644 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 29da7fe..8750b87 100644 +index 137bc85..a322d37 100644 --- a/tests/resumable-stop/README +++ b/tests/resumable-stop/README -@@ -49,3 +49,19 @@ barrier, and queued-g33 drops and restores at-speed after Resume as a +@@ -70,3 +70,19 @@ barrier, and queued-g33 drops and restores at-speed after Resume as a spindle would while spinning up. 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. @@ -1394,16 +1399,6 @@ index 29da7fe..8750b87 100644 +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/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -index 5586b64..631b3a4 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 31 -+test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 39 - 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 0000000..a12bcb3 @@ -1453,6 +1448,42 @@ index 0000000..c8ee28f +G1 X20 F600 +M5 +M2 +diff --git a/tests/resumable-stop/g76-step/checkresult b/tests/resumable-stop/g76-step/checkresult +index 55a8859..92d147c 100755 +--- a/tests/resumable-stop/g76-step/checkresult ++++ b/tests/resumable-stop/g76-step/checkresult +@@ -1,2 +1,2 @@ + #!/bin/sh +-exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 1 ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 5 +diff --git a/tests/resumable-stop/g76-step/scenarios b/tests/resumable-stop/g76-step/scenarios +index f0a4053..576921d 100644 +--- a/tests/resumable-stop/g76-step/scenarios ++++ b/tests/resumable-stop/g76-step/scenarios +@@ -1 +1,5 @@ ++g76-single-step ++g76-tapered-single-step ++g76-exit-taper ++g76-tapered-exit-taper + trapezoidal:fperrev +diff --git a/tests/resumable-stop/g76-stop/checkresult b/tests/resumable-stop/g76-stop/checkresult +index 30bd373..92d147c 100755 +--- a/tests/resumable-stop/g76-stop/checkresult ++++ b/tests/resumable-stop/g76-stop/checkresult +@@ -1,2 +1,2 @@ + #!/bin/sh +-exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 2 ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 5 +diff --git a/tests/resumable-stop/g76-stop/scenarios b/tests/resumable-stop/g76-stop/scenarios +index bea05471..e39cc37 100644 +--- a/tests/resumable-stop/g76-stop/scenarios ++++ b/tests/resumable-stop/g76-stop/scenarios +@@ -1,2 +1,5 @@ ++g76-handoff-stress + g76 ++g76-tapered ++g76-waiting-index + fperrev 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 0000000..488d2a9 @@ -1489,6 +1520,27 @@ index 0000000..b0eb997 +G1 X20 F600 +M5 +M2 +diff --git a/tests/resumable-stop/run-scenarios.sh b/tests/resumable-stop/run-scenarios.sh +index c756dd3..f572282 100755 +--- a/tests/resumable-stop/run-scenarios.sh ++++ b/tests/resumable-stop/run-scenarios.sh +@@ -16,6 +16,16 @@ 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; } diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py index 0b39992..d29f03f 100755 --- a/tests/resumable-stop/test-ui.py @@ -1885,43 +1937,21 @@ index a422788..96b5a38 100644 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 c70a720..4b7d7c2 100755 ---- a/tests/resumable-stop/test.sh -+++ b/tests/resumable-stop/test.sh -@@ -7,6 +7,11 @@ 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 -@@ -17,8 +22,11 @@ scenarios=( - abort-empty - queued-g33 - g33 -+ g33-no-following-rapid - fperrev - g76 -+ g76-waiting-index -+ g76-tapered - rigid-tap - orientation - dwell -@@ -35,6 +43,11 @@ scenarios=( - step-resume-stopping - g95-between-g33 - spindle-state -+ g76-single-step -+ g76-tapered-single-step -+ g76-exit-taper -+ g76-tapered-exit-taper -+ g76-handoff-stress - ) - - # test.ini selects the jerk-limited planner. Repeat the scenarios whose +diff --git a/tests/resumable-stop/threading/checkresult b/tests/resumable-stop/threading/checkresult +index e619f41..0201d4f 100755 +--- a/tests/resumable-stop/threading/checkresult ++++ b/tests/resumable-stop/threading/checkresult +@@ -1,2 +1,2 @@ + #!/bin/sh +-exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 8 ++exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 9 +diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios +index 9fdbe0c..0f41046 100644 +--- a/tests/resumable-stop/threading/scenarios ++++ b/tests/resumable-stop/threading/scenarios +@@ -5,4 +5,5 @@ g33-chain + trapezoidal:g33-chain + step-resume-stopping + g95-between-g33 ++g33-no-following-rapid + command-after-sync 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 84d9ef2..c3ebbcd 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 @@ -16,58 +16,32 @@ feature and its program. src/emc/task/emctaskmain.cc | 48 +++-- src/emc/tp/tp.c | 80 +++++-- src/emc/tp/tp_types.h | 6 +- - tests/resumable-stop/README | 33 +++ + tests/resumable-stop/README | 12 ++ tests/resumable-stop/after-tap-m5.ngc | 2 +- tests/resumable-stop/after-thread-m5.ngc | 2 +- tests/resumable-stop/after-thread-m9.ngc | 2 +- tests/resumable-stop/after-thread-s.ngc | 2 +- - tests/resumable-stop/check-result.sh | 15 ++ - tests/resumable-stop/checkresult | 4 - tests/resumable-stop/css.ngc | 2 +- - tests/resumable-stop/g76-step/checkresult | 2 + - tests/resumable-stop/g76-step/scenarios | 6 + - tests/resumable-stop/g76-step/test.sh | 3 + - tests/resumable-stop/g76-stop/checkresult | 2 + - tests/resumable-stop/g76-stop/scenarios | 5 + - tests/resumable-stop/g76-stop/test.sh | 3 + - tests/resumable-stop/general/checkresult | 2 + - tests/resumable-stop/general/scenarios | 24 +++ - tests/resumable-stop/general/test.sh | 3 + + tests/resumable-stop/g76-step/checkresult | 2 +- + tests/resumable-stop/g76-step/scenarios | 1 + + tests/resumable-stop/general/checkresult | 2 +- + tests/resumable-stop/general/scenarios | 4 + tests/resumable-stop/inflight-step.ngc | 7 + tests/resumable-stop/multi-spindle.ngc | 2 +- tests/resumable-stop/orient.ngc | 2 +- tests/resumable-stop/rapid-then-feed.ngc | 2 +- tests/resumable-stop/resume-s0.ngc | 7 + - tests/resumable-stop/run-scenarios.sh | 61 ++++++ tests/resumable-stop/tap.ngc | 6 +- tests/resumable-stop/test-ui.py | 237 +++++++++++++++++++++ tests/resumable-stop/test.ngc | 2 +- - tests/resumable-stop/test.sh | 87 -------- tests/resumable-stop/thread-g95-thread.ngc | 2 +- tests/resumable-stop/thread-then-steps.ngc | 4 +- tests/resumable-stop/thread.ngc | 6 +- - tests/resumable-stop/threading/checkresult | 2 + - tests/resumable-stop/threading/scenarios | 11 + - tests/resumable-stop/threading/test.sh | 3 + - 38 files changed, 560 insertions(+), 160 deletions(-) - create mode 100755 tests/resumable-stop/check-result.sh - delete mode 100755 tests/resumable-stop/checkresult - create mode 100755 tests/resumable-stop/g76-step/checkresult - create mode 100644 tests/resumable-stop/g76-step/scenarios - create mode 100755 tests/resumable-stop/g76-step/test.sh - create mode 100755 tests/resumable-stop/g76-stop/checkresult - create mode 100644 tests/resumable-stop/g76-stop/scenarios - create mode 100755 tests/resumable-stop/g76-stop/test.sh - create mode 100755 tests/resumable-stop/general/checkresult - create mode 100644 tests/resumable-stop/general/scenarios - create mode 100755 tests/resumable-stop/general/test.sh + tests/resumable-stop/threading/checkresult | 2 +- + tests/resumable-stop/threading/scenarios | 2 + + 28 files changed, 407 insertions(+), 72 deletions(-) create mode 100644 tests/resumable-stop/inflight-step.ngc create mode 100644 tests/resumable-stop/resume-s0.ngc - create mode 100755 tests/resumable-stop/run-scenarios.sh - delete mode 100755 tests/resumable-stop/test.sh - create mode 100755 tests/resumable-stop/threading/checkresult - create mode 100644 tests/resumable-stop/threading/scenarios - create mode 100755 tests/resumable-stop/threading/test.sh diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c index a8e8ae3..ff48890 100644 @@ -460,38 +434,10 @@ index 2963bcc..819f508 100644 } TP_STRUCT; diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -index 8750b87..6274c79 100644 +index a322d37..6c8eb25 100644 --- a/tests/resumable-stop/README +++ b/tests/resumable-stop/README -@@ -1,6 +1,27 @@ - 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 run in parallel under ci/test-sharded.sh: -+ -+ 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 -@@ -47,6 +68,12 @@ Resume waits for at-speed, rapid-no-atspeed checks that an interrupted rapid +@@ -68,6 +68,12 @@ 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. @@ -504,7 +450,7 @@ index 8750b87..6274c79 100644 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 -@@ -61,6 +88,12 @@ step. It also starts G76 in normal AUTO_RUN, stops after the first pass with +@@ -82,6 +88,12 @@ 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. @@ -561,37 +507,6 @@ index 336d6be..6e468d1 100644 -G1 X5 F60 +G1 X5 F300 M2 -diff --git a/tests/resumable-stop/check-result.sh b/tests/resumable-stop/check-result.sh -new file mode 100755 -index 0000000..7e07466 ---- /dev/null -+++ b/tests/resumable-stop/check-result.sh -@@ -0,0 +1,15 @@ -+#!/bin/sh -+# Shared checkresult for the tests/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/tests/resumable-stop/checkresult b/tests/resumable-stop/checkresult -deleted file mode 100755 -index 631b3a4..0000000 ---- a/tests/resumable-stop/checkresult -+++ /dev/null -@@ -1,4 +0,0 @@ --#!/bin/sh --set -e --test "$(grep -c '^resumable stop scenario ok:' "$1")" -eq 39 --grep -q '^resumable stop scenarios complete$' "$1" diff --git a/tests/resumable-stop/css.ngc b/tests/resumable-stop/css.ngc index 382aaff..8a70da2 100644 --- a/tests/resumable-stop/css.ngc @@ -605,109 +520,51 @@ index 382aaff..8a70da2 100644 M5 M2 diff --git a/tests/resumable-stop/g76-step/checkresult b/tests/resumable-stop/g76-step/checkresult -new file mode 100755 -index 0000000..0562404 ---- /dev/null +index 92d147c..0562404 100755 +--- a/tests/resumable-stop/g76-step/checkresult +++ b/tests/resumable-stop/g76-step/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh +@@ -1,2 +1,2 @@ + #!/bin/sh +-exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 5 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 6 diff --git a/tests/resumable-stop/g76-step/scenarios b/tests/resumable-stop/g76-step/scenarios -new file mode 100644 -index 0000000..df2a2ab ---- /dev/null +index 576921d..df2a2ab 100644 +--- a/tests/resumable-stop/g76-step/scenarios +++ b/tests/resumable-stop/g76-step/scenarios -@@ -0,0 +1,6 @@ -+g76-single-step -+g76-tapered-single-step +@@ -1,5 +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/tests/resumable-stop/g76-step/test.sh b/tests/resumable-stop/g76-step/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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/tests/resumable-stop/g76-stop/checkresult b/tests/resumable-stop/g76-stop/checkresult -new file mode 100755 -index 0000000..92d147c ---- /dev/null -+++ b/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/tests/resumable-stop/g76-stop/scenarios b/tests/resumable-stop/g76-stop/scenarios -new file mode 100644 -index 0000000..e39cc37 ---- /dev/null -+++ b/tests/resumable-stop/g76-stop/scenarios -@@ -0,0 +1,5 @@ -+g76-handoff-stress -+g76 -+g76-tapered -+g76-waiting-index -+fperrev -diff --git a/tests/resumable-stop/g76-stop/test.sh b/tests/resumable-stop/g76-stop/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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 + g76-exit-taper + g76-tapered-exit-taper + trapezoidal:fperrev diff --git a/tests/resumable-stop/general/checkresult b/tests/resumable-stop/general/checkresult -new file mode 100755 -index 0000000..362de54 ---- /dev/null +index 2d7e132..362de54 100755 +--- a/tests/resumable-stop/general/checkresult +++ b/tests/resumable-stop/general/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh +@@ -1,2 +1,2 @@ + #!/bin/sh +-exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 20 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 24 diff --git a/tests/resumable-stop/general/scenarios b/tests/resumable-stop/general/scenarios -new file mode 100644 -index 0000000..d8e2870 ---- /dev/null +index f3792d2..d8e2870 100644 +--- a/tests/resumable-stop/general/scenarios +++ b/tests/resumable-stop/general/scenarios -@@ -0,0 +1,24 @@ -+idle-rejected -+ordinary -+trapezoidal:ordinary -+single-step -+trapezoidal:single-step +@@ -3,6 +3,7 @@ ordinary + trapezoidal:ordinary + single-step + trapezoidal:single-step +inflight-single-step -+rapid-no-atspeed -+paused-resume -+paused-run -+abort-empty -+orientation -+dwell -+dwell-atspeed -+multi-spindle -+css -+homing -+homing-interrupted -+speed-change-atspeed -+queued-feed-atspeed -+spindle-state -+resume-atspeed + rapid-no-atspeed + paused-resume + paused-run +@@ -18,3 +19,6 @@ speed-change-atspeed + queued-feed-atspeed + spindle-state + resume-atspeed +pause-starting +resume-s0 +pause-inflight-step -diff --git a/tests/resumable-stop/general/test.sh b/tests/resumable-stop/general/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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/tests/resumable-stop/inflight-step.ngc b/tests/resumable-stop/inflight-step.ngc new file mode 100644 index 0000000..1f72544 @@ -767,73 +624,6 @@ index 0000000..69d6ce7 +G1 X4 +M5 +M2 -diff --git a/tests/resumable-stop/run-scenarios.sh b/tests/resumable-stop/run-scenarios.sh -new file mode 100755 -index 0000000..f572282 ---- /dev/null -+++ b/tests/resumable-stop/run-scenarios.sh -@@ -0,0 +1,61 @@ -+#!/bin/bash -e -+# Shared driver for the tests/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 "$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/tests/resumable-stop/tap.ngc b/tests/resumable-stop/tap.ngc index 3060ac4..2182f18 100644 --- a/tests/resumable-stop/tap.ngc @@ -1144,99 +934,6 @@ index 416044b..c44a2cd 100644 S300 M3 M8 G1 X10 -diff --git a/tests/resumable-stop/test.sh b/tests/resumable-stop/test.sh -deleted file mode 100755 -index 4b7d7c2..0000000 ---- a/tests/resumable-stop/test.sh -+++ /dev/null -@@ -1,87 +0,0 @@ --#!/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 -- --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 -- 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 -- dwell-atspeed -- command-after-sync -- resume-atspeed -- multi-spindle -- css -- homing -- homing-interrupted -- speed-change-atspeed -- queued-feed-atspeed -- g33-chain -- step-resume-stopping -- g95-between-g33 -- spindle-state -- g76-single-step -- g76-tapered-single-step -- g76-exit-taper -- g76-tapered-exit-taper -- g76-handoff-stress --) -- --# test.ini selects the jerk-limited planner. Repeat the scenarios whose --# unsynchronized motion is most planner dependent, and g33-chain (which ends --# in a blend arc only with this planner), with the default trapezoidal planner. --trapezoidal_scenarios=( -- ordinary -- single-step -- fperrev -- g33-chain --) -- --scenario_log=$(mktemp) --trapezoidal_ini=test-trapezoidal.ini --trap 'rm -f "$scenario_log" "$trapezoidal_ini"' EXIT --sed 's/^PLANNER_TYPE = 1$/PLANNER_TYPE = 0/' test.ini > "$trapezoidal_ini" --grep -q '^PLANNER_TYPE = 0$' "$trapezoidal_ini" -- --run_scenario() { -- local ini=$1 scenario=$2 -- echo "Running resumable-stop scenario: $scenario ($ini)" -- : > "$scenario_log" -- 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 --} -- --for scenario in "${scenarios[@]}"; do -- run_scenario test.ini "$scenario" --done --for scenario in "${trapezoidal_scenarios[@]}"; do -- run_scenario "$trapezoidal_ini" "$scenario" --done --echo "resumable stop scenarios complete" diff --git a/tests/resumable-stop/thread-g95-thread.ngc b/tests/resumable-stop/thread-g95-thread.ngc index d6630aa..2bc7489 100644 --- a/tests/resumable-stop/thread-g95-thread.ngc @@ -1279,36 +976,20 @@ index 5976979..c3ec6d0 100644 M5 M2 diff --git a/tests/resumable-stop/threading/checkresult b/tests/resumable-stop/threading/checkresult -new file mode 100755 -index 0000000..664eed8 ---- /dev/null +index 0201d4f..664eed8 100755 +--- a/tests/resumable-stop/threading/checkresult +++ b/tests/resumable-stop/threading/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh +@@ -1,2 +1,2 @@ + #!/bin/sh +-exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 9 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 11 diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios -new file mode 100644 -index 0000000..a4410d4 ---- /dev/null +index 0f41046..a4410d4 100644 +--- a/tests/resumable-stop/threading/scenarios +++ b/tests/resumable-stop/threading/scenarios -@@ -0,0 +1,11 @@ -+rigid-tap -+g33 -+queued-g33 -+g33-chain -+trapezoidal:g33-chain -+step-resume-stopping -+g95-between-g33 -+g33-no-following-rapid -+command-after-sync +@@ -7,3 +7,5 @@ step-resume-stopping + g95-between-g33 + g33-no-following-rapid + command-after-sync +pause-latched-resume +stop-latched-resume -diff --git a/tests/resumable-stop/threading/test.sh b/tests/resumable-stop/threading/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index bad297d..fb5957c 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -39,7 +39,7 @@ homing ends as it does during G28.2. tests/availability-mcodes/no-force.ini.in | 6 + tests/availability-mcodes/ordered.ngc | 6 + tests/availability-mcodes/test-ui.py | 205 ++++++++++++++++++ - tests/availability-mcodes/test.ini | 1 + + tests/availability-mcodes/test.ini.in | 3 + tests/availability-mcodes/test.sh | 5 + tests/availability-mcodes/timeout.ngc | 4 + tests/availability-mcodes/tool.tbl | 1 + @@ -74,7 +74,7 @@ homing ends as it does during G28.2. tests/interp/availability-mcodes/test.sh | 80 +++++++ .../availability-mcodes/valid-joint.ngc | 3 + .../availability-mcodes/valid-spindle.ngc | 3 + - 65 files changed, 703 insertions(+), 7 deletions(-) + 65 files changed, 705 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 @@ -90,7 +90,7 @@ homing ends as it does during G28.2. 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 100644 tests/availability-mcodes/test.ini.in create mode 100755 tests/availability-mcodes/test.sh create mode 100644 tests/availability-mcodes/timeout.ngc create mode 120000 tests/availability-mcodes/tool.tbl @@ -938,14 +938,15 @@ index 0000000..0f3d8df +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 0000000..800b1b7 +diff --git a/tests/availability-mcodes/test.ini.in b/tests/availability-mcodes/test.ini.in +new file mode 100644 +index 0000000..fe357c0 --- /dev/null -+++ b/tests/availability-mcodes/test.ini -@@ -0,0 +1 @@ -+../runtime-availability/base.ini -\ No newline at end of file ++++ b/tests/availability-mcodes/test.ini.in +@@ -0,0 +1,3 @@ ++# Uses the shared base unchanged. ++[FIXTURE] ++BASE = ../runtime-availability/base.ini diff --git a/tests/availability-mcodes/test.sh b/tests/availability-mcodes/test.sh new file mode 100755 index 0000000..882b151 From 23fa69c3cd9a861822a951b569f52ae9040d6d11 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 14:30:14 +0100 Subject: [PATCH 28/45] fix(linuxcnc): generate the tool-crud-refusal configuration The test copied tool-table-load's INI, which the fixture trim replaced with the shared lathe template. --- .../0012-emc-own-transactional-tool-CRUD-in-task.patch | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 e3212f6..61fd17d 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 @@ -1763,7 +1763,7 @@ index 0000000..8d6ef70 +sys.exit(0) diff --git a/tests/tool-crud-refusal/test.sh b/tests/tool-crud-refusal/test.sh new file mode 100755 -index 0000000..c9a8d42 +index 0000000..bad1a01 --- /dev/null +++ b/tests/tool-crud-refusal/test.sh @@ -0,0 +1,12 @@ @@ -1777,7 +1777,7 @@ index 0000000..c9a8d42 + -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 -+cp ../tool-table-load/test.ini run.ini ++../tool-wear-common/make-ini.sh run.ini +linuxcnc -r run.ini diff --git a/tests/tool-crud-refusal/tool-cmd.cc b/tests/tool-crud-refusal/tool-cmd.cc new file mode 100644 From c8f4b249498e5b657e02572ee06e5b7dbbb48986 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 19:16:10 +0100 Subject: [PATCH 29/45] refactor(native): move the preview recorder out of the patch series Only the native server builds the recording canon, so it now lives in native/server/src/gcode. Patch 0010 keeps what must be in LinuxCNC: the cutter compensation canon calls and a thread-safe tool_mmap_user(). Verified locally: native build, unit and live tests, format, lint and the patch-stack test. --- ...-rs274-support-native-gcode-preview.patch} | 831 +----------------- .../0018-availability-mcodes.patch | 33 +- linuxcnc-patches/README.md | 12 +- native/server/CMakeLists.txt | 2 +- native/server/GCODE_PARSER_INTEGRATION.md | 8 +- native/server/src/gcode/canon_preview.cc | 2 +- native/server/src/gcode/parser.cc | 2 +- native/server/src/gcode/recording_canon.cc | 617 +++++++++++++ native/server/src/gcode/recording_canon.hpp | 149 ++++ 9 files changed, 802 insertions(+), 854 deletions(-) rename linuxcnc-patches/{0010-rs274-add-recording-canon-preview-backend.patch => 0010-rs274-support-native-gcode-preview.patch} (72%) create mode 100644 native/server/src/gcode/recording_canon.cc create mode 100644 native/server/src/gcode/recording_canon.hpp 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 69e2b02..b6d9dfe 100644 --- a/linuxcnc-patches/0010-rs274-add-recording-canon-preview-backend.patch +++ b/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch @@ -1,38 +1,30 @@ 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 -Ported to v2.10.0-pre2. The recording canon implements the canon -interface as it is here: SET_MOTION_CONTROL_MODE takes upstream's planner -arguments and STOP_SPINDLE_TURNING its wait argument, and HOME_CYCLE, -HOME_CYCLE_JOINT, LOCK_SPEED_OVERRIDE, SELECT_KINS_TYPE, -GET_EXTERNAL_AXIS_MAX_VELOCITY, GET_EXTERNAL_SPINDLE_MAX_VELOCITY, -GET_EXTERNAL_KINS_TYPE and GET_EXTERNAL_KINS_TYPE_FLAGS are added with -the same preview behaviour as the Axis module. -tool_mmap_user() keeps upstream's record of the mapping descriptor -(8c8e048) instead of closing it; the mutex and the early return for an -existing mapping remain. +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 | 636 +++++++++++++++++++ - src/emc/rs274ngc/recordingcanon.hh | 147 +++++ + 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, 943 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 e894e64..462eb90 100644 +index 0183299..3c676b6 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -2528,6 +2528,7 @@ Called by: convert_cutter_compensation @@ -62,801 +54,6 @@ index e894e64..462eb90 100644 return INTERP_OK; } -diff --git a/src/emc/rs274ngc/recordingcanon.cc b/src/emc/rs274ngc/recordingcanon.cc -new file mode 100644 -index 0000000..f64dbd7 ---- /dev/null -+++ b/src/emc/rs274ngc/recordingcanon.cc -@@ -0,0 +1,636 @@ -+#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 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 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 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 SELECT_KINS_TYPE(int) {} -+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 0000000..dca1242 ---- /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 7ba07b4..d13d877 100644 --- a/src/emc/tooldata/tooldata_mmap.cc diff --git a/linuxcnc-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index fb5957c..e0cf38c 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -21,7 +21,6 @@ homing ends as it does during G28.2. 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 + @@ -74,7 +73,7 @@ homing ends as it does during G28.2. tests/interp/availability-mcodes/test.sh | 80 +++++++ .../availability-mcodes/valid-joint.ngc | 3 + .../availability-mcodes/valid-spindle.ngc | 3 + - 65 files changed, 705 insertions(+), 7 deletions(-) + 64 files changed, 702 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 @@ -256,7 +255,7 @@ index a900d33..d95b187 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 50781c6..7981131 100644 +index c65a3b2..219a007 100644 --- a/src/emc/rs274ngc/interp_check.cc +++ b/src/emc/rs274ngc/interp_check.cc @@ -17,6 +17,7 @@ @@ -317,7 +316,7 @@ index 50781c6..7981131 100644 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 462eb90..fddac65 100644 +index 3c676b6..624903f 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -4443,6 +4443,17 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ @@ -354,10 +353,10 @@ index 46eb9e1..6bb5760 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 4ec4f7a..41e032d 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; @@ -366,10 +365,10 @@ index 4ec4f7a..41e032d 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 ff5f379..d642007 100644 +index 65197e8..ddae1dc 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh -@@ -478,12 +478,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{}; @@ -390,7 +389,7 @@ index ff5f379..d642007 100644 bool b_flag{}; bool c_flag{}; diff --git a/src/emc/rs274ngc/interp_read.cc b/src/emc/rs274ngc/interp_read.cc -index 6e58d16..22eb924 100644 +index b397cc0..2480073 100644 --- a/src/emc/rs274ngc/interp_read.cc +++ b/src/emc/rs274ngc/interp_read.cc @@ -20,6 +20,7 @@ @@ -414,7 +413,7 @@ index 6e58d16..22eb924 100644 block->dollar_flag = true; return INTERP_OK; } -@@ -871,7 +876,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;) { @@ -437,20 +436,6 @@ index cf192c1..6cfdd5c 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 f64dbd7..61735a9 100644 ---- a/src/emc/rs274ngc/recordingcanon.cc -+++ b/src/emc/rs274ngc/recordingcanon.cc -@@ -429,6 +429,9 @@ void STOP_SPINDLE_TURNING(int spindle, int) - 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 faeae9f..a45ebab 100644 --- a/src/emc/sai/saicanon.cc diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index cc9c876..8765e89 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -374,13 +374,13 @@ 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 — Recording canon backend for native G-code preview +### 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 diff --git a/native/server/CMakeLists.txt b/native/server/CMakeLists.txt index aaacd2b..dc23dd0 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) diff --git a/native/server/GCODE_PARSER_INTEGRATION.md b/native/server/GCODE_PARSER_INTEGRATION.md index 6273405..980f76c 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/src/gcode/canon_preview.cc b/native/server/src/gcode/canon_preview.cc index 404a659..f103e57 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 a3c7f3b..24c263a 100644 --- a/native/server/src/gcode/parser.cc +++ b/native/server/src/gcode/parser.cc @@ -12,7 +12,7 @@ #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" diff --git a/native/server/src/gcode/recording_canon.cc b/native/server/src/gcode/recording_canon.cc new file mode 100644 index 0000000..c3d320a --- /dev/null +++ b/native/server/src/gcode/recording_canon.cc @@ -0,0 +1,617 @@ +#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; + 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 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 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 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 0000000..a58a76b --- /dev/null +++ b/native/server/src/gcode/recording_canon.hpp @@ -0,0 +1,149 @@ +// 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; + 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 From 02fc6cc813cd4d11cc16056d3137701a03f14e3e Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Wed, 18 Nov 2026 19:16:16 +0100 Subject: [PATCH 30/45] feat(linuxcnc): select alternating G76 infeed with G76.1 Upstream master uses D on G76 for a spindle start angle, so patch 0008 no longer uses it for the infeed mode. G76.1 takes the same words as G76 and alternates roughing passes; D is refused on both codes. Verified locally: 346 of 354 regression tests passed; the 8 failures are out-of-scope GUI tests on a --disable-gui build. Native build, unit and live tests, format, lint and the patch-stack test passed. --- .../0008-tapered-g76-drive-lines.patch | 284 ++++++++++-------- ...reading-stop-clear-and-pass-stepping.patch | 6 +- ...4ngc-add-composable-executor-stdglue.patch | 4 +- linuxcnc-patches/README.md | 9 +- 4 files changed, 166 insertions(+), 137 deletions(-) diff --git a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch index ffc8792..cd1f61e 100644 --- a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch +++ b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch @@ -12,31 +12,31 @@ 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. A D word in a block with both G96 and G76 is -reported as ambiguous before it is range-checked as an infeed mode. +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 | 52 ++- - src/emc/rs274ngc/interp_check.cc | 13 +- - src/emc/rs274ngc/interp_convert.cc | 253 +++++++++-- + docs/src/gcode/g-code.adoc | 53 ++- + src/emc/rs274ngc/interp_convert.cc | 252 +++++++++-- + 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 + tests/g76-tapered-pitch/README | 34 ++ tests/g76-tapered-pitch/checkresult | 2 + tests/g76-tapered-pitch/core_sim.hal | 18 + - tests/g76-tapered-pitch/test-ui.py | 173 ++++++++ + tests/g76-tapered-pitch/test-ui.py | 173 +++++++ tests/g76-tapered-pitch/test.ini | 67 +++ tests/g76-tapered-pitch/test.sh | 3 + - tests/interp/g76-tapered/README | 14 + - tests/interp/g76-tapered/expected | 403 ++++++++++++++++++ - .../interp/g76-tapered/invalid-d-fraction.ngc | 5 + - tests/interp/g76-tapered/invalid-d2.ngc | 5 + - .../g76-tapered/invalid-g96-d-limit.ngc | 5 + - tests/interp/g76-tapered/invalid-g96-d.ngc | 5 + + tests/interp/g76-tapered/README | 13 + + tests/interp/g76-tapered/expected | 424 ++++++++++++++++++ + .../interp/g76-tapered/invalid-both-modes.ngc | 5 + + tests/interp/g76-tapered/invalid-d.ngc | 5 + tests/interp/g76-tapered/invalid-y.ngc | 5 + tests/interp/g76-tapered/invalid-zero-z.ngc | 5 + - tests/interp/g76-tapered/test.ngc | 63 +++ - tests/interp/g76-tapered/test.sh | 31 ++ - 20 files changed, 1118 insertions(+), 42 deletions(-) + tests/interp/g76-tapered/test.ngc | 67 +++ + tests/interp/g76-tapered/test.sh | 29 ++ + 20 files changed, 1125 insertions(+), 42 deletions(-) create mode 100644 tests/g76-tapered-pitch/README create mode 100755 tests/g76-tapered-pitch/checkresult create mode 100644 tests/g76-tapered-pitch/core_sim.hal @@ -45,19 +45,26 @@ tests/g76-tapered-pitch exercises the check on a simulated lathe. create mode 100755 tests/g76-tapered-pitch/test.sh 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-limit.ngc - create mode 100644 tests/interp/g76-tapered/invalid-g96-d.ngc + create mode 100644 tests/interp/g76-tapered/invalid-both-modes.ngc + create mode 100644 tests/interp/g76-tapered/invalid-d.ngc create mode 100644 tests/interp/g76-tapered/invalid-y.ngc create mode 100644 tests/interp/g76-tapered/invalid-zero-z.ngc create mode 100644 tests/interp/g76-tapered/test.ngc create mode 100644 tests/interp/g76-tapered/test.sh diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index f8f9d01..950dc5c 100644 +index f8f9d01..39cbf04 100644 --- a/docs/src/gcode/g-code.adoc +++ b/docs/src/gcode/g-code.adoc +@@ -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 @@ -71,12 +78,18 @@ index f8f9d01..950dc5c 100644 [[gcode:g38]] == G38._n_ Straight Probe(((G38.n Probe))) -@@ -2217,15 +2221,24 @@ In example S100 with 1.25MM per revolution thread pitch gives a feed of F125. +@@ -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 @@ -100,7 +113,7 @@ index f8f9d01..950dc5c 100644 [NOTE] When G7 'Lathe Diameter Mode' is in force the values for 'I', 'J' and 'K' are diameter measurements. -@@ -2254,7 +2267,17 @@ Unnecessarily high degression values will produce an unnecessarily high number o +@@ -2254,11 +2268,20 @@ 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. @@ -108,17 +121,20 @@ index f8f9d01..950dc5c 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'. + ++'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. 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 +2297,10 @@ Thread entries and exits can be programmed tapered with the 'E' and 'L' values. cut depth then synchronize and begin the cut. @@ -132,15 +148,12 @@ index f8f9d01..950dc5c 100644 The tool will pause briefly for synchronization before each threading pass, so a relief groove will be required at the entry unless the -@@ -2298,14 +2323,21 @@ from the hole. +@@ -2298,14 +2323,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. -+* A 'D-' word is given in a block with both 'G96' and 'G76', where it could be -+ either the G96 spindle speed limit or the G76 infeed mode. * The 'R-' degression value is less than 1.0. * All the required words are not specified. * 'P-', 'J-', 'K-' or 'H-' is negative. @@ -156,40 +169,8 @@ index f8f9d01..950dc5c 100644 [NOTE] The spindle speed override is held for the whole G76 cycle at the value in -diff --git a/src/emc/rs274ngc/interp_check.cc b/src/emc/rs274ngc/interp_check.cc -index c65a3b2..50781c6 100644 ---- a/src/emc/rs274ngc/interp_check.cc -+++ b/src/emc/rs274ngc/interp_check.cc -@@ -262,9 +262,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) { -@@ -397,6 +397,15 @@ 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) { -+ // G96 reads D as its spindle speed limit; check this first so a limit -+ // such as D2000 is not reported as a bad infeed mode. -+ CHKS((block->g_modes[GM_SPINDLE_MODE] == G_96), -+ _("D cannot select both G76 infeed mode and G96 spindle limit in the same block")); -+ CHKS((block->d_number_float != 0.0 && block->d_number_float != 1.0), -+ _("In G76, D must be 0 or 1")); -+ } - } - - return INTERP_OK; diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 10bf98d..196d48c 100644 +index 10bf98d..7b19bf8 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -5984,6 +5984,152 @@ threading_pass(setup_pointer settings, block_pointer block, @@ -354,13 +335,12 @@ index 10bf98d..196d48c 100644 CHKS((block->i_number == 0), (_("In G76, I must not be 0"))); -@@ -6030,7 +6178,18 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6030,7 +6178,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), @@ -374,7 +354,7 @@ index 10bf98d..196d48c 100644 int spring_cuts = block->h_flag ? block->h_number: 0; -@@ -6042,7 +6201,8 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6042,7 +6200,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; @@ -384,7 +364,7 @@ index 10bf98d..196d48c 100644 int taper_flags = block->l_number; if(taper_flags < 0) taper_flags = 0; -@@ -6053,44 +6213,77 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6053,44 +6212,77 @@ int Interp::convert_threading_cycle(block_pointer block, double depth, zoff; int pass = 1; @@ -490,6 +470,54 @@ index 10bf98d..196d48c 100644 } restore_speed_override(settings); STRAIGHT_TRAVERSE(block->line_number, end_x, end_y, end_z, AABBCC); +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 @@ -514,7 +542,7 @@ index e834041..2fb074a 100644 setup_pointer settings); diff --git a/tests/g76-tapered-pitch/README b/tests/g76-tapered-pitch/README new file mode 100644 -index 0000000..7c9fb65 +index 0000000..ff9a863 --- /dev/null +++ b/tests/g76-tapered-pitch/README @@ -0,0 +1,34 @@ @@ -540,7 +568,7 @@ index 0000000..7c9fb65 + 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 D1 (the G96 ++ 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 = @@ -586,7 +614,7 @@ index 0000000..47884cf +setp spindle.0.at-speed true diff --git a/tests/g76-tapered-pitch/test-ui.py b/tests/g76-tapered-pitch/test-ui.py new file mode 100755 -index 0000000..b8107b9 +index 0000000..38ac4f5 --- /dev/null +++ b/tests/g76-tapered-pitch/test-ui.py @@ -0,0 +1,173 @@ @@ -691,8 +719,8 @@ index 0000000..b8107b9 + ["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 D1", -+ ["g8 g0 x10 z0", "g96 s100 d201 m3"], EXTERNAL + " d1", ++ ("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. @@ -847,30 +875,29 @@ index 0000000..411ae8c +linuxcnc -r test.ini diff --git a/tests/interp/g76-tapered/README b/tests/interp/g76-tapered/README new file mode 100644 -index 0000000..969bf22 +index 0000000..01ddc00 --- /dev/null +++ b/tests/interp/g76-tapered/README -@@ -0,0 +1,14 @@ +@@ -0,0 +1,13 @@ +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 ++passes. Compound-infeed coverage verifies fixed-direction G76 and ++alternating-flank G76.1 on tapered and cylindrical drive lines, plus centered Q0 +paths. 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, invalid D modes, and a same-block G96 D word whether it looks like an -+infeed mode (D1) or a spindle limit (D2000). ++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 tests/g76-tapered-pitch. diff --git a/tests/interp/g76-tapered/expected b/tests/interp/g76-tapered/expected new file mode 100644 -index 0000000..98bbf96 +index 0000000..6126bc2 --- /dev/null +++ b/tests/interp/g76-tapered/expected -@@ -0,0 +1,403 @@ +@@ -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) @@ -1226,6 +1253,27 @@ index 0000000..98bbf96 + 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) @@ -1274,49 +1322,27 @@ index 0000000..98bbf96 + 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 0000000..6eb002d ---- /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 +diff --git a/tests/interp/g76-tapered/invalid-both-modes.ngc b/tests/interp/g76-tapered/invalid-both-modes.ngc new file mode 100644 -index 0000000..87e8094 +index 0000000..110edb2 --- /dev/null -+++ b/tests/interp/g76-tapered/invalid-d2.ngc ++++ b/tests/interp/g76-tapered/invalid-both-modes.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 ++g76 g76.1 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 +m2 -diff --git a/tests/interp/g76-tapered/invalid-g96-d-limit.ngc b/tests/interp/g76-tapered/invalid-g96-d-limit.ngc +diff --git a/tests/interp/g76-tapered/invalid-d.ngc b/tests/interp/g76-tapered/invalid-d.ngc new file mode 100644 -index 0000000..5061982 +index 0000000..c6a6349 --- /dev/null -+++ b/tests/interp/g76-tapered/invalid-g96-d-limit.ngc -@@ -0,0 +1,5 @@ -+g21 g18 g8 -+s500 m3 -+g0 x10 z0 -+g96 s100 d2000 g76 p1.5 x8 z-20 i-1 j.2 k1 h0 q30 -+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 0000000..66e30e8 ---- /dev/null -+++ b/tests/interp/g76-tapered/invalid-g96-d.ngc ++++ b/tests/interp/g76-tapered/invalid-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 ++g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 d1 +m2 diff --git a/tests/interp/g76-tapered/invalid-y.ngc b/tests/interp/g76-tapered/invalid-y.ngc new file mode 100644 @@ -1342,10 +1368,10 @@ index 0000000..9384803 +m2 diff --git a/tests/interp/g76-tapered/test.ngc b/tests/interp/g76-tapered/test.ngc new file mode 100644 -index 0000000..fc3f9a5 +index 0000000..46d331b --- /dev/null +++ b/tests/interp/g76-tapered/test.ngc -@@ -0,0 +1,63 @@ +@@ -0,0 +1,67 @@ +(Test tapered G76 drive lines) + +g20 g18 g8 @@ -1389,19 +1415,23 @@ index 0000000..fc3f9a5 + +(fixed-direction compound infeed) +g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 d0 ++g76 p.1 x.8 z-1 i-.1 j.09 k.1 h0 q30 + +(alternating-flank compound infeed) +g0 x1 z0 -+g76 p.1 x.8 z-1 i-.1 j.03 k.1 r1 h2 q30 d1 ++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 p.1 z-1 i-.1 j.03 k.1 r1 h0 q0 d1 ++g76.1 p.1 z-1 i-.1 j.03 k.1 r1 h0 q0 + +(cylindrical alternating-flank compound infeed) +g0 x1 z0 -+g76 p.1 z-1 i-.1 j.03 k.1 r1 h1 q30 d1 ++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 @@ -1411,10 +1441,10 @@ index 0000000..fc3f9a5 +m2 diff --git a/tests/interp/g76-tapered/test.sh b/tests/interp/g76-tapered/test.sh new file mode 100644 -index 0000000..70f3986 +index 0000000..51b894c --- /dev/null +++ b/tests/interp/g76-tapered/test.sh -@@ -0,0 +1,31 @@ +@@ -0,0 +1,29 @@ +#!/bin/bash + +rs274 -g test.ngc | awk '{$1=""; print}' @@ -1425,10 +1455,8 @@ index 0000000..70f3986 + +# Each invalid program must be rejected with its own message. +declare -A expected_error=( -+ [invalid-d-fraction.ngc]="In G76, D must be 0 or 1" -+ [invalid-d2.ngc]="In G76, D must be 0 or 1" -+ [invalid-g96-d.ngc]="D cannot select both G76 infeed mode and G96 spindle limit in the same block" -+ [invalid-g96-d-limit.ngc]="D cannot select both G76 infeed mode and G96 spindle limit in the same block" ++ [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" +) 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 5bc7e30..8c8f50a 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -70,7 +70,7 @@ that adds in-flight stepping. create mode 100644 tests/resumable-stop/g76-tapered.ngc diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index 950dc5c..f13ec12 100644 +index 39cbf04..67dd545 100644 --- a/docs/src/gcode/g-code.adoc +++ b/docs/src/gcode/g-code.adoc @@ -2307,6 +2307,21 @@ pass, so a relief groove will be required at the entry unless the @@ -474,7 +474,7 @@ index 91d4b7b..109cf46 100644 void PALLET_SHUTTLE() {} 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 196d48c..e894e64 100644 +index 7b19bf8..0183299 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -5943,11 +5943,13 @@ threading_pass(setup_pointer settings, block_pointer block, @@ -546,7 +546,7 @@ index 196d48c..e894e64 100644 } int Interp::check_tapered_threading_pass(setup_pointer settings, -@@ -6273,9 +6283,13 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6272,9 +6282,13 @@ int Interp::convert_threading_cycle(block_pointer block, } } diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index a5865eb..5592078 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -462,10 +462,10 @@ index 8457e40..f7d7d47 100644 - - diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh -index 6f90dbe..ff5f379 100644 +index 210b4db..65197e8 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh -@@ -618,6 +618,9 @@ struct pycontext { +@@ -620,6 +620,9 @@ struct pycontext { pycontext(const struct pycontext &); pycontext &operator=(const struct pycontext &); ~pycontext(); diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 8765e89..e0759df 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -328,10 +328,11 @@ 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. 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: From 8b130a191b53edda073a3dc35ccb329b3419ca1a Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 09:06:55 +0100 Subject: [PATCH 31/45] docs: put RTAI and kernel-module realtime out of scope --- AGENTS.md | 5 +++-- README.md | 9 +++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index b38f415..887b1aa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -2,8 +2,9 @@ ## Project scope -- LinuxCNC's own GUIs and GUI tools, its older remote interfaces and tool - database programs are out of scope (see `README.md`). Do not +- 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. diff --git a/README.md b/README.md index 912d09a..01e8855 100644 --- a/README.md +++ b/README.md @@ -19,10 +19,11 @@ 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`) and tool -database programs (`[EMCIO]DB_PROGRAM`) are out of scope in the same way: -clients use this repository's gRPC APIs, and tool data lives in the file-backed -tool table. +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 From d56f6c00915d72f92b59b4eb01b795a959a94934 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 09:06:55 +0100 Subject: [PATCH 32/45] fix(linuxcnc): refuse an interpreter reset unless the machine is idle EMC_TASK_PLAN_INIT re-initialises the interpreter at once, whatever task is doing, so a reset during an MDI move, dwell, jog or queued work swapped the modes underneath it. New patch 0025 makes task refuse the reset with an operator error unless the interpreter, task, the MDI queue and motion are at rest. The check runs where task handles the command, so it covers every client with no race. Patch 0024 drops its own EMC_TASK_PLAN_INIT handling and keeps only the interrupted MDI cleanup on abort. 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. The live test checks that a reset during an MDI move is refused, keeps G91, and succeeds after Abort. --- ...te-whenever-the-interpreter-is-reset.patch | 323 ++------------- ...ter-reset-unless-the-machine-is-idle.patch | 386 ++++++++++++++++++ linuxcnc-patches/README.md | 54 ++- native/server/src/linuxcnc/nml_adapter.cc | 8 + native/server/tests/grpc_live_integration.cc | 2 + native/server/tests/grpc_live_support.cc | 71 ++++ native/server/tests/grpc_live_support.hpp | 3 + native/server/tests/native_edge_tests.cc | 15 + proto/linuxcnc/v1/machine.proto | 2 + 9 files changed, 565 insertions(+), 299 deletions(-) create mode 100644 linuxcnc-patches/0025-task-refuse-an-interpreter-reset-unless-the-machine-is-idle.patch 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 index f41bdcb..f3bc015 100644 --- 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 @@ -14,38 +14,35 @@ 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(). An -EMC_TASK_PLAN_INIT re-initializes the interpreter without any of it. 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. +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, and before -emcTaskPlanInit() for EMC_TASK_PLAN_INIT. The existing explicit calls next -to emcTaskAbort() are left as they are; a second call is a no-op. +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, interpreter re-init and a mode -change, and checks that milltask survives and MDI works afterwards. +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/nml_intf/interpl.cc | 14 ++ - src/emc/nml_intf/interpl.hh | 2 + src/emc/task/emctask.cc | 4 + - src/emc/task/emctaskmain.cc | 46 +++- + src/emc/task/emctaskmain.cc | 2 +- src/emc/task/task.hh | 1 + - tests/remap/mdi-remap-abort/README | 22 ++ + tests/remap/mdi-remap-abort/README | 18 +++ tests/remap/mdi-remap-abort/checkresult | 2 + tests/remap/mdi-remap-abort/m400.ngc | 5 + - tests/remap/mdi-remap-abort/remap.py | 9 + - tests/remap/mdi-remap-abort/test-ui.py | 290 ++++++++++++++++++++++++ - tests/remap/mdi-remap-abort/test.ini | 101 +++++++++ + tests/remap/mdi-remap-abort/remap.py | 9 ++ + tests/remap/mdi-remap-abort/test-ui.py | 161 ++++++++++++++++++++++++ + tests/remap/mdi-remap-abort/test.ini | 101 +++++++++++++++ tests/remap/mdi-remap-abort/test.sh | 2 + tests/remap/mdi-remap-abort/toplevel.py | 1 + - 13 files changed, 491 insertions(+), 8 deletions(-) + 11 files changed, 305 insertions(+), 1 deletion(-) create mode 100644 tests/remap/mdi-remap-abort/README create mode 100755 tests/remap/mdi-remap-abort/checkresult create mode 100644 tests/remap/mdi-remap-abort/m400.ngc @@ -55,44 +52,6 @@ change, and checks that milltask survives and MDI works afterwards. create mode 100755 tests/remap/mdi-remap-abort/test.sh create mode 100644 tests/remap/mdi-remap-abort/toplevel.py -diff --git a/src/emc/nml_intf/interpl.cc b/src/emc/nml_intf/interpl.cc -index 415f873..1c36637 100644 ---- a/src/emc/nml_intf/interpl.cc -+++ b/src/emc/nml_intf/interpl.cc -@@ -109,6 +109,20 @@ void NML_INTERP_LIST::clear() - pass_group = 0; - } - -+int NML_INTERP_LIST::remove_type(int type) -+{ -+ int removed = 0; -+ for (auto it = linked_list.begin(); it != linked_list.end();) { -+ if (it->command->_type == type) { -+ it = linked_list.erase(it); -+ removed++; -+ } else { -+ ++it; -+ } -+ } -+ return removed; -+} -+ - void NML_INTERP_LIST::print() - { - rcs_print("NML_INTERP_LIST::print(): list size=%lu\n", linked_list.size()); -diff --git a/src/emc/nml_intf/interpl.hh b/src/emc/nml_intf/interpl.hh -index 52c338e..86ae5ab 100644 ---- a/src/emc/nml_intf/interpl.hh -+++ b/src/emc/nml_intf/interpl.hh -@@ -42,6 +42,8 @@ public: - int append(std::unique_ptr&& command); - std::unique_ptr get(); - void clear(); -+ // removes every queued command of this type, returns how many -+ int remove_type(int type); - void print(); - int len(); - // the most recently appended command still on the list whose type is diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc index 5a1e60e..67edc9b 100644 --- a/src/emc/task/emctask.cc @@ -109,83 +68,18 @@ index 5a1e60e..67edc9b 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 9097f40..7176809 100644 +index 9097f40..65846a8 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -798,10 +798,18 @@ interpret_again: +@@ -798,7 +798,7 @@ interpret_again: } // if interp len is less than max } -static void mdi_execute_abort(void) -+static void mdi_execute_drop_queue(void) - { -- int queued_mdi_commands; -+ int queued_mdi_commands = mdi_execute_queue.len(); -+ if (queued_mdi_commands > 0) { -+ rcs_print("mdi_execute_abort: dropping %d queued MDI commands\n", queued_mdi_commands); -+ } -+ mdi_execute_queue.clear(); -+ emcStatus->task.queuedMDIcommands = 0; -+} - +void mdi_execute_abort(void) -+{ - // XXX: Reset needed? - if (mdi_execute_wait || mdi_execute_next) - emcTaskPlanReset(); -@@ -809,16 +817,22 @@ static void mdi_execute_abort(void) - mdi_execute_wait = 0; - mdi_execute_next = 0; - -- queued_mdi_commands = mdi_execute_queue.len(); -- if (queued_mdi_commands > 0) { -- rcs_print("mdi_execute_abort: dropping %d queued MDI commands\n", queued_mdi_commands); -- } -- mdi_execute_queue.clear(); -- emcStatus->task.queuedMDIcommands = 0; -+ mdi_execute_drop_queue(); - - emcStatus->task.interpState = EMC_TASK_INTERP::IDLE; - } - -+// Drop every MDI command the interpreter has not read yet: the queue, and -+// what mdi_execute_hook() already moved from it towards execution. -+static void mdi_execute_drop_unread(void) -+{ -+ mdi_execute_drop_queue(); -+ interp_list.remove_type(EMC_TASK_PLAN_EXECUTE_TYPE); -+ if (emcTaskCommand && emcTaskCommand->_type == EMC_TASK_PLAN_EXECUTE_TYPE) { -+ emcTaskCommand = NULL; -+ } -+} -+ - static void mdi_execute_hook(void) { - if (mdi_execute_wait && emcTaskPlanIsWait()) { -@@ -3196,7 +3210,23 @@ static int emcTaskIssueCommand(NMLmsg * cmd) - break; + int queued_mdi_commands; - case EMC_TASK_PLAN_INIT_TYPE: -+ // MDI commands not read yet were written for the modal state this -+ // discards, so they never run. -+ mdi_execute_drop_unread(); -+ // Re-initializing the interpreter drops any call an interrupted MDI -+ // command is still inside of. A command already read keeps running and -+ // keeps its interpreter state, including one that returned -+ // INTERP_EXECUTE_FINISH outside a call (G38.n, M66, M6, G28.2). -+ if (mdi_execute_next || mdi_execute_level >= 0) { -+ mdi_execute_abort(); -+ emcStatus->task.command[0] = 0; -+ } - retval = emcTaskPlanInit(); -+ // emcTaskPlanInit() clears the wait; mdi_execute_hook() needs it to see -+ // that command finish -+ if (mdi_execute_wait) { -+ emcTaskPlanSetWait(); -+ } - if (retval > INTERP_MIN_ERROR) { - retval = -1; - } diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh index 223886e..1a7a999 100644 --- a/src/emc/task/task.hh @@ -200,13 +94,13 @@ index 223886e..1a7a999 100644 int emcTaskSetState(EMC_TASK_STATE state); diff --git a/tests/remap/mdi-remap-abort/README b/tests/remap/mdi-remap-abort/README new file mode 100644 -index 0000000..cdb34f9 +index 0000000..03bb42d --- /dev/null +++ b/tests/remap/mdi-remap-abort/README -@@ -0,0 +1,22 @@ +@@ -0,0 +1,18 @@ +Interrupt an MDI command whose remap is mid-execution with an E-stop, a -+machine off, an interpreter re-init (EMC_TASK_PLAN_INIT) and a mode change -+to AUTO and back, instead of an operator abort, then bring the machine back ++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. @@ -218,14 +112,10 @@ index 0000000..cdb34f9 +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. Finally, an interpreter re-init during -+an ordinary MDI G1 move, with no interrupted call, must leave the move -+running and the interpreter state non-idle until the move ends. -+ -+Commands queued behind an ordinary move are dropped by the re-init too: they -+were written for the modal state it discards. M66 and G38.3 return -+INTERP_EXECUTE_FINISH without entering a call, so a re-init while they run -+leaves them active (not IDLE, still the current command) until they finish. ++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/tests/remap/mdi-remap-abort/checkresult b/tests/remap/mdi-remap-abort/checkresult new file mode 100755 index 0000000..24dc9aa @@ -262,16 +152,16 @@ index 0000000..b616b52 + yield INTERP_EXECUTE_FINISH diff --git a/tests/remap/mdi-remap-abort/test-ui.py b/tests/remap/mdi-remap-abort/test-ui.py new file mode 100755 -index 0000000..b6c86ff +index 0000000..3341617 --- /dev/null +++ b/tests/remap/mdi-remap-abort/test-ui.py -@@ -0,0 +1,290 @@ +@@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# +# Interrupt an MDI command whose remap is mid-execution in every way that -+# resets the interpreter without an operator abort (E-stop, machine off, -+# interpreter re-init, mode change), then bring the machine back and check -+# that task is still alive and MDI still works. ++# 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 @@ -345,17 +235,15 @@ index 0000000..b6c86ff + set_state(linuxcnc.STATE_ON) + + -+def plan_init(): -+ c.reset_interpreter() ++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() -+ -+ -+def plan_init_received(): -+ # for a command that keeps task busy: wait_complete() would wait it out ++ 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() -+ serial = c.serial -+ wait_for(lambda: s.echo_serial_number >= serial, -+ "interpreter re-init to be received") ++ c.wait_complete() + + +def mode_auto(): @@ -415,125 +303,6 @@ index 0000000..b6c86ff + print("%s: ok" % name, flush=True) + + -+def plain_move_reset(): -+ # Re-initializing the interpreter during an ordinary MDI move, with no -+ # interrupted call, leaves the move running and the MDI command active -+ # until the move ends. -+ set_mode(linuxcnc.MODE_MDI) -+ end = target[0] + 4.0 -+ c.mdi("G1 X%.1f F120" % end) -+ wait_for(lambda: s.current_vel > 0.0, "plain MDI move to start") -+ # task stays busy until the move ends, so do not wait for completion -+ c.reset_interpreter() -+ serial = c.serial -+ wait_for(lambda: s.echo_serial_number >= serial, -+ "interpreter re-init to be received") -+ if abs(s.position[0] - end) < 0.5: -+ fail("plain MDI move ended before the interpreter re-init") -+ start = time.time() -+ while abs(s.position[0] - end) > 1e-6: -+ if time.time() - start > 10.0: -+ fail("plain MDI move did not end after the interpreter re-init " -+ "(X=%.4f interp_state=%d)" % (s.position[0], s.interp_state)) -+ if s.interp_state == linuxcnc.INTERP_IDLE: -+ fail("interpreter re-init during a plain MDI move reported " -+ "IDLE while moving (X=%.4f)" % s.position[0]) -+ time.sleep(0.02) -+ s.poll() -+ wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE -+ and s.exec_state == linuxcnc.EXEC_DONE, -+ "plain MDI move to finish after interpreter re-init") -+ target[0] = end -+ check_mdi_works("plain move interpreter re-init") -+ print("plain move interpreter re-init: ok") -+ -+ -+def queued_reset(name, during_move): -+ # A command is queued only while task is busy with an earlier one; the -+ # block below keeps its move on the interp list behind the dwell. What is -+ # queued was written for the modal state the re-init discards (here G91), -+ # so none of it may run after the re-init. Once the move is issued the -+ # first queued command is already task's pending command. -+ set_mode(linuxcnc.MODE_MDI) -+ end = target[0] + 4.0 -+ c.mdi("G91") -+ c.wait_complete() -+ c.mdi("G4 P0.5 G1 X4 F120") -+ wait_for(lambda: s.exec_state == linuxcnc.EXEC_WAITING_FOR_DELAY, -+ "%s: dwell to start" % name) -+ c.mdi("G0 X1") -+ c.mdi("G0 X1") -+ wait_for(lambda: s.queued_mdi_commands == 2, -+ "%s: G0 X1 to be queued" % name) -+ if during_move: -+ wait_for(lambda: s.current_vel > 0.0 and s.queued_mdi_commands == 1, -+ "%s: move to start" % name) -+ plan_init_received() -+ s.poll() -+ if s.queued_mdi_commands != 0: -+ fail("%s: %d queued MDI commands survived" -+ % (name, s.queued_mdi_commands)) -+ start = time.time() -+ while abs(s.position[0] - end) > 1e-6: -+ if time.time() - start > 10.0: -+ fail("%s: move did not reach X%.1f (X=%.4f)" -+ % (name, end, s.position[0])) -+ if s.interp_state == linuxcnc.INTERP_IDLE: -+ fail("%s: IDLE while moving (X=%.4f)" % (name, s.position[0])) -+ time.sleep(0.02) -+ s.poll() -+ wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE -+ and s.exec_state == linuxcnc.EXEC_DONE, -+ "%s: move to finish" % name) -+ time.sleep(0.5) -+ s.poll() -+ if abs(s.position[0] - end) > 1e-6: -+ fail("%s: a dropped command ran (X=%.4f, expected %.4f)" -+ % (name, s.position[0], end)) -+ target[0] = end -+ check_mdi_works(name) -+ print("%s: ok" % name, flush=True) -+ -+ -+def execute_finish_reset(name, code, busy_for, end=None): -+ # These commands return INTERP_EXECUTE_FINISH without entering a call. A -+ # re-init leaves them running: still reported, not IDLE, and finished -+ # normally, with what was queued behind them dropped. -+ set_mode(linuxcnc.MODE_MDI) -+ c.mdi(code) -+ wait_for(lambda: s.interp_state != linuxcnc.INTERP_IDLE, -+ "%s: to start" % name) -+ time.sleep(0.2) -+ c.mdi("G0 X5") -+ wait_for(lambda: s.queued_mdi_commands == 1, -+ "%s: G0 X5 to be queued" % name) -+ plan_init_received() -+ s.poll() -+ if s.queued_mdi_commands != 0: -+ fail("%s: %d queued MDI commands survived" -+ % (name, s.queued_mdi_commands)) -+ start = time.time() -+ while time.time() - start < busy_for: -+ s.poll() -+ if s.interp_state == linuxcnc.INTERP_IDLE: -+ fail("%s: reported IDLE while running" % name) -+ if s.command != code: -+ fail("%s: active command is %r" % (name, s.command)) -+ time.sleep(0.02) -+ wait_for(lambda: s.interp_state == linuxcnc.INTERP_IDLE -+ and s.exec_state == linuxcnc.EXEC_DONE, -+ "%s: to finish" % name) -+ wait_for(lambda: s.command == "", "%s: active command to clear" % name) -+ if end is not None: -+ target[0] = end -+ time.sleep(0.3) -+ s.poll() -+ if abs(s.position[0] - target[0]) > 1e-6: -+ fail("%s: X=%.4f, expected %.4f" % (name, s.position[0], target[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) @@ -542,17 +311,9 @@ index 0000000..b6c86ff +for code in ("M400", "M401"): + scenario("%s E-stop" % code, code, estop) + scenario("%s machine off" % code, code, machine_off) -+ scenario("%s interpreter re-init" % code, code, plan_init) ++ scenario("%s abort and re-init" % code, code, abort_then_plan_init) + scenario("%s mode change" % code, code, mode_auto) + -+plain_move_reset() -+queued_reset("queue re-init during dwell", False) -+queued_reset("queue re-init during move", True) -+execute_finish_reset("M66 interpreter re-init", "M66 P0 L3 Q2", 0.8) -+probe_end = target[0] + 3.0 -+execute_finish_reset("G38.3 interpreter re-init", -+ "G38.3 X%.1f F120" % probe_end, 0.5, probe_end) -+ +print("all scenarios passed") +set_state(linuxcnc.STATE_ESTOP) +sys.exit(0) 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 0000000..2f770a5 --- /dev/null +++ b/linuxcnc-patches/0025-task-refuse-an-interpreter-reset-unless-the-machine-is-idle.patch @@ -0,0 +1,386 @@ +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 | 50 ++++++ + tests/task/interp-reset-requires-idle/README | 5 + + .../interp-reset-requires-idle/checkresult | 2 + + .../interp-reset-requires-idle/test-ui.py | 153 ++++++++++++++++++ + .../task/interp-reset-requires-idle/test.ini | 93 +++++++++++ + tests/task/interp-reset-requires-idle/test.sh | 2 + + 6 files changed, 305 insertions(+) + create mode 100644 tests/task/interp-reset-requires-idle/README + create mode 100755 tests/task/interp-reset-requires-idle/checkresult + create mode 100755 tests/task/interp-reset-requires-idle/test-ui.py + create mode 100644 tests/task/interp-reset-requires-idle/test.ini + create mode 100755 tests/task/interp-reset-requires-idle/test.sh + +diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc +index 65846a8..968fb84 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -1216,6 +1216,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() + +@@ -1273,6 +1312,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/tests/task/interp-reset-requires-idle/README b/tests/task/interp-reset-requires-idle/README +new file mode 100644 +index 0000000..ef58eb2 +--- /dev/null ++++ b/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/tests/task/interp-reset-requires-idle/checkresult b/tests/task/interp-reset-requires-idle/checkresult +new file mode 100755 +index 0000000..24dc9aa +--- /dev/null ++++ b/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/tests/task/interp-reset-requires-idle/test-ui.py b/tests/task/interp-reset-requires-idle/test-ui.py +new file mode 100755 +index 0000000..d4e6742 +--- /dev/null ++++ b/tests/task/interp-reset-requires-idle/test-ui.py +@@ -0,0 +1,153 @@ ++#!/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") ++ ++# 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") ++ ++print("all scenarios passed") ++set_state(linuxcnc.STATE_ESTOP) ++sys.exit(0) +diff --git a/tests/task/interp-reset-requires-idle/test.ini b/tests/task/interp-reset-requires-idle/test.ini +new file mode 100644 +index 0000000..8cff916 +--- /dev/null ++++ b/tests/task/interp-reset-requires-idle/test.ini +@@ -0,0 +1,93 @@ ++[EMC] ++VERSION = 1.1 ++DEBUG = 0 ++ ++[DISPLAY] ++DISPLAY = ./test-ui.py ++ ++[RS274NGC] ++PARAMETER_FILE = sim.var ++RS274NGC_STARTUP_CODE = G21 G90 ++ ++[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/tests/task/interp-reset-requires-idle/test.sh b/tests/task/interp-reset-requires-idle/test.sh +new file mode 100755 +index 0000000..a16f6fa +--- /dev/null ++++ b/tests/task/interp-reset-requires-idle/test.sh +@@ -0,0 +1,2 @@ ++#!/bin/bash ++exec linuxcnc -r test.ini diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index e0759df..4206b34 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -715,24 +715,42 @@ a failure while creating the parameters leaves a partially created thread. 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, a drop out of the ON state and an `EMC_TASK_PLAN_INIT` reset -or re-initialise 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, -and `EMC_TASK_PLAN_INIT` always drops MDI commands the interpreter has not read, -including one already moved towards execution, because they were written for -the modal state being discarded. It runs `mdi_execute_abort()` only when a call -is interrupted. A command already read keeps running and stays reported until it -ends, including one that returned `INTERP_EXECUTE_FINISH` outside a call -(`G38.n`, `M66`, `M6`, `G28.2`). `tests/remap/mdi-remap-abort` interrupts a waiting NGC and -Python remap with each of these, checks that an MDI command queued behind it -never runs and that MDI still works, and resets the interpreter during a plain -MDI move. The bug is present in plain -v2.10.0-pre2; the fix touches only upstream code paths. +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. +`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. + +`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. 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 diff --git a/native/server/src/linuxcnc/nml_adapter.cc b/native/server/src/linuxcnc/nml_adapter.cc index 3dc0f2e..18bfa68 100644 --- a/native/server/src/linuxcnc/nml_adapter.cc +++ b/native/server/src/linuxcnc/nml_adapter.cc @@ -582,6 +582,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: { diff --git a/native/server/tests/grpc_live_integration.cc b/native/server/tests/grpc_live_integration.cc index 2257a31..3d29575 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. diff --git a/native/server/tests/grpc_live_support.cc b/native/server/tests/grpc_live_support.cc index d942437..0fb6dab 100644 --- a/native/server/tests/grpc_live_support.cc +++ b/native/server/tests/grpc_live_support.cc @@ -626,6 +626,77 @@ void verify_task_queued_command_ordering( "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 4c12f02..1448280 100644 --- a/native/server/tests/grpc_live_support.hpp +++ b/native/server/tests/grpc_live_support.hpp @@ -51,6 +51,9 @@ void live_require(bool condition, const char* description); 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/native_edge_tests.cc b/native/server/tests/native_edge_tests.cc index a0e64cc..f6a4299 100644 --- a/native/server/tests/native_edge_tests.cc +++ b/native/server/tests/native_edge_tests.cc @@ -636,6 +636,20 @@ void queued_command_channel_failure_releases_hold_test() { "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; @@ -1333,6 +1347,7 @@ int main() { 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/proto/linuxcnc/v1/machine.proto b/proto/linuxcnc/v1/machine.proto index b41b60d..99c5703 100644 --- a/proto/linuxcnc/v1/machine.proto +++ b/proto/linuxcnc/v1/machine.proto @@ -497,6 +497,8 @@ message ExecuteCommandRequest { SetTaskMode set_task_mode = 2; 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; From 6cf3f1bb45470dfcca7ec63b9d5af874df3431ff Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 09:38:50 +0100 Subject: [PATCH 33/45] fix(native): cancel queued commands on abort, E-stop and machine off Abort, E-stop and machine off went ahead of a hold behind a task-queued tool edit or availability change, but left the held commands queued, so work requested before the abort still reached LinuxCNC after it. These three now use a new Interrupt priority. Under the same lock that queues them, the coordinator takes every normal command still waiting and answers it with "cancelled before reaching LinuxCNC". Commands submitted afterwards are kept; Pause and Stop keep queued work as before. A cancelled command never runs, but its cleanup does, so a queued Program Open still rolls back the program it staged. Unit tests cover held and unheld queues, Pause, later commands and the cleanup; the live test checks that Abort cancels an MDI command held behind a queued tool delete. --- .../linuxcnc_grpc/command_coordinator.hpp | 13 +- .../linuxcnc_grpc/linuxcnc/nml_adapter.hpp | 8 +- native/server/src/command_coordinator.cc | 76 +++++++----- native/server/src/linuxcnc/nml_adapter.cc | 8 +- native/server/tests/grpc_live_support.cc | 22 +++- native/server/tests/native_edge_tests.cc | 113 +++++++++++++++++- proto/linuxcnc/v1/machine.proto | 5 + 7 files changed, 207 insertions(+), 38 deletions(-) diff --git a/native/server/include/linuxcnc_grpc/command_coordinator.hpp b/native/server/include/linuxcnc_grpc/command_coordinator.hpp index edbdd54..a43e493 100644 --- a/native/server/include/linuxcnc_grpc/command_coordinator.hpp +++ b/native/server/include/linuxcnc_grpc/command_coordinator.hpp @@ -29,6 +29,9 @@ 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. @@ -77,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: @@ -139,7 +145,8 @@ class CommandCoordinator { CommandSubmission submit_with_context( ContextCommandAction action, const std::stop_token& stop_token, CommandPriority priority = CommandPriority::Normal, - CommandHoldPolicy hold_policy = CommandHoldPolicy::Wait); + 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(); @@ -152,9 +159,13 @@ class CommandCoordinator { 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); diff --git a/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp b/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp index b0048c5..7a65bbb 100644 --- a/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp +++ b/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp @@ -282,6 +282,8 @@ struct NmlCommandRouting { // 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. @@ -290,13 +292,15 @@ inline NmlCommandRouting nml_command_routing(const NmlCommand& command) { switch (command.kind) { case NmlCommandKind::StopProgram: case NmlCommandKind::Pause: - case NmlCommandKind::AbortTask: 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::Safety; + routing.priority = CommandPriority::Interrupt; break; case NmlCommandKind::Resume: case NmlCommandKind::Step: diff --git a/native/server/src/command_coordinator.cc b/native/server/src/command_coordinator.cc index cfc10f8..3a34f0f 100644 --- a/native/server/src/command_coordinator.cc +++ b/native/server/src/command_coordinator.cc @@ -75,20 +75,11 @@ 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, false}); - 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( @@ -99,29 +90,60 @@ CommandSubmission CommandCoordinator::submit_with_context( CommandSubmission CommandCoordinator::submit_with_context( ContextCommandAction action, const std::stop_token& stop_token, - CommandPriority priority, CommandHoldPolicy hold_policy) { + 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, - hold_policy == CommandHoldPolicy::Bypass}); - lock.unlock(); + 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() { diff --git a/native/server/src/linuxcnc/nml_adapter.cc b/native/server/src/linuxcnc/nml_adapter.cc index 18bfa68..853edf0 100644 --- a/native/server/src/linuxcnc/nml_adapter.cc +++ b/native/server/src/linuxcnc/nml_adapter.cc @@ -548,7 +548,10 @@ CommandSubmission NmlAdapter::submit( std::stop_token stop_token) { #ifdef LINUXCNC_GRPC_HAS_NML const auto routing = detail::nml_command_routing(command); - const bool safety_command = routing.priority == CommandPriority::Safety; + 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, routing](CommandContext& context) mutable { @@ -952,7 +955,8 @@ CommandSubmission NmlAdapter::submit( throw; } }, - stop_token, routing.priority, routing.hold_policy); + stop_token, routing.priority, routing.hold_policy, + std::move(on_cancelled)); #else (void)command; (void)stop_token; diff --git a/native/server/tests/grpc_live_support.cc b/native/server/tests/grpc_live_support.cc index 0fb6dab..7cf4158 100644 --- a/native/server/tests/grpc_live_support.cc +++ b/native/server/tests/grpc_live_support.cc @@ -552,10 +552,23 @@ void verify_task_queued_command_ordering( } // Abort passes the hold. It discards the queued delete, which must not be - // reported as done. + // 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(); @@ -568,6 +581,13 @@ void verify_task_queued_command_ordering( "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. diff --git a/native/server/tests/native_edge_tests.cc b/native/server/tests/native_edge_tests.cc index f6a4299..0557be0 100644 --- a/native/server/tests/native_edge_tests.cc +++ b/native/server/tests/native_edge_tests.cc @@ -412,6 +412,82 @@ void command_hold_shutdown_test() { 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; @@ -429,17 +505,20 @@ void nml_command_routing_test() { routing.hold_policy == CommandHoldPolicy::Wait, "task-queued commands wait for an earlier hold"); } - for (const auto kind : {NmlCommandKind::AbortTask, NmlCommandKind::Pause, - NmlCommandKind::StopProgram}) { + for (const auto kind : {NmlCommandKind::Pause, NmlCommandKind::StopProgram}) { const auto routing = routed(kind); - require(routing.priority == CommandPriority::Safety, "stops are safety"); + 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::Safety, - "E-stop and machine off are safety commands"); + CommandPriority::Interrupt, + "E-stop and machine off cancel queued work"); } for (const auto state : {2, 4}) { const auto routing = routed(NmlCommandKind::SetTaskState, state); @@ -575,6 +654,27 @@ void queued_command_superseded_by_safety_test() { (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); @@ -1339,10 +1439,13 @@ int main() { 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(); diff --git a/proto/linuxcnc/v1/machine.proto b/proto/linuxcnc/v1/machine.proto index 99c5703..c4d6763 100644 --- a/proto/linuxcnc/v1/machine.proto +++ b/proto/linuxcnc/v1/machine.proto @@ -495,6 +495,8 @@ 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 @@ -509,6 +511,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; From f7c6243b8773c0bf801c0fd8b6ddcb227dbc65ba Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 09:38:50 +0100 Subject: [PATCH 34/45] fix(linuxcnc): keep mirrored G76.1 passes within the programmed Z With alternating infeed, every second roughing pass is mirrored about the final thread line, so its compound offset lies beyond the final one. The pass shifted its end by that offset too and fed past the programmed Z: g76.1 p.1 z-1 i-.1 j.03 k.1 r1 h1 q30 reached Z-1.0231. A mirrored pass in patch 0008 now keeps its offset at the start, which puts it on the other flank, and ends where the final pass ends, on cylindrical and tapered drive lines. The g76-tapered test checks that no G76.1 feed leaves the programmed Z range in either direction, with exit taper, boring and a tapered drive line. --- .../0008-tapered-g76-drive-lines.patch | 177 ++++++++++++++---- ...reading-stop-clear-and-pass-stepping.patch | 26 +-- ...0-rs274-support-native-gcode-preview.patch | 2 +- .../0018-availability-mcodes.patch | 2 +- linuxcnc-patches/README.md | 4 +- 5 files changed, 161 insertions(+), 50 deletions(-) diff --git a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch index cd1f61e..e8a0369 100644 --- a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch +++ b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch @@ -16,8 +16,8 @@ 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 | 53 ++- - src/emc/rs274ngc/interp_convert.cc | 252 +++++++++-- + 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 + @@ -28,15 +28,16 @@ tests/g76-tapered-pitch exercises the check on a simulated lathe. tests/g76-tapered-pitch/test-ui.py | 173 +++++++ tests/g76-tapered-pitch/test.ini | 67 +++ tests/g76-tapered-pitch/test.sh | 3 + - tests/interp/g76-tapered/README | 13 + + tests/interp/g76-tapered/README | 14 + + .../g76-tapered/alternating-z-range.ngc | 31 ++ tests/interp/g76-tapered/expected | 424 ++++++++++++++++++ .../interp/g76-tapered/invalid-both-modes.ngc | 5 + tests/interp/g76-tapered/invalid-d.ngc | 5 + tests/interp/g76-tapered/invalid-y.ngc | 5 + tests/interp/g76-tapered/invalid-zero-z.ngc | 5 + tests/interp/g76-tapered/test.ngc | 67 +++ - tests/interp/g76-tapered/test.sh | 29 ++ - 20 files changed, 1125 insertions(+), 42 deletions(-) + tests/interp/g76-tapered/test.sh | 54 +++ + 21 files changed, 1200 insertions(+), 47 deletions(-) create mode 100644 tests/g76-tapered-pitch/README create mode 100755 tests/g76-tapered-pitch/checkresult create mode 100644 tests/g76-tapered-pitch/core_sim.hal @@ -44,6 +45,7 @@ tests/g76-tapered-pitch exercises the check on a simulated lathe. create mode 100644 tests/g76-tapered-pitch/test.ini create mode 100755 tests/g76-tapered-pitch/test.sh create mode 100644 tests/interp/g76-tapered/README + create mode 100644 tests/interp/g76-tapered/alternating-z-range.ngc create mode 100644 tests/interp/g76-tapered/expected create mode 100644 tests/interp/g76-tapered/invalid-both-modes.ngc create mode 100644 tests/interp/g76-tapered/invalid-d.ngc @@ -53,7 +55,7 @@ tests/g76-tapered-pitch exercises the check on a simulated lathe. create mode 100644 tests/interp/g76-tapered/test.sh diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index f8f9d01..39cbf04 100644 +index f8f9d01..6f196b6 100644 --- a/docs/src/gcode/g-code.adoc +++ b/docs/src/gcode/g-code.adoc @@ -98,7 +98,7 @@ as the 'L number', and so on for any other letter. @@ -113,7 +115,7 @@ index f8f9d01..39cbf04 100644 [NOTE] When G7 'Lathe Diameter Mode' is in force the values for 'I', 'J' and 'K' are diameter measurements. -@@ -2254,11 +2268,20 @@ 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. @@ -128,14 +130,16 @@ index f8f9d01..39cbf04 100644 +'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. The full-depth ++'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 +2297,10 @@ Thread entries and exits can be programmed tapered with the 'E' and 'L' values. +@@ -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 @@ -148,7 +152,7 @@ index f8f9d01..39cbf04 100644 The tool will pause briefly for synchronization before each threading pass, so a relief groove will be required at the entry unless the -@@ -2298,14 +2323,18 @@ from the hole. +@@ -2298,14 +2325,18 @@ from the hole. It is an error if: * The active plane is not the ZX plane. @@ -170,10 +174,42 @@ index f8f9d01..39cbf04 100644 [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 10bf98d..7b19bf8 100644 +index 10bf98d..560748a 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -5984,6 +5984,152 @@ threading_pass(setup_pointer settings, block_pointer block, +@@ -5940,7 +5940,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? +@@ -5966,24 +5967,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(); } @@ -196,7 +232,8 @@ index 10bf98d..7b19bf8 100644 +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 full_compound_offset, ++ 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 = {}; @@ -211,9 +248,9 @@ index 10bf98d..7b19bf8 100644 + const double pass_start_x = start_x + drive_x * 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); ++ (end_compound_offset - full_compound_offset); + g.pass_end_z = end_z + drive_z * -+ (compound_offset - full_compound_offset); ++ (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; @@ -326,7 +363,7 @@ index 10bf98d..7b19bf8 100644 int Interp::convert_threading_cycle(block_pointer block, setup_pointer settings, double end_x, double end_y, double end_z) { -@@ -5991,6 +6137,8 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -5991,6 +6139,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"))); @@ -335,7 +372,7 @@ index 10bf98d..7b19bf8 100644 CHKS((block->i_number == 0), (_("In G76, I must not be 0"))); -@@ -6030,7 +6178,17 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6030,7 +6180,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; @@ -354,7 +391,7 @@ index 10bf98d..7b19bf8 100644 int spring_cuts = block->h_flag ? block->h_number: 0; -@@ -6042,7 +6200,8 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6042,7 +6202,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; @@ -364,7 +401,7 @@ index 10bf98d..7b19bf8 100644 int taper_flags = block->l_number; if(taper_flags < 0) taper_flags = 0; -@@ -6053,44 +6212,77 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6053,44 +6214,86 @@ int Interp::convert_threading_cycle(block_pointer block, double depth, zoff; int pass = 1; @@ -392,8 +429,17 @@ index 10bf98d..7b19bf8 100644 - 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; ++ 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; @@ -409,7 +455,7 @@ index 10bf98d..7b19bf8 100644 + // passes always use the same centered final path. + if(alternating_infeed && !(pass & 1)) + zoff = 2.0 * full_compound_offset - zoff; -+ passes.push_back({depth, zoff}); ++ 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; @@ -425,14 +471,14 @@ index 10bf98d..7b19bf8 100644 - start_z, zoff, taper_dist, entry_taper, exit_taper, - taper_pitch, pitch, full_threadheight, target_z); + 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, full_compound_offset, ++ 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())); @@ -464,7 +510,7 @@ index 10bf98d..7b19bf8 100644 + } else { + threading_pass(settings, block, boring, safe_x, passes[i].depth, + end_depth, start_y, start_z, passes[i].zoff, -+ taper_dist, entry_taper, exit_taper, taper_pitch, ++ passes[i].end_zoff, taper_dist, entry_taper, exit_taper, taper_pitch, + pitch, full_threadheight, target_z); + } } @@ -875,26 +921,64 @@ index 0000000..411ae8c +linuxcnc -r test.ini diff --git a/tests/interp/g76-tapered/README b/tests/interp/g76-tapered/README new file mode 100644 -index 0000000..01ddc00 +index 0000000..14964ef --- /dev/null +++ b/tests/interp/g76-tapered/README -@@ -0,0 +1,13 @@ +@@ -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. Every cycle runs inside the spindle override hold (LOCK_SPEED_OVERRIDE ++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 tests/g76-tapered-pitch. +diff --git a/tests/interp/g76-tapered/alternating-z-range.ngc b/tests/interp/g76-tapered/alternating-z-range.ngc +new file mode 100644 +index 0000000..979eccd +--- /dev/null ++++ b/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/tests/interp/g76-tapered/expected b/tests/interp/g76-tapered/expected new file mode 100644 -index 0000000..6126bc2 +index 0000000..ab05650 --- /dev/null +++ b/tests/interp/g76-tapered/expected @@ -0,0 +1,424 @@ @@ -1133,9 +1217,9 @@ index 0000000..6126bc2 + 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..... STRAIGHT_FEED(0.6400, 0.0000, -1.0000, 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..... 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) @@ -1223,9 +1307,9 @@ index 0000000..6126bc2 + 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..... 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.0231, 0.0000, 0.0000, 0.0000) ++ 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) @@ -1441,10 +1525,10 @@ index 0000000..46d331b +m2 diff --git a/tests/interp/g76-tapered/test.sh b/tests/interp/g76-tapered/test.sh new file mode 100644 -index 0000000..51b894c +index 0000000..73b58bc --- /dev/null +++ b/tests/interp/g76-tapered/test.sh -@@ -0,0 +1,29 @@ +@@ -0,0 +1,54 @@ +#!/bin/bash + +rs274 -g test.ngc | awk '{$1=""; print}' @@ -1453,6 +1537,31 @@ index 0000000..51b894c + 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" 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 8c8f50a..7c14faa 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -70,10 +70,10 @@ that adds in-flight stepping. create mode 100644 tests/resumable-stop/g76-tapered.ngc diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc -index 39cbf04..67dd545 100644 +index 6f196b6..3b3d18c 100644 --- a/docs/src/gcode/g-code.adoc +++ b/docs/src/gcode/g-code.adoc -@@ -2307,6 +2307,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. @@ -474,11 +474,11 @@ index 91d4b7b..109cf46 100644 void PALLET_SHUTTLE() {} 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 7b19bf8..0183299 100644 +index 560748a..47f2509 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -5943,11 +5943,13 @@ threading_pass(setup_pointer settings, block_pointer block, - double start_y, double start_z, double zoff, double taper_dist, +@@ -5944,11 +5944,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) { + FINISH_G76_APPROACH(); @@ -491,7 +491,7 @@ index 7b19bf8..0183299 100644 DISABLE_FEED_OVERRIDE(); START_SPEED_FEED_SYNCH(settings->active_spindle, taper_pitch, 0); STRAIGHT_FEED(block->line_number, boring? -@@ -5958,6 +5960,7 @@ threading_pass(setup_pointer settings, block_pointer block, +@@ -5959,6 +5961,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 { @@ -499,21 +499,21 @@ index 7b19bf8..0183299 100644 STRAIGHT_TRAVERSE(block->line_number, boring? safe_x + depth: safe_x - depth, start_y, start_z - zoff, AABBCC); //in DISABLE_FEED_OVERRIDE(); -@@ -5977,11 +5980,13 @@ threading_pass(setup_pointer settings, block_pointer block, - start_y, target_z - zoff, AABBCC); //over +@@ -5978,11 +5981,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); } // Geometry of one threading pass along a tapered XZ drive line. X coordinates -@@ -6054,10 +6059,12 @@ tapered_pass(int boring, double start_x, double start_z, +@@ -6056,10 +6061,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) { @@ -526,7 +526,7 @@ index 7b19bf8..0183299 100644 DISABLE_FEED_OVERRIDE(); START_SPEED_FEED_SYNCH(settings->active_spindle, g.entry_pitch, 0); STRAIGHT_FEED(block->line_number, g.crest_start_x, -@@ -6066,6 +6073,7 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, +@@ -6068,6 +6075,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 { @@ -534,7 +534,7 @@ index 7b19bf8..0183299 100644 STRAIGHT_TRAVERSE(block->line_number, g.cut_start_x, start_y, g.pass_start_z, AABBCC); // in DISABLE_FEED_OVERRIDE(); -@@ -6083,9 +6091,11 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, +@@ -6085,9 +6093,11 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, start_y, g.pass_end_z, AABBCC); // over } STOP_SPEED_FEED_SYNCH(); @@ -546,7 +546,7 @@ index 7b19bf8..0183299 100644 } int Interp::check_tapered_threading_pass(setup_pointer settings, -@@ -6272,9 +6282,13 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6283,9 +6293,13 @@ int Interp::convert_threading_cycle(block_pointer block, } } diff --git a/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch b/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch index b6d9dfe..eeb55a2 100644 --- a/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch +++ b/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch @@ -24,7 +24,7 @@ keeps upstream's record of the mapping descriptor (8c8e048). 11 files changed, 160 insertions(+) diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 0183299..3c676b6 100644 +index 47f2509..a02c025 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -2528,6 +2528,7 @@ Called by: convert_cutter_compensation diff --git a/linuxcnc-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index e0cf38c..f066a68 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -316,7 +316,7 @@ index c65a3b2..219a007 100644 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 3c676b6..624903f 100644 +index a02c025..cb7f482 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -4443,6 +4443,17 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 4206b34..731dfe3 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -330,7 +330,9 @@ 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.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. Status reports it as `G76`. `D` is +`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. From 3ce05fd6bd9a5af50b9e3f848294c3a9e9bd364d Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 11:49:44 +0100 Subject: [PATCH 35/45] fix(native): give the G-code preview the configured axes The preview recording canon told the interpreter that only X, Y and Z exist, so it rejected any A, B, C, U, V or W word ("Bad character 'a' used") and machines with a rotary or UVW axis got no preview. The preview now builds the axis mask from [TRAJ]COORDINATES the way task does: every XYZABCUVW letter, in any case, with X, Y and Z when the key is missing. The parser integration test previews G0 X1 A90 U2 on an X Y Z A U configuration and checks that the plain X Y Z configuration still refuses the A word. --- native/server/src/gcode/parser.cc | 22 +++++++++++ native/server/src/gcode/recording_canon.cc | 4 +- native/server/src/gcode/recording_canon.hpp | 3 ++ native/server/tests/fixtures/rotary_axis.ngc | 3 ++ .../server/tests/gcode_parser_integration.cc | 38 ++++++++++++++++++- .../tests/run_gcode_parser_integration.sh | 8 +++- 6 files changed, 74 insertions(+), 4 deletions(-) create mode 100644 native/server/tests/fixtures/rotary_axis.ngc diff --git a/native/server/src/gcode/parser.cc b/native/server/src/gcode/parser.cc index 24c263a..bc62791 100644 --- a/native/server/src/gcode/parser.cc +++ b/native/server/src/gcode/parser.cc @@ -6,7 +6,10 @@ #include #include #include +#include #include +#include +#include #include "interp_base.hh" #include "interp_return.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 index c3d320a..f70f251 100644 --- a/native/server/src/gcode/recording_canon.cc +++ b/native/server/src/gcode/recording_canon.cc @@ -22,6 +22,7 @@ struct Session::Impl { 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; @@ -174,6 +175,7 @@ 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; @@ -594,7 +596,7 @@ 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 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; diff --git a/native/server/src/gcode/recording_canon.hpp b/native/server/src/gcode/recording_canon.hpp index a58a76b..6d50b89 100644 --- a/native/server/src/gcode/recording_canon.hpp +++ b/native/server/src/gcode/recording_canon.hpp @@ -13,6 +13,9 @@ 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; diff --git a/native/server/tests/fixtures/rotary_axis.ngc b/native/server/tests/fixtures/rotary_axis.ngc new file mode 100644 index 0000000..a5cbd8d --- /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 3e3072d..0e5edf0 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/run_gcode_parser_integration.sh b/native/server/tests/run_gcode_parser_integration.sh index 2c26f58..561b4d6 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" From 14e3abf1560bfe605921036bb0a18aa25292f213 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 11:49:44 +0100 Subject: [PATCH 36/45] test(linuxcnc): give resumable-stop programs time to finish on slow runners On a loaded CI runner the simulated machine runs slower than real time, and a resumed tapered G76 program was still running when the fixed 15 s completion wait ran out. Raise the default wait to 60 s; a passing run never waits longer than the program takes. --- linuxcnc-patches/0004-resumable-stop.patch | 12 +++++++----- ...09-threading-stop-clear-and-pass-stepping.patch | 10 +++++----- ...n-arm-single-step-during-active-execution.patch | 14 +++++++------- 3 files changed, 19 insertions(+), 17 deletions(-) diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 70907d5..6466276 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -73,7 +73,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/speed-change.ngc | 9 + tests/resumable-stop/spindle-state.ngc | 10 + tests/resumable-stop/tap.ngc | 7 + - tests/resumable-stop/test-ui.py | 1492 +++++++++++++++++ + tests/resumable-stop/test-ui.py | 1494 +++++++++++++++++ tests/resumable-stop/test.ini | 98 ++ tests/resumable-stop/test.ngc | 9 + tests/resumable-stop/thread-chain.ngc | 8 + @@ -84,7 +84,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: tests/resumable-stop/threading/scenarios | 8 + tests/resumable-stop/threading/test.sh | 3 + tests/resumable-stop/tool.tbl | 1 + - 64 files changed, 2828 insertions(+), 25 deletions(-) + 64 files changed, 2830 insertions(+), 25 deletions(-) create mode 100644 tests/resumable-stop/README create mode 100644 tests/resumable-stop/after-abort.ngc create mode 100644 tests/resumable-stop/after-tap-m5.ngc @@ -2249,10 +2249,10 @@ index 0000000..3060ac4 +M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py new file mode 100755 -index 0000000..0b39992 +index 0000000..4cf91ee --- /dev/null +++ b/tests/resumable-stop/test-ui.py -@@ -0,0 +1,1492 @@ +@@ -0,0 +1,1494 @@ +#!/usr/bin/env python3 + +import math @@ -2307,7 +2307,9 @@ index 0000000..0b39992 + wait_complete("%s did not open" % path) + + -+def wait_for_program_complete(expected_x, expected_z=0.0, timeout=15.0): ++# 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 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 7c14faa..d5f3219 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -1542,7 +1542,7 @@ index c756dd3..f572282 100755 mapfile -t items < <(grep -v '^[[:space:]]*\(#\|$\)' "$1") [ ${#items[@]} -gt 0 ] || { echo "run-scenarios.sh: no scenarios in $1" >&2; exit 1; } diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index 0b39992..d29f03f 100755 +index 4cf91ee..83dfcc5 100755 --- a/tests/resumable-stop/test-ui.py +++ b/tests/resumable-stop/test-ui.py @@ -2,6 +2,7 @@ @@ -1589,7 +1589,7 @@ index 0b39992..d29f03f 100755 def wait_complete(message, timeout=10.0): -@@ -478,6 +497,41 @@ def run_threading_stop_resume_test(): +@@ -480,6 +499,41 @@ def run_threading_stop_resume_test(): ) @@ -1631,7 +1631,7 @@ index 0b39992..d29f03f 100755 def run_fperrev_stop_resume_test(): open_auto_program("fperrev.ngc") c.auto(linuxcnc.AUTO_RUN, 0) -@@ -542,9 +596,9 @@ def run_g76_stop_resume_test(): +@@ -544,9 +598,9 @@ def run_g76_stop_resume_test(): if s.position[2] > -4.90: fail("G76 stopped before its active threading TC completed") @@ -1643,7 +1643,7 @@ index 0b39992..d29f03f 100755 % s.position[0] ) -@@ -563,6 +617,264 @@ def run_g76_stop_resume_test(): +@@ -565,6 +619,264 @@ def run_g76_stop_resume_test(): assert_outputs_stopped_after_program() @@ -1908,7 +1908,7 @@ index 0b39992..d29f03f 100755 def run_queued_threading_stop_resume_test(): hal.set_p("spindle.0.at-speed", "false") open_auto_program("thread.ngc") -@@ -1463,8 +1775,16 @@ SCENARIOS = { +@@ -1465,8 +1777,16 @@ SCENARIOS = { "abort-empty": run_abort_from_empty_stopped_queue_test, "queued-g33": run_queued_threading_stop_resume_test, "g33": run_threading_stop_resume_test, 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 c3ebbcd..4758657 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 @@ -640,10 +640,10 @@ index 3060ac4..2182f18 100644 M5 M2 diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index d29f03f..9d8a771 100755 +index 83dfcc5..ec9e072 100755 --- a/tests/resumable-stop/test-ui.py +++ b/tests/resumable-stop/test-ui.py -@@ -261,6 +261,74 @@ def run_stop_single_step_test(): +@@ -263,6 +263,74 @@ def run_stop_single_step_test(): wait_for_program_complete(20.0) assert_outputs_stopped_after_program() @@ -718,7 +718,7 @@ index d29f03f..9d8a771 100755 def run_rapid_resume_without_at_speed_test(): hal.set_p("spindle.0.at-speed", "false") -@@ -790,6 +858,48 @@ def run_tapered_g76_single_step_test(): +@@ -792,6 +860,48 @@ def run_tapered_g76_single_step_test(): "tapered-drive G76", ) @@ -767,7 +767,7 @@ index d29f03f..9d8a771 100755 def run_g76_exit_taper_stop_test(program, expected_clear_x, label): open_auto_program(program) -@@ -1286,6 +1396,124 @@ def run_resume_atspeed_wait_test(): +@@ -1288,6 +1398,124 @@ def run_resume_atspeed_wait_test(): fail("Abort while waiting: the feed moved") @@ -892,7 +892,7 @@ index d29f03f..9d8a771 100755 def run_multi_spindle_stop_resume_test(): open_auto_program("multi-spindle.ngc") c.spindle(linuxcnc.SPINDLE_FORWARD, 120.0, 0) -@@ -1769,6 +1997,7 @@ SCENARIOS = { +@@ -1771,6 +1999,7 @@ SCENARIOS = { "idle-rejected": run_idle_program_stop_rejected_test, "ordinary": run_ordinary_stop_resume_test, "single-step": run_stop_single_step_test, @@ -900,7 +900,7 @@ index d29f03f..9d8a771 100755 "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), -@@ -1782,6 +2011,7 @@ SCENARIOS = { +@@ -1784,6 +2013,7 @@ SCENARIOS = { "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, @@ -908,7 +908,7 @@ index d29f03f..9d8a771 100755 "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, -@@ -1791,6 +2021,13 @@ SCENARIOS = { +@@ -1793,6 +2023,13 @@ SCENARIOS = { "dwell-atspeed": run_dwell_atspeed_barrier_test, "command-after-sync": run_command_after_sync_motion_test, "resume-atspeed": run_resume_atspeed_wait_test, From 186208e284264551b7733d8d6f0d16a71bee6c26 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 14:02:00 +0100 Subject: [PATCH 37/45] test(linuxcnc): move the patches' new tests into linuxcnc-tests/ The 301 test files the patches added to LinuxCNC's tests/ now live in linuxcnc-tests/, with the same layout, and run out of tree with `scripts/runtests tests /linuxcnc-tests`. The patches keep only their changes to upstream tests and the skip file for the DB_PROGRAM test, which shrinks them by about 13,000 lines. Tests that reached the LinuxCNC tree through relative paths now use $EMC2_HOME; remap/executor generates its INI from a template for that. CI runs both sets and triggers on linuxcnc-tests/ changes. --- .github/workflows/linuxcnc-patches.yml | 21 +- linuxcnc-patches/0004-resumable-stop.patch | 2424 +---------------- ...dered-realtime-component-search-path.patch | 154 +- .../0007-native-automatic-tool-wear.patch | 1889 +------------ .../0008-tapered-g76-drive-lines.patch | 1041 +------ ...reading-stop-clear-and-pass-stepping.patch | 652 +---- ...-single-step-during-active-execution.patch | 597 +--- ...-own-transactional-tool-CRUD-in-task.patch | 904 +----- ...4ngc-add-composable-executor-stdglue.patch | 405 +-- ...-publish-modal-CSS-maximum-in-status.patch | 203 +- ...ngc-pass-spindle-selectors-to-remaps.patch | 165 +- ...0016-motion-joint-target-preparation.patch | 135 +- ...ntime-joint-and-spindle-availability.patch | 1776 +----------- .../0018-availability-mcodes.patch | 1004 +------ ...w-concurrent-individual-joint-homing.patch | 485 +--- ...otion-add-native-lathe-power-jogging.patch | 380 +-- ...-cross-compiling-external-components.patch | 222 +- ...pose-native-thread-period-statistics.patch | 221 +- ...te-whenever-the-interpreter-is-reset.patch | 371 +-- ...ter-reset-unless-the-machine-is-idle.patch | 299 +- linuxcnc-patches/README.md | 39 +- linuxcnc-tests/.gitignore | 7 + .../.gitignore | 2 + .../availability-mcodes-regressions/README | 9 + .../checkresult | 5 + .../availability-mcodes-regressions/step.ngc | 6 + .../test-ui.py | 74 + .../test.ini.in | 9 + .../availability-mcodes-regressions/test.sh | 6 + linuxcnc-tests/availability-mcodes/.gitignore | 2 + linuxcnc-tests/availability-mcodes/README | 12 + .../availability-mcodes/checkresult | 4 + .../availability-mcodes/core_sim.hal | 1 + linuxcnc-tests/availability-mcodes/homing.ngc | 4 + .../availability-mcodes/no-force.ini.in | 6 + .../availability-mcodes/ordered.ngc | 6 + linuxcnc-tests/availability-mcodes/test-ui.py | 205 ++ .../availability-mcodes/test.ini.in | 3 + linuxcnc-tests/availability-mcodes/test.sh | 5 + .../availability-mcodes/timeout.ngc | 4 + linuxcnc-tests/availability-mcodes/tool.tbl | 1 + .../availability-mcodes/unhomed.ngc | 4 + linuxcnc-tests/css-status/README | 6 + linuxcnc-tests/css-status/checkresult | 4 + linuxcnc-tests/css-status/core_sim.hal | 10 + linuxcnc-tests/css-status/test-ui.py | 61 + linuxcnc-tests/css-status/test.ini | 55 + linuxcnc-tests/css-status/test.sh | 4 + linuxcnc-tests/css-status/tool.tbl | 0 linuxcnc-tests/g76-tapered-pitch/README | 34 + linuxcnc-tests/g76-tapered-pitch/checkresult | 2 + linuxcnc-tests/g76-tapered-pitch/core_sim.hal | 18 + linuxcnc-tests/g76-tapered-pitch/test-ui.py | 173 ++ linuxcnc-tests/g76-tapered-pitch/test.ini | 67 + linuxcnc-tests/g76-tapered-pitch/test.sh | 3 + .../halcompile/cross-tools/.gitignore | 2 + .../halcompile/cross-tools/checkresult | 4 + .../halcompile/cross-tools/cross_tools.comp | 6 + linuxcnc-tests/halcompile/cross-tools/test.sh | 170 ++ linuxcnc-tests/homing-concurrent/checkresult | 3 + linuxcnc-tests/homing-concurrent/homing.hal | 16 + linuxcnc-tests/homing-concurrent/test-ui.py | 235 ++ linuxcnc-tests/homing-concurrent/test.ini | 170 ++ linuxcnc-tests/homing-concurrent/test.sh | 4 + linuxcnc-tests/homing-concurrent/tool.tbl | 0 .../interp/availability-mcodes/README | 6 + .../interp/availability-mcodes/bad-joint.ngc | 2 + .../availability-mcodes/double-selector.ngc | 2 + .../availability-mcodes/execute-status.cc | 29 + .../availability-mcodes/execute-status.py | 30 + .../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 + .../interp/availability-mcodes/legacy54.ngc | 5 + .../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 + .../interp/availability-mcodes/remap.ini | 5 + .../interp/availability-mcodes/remapped.ngc | 3 + .../interp/availability-mcodes/test.ini | 2 + .../interp/availability-mcodes/test.sh | 80 + .../availability-mcodes/valid-joint.ngc | 3 + .../availability-mcodes/valid-spindle.ngc | 3 + .../interp/g28.2/instant-home/README | 7 + .../interp/g28.2/instant-home/checkresult | 2 + .../interp/g28.2/instant-home/sim.tbl | 0 .../interp/g28.2/instant-home/test-ui.py | 80 + .../interp/g28.2/instant-home/test.ini | 103 + .../interp/g28.2/instant-home/test.sh | 2 + linuxcnc-tests/interp/g76-tapered/README | 14 + .../g76-tapered/alternating-z-range.ngc | 31 + linuxcnc-tests/interp/g76-tapered/expected | 424 +++ .../interp/g76-tapered/invalid-both-modes.ngc | 5 + .../interp/g76-tapered/invalid-d.ngc | 5 + .../interp/g76-tapered/invalid-y.ngc | 5 + .../interp/g76-tapered/invalid-zero-z.ngc | 5 + linuxcnc-tests/interp/g76-tapered/test.ngc | 67 + linuxcnc-tests/interp/g76-tapered/test.sh | 54 + .../interp/tool-line-length/expected | 23 + .../interp/tool-line-length/missing-t2.ngc | 3 + .../interp/tool-line-length/missing-t3.ngc | 3 + .../interp/tool-line-length/missing-t4.ngc | 3 + .../interp/tool-line-length/test.ngc | 12 + .../interp/tool-line-length/test.sh | 17 + .../interp/tool-line-length/test.tbl | 5 + linuxcnc-tests/interp/tool-wear/expected | 69 + linuxcnc-tests/interp/tool-wear/invalid-i.ngc | 3 + linuxcnc-tests/interp/tool-wear/invalid-j.ngc | 3 + .../interp/tool-wear/invalid-m61-comp.ngc | 5 + .../interp/tool-wear/invalid-missing-tool.ngc | 3 + linuxcnc-tests/interp/tool-wear/invalid-q.ngc | 3 + linuxcnc-tests/interp/tool-wear/invalid-r.ngc | 3 + .../interp/tool-wear/invalid-zero-tool.ngc | 3 + linuxcnc-tests/interp/tool-wear/test.ngc | 46 + linuxcnc-tests/interp/tool-wear/test.sh | 27 + linuxcnc-tests/interp/tool-wear/test.tbl | 3 + .../motion-target-preparation/README | 5 + .../availability-cases.h | 21 + .../availability-fixture.h | 5 + .../motion-target-preparation/expected | 0 .../motion-target-preparation/test.py | 147 + .../motion-target-preparation/test.sh | 3 + linuxcnc-tests/power-jog/.gitignore | 3 + linuxcnc-tests/power-jog/checkresult | 4 + linuxcnc-tests/power-jog/core_sim.hal | 11 + linuxcnc-tests/power-jog/test-ui.py | 199 ++ linuxcnc-tests/power-jog/test.ini | 69 + linuxcnc-tests/power-jog/test.sh | 7 + linuxcnc-tests/power-jog/tool.tbl | 1 + linuxcnc-tests/remap/dollar-argspec/README | 1 + linuxcnc-tests/remap/dollar-argspec/expected | 29 + linuxcnc-tests/remap/dollar-argspec/m501.ngc | 9 + linuxcnc-tests/remap/dollar-argspec/m502.ngc | 5 + linuxcnc-tests/remap/dollar-argspec/remap.py | 10 + linuxcnc-tests/remap/dollar-argspec/test.ini | 18 + linuxcnc-tests/remap/dollar-argspec/test.ngc | 11 + linuxcnc-tests/remap/dollar-argspec/test.sh | 3 + .../remap/dollar-argspec/toplevel.py | 1 + linuxcnc-tests/remap/executor/.gitignore | 1 + linuxcnc-tests/remap/executor/checkresult | 5 + linuxcnc-tests/remap/executor/remap.py | 52 + linuxcnc-tests/remap/executor/test-ui.py | 177 ++ linuxcnc-tests/remap/executor/test.ini.in | 95 + linuxcnc-tests/remap/executor/test.sh | 12 + linuxcnc-tests/remap/executor/toplevel.py | 18 + linuxcnc-tests/remap/mdi-remap-abort/README | 18 + .../remap/mdi-remap-abort/checkresult | 2 + linuxcnc-tests/remap/mdi-remap-abort/m400.ngc | 5 + linuxcnc-tests/remap/mdi-remap-abort/remap.py | 9 + .../remap/mdi-remap-abort/test-ui.py | 161 ++ linuxcnc-tests/remap/mdi-remap-abort/test.ini | 101 + linuxcnc-tests/remap/mdi-remap-abort/test.sh | 2 + .../remap/mdi-remap-abort/toplevel.py | 1 + linuxcnc-tests/resumable-stop/README | 100 + linuxcnc-tests/resumable-stop/after-abort.ngc | 4 + .../resumable-stop/after-tap-m5.ngc | 7 + .../resumable-stop/after-thread-m5.ngc | 7 + .../resumable-stop/after-thread-m9.ngc | 8 + .../resumable-stop/after-thread-s.ngc | 7 + linuxcnc-tests/resumable-stop/check-result.sh | 15 + linuxcnc-tests/resumable-stop/core_sim.hal | 42 + linuxcnc-tests/resumable-stop/css.ngc | 6 + .../resumable-stop/dwell-atspeed.ngc | 7 + linuxcnc-tests/resumable-stop/dwell.ngc | 5 + .../resumable-stop/feed-atspeed.ngc | 7 + linuxcnc-tests/resumable-stop/fperrev.ngc | 7 + .../resumable-stop/g33-followed-by-rapid.ngc | 7 + .../resumable-stop/g76-exit-taper.ngc | 7 + linuxcnc-tests/resumable-stop/g76-handoff.ngc | 7 + linuxcnc-tests/resumable-stop/g76-step.ngc | 4 + .../resumable-stop/g76-step/checkresult | 2 + .../resumable-stop/g76-step/scenarios | 6 + .../resumable-stop/g76-step/test.sh | 3 + .../resumable-stop/g76-stop/checkresult | 2 + .../resumable-stop/g76-stop/scenarios | 5 + .../resumable-stop/g76-stop/test.sh | 3 + .../resumable-stop/g76-tapered-exit-taper.ngc | 7 + .../resumable-stop/g76-tapered-step.ngc | 4 + linuxcnc-tests/resumable-stop/g76-tapered.ngc | 7 + linuxcnc-tests/resumable-stop/g76.ngc | 7 + .../resumable-stop/general/checkresult | 2 + .../resumable-stop/general/scenarios | 24 + linuxcnc-tests/resumable-stop/general/test.sh | 3 + linuxcnc-tests/resumable-stop/homing-long.ngc | 6 + linuxcnc-tests/resumable-stop/homing.ngc | 6 + .../resumable-stop/inflight-step.ngc | 7 + .../resumable-stop/multi-spindle.ngc | 4 + linuxcnc-tests/resumable-stop/orient.ngc | 6 + linuxcnc-tests/resumable-stop/pause.ngc | 7 + .../resumable-stop/rapid-then-feed.ngc | 7 + .../resumable-stop/resume-atspeed.ngc | 7 + linuxcnc-tests/resumable-stop/resume-s0.ngc | 7 + .../resumable-stop/run-scenarios.sh | 61 + linuxcnc-tests/resumable-stop/single-step.ngc | 10 + .../resumable-stop/speed-change.ngc | 9 + .../resumable-stop/spindle-state.ngc | 10 + linuxcnc-tests/resumable-stop/tap.ngc | 7 + linuxcnc-tests/resumable-stop/test-ui.py | 2051 ++++++++++++++ linuxcnc-tests/resumable-stop/test.ini | 99 + linuxcnc-tests/resumable-stop/test.ngc | 9 + .../resumable-stop/thread-chain.ngc | 8 + .../resumable-stop/thread-g95-thread.ngc | 9 + .../resumable-stop/thread-then-steps.ngc | 10 + linuxcnc-tests/resumable-stop/thread.ngc | 7 + .../resumable-stop/threading/checkresult | 2 + .../resumable-stop/threading/scenarios | 11 + .../resumable-stop/threading/test.sh | 3 + linuxcnc-tests/resumable-stop/tool.tbl | 1 + linuxcnc-tests/rtmod-path/expected | 1 + linuxcnc-tests/rtmod-path/load.hal | 2 + linuxcnc-tests/rtmod-path/test.c | 109 + linuxcnc-tests/rtmod-path/test.sh | 8 + .../.gitignore | 2 + .../runtime-availability-regressions/README | 22 + .../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 | 81 + .../joghome.ini.in | 6 + .../record_abort.ngc | 6 + .../sequence.ini.in | 6 + .../slowtask.ini.in | 7 + .../runtime-availability-regressions/tail.hal | 30 + .../tail.ini.in | 7 + .../test-ui.py | 198 ++ .../test.ini.in | 3 + .../runtime-availability-regressions/test.sh | 35 + .../runtime-availability-regressions/tool.tbl | 1 + .../runtime-availability-regressions/xzc.hal | 12 + .../xzc.ini.in | 17 + .../runtime-availability/.gitignore | 2 + linuxcnc-tests/runtime-availability/README | 8 + linuxcnc-tests/runtime-availability/base.ini | 99 + .../runtime-availability/checkresult | 4 + .../runtime-availability/core_sim.hal | 17 + .../runtime-availability/initial-ui.py | 58 + .../runtime-availability/initial.ini.in | 9 + .../runtime-availability/make-fixtures.py | 34 + .../runtime-availability/paused.ngc | 3 + .../runtime-availability/test-ui.py | 297 ++ .../runtime-availability/test.ini.in | 3 + linuxcnc-tests/runtime-availability/test.sh | 5 + linuxcnc-tests/runtime-availability/tool.tbl | 0 .../task/interp-reset-requires-idle/README | 5 + .../interp-reset-requires-idle/checkresult | 2 + .../interp-reset-requires-idle/test-ui.py | 153 ++ .../task/interp-reset-requires-idle/test.ini | 93 + .../task/interp-reset-requires-idle/test.sh | 2 + .../arithmetic.c | 109 + .../thread-period-stats-arithmetic/expected | 0 .../thread-period-stats-arithmetic/test.sh | 9 + linuxcnc-tests/thread-period-stats/README | 4 + .../thread-period-stats/checkresult | 29 + linuxcnc-tests/thread-period-stats/test.hal | 11 + linuxcnc-tests/tool-crud-refusal/.gitignore | 5 + linuxcnc-tests/tool-crud-refusal/README | 7 + linuxcnc-tests/tool-crud-refusal/checkresult | 2 + linuxcnc-tests/tool-crud-refusal/program.ngc | 2 + linuxcnc-tests/tool-crud-refusal/test-ui.py | 83 + linuxcnc-tests/tool-crud-refusal/test.sh | 12 + linuxcnc-tests/tool-crud-refusal/tool-cmd.cc | 50 + .../tool-line-length-save/.gitignore | 6 + .../tool-line-length-save/checkresult | 2 + .../tool-line-length-save/make-table.py | 13 + .../tool-line-length-save/random-ui.py | 93 + .../tool-line-length-save/test-ui.py | 116 + linuxcnc-tests/tool-line-length-save/test.sh | 12 + linuxcnc-tests/tool-table-load/.gitignore | 6 + linuxcnc-tests/tool-table-load/checkresult | 2 + linuxcnc-tests/tool-table-load/common.py | 121 + linuxcnc-tests/tool-table-load/crlf-ui.py | 27 + .../tool-table-load/external-edit-ui.py | 74 + linuxcnc-tests/tool-table-load/garbage-ui.py | 51 + linuxcnc-tests/tool-table-load/missing-ui.py | 52 + .../tool-table-load/other-table-ui.py | 33 + .../tool-table-load/random-start-ui.py | 36 + linuxcnc-tests/tool-table-load/reload-ui.py | 26 + linuxcnc-tests/tool-table-load/symlink-ui.py | 55 + linuxcnc-tests/tool-table-load/test.sh | 64 + linuxcnc-tests/tool-wear-abort/.gitignore | 4 + .../tool-wear-abort/change-move.ngc | 5 + .../tool-wear-abort/change-then-end.ngc | 3 + linuxcnc-tests/tool-wear-abort/checkresult | 2 + .../tool-wear-abort/core_sim_handshake.hal | 18 + .../tool-wear-abort/interp-error-m6.ngc | 7 + .../tool-wear-abort/move-origin.ngc | 5 + linuxcnc-tests/tool-wear-abort/postgui.hal | 5 + .../tool-wear-abort/readahead-g43.ngc | 6 + .../tool-wear-abort/readahead-m61.ngc | 7 + linuxcnc-tests/tool-wear-abort/test-ui.py | 359 +++ linuxcnc-tests/tool-wear-abort/test.sh | 7 + .../tool-wear-abort/tool.tbl.original | 2 + linuxcnc-tests/tool-wear-common/lathe.ini.in | 84 + linuxcnc-tests/tool-wear-common/make-ini.sh | 18 + linuxcnc-tests/tool-wear-restart/.gitignore | 5 + linuxcnc-tests/tool-wear-restart/checkresult | 2 + linuxcnc-tests/tool-wear-restart/common.py | 72 + linuxcnc-tests/tool-wear-restart/run1.py | 10 + linuxcnc-tests/tool-wear-restart/run2.py | 18 + linuxcnc-tests/tool-wear-restart/test.sh | 14 + .../tool-wear-restart/tool.tbl.original | 2 + linuxcnc-tests/tool-wear-task/.gitignore | 4 + linuxcnc-tests/tool-wear-task/checkresult | 2 + linuxcnc-tests/tool-wear-task/remap.py | 15 + linuxcnc-tests/tool-wear-task/test-ui.py | 297 ++ linuxcnc-tests/tool-wear-task/test.sh | 10 + .../tool-wear-task/tool.tbl.original | 2 + linuxcnc-tests/tool-wear-task/toplevel.py | 1 + skills/patch-linuxcnc/SKILL.md | 5 + 325 files changed, 10376 insertions(+), 13201 deletions(-) create mode 100644 linuxcnc-tests/.gitignore create mode 100644 linuxcnc-tests/availability-mcodes-regressions/.gitignore create mode 100644 linuxcnc-tests/availability-mcodes-regressions/README create mode 100755 linuxcnc-tests/availability-mcodes-regressions/checkresult create mode 100644 linuxcnc-tests/availability-mcodes-regressions/step.ngc create mode 100755 linuxcnc-tests/availability-mcodes-regressions/test-ui.py create mode 100644 linuxcnc-tests/availability-mcodes-regressions/test.ini.in create mode 100755 linuxcnc-tests/availability-mcodes-regressions/test.sh create mode 100644 linuxcnc-tests/availability-mcodes/.gitignore create mode 100644 linuxcnc-tests/availability-mcodes/README create mode 100755 linuxcnc-tests/availability-mcodes/checkresult create mode 120000 linuxcnc-tests/availability-mcodes/core_sim.hal create mode 100644 linuxcnc-tests/availability-mcodes/homing.ngc create mode 100644 linuxcnc-tests/availability-mcodes/no-force.ini.in create mode 100644 linuxcnc-tests/availability-mcodes/ordered.ngc create mode 100755 linuxcnc-tests/availability-mcodes/test-ui.py create mode 100644 linuxcnc-tests/availability-mcodes/test.ini.in create mode 100755 linuxcnc-tests/availability-mcodes/test.sh create mode 100644 linuxcnc-tests/availability-mcodes/timeout.ngc create mode 120000 linuxcnc-tests/availability-mcodes/tool.tbl create mode 100644 linuxcnc-tests/availability-mcodes/unhomed.ngc create mode 100644 linuxcnc-tests/css-status/README create mode 100755 linuxcnc-tests/css-status/checkresult create mode 100644 linuxcnc-tests/css-status/core_sim.hal create mode 100755 linuxcnc-tests/css-status/test-ui.py create mode 100644 linuxcnc-tests/css-status/test.ini create mode 100755 linuxcnc-tests/css-status/test.sh create mode 100644 linuxcnc-tests/css-status/tool.tbl create mode 100644 linuxcnc-tests/g76-tapered-pitch/README create mode 100755 linuxcnc-tests/g76-tapered-pitch/checkresult create mode 100644 linuxcnc-tests/g76-tapered-pitch/core_sim.hal create mode 100755 linuxcnc-tests/g76-tapered-pitch/test-ui.py create mode 100644 linuxcnc-tests/g76-tapered-pitch/test.ini create mode 100755 linuxcnc-tests/g76-tapered-pitch/test.sh create mode 100644 linuxcnc-tests/halcompile/cross-tools/.gitignore create mode 100755 linuxcnc-tests/halcompile/cross-tools/checkresult create mode 100644 linuxcnc-tests/halcompile/cross-tools/cross_tools.comp create mode 100755 linuxcnc-tests/halcompile/cross-tools/test.sh create mode 100755 linuxcnc-tests/homing-concurrent/checkresult create mode 100644 linuxcnc-tests/homing-concurrent/homing.hal create mode 100755 linuxcnc-tests/homing-concurrent/test-ui.py create mode 100644 linuxcnc-tests/homing-concurrent/test.ini create mode 100755 linuxcnc-tests/homing-concurrent/test.sh create mode 100644 linuxcnc-tests/homing-concurrent/tool.tbl create mode 100644 linuxcnc-tests/interp/availability-mcodes/README create mode 100644 linuxcnc-tests/interp/availability-mcodes/bad-joint.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/double-selector.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/execute-status.cc create mode 100644 linuxcnc-tests/interp/availability-mcodes/execute-status.py create mode 100644 linuxcnc-tests/interp/availability-mcodes/expected create mode 100644 linuxcnc-tests/interp/availability-mcodes/fractional-joint.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/fractional-spindle.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/group-spindle.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/huge-spindle.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/legacy54.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/legacy55.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/missing-selector.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-feed.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-modal.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-motion.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-parameter.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-polar.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-speed.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-stop.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-tool.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/mixed-word.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/negative-fractional-spindle.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/negative-joint.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/remap.ini create mode 100644 linuxcnc-tests/interp/availability-mcodes/remapped.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/test.ini create mode 100755 linuxcnc-tests/interp/availability-mcodes/test.sh create mode 100644 linuxcnc-tests/interp/availability-mcodes/valid-joint.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/valid-spindle.ngc create mode 100644 linuxcnc-tests/interp/g28.2/instant-home/README create mode 100755 linuxcnc-tests/interp/g28.2/instant-home/checkresult create mode 100644 linuxcnc-tests/interp/g28.2/instant-home/sim.tbl create mode 100755 linuxcnc-tests/interp/g28.2/instant-home/test-ui.py create mode 100644 linuxcnc-tests/interp/g28.2/instant-home/test.ini create mode 100755 linuxcnc-tests/interp/g28.2/instant-home/test.sh create mode 100644 linuxcnc-tests/interp/g76-tapered/README create mode 100644 linuxcnc-tests/interp/g76-tapered/alternating-z-range.ngc create mode 100644 linuxcnc-tests/interp/g76-tapered/expected create mode 100644 linuxcnc-tests/interp/g76-tapered/invalid-both-modes.ngc create mode 100644 linuxcnc-tests/interp/g76-tapered/invalid-d.ngc create mode 100644 linuxcnc-tests/interp/g76-tapered/invalid-y.ngc create mode 100644 linuxcnc-tests/interp/g76-tapered/invalid-zero-z.ngc create mode 100644 linuxcnc-tests/interp/g76-tapered/test.ngc create mode 100644 linuxcnc-tests/interp/g76-tapered/test.sh create mode 100644 linuxcnc-tests/interp/tool-line-length/expected create mode 100644 linuxcnc-tests/interp/tool-line-length/missing-t2.ngc create mode 100644 linuxcnc-tests/interp/tool-line-length/missing-t3.ngc create mode 100644 linuxcnc-tests/interp/tool-line-length/missing-t4.ngc create mode 100644 linuxcnc-tests/interp/tool-line-length/test.ngc create mode 100755 linuxcnc-tests/interp/tool-line-length/test.sh create mode 100644 linuxcnc-tests/interp/tool-line-length/test.tbl create mode 100644 linuxcnc-tests/interp/tool-wear/expected create mode 100644 linuxcnc-tests/interp/tool-wear/invalid-i.ngc create mode 100644 linuxcnc-tests/interp/tool-wear/invalid-j.ngc create mode 100644 linuxcnc-tests/interp/tool-wear/invalid-m61-comp.ngc create mode 100644 linuxcnc-tests/interp/tool-wear/invalid-missing-tool.ngc create mode 100644 linuxcnc-tests/interp/tool-wear/invalid-q.ngc create mode 100644 linuxcnc-tests/interp/tool-wear/invalid-r.ngc create mode 100644 linuxcnc-tests/interp/tool-wear/invalid-zero-tool.ngc create mode 100644 linuxcnc-tests/interp/tool-wear/test.ngc create mode 100755 linuxcnc-tests/interp/tool-wear/test.sh create mode 100644 linuxcnc-tests/interp/tool-wear/test.tbl create mode 100644 linuxcnc-tests/motion-target-preparation/README create mode 100644 linuxcnc-tests/motion-target-preparation/availability-cases.h create mode 100644 linuxcnc-tests/motion-target-preparation/availability-fixture.h create mode 100644 linuxcnc-tests/motion-target-preparation/expected create mode 100644 linuxcnc-tests/motion-target-preparation/test.py create mode 100755 linuxcnc-tests/motion-target-preparation/test.sh create mode 100644 linuxcnc-tests/power-jog/.gitignore create mode 100755 linuxcnc-tests/power-jog/checkresult create mode 100644 linuxcnc-tests/power-jog/core_sim.hal create mode 100755 linuxcnc-tests/power-jog/test-ui.py create mode 100644 linuxcnc-tests/power-jog/test.ini create mode 100755 linuxcnc-tests/power-jog/test.sh create mode 100644 linuxcnc-tests/power-jog/tool.tbl create mode 100644 linuxcnc-tests/remap/dollar-argspec/README create mode 100644 linuxcnc-tests/remap/dollar-argspec/expected create mode 100644 linuxcnc-tests/remap/dollar-argspec/m501.ngc create mode 100644 linuxcnc-tests/remap/dollar-argspec/m502.ngc create mode 100644 linuxcnc-tests/remap/dollar-argspec/remap.py create mode 100644 linuxcnc-tests/remap/dollar-argspec/test.ini create mode 100644 linuxcnc-tests/remap/dollar-argspec/test.ngc create mode 100755 linuxcnc-tests/remap/dollar-argspec/test.sh create mode 100644 linuxcnc-tests/remap/dollar-argspec/toplevel.py create mode 100644 linuxcnc-tests/remap/executor/.gitignore create mode 100755 linuxcnc-tests/remap/executor/checkresult create mode 100644 linuxcnc-tests/remap/executor/remap.py create mode 100755 linuxcnc-tests/remap/executor/test-ui.py create mode 100644 linuxcnc-tests/remap/executor/test.ini.in create mode 100755 linuxcnc-tests/remap/executor/test.sh create mode 100644 linuxcnc-tests/remap/executor/toplevel.py create mode 100644 linuxcnc-tests/remap/mdi-remap-abort/README create mode 100755 linuxcnc-tests/remap/mdi-remap-abort/checkresult create mode 100644 linuxcnc-tests/remap/mdi-remap-abort/m400.ngc create mode 100644 linuxcnc-tests/remap/mdi-remap-abort/remap.py create mode 100755 linuxcnc-tests/remap/mdi-remap-abort/test-ui.py create mode 100644 linuxcnc-tests/remap/mdi-remap-abort/test.ini create mode 100755 linuxcnc-tests/remap/mdi-remap-abort/test.sh create mode 100644 linuxcnc-tests/remap/mdi-remap-abort/toplevel.py create mode 100644 linuxcnc-tests/resumable-stop/README create mode 100644 linuxcnc-tests/resumable-stop/after-abort.ngc create mode 100644 linuxcnc-tests/resumable-stop/after-tap-m5.ngc create mode 100644 linuxcnc-tests/resumable-stop/after-thread-m5.ngc create mode 100644 linuxcnc-tests/resumable-stop/after-thread-m9.ngc create mode 100644 linuxcnc-tests/resumable-stop/after-thread-s.ngc create mode 100755 linuxcnc-tests/resumable-stop/check-result.sh create mode 100644 linuxcnc-tests/resumable-stop/core_sim.hal create mode 100644 linuxcnc-tests/resumable-stop/css.ngc create mode 100644 linuxcnc-tests/resumable-stop/dwell-atspeed.ngc create mode 100644 linuxcnc-tests/resumable-stop/dwell.ngc create mode 100644 linuxcnc-tests/resumable-stop/feed-atspeed.ngc create mode 100644 linuxcnc-tests/resumable-stop/fperrev.ngc create mode 100644 linuxcnc-tests/resumable-stop/g33-followed-by-rapid.ngc create mode 100644 linuxcnc-tests/resumable-stop/g76-exit-taper.ngc create mode 100644 linuxcnc-tests/resumable-stop/g76-handoff.ngc create mode 100644 linuxcnc-tests/resumable-stop/g76-step.ngc create mode 100755 linuxcnc-tests/resumable-stop/g76-step/checkresult create mode 100644 linuxcnc-tests/resumable-stop/g76-step/scenarios create mode 100755 linuxcnc-tests/resumable-stop/g76-step/test.sh create mode 100755 linuxcnc-tests/resumable-stop/g76-stop/checkresult create mode 100644 linuxcnc-tests/resumable-stop/g76-stop/scenarios create mode 100755 linuxcnc-tests/resumable-stop/g76-stop/test.sh create mode 100644 linuxcnc-tests/resumable-stop/g76-tapered-exit-taper.ngc create mode 100644 linuxcnc-tests/resumable-stop/g76-tapered-step.ngc create mode 100644 linuxcnc-tests/resumable-stop/g76-tapered.ngc create mode 100644 linuxcnc-tests/resumable-stop/g76.ngc create mode 100755 linuxcnc-tests/resumable-stop/general/checkresult create mode 100644 linuxcnc-tests/resumable-stop/general/scenarios create mode 100755 linuxcnc-tests/resumable-stop/general/test.sh create mode 100644 linuxcnc-tests/resumable-stop/homing-long.ngc create mode 100644 linuxcnc-tests/resumable-stop/homing.ngc create mode 100644 linuxcnc-tests/resumable-stop/inflight-step.ngc create mode 100644 linuxcnc-tests/resumable-stop/multi-spindle.ngc create mode 100644 linuxcnc-tests/resumable-stop/orient.ngc create mode 100644 linuxcnc-tests/resumable-stop/pause.ngc create mode 100644 linuxcnc-tests/resumable-stop/rapid-then-feed.ngc create mode 100644 linuxcnc-tests/resumable-stop/resume-atspeed.ngc create mode 100644 linuxcnc-tests/resumable-stop/resume-s0.ngc create mode 100755 linuxcnc-tests/resumable-stop/run-scenarios.sh create mode 100644 linuxcnc-tests/resumable-stop/single-step.ngc create mode 100644 linuxcnc-tests/resumable-stop/speed-change.ngc create mode 100644 linuxcnc-tests/resumable-stop/spindle-state.ngc create mode 100644 linuxcnc-tests/resumable-stop/tap.ngc create mode 100755 linuxcnc-tests/resumable-stop/test-ui.py create mode 100644 linuxcnc-tests/resumable-stop/test.ini create mode 100644 linuxcnc-tests/resumable-stop/test.ngc create mode 100644 linuxcnc-tests/resumable-stop/thread-chain.ngc create mode 100644 linuxcnc-tests/resumable-stop/thread-g95-thread.ngc create mode 100644 linuxcnc-tests/resumable-stop/thread-then-steps.ngc create mode 100644 linuxcnc-tests/resumable-stop/thread.ngc create mode 100755 linuxcnc-tests/resumable-stop/threading/checkresult create mode 100644 linuxcnc-tests/resumable-stop/threading/scenarios create mode 100755 linuxcnc-tests/resumable-stop/threading/test.sh create mode 100644 linuxcnc-tests/resumable-stop/tool.tbl create mode 100644 linuxcnc-tests/rtmod-path/expected create mode 100644 linuxcnc-tests/rtmod-path/load.hal create mode 100644 linuxcnc-tests/rtmod-path/test.c create mode 100755 linuxcnc-tests/rtmod-path/test.sh create mode 100644 linuxcnc-tests/runtime-availability-regressions/.gitignore create mode 100644 linuxcnc-tests/runtime-availability-regressions/README create mode 100644 linuxcnc-tests/runtime-availability-regressions/base.ini create mode 100755 linuxcnc-tests/runtime-availability-regressions/checkresult create mode 100644 linuxcnc-tests/runtime-availability-regressions/core.hal create mode 100644 linuxcnc-tests/runtime-availability-regressions/dwell.ngc create mode 100644 linuxcnc-tests/runtime-availability-regressions/extra.hal create mode 100644 linuxcnc-tests/runtime-availability-regressions/extra.ini.in create mode 100644 linuxcnc-tests/runtime-availability-regressions/fault.ini.in create mode 100644 linuxcnc-tests/runtime-availability-regressions/fixture.py create mode 100644 linuxcnc-tests/runtime-availability-regressions/joghome.ini.in create mode 100644 linuxcnc-tests/runtime-availability-regressions/record_abort.ngc create mode 100644 linuxcnc-tests/runtime-availability-regressions/sequence.ini.in create mode 100644 linuxcnc-tests/runtime-availability-regressions/slowtask.ini.in create mode 100644 linuxcnc-tests/runtime-availability-regressions/tail.hal create mode 100644 linuxcnc-tests/runtime-availability-regressions/tail.ini.in create mode 100755 linuxcnc-tests/runtime-availability-regressions/test-ui.py create mode 100644 linuxcnc-tests/runtime-availability-regressions/test.ini.in create mode 100755 linuxcnc-tests/runtime-availability-regressions/test.sh create mode 100644 linuxcnc-tests/runtime-availability-regressions/tool.tbl create mode 100644 linuxcnc-tests/runtime-availability-regressions/xzc.hal create mode 100644 linuxcnc-tests/runtime-availability-regressions/xzc.ini.in create mode 100644 linuxcnc-tests/runtime-availability/.gitignore create mode 100644 linuxcnc-tests/runtime-availability/README create mode 100644 linuxcnc-tests/runtime-availability/base.ini create mode 100755 linuxcnc-tests/runtime-availability/checkresult create mode 100644 linuxcnc-tests/runtime-availability/core_sim.hal create mode 100755 linuxcnc-tests/runtime-availability/initial-ui.py create mode 100644 linuxcnc-tests/runtime-availability/initial.ini.in create mode 100644 linuxcnc-tests/runtime-availability/make-fixtures.py create mode 100644 linuxcnc-tests/runtime-availability/paused.ngc create mode 100755 linuxcnc-tests/runtime-availability/test-ui.py create mode 100644 linuxcnc-tests/runtime-availability/test.ini.in create mode 100755 linuxcnc-tests/runtime-availability/test.sh create mode 100644 linuxcnc-tests/runtime-availability/tool.tbl create mode 100644 linuxcnc-tests/task/interp-reset-requires-idle/README create mode 100755 linuxcnc-tests/task/interp-reset-requires-idle/checkresult create mode 100755 linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py create mode 100644 linuxcnc-tests/task/interp-reset-requires-idle/test.ini create mode 100755 linuxcnc-tests/task/interp-reset-requires-idle/test.sh create mode 100644 linuxcnc-tests/thread-period-stats-arithmetic/arithmetic.c create mode 100644 linuxcnc-tests/thread-period-stats-arithmetic/expected create mode 100644 linuxcnc-tests/thread-period-stats-arithmetic/test.sh create mode 100644 linuxcnc-tests/thread-period-stats/README create mode 100755 linuxcnc-tests/thread-period-stats/checkresult create mode 100644 linuxcnc-tests/thread-period-stats/test.hal create mode 100644 linuxcnc-tests/tool-crud-refusal/.gitignore create mode 100644 linuxcnc-tests/tool-crud-refusal/README create mode 100755 linuxcnc-tests/tool-crud-refusal/checkresult create mode 100644 linuxcnc-tests/tool-crud-refusal/program.ngc create mode 100755 linuxcnc-tests/tool-crud-refusal/test-ui.py create mode 100755 linuxcnc-tests/tool-crud-refusal/test.sh create mode 100644 linuxcnc-tests/tool-crud-refusal/tool-cmd.cc create mode 100644 linuxcnc-tests/tool-line-length-save/.gitignore create mode 100755 linuxcnc-tests/tool-line-length-save/checkresult create mode 100755 linuxcnc-tests/tool-line-length-save/make-table.py create mode 100755 linuxcnc-tests/tool-line-length-save/random-ui.py create mode 100755 linuxcnc-tests/tool-line-length-save/test-ui.py create mode 100755 linuxcnc-tests/tool-line-length-save/test.sh create mode 100644 linuxcnc-tests/tool-table-load/.gitignore create mode 100755 linuxcnc-tests/tool-table-load/checkresult create mode 100644 linuxcnc-tests/tool-table-load/common.py create mode 100755 linuxcnc-tests/tool-table-load/crlf-ui.py create mode 100755 linuxcnc-tests/tool-table-load/external-edit-ui.py create mode 100755 linuxcnc-tests/tool-table-load/garbage-ui.py create mode 100755 linuxcnc-tests/tool-table-load/missing-ui.py create mode 100755 linuxcnc-tests/tool-table-load/other-table-ui.py create mode 100755 linuxcnc-tests/tool-table-load/random-start-ui.py create mode 100755 linuxcnc-tests/tool-table-load/reload-ui.py create mode 100755 linuxcnc-tests/tool-table-load/symlink-ui.py create mode 100755 linuxcnc-tests/tool-table-load/test.sh create mode 100644 linuxcnc-tests/tool-wear-abort/.gitignore create mode 100644 linuxcnc-tests/tool-wear-abort/change-move.ngc create mode 100644 linuxcnc-tests/tool-wear-abort/change-then-end.ngc create mode 100755 linuxcnc-tests/tool-wear-abort/checkresult create mode 100644 linuxcnc-tests/tool-wear-abort/core_sim_handshake.hal create mode 100644 linuxcnc-tests/tool-wear-abort/interp-error-m6.ngc create mode 100644 linuxcnc-tests/tool-wear-abort/move-origin.ngc create mode 100644 linuxcnc-tests/tool-wear-abort/postgui.hal create mode 100644 linuxcnc-tests/tool-wear-abort/readahead-g43.ngc create mode 100644 linuxcnc-tests/tool-wear-abort/readahead-m61.ngc create mode 100755 linuxcnc-tests/tool-wear-abort/test-ui.py create mode 100755 linuxcnc-tests/tool-wear-abort/test.sh create mode 100644 linuxcnc-tests/tool-wear-abort/tool.tbl.original create mode 100644 linuxcnc-tests/tool-wear-common/lathe.ini.in create mode 100755 linuxcnc-tests/tool-wear-common/make-ini.sh create mode 100644 linuxcnc-tests/tool-wear-restart/.gitignore create mode 100755 linuxcnc-tests/tool-wear-restart/checkresult create mode 100644 linuxcnc-tests/tool-wear-restart/common.py create mode 100755 linuxcnc-tests/tool-wear-restart/run1.py create mode 100755 linuxcnc-tests/tool-wear-restart/run2.py create mode 100755 linuxcnc-tests/tool-wear-restart/test.sh create mode 100644 linuxcnc-tests/tool-wear-restart/tool.tbl.original create mode 100644 linuxcnc-tests/tool-wear-task/.gitignore create mode 100755 linuxcnc-tests/tool-wear-task/checkresult create mode 100644 linuxcnc-tests/tool-wear-task/remap.py create mode 100755 linuxcnc-tests/tool-wear-task/test-ui.py create mode 100755 linuxcnc-tests/tool-wear-task/test.sh create mode 100644 linuxcnc-tests/tool-wear-task/tool.tbl.original create mode 100644 linuxcnc-tests/tool-wear-task/toplevel.py diff --git a/.github/workflows/linuxcnc-patches.yml b/.github/workflows/linuxcnc-patches.yml index 99b9ff9..77a6203 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: @@ -104,14 +106,18 @@ jobs: run: | set -euo pipefail - # tests/resumable-stop/* are the longest tests (about 2.5 minutes - # each); spread them one per shard. Everything else is hashed - # across all shards. + # Upstream tests run from the LinuxCNC tree, the patches' own tests + # from linuxcnc-tests/ in this repository. + # + # linuxcnc-tests/resumable-stop/* are the longest tests (about + # 2.5 minutes each); spread them one per shard. Everything else is + # hashed across all shards. shard_tests=() resumable_index=0 while IFS= read -r -d '' test_path; do + relative_path="${test_path#"${GITHUB_WORKSPACE}/"}" # LinuxCNC features that are out of scope for this repository. - case "${test_path}" in + case "${relative_path}" in tests/build/ui/* | tests/glcanon/* | tests/halrmt/* | \ tests/linuxcncrsh/* | tests/linuxcncrsh-tcp/* | \ tests/pyvcp/* | tests/tooldb/* | tests/tooledit/* | \ @@ -119,11 +125,11 @@ jobs: continue ;; esac - if [[ "${test_path}" == tests/resumable-stop/* ]]; then + if [[ "${relative_path}" == linuxcnc-tests/resumable-stop/* ]]; then test_shard=$((resumable_index % SHARD_COUNT)) resumable_index=$((resumable_index + 1)) else - checksum="$(printf '%s' "${test_path}" | cksum)" + checksum="$(printf '%s' "${relative_path}" | cksum)" checksum="${checksum%% *}" test_shard=$((checksum % SHARD_COUNT)) fi @@ -131,7 +137,8 @@ jobs: shard_tests+=("${test_path}") fi done < <( - find tests \( -name test -o -name test.sh -o -name test.hal \) \ + find tests "${GITHUB_WORKSPACE}/linuxcnc-tests" \ + \( -name test -o -name test.sh -o -name test.hal \) \ -print0 | sort -z ) diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 6466276..e45c509 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -20,117 +20,25 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: - 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/python-interface.adoc | 12 + - docs/src/gui/halui.adoc | 3 +- - docs/src/man/man1/halui.1.adoc | 5 +- - 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 | 7 + - src/emc/nml_intf/emc.cc | 24 + - src/emc/nml_intf/emc.hh | 14 + - src/emc/nml_intf/emc_nml.hh | 22 + - src/emc/nml_intf/emcops.cc | 4 + - src/emc/task/emctaskmain.cc | 440 ++++- - src/emc/task/taskintf.cc | 67 +- - src/emc/tp/tp.c | 133 +- - src/emc/tp/tp_types.h | 12 + - src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + - src/emc/usr_intf/halui.cc | 9 +- - tests/resumable-stop/README | 72 + - tests/resumable-stop/after-abort.ngc | 4 + - tests/resumable-stop/after-tap-m5.ngc | 7 + - tests/resumable-stop/after-thread-m5.ngc | 7 + - tests/resumable-stop/after-thread-m9.ngc | 8 + - tests/resumable-stop/after-thread-s.ngc | 7 + - tests/resumable-stop/check-result.sh | 15 + - tests/resumable-stop/core_sim.hal | 42 + - tests/resumable-stop/css.ngc | 6 + - tests/resumable-stop/dwell-atspeed.ngc | 7 + - tests/resumable-stop/dwell.ngc | 5 + - tests/resumable-stop/feed-atspeed.ngc | 7 + - tests/resumable-stop/fperrev.ngc | 7 + - tests/resumable-stop/g76-step/checkresult | 2 + - tests/resumable-stop/g76-step/scenarios | 1 + - tests/resumable-stop/g76-step/test.sh | 3 + - tests/resumable-stop/g76-stop/checkresult | 2 + - tests/resumable-stop/g76-stop/scenarios | 2 + - tests/resumable-stop/g76-stop/test.sh | 3 + - tests/resumable-stop/g76.ngc | 7 + - tests/resumable-stop/general/checkresult | 2 + - tests/resumable-stop/general/scenarios | 20 + - tests/resumable-stop/general/test.sh | 3 + - tests/resumable-stop/homing-long.ngc | 6 + - tests/resumable-stop/homing.ngc | 6 + - 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/resume-atspeed.ngc | 7 + - tests/resumable-stop/run-scenarios.sh | 51 + - tests/resumable-stop/single-step.ngc | 10 + - tests/resumable-stop/speed-change.ngc | 9 + - tests/resumable-stop/spindle-state.ngc | 10 + - tests/resumable-stop/tap.ngc | 7 + - tests/resumable-stop/test-ui.py | 1494 +++++++++++++++++ - tests/resumable-stop/test.ini | 98 ++ - tests/resumable-stop/test.ngc | 9 + - tests/resumable-stop/thread-chain.ngc | 8 + - tests/resumable-stop/thread-g95-thread.ngc | 9 + - tests/resumable-stop/thread-then-steps.ngc | 10 + - tests/resumable-stop/thread.ngc | 7 + - tests/resumable-stop/threading/checkresult | 2 + - tests/resumable-stop/threading/scenarios | 8 + - tests/resumable-stop/threading/test.sh | 3 + - tests/resumable-stop/tool.tbl | 1 + - 64 files changed, 2830 insertions(+), 25 deletions(-) - create mode 100644 tests/resumable-stop/README - create mode 100644 tests/resumable-stop/after-abort.ngc - create mode 100644 tests/resumable-stop/after-tap-m5.ngc - create mode 100644 tests/resumable-stop/after-thread-m5.ngc - create mode 100644 tests/resumable-stop/after-thread-m9.ngc - create mode 100644 tests/resumable-stop/after-thread-s.ngc - create mode 100755 tests/resumable-stop/check-result.sh - create mode 100644 tests/resumable-stop/core_sim.hal - create mode 100644 tests/resumable-stop/css.ngc - create mode 100644 tests/resumable-stop/dwell-atspeed.ngc - create mode 100644 tests/resumable-stop/dwell.ngc - create mode 100644 tests/resumable-stop/feed-atspeed.ngc - create mode 100644 tests/resumable-stop/fperrev.ngc - create mode 100755 tests/resumable-stop/g76-step/checkresult - create mode 100644 tests/resumable-stop/g76-step/scenarios - create mode 100755 tests/resumable-stop/g76-step/test.sh - create mode 100755 tests/resumable-stop/g76-stop/checkresult - create mode 100644 tests/resumable-stop/g76-stop/scenarios - create mode 100755 tests/resumable-stop/g76-stop/test.sh - create mode 100644 tests/resumable-stop/g76.ngc - create mode 100755 tests/resumable-stop/general/checkresult - create mode 100644 tests/resumable-stop/general/scenarios - create mode 100755 tests/resumable-stop/general/test.sh - create mode 100644 tests/resumable-stop/homing-long.ngc - create mode 100644 tests/resumable-stop/homing.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/resume-atspeed.ngc - create mode 100755 tests/resumable-stop/run-scenarios.sh - create mode 100644 tests/resumable-stop/single-step.ngc - create mode 100644 tests/resumable-stop/speed-change.ngc - create mode 100644 tests/resumable-stop/spindle-state.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 100644 tests/resumable-stop/thread-chain.ngc - create mode 100644 tests/resumable-stop/thread-g95-thread.ngc - create mode 100644 tests/resumable-stop/thread-then-steps.ngc - create mode 100644 tests/resumable-stop/thread.ngc - create mode 100755 tests/resumable-stop/threading/checkresult - create mode 100644 tests/resumable-stop/threading/scenarios - create mode 100755 tests/resumable-stop/threading/test.sh - create mode 100644 tests/resumable-stop/tool.tbl + docs/src/config/python-interface.adoc | 12 + + docs/src/gui/halui.adoc | 3 +- + docs/src/man/man1/halui.1.adoc | 5 +- + 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 | 7 + + src/emc/nml_intf/emc.cc | 24 + + src/emc/nml_intf/emc.hh | 14 + + src/emc/nml_intf/emc_nml.hh | 22 + + src/emc/nml_intf/emcops.cc | 4 + + src/emc/task/emctaskmain.cc | 440 +++++++++++++++++- + src/emc/task/taskintf.cc | 67 ++- + src/emc/tp/tp.c | 133 +++++- + src/emc/tp/tp_types.h | 12 + + src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + + src/emc/usr_intf/halui.cc | 9 +- + 18 files changed, 812 insertions(+), 25 deletions(-) diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc index 25d5762..fa546b7 100644 @@ -1668,2297 +1576,3 @@ index 1d0cb6e..65b890a 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 0000000..137bc85 ---- /dev/null -+++ b/tests/resumable-stop/README -@@ -0,0 +1,72 @@ -+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 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. -diff --git a/tests/resumable-stop/after-abort.ngc b/tests/resumable-stop/after-abort.ngc -new file mode 100644 -index 0000000..df711f6 ---- /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/after-tap-m5.ngc b/tests/resumable-stop/after-tap-m5.ngc -new file mode 100644 -index 0000000..f8fa1b5 ---- /dev/null -+++ b/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 F60 -+M2 -diff --git a/tests/resumable-stop/after-thread-m5.ngc b/tests/resumable-stop/after-thread-m5.ngc -new file mode 100644 -index 0000000..db6cb3d ---- /dev/null -+++ b/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 F60 -+M2 -diff --git a/tests/resumable-stop/after-thread-m9.ngc b/tests/resumable-stop/after-thread-m9.ngc -new file mode 100644 -index 0000000..30b558d ---- /dev/null -+++ b/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 F60 -+M2 -diff --git a/tests/resumable-stop/after-thread-s.ngc b/tests/resumable-stop/after-thread-s.ngc -new file mode 100644 -index 0000000..336d6be ---- /dev/null -+++ b/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 F60 -+M2 -diff --git a/tests/resumable-stop/check-result.sh b/tests/resumable-stop/check-result.sh -new file mode 100755 -index 0000000..7e07466 ---- /dev/null -+++ b/tests/resumable-stop/check-result.sh -@@ -0,0 +1,15 @@ -+#!/bin/sh -+# Shared checkresult for the tests/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/tests/resumable-stop/core_sim.hal b/tests/resumable-stop/core_sim.hal -new file mode 100644 -index 0000000..bbc7166 ---- /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 0000000..382aaff ---- /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-atspeed.ngc b/tests/resumable-stop/dwell-atspeed.ngc -new file mode 100644 -index 0000000..be7e5af ---- /dev/null -+++ b/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/tests/resumable-stop/dwell.ngc b/tests/resumable-stop/dwell.ngc -new file mode 100644 -index 0000000..f7a54f8 ---- /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/feed-atspeed.ngc b/tests/resumable-stop/feed-atspeed.ngc -new file mode 100644 -index 0000000..8af98dc ---- /dev/null -+++ b/tests/resumable-stop/feed-atspeed.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+G0 X0 -+F600 -+S300 M3 -+G1 X5 -+M5 -+M2 -diff --git a/tests/resumable-stop/fperrev.ngc b/tests/resumable-stop/fperrev.ngc -new file mode 100644 -index 0000000..92dbe87 ---- /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-step/checkresult b/tests/resumable-stop/g76-step/checkresult -new file mode 100755 -index 0000000..55a8859 ---- /dev/null -+++ b/tests/resumable-stop/g76-step/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 1 -diff --git a/tests/resumable-stop/g76-step/scenarios b/tests/resumable-stop/g76-step/scenarios -new file mode 100644 -index 0000000..f0a4053 ---- /dev/null -+++ b/tests/resumable-stop/g76-step/scenarios -@@ -0,0 +1 @@ -+trapezoidal:fperrev -diff --git a/tests/resumable-stop/g76-step/test.sh b/tests/resumable-stop/g76-step/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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/tests/resumable-stop/g76-stop/checkresult b/tests/resumable-stop/g76-stop/checkresult -new file mode 100755 -index 0000000..30bd373 ---- /dev/null -+++ b/tests/resumable-stop/g76-stop/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 2 -diff --git a/tests/resumable-stop/g76-stop/scenarios b/tests/resumable-stop/g76-stop/scenarios -new file mode 100644 -index 0000000..bea05471 ---- /dev/null -+++ b/tests/resumable-stop/g76-stop/scenarios -@@ -0,0 +1,2 @@ -+g76 -+fperrev -diff --git a/tests/resumable-stop/g76-stop/test.sh b/tests/resumable-stop/g76-stop/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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/tests/resumable-stop/g76.ngc b/tests/resumable-stop/g76.ngc -new file mode 100644 -index 0000000..1c6a3ea ---- /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/general/checkresult b/tests/resumable-stop/general/checkresult -new file mode 100755 -index 0000000..2d7e132 ---- /dev/null -+++ b/tests/resumable-stop/general/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 20 -diff --git a/tests/resumable-stop/general/scenarios b/tests/resumable-stop/general/scenarios -new file mode 100644 -index 0000000..f3792d2 ---- /dev/null -+++ b/tests/resumable-stop/general/scenarios -@@ -0,0 +1,20 @@ -+idle-rejected -+ordinary -+trapezoidal:ordinary -+single-step -+trapezoidal:single-step -+rapid-no-atspeed -+paused-resume -+paused-run -+abort-empty -+orientation -+dwell -+dwell-atspeed -+multi-spindle -+css -+homing -+homing-interrupted -+speed-change-atspeed -+queued-feed-atspeed -+spindle-state -+resume-atspeed -diff --git a/tests/resumable-stop/general/test.sh b/tests/resumable-stop/general/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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/tests/resumable-stop/homing-long.ngc b/tests/resumable-stop/homing-long.ngc -new file mode 100644 -index 0000000..2cc583c ---- /dev/null -+++ b/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/tests/resumable-stop/homing.ngc b/tests/resumable-stop/homing.ngc -new file mode 100644 -index 0000000..4f214ea ---- /dev/null -+++ b/tests/resumable-stop/homing.ngc -@@ -0,0 +1,6 @@ -+G21 G90 -+F600 -+G1 X5 -+G28.2 P0 -+G1 X30 -+M2 -diff --git a/tests/resumable-stop/multi-spindle.ngc b/tests/resumable-stop/multi-spindle.ngc -new file mode 100644 -index 0000000..ba2e66f ---- /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 0000000..bb08db3 ---- /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 0000000..6fe71e3 ---- /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 0000000..c562a57 ---- /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/resume-atspeed.ngc b/tests/resumable-stop/resume-atspeed.ngc -new file mode 100644 -index 0000000..cf66123 ---- /dev/null -+++ b/tests/resumable-stop/resume-atspeed.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+G0 X0 -+F60 -+S300 M3 -+G1 X4 -+M5 -+M2 -diff --git a/tests/resumable-stop/run-scenarios.sh b/tests/resumable-stop/run-scenarios.sh -new file mode 100755 -index 0000000..c756dd3 ---- /dev/null -+++ b/tests/resumable-stop/run-scenarios.sh -@@ -0,0 +1,51 @@ -+#!/bin/bash -e -+# Shared driver for the tests/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) -+ -+[ $# -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 "$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/tests/resumable-stop/single-step.ngc b/tests/resumable-stop/single-step.ngc -new file mode 100644 -index 0000000..8955e51 ---- /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/speed-change.ngc b/tests/resumable-stop/speed-change.ngc -new file mode 100644 -index 0000000..927c3ca ---- /dev/null -+++ b/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/tests/resumable-stop/spindle-state.ngc b/tests/resumable-stop/spindle-state.ngc -new file mode 100644 -index 0000000..c5f21ab ---- /dev/null -+++ b/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/tests/resumable-stop/tap.ngc b/tests/resumable-stop/tap.ngc -new file mode 100644 -index 0000000..3060ac4 ---- /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 0000000..4cf91ee ---- /dev/null -+++ b/tests/resumable-stop/test-ui.py -@@ -0,0 +1,1494 @@ -+#!/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() if callable(message) else 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) -+ -+ -+# 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_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_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_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], -+ 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_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_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_step_then_resume_while_stopping_test(): -+ # Step followed by Resume while Stop waits for G33 must resume the -+ # program normally rather than single-step it. -+ 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, -+ ) -+ -+ # Stop completes only on STOPPED, so do not wait for it here. -+ c.program_stop() -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPING, -+ "Stop did not wait for the active G33", -+ timeout=1.0, -+ ) -+ c.auto(linuxcnc.AUTO_STEP) -+ c.auto(linuxcnc.AUTO_RESUME) -+ s.poll() -+ if s.stop_state != linuxcnc.STOP_STOPPING: -+ fail("G33 finished before Step and Resume were sent") -+ -+ 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), -+ lambda: "program did not run to completion after Step and Resume: " -+ "X=%.3f interp=%d paused=%d stop=%d" -+ % (s.position[0], s.interp_state, s.task_paused, s.stop_state), -+ timeout=20.0, -+ ) -+ assert_outputs_stopped_after_program() -+ -+ -+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, -+ "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, -+ "dwell-atspeed": run_dwell_atspeed_barrier_test, -+ "command-after-sync": run_command_after_sync_motion_test, -+ "resume-atspeed": run_resume_atspeed_wait_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, -+ "step-resume-stopping": run_step_then_resume_while_stopping_test, -+ "g95-between-g33": run_g95_between_g33_stop_resume_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/tests/resumable-stop/test.ini b/tests/resumable-stop/test.ini -new file mode 100644 -index 0000000..a422788 ---- /dev/null -+++ b/tests/resumable-stop/test.ini -@@ -0,0 +1,98 @@ -+[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 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/tests/resumable-stop/test.ngc b/tests/resumable-stop/test.ngc -new file mode 100644 -index 0000000..416044b ---- /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/thread-chain.ngc b/tests/resumable-stop/thread-chain.ngc -new file mode 100644 -index 0000000..ca80839 ---- /dev/null -+++ b/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/tests/resumable-stop/thread-g95-thread.ngc b/tests/resumable-stop/thread-g95-thread.ngc -new file mode 100644 -index 0000000..d6630aa ---- /dev/null -+++ b/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 F60 -+M5 -+M2 -diff --git a/tests/resumable-stop/thread-then-steps.ngc b/tests/resumable-stop/thread-then-steps.ngc -new file mode 100644 -index 0000000..e744543 ---- /dev/null -+++ b/tests/resumable-stop/thread-then-steps.ngc -@@ -0,0 +1,10 @@ -+G21 G90 -+G0 X0 Z0 -+S6 M3 -+G33 Z-5 K10 -+G1 X5 F600 -+M8 -+G1 X10 -+M9 -+M5 -+M2 -diff --git a/tests/resumable-stop/thread.ngc b/tests/resumable-stop/thread.ngc -new file mode 100644 -index 0000000..5976979 ---- /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/threading/checkresult b/tests/resumable-stop/threading/checkresult -new file mode 100755 -index 0000000..e619f41 ---- /dev/null -+++ b/tests/resumable-stop/threading/checkresult -@@ -0,0 +1,2 @@ -+#!/bin/sh -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 8 -diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios -new file mode 100644 -index 0000000..9fdbe0c ---- /dev/null -+++ b/tests/resumable-stop/threading/scenarios -@@ -0,0 +1,8 @@ -+rigid-tap -+g33 -+queued-g33 -+g33-chain -+trapezoidal:g33-chain -+step-resume-stopping -+g95-between-g33 -+command-after-sync -diff --git a/tests/resumable-stop/threading/test.sh b/tests/resumable-stop/threading/test.sh -new file mode 100755 -index 0000000..713f576 ---- /dev/null -+++ b/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/tests/resumable-stop/tool.tbl b/tests/resumable-stop/tool.tbl -new file mode 100644 -index 0000000..68840ea ---- /dev/null -+++ b/tests/resumable-stop/tool.tbl -@@ -0,0 +1 @@ -+T1 P1 Z0 D0 diff --git a/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch b/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch index 90df789..7c6d4c3 100644 --- a/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch +++ b/linuxcnc-patches/0006-ordered-realtime-component-search-path.patch @@ -18,17 +18,9 @@ Subject: [PATCH] hal: add ordered trusted realtime component search path src/rtapi/rtmod_path.c | 195 ++++++++++++++++++++++++++++++ src/rtapi/rtmod_path.h | 34 ++++++ src/rtapi/uspace_rtapi_main.cc | 42 +++++-- - tests/rtmod-path/expected | 1 + - tests/rtmod-path/load.hal | 2 + - tests/rtmod-path/test.c | 109 +++++++++++++++++ - tests/rtmod-path/test.sh | 8 ++ - 18 files changed, 513 insertions(+), 58 deletions(-) + 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 1538013..34bcc9d 100644 @@ -744,147 +736,3 @@ index 32c5ddd..95dc8ac 100644 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 0000000..55233dc ---- /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 0000000..b443927 ---- /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 0000000..fffdf47 ---- /dev/null -+++ b/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/tests/rtmod-path/test.sh b/tests/rtmod-path/test.sh -new file mode 100755 -index 0000000..d4e8e67 ---- /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 45b0ae5..7a3859e 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -60,10 +60,10 @@ Fixes from review of the port: 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 | 69 +++- + 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/gcode/tool-compensation.adoc | 28 ++- docs/src/tooldatabase/tooldatabase.adoc | 7 +- lib/python/rs274/glcanon_scene.py | 4 +- lib/python/tooldb.py | 2 +- @@ -72,34 +72,34 @@ Fixes from review of the port: 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/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/gcodemodule.cc | 27 ++- src/emc/rs274ngc/interp_array.cc | 1 + src/emc/rs274ngc/interp_check.cc | 4 +- - src/emc/rs274ngc/interp_convert.cc | 171 ++++++--- + src/emc/rs274ngc/interp_convert.cc | 171 ++++++++++------ src/emc/rs274ngc/interp_internal.hh | 2 - src/emc/rs274ngc/interp_parameter_def.hh | 10 + src/emc/rs274ngc/pyemctypes.cc | 2 + src/emc/rs274ngc/rs274ngc_interp.hh | 1 + - src/emc/rs274ngc/rs274ngc_pre.cc | 37 +- + src/emc/rs274ngc/rs274ngc_pre.cc | 37 +++- src/emc/sai/saicanon.cc | 5 +- - src/emc/task/emccanon.cc | 61 ++- + 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/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 +- + 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/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 | 4 + @@ -107,122 +107,16 @@ Fixes from review of the port: tests/interp/g72-facing/expected | 1 + tests/interp/g72-missing-iteration/expected | 1 + tests/interp/g76/expected | 1 + - tests/interp/tool-line-length/expected | 23 ++ - tests/interp/tool-line-length/missing-t2.ngc | 3 + - tests/interp/tool-line-length/missing-t3.ngc | 3 + - tests/interp/tool-line-length/missing-t4.ngc | 3 + - tests/interp/tool-line-length/test.ngc | 12 + - tests/interp/tool-line-length/test.sh | 17 + - tests/interp/tool-line-length/test.tbl | 5 + - tests/interp/tool-wear/expected | 69 ++++ - tests/interp/tool-wear/invalid-i.ngc | 3 + - tests/interp/tool-wear/invalid-j.ngc | 3 + - tests/interp/tool-wear/invalid-m61-comp.ngc | 5 + - .../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 | 46 +++ - tests/interp/tool-wear/test.sh | 27 ++ - tests/interp/tool-wear/test.tbl | 3 + - tests/remap/introspect/expected | 25 +- - tests/remap/oword-pycall/expected | 25 +- + tests/remap/introspect/expected | 25 +-- + tests/remap/oword-pycall/expected | 25 +-- 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/tool-line-length-save/.gitignore | 6 + - tests/tool-line-length-save/checkresult | 2 + - tests/tool-line-length-save/make-table.py | 13 + - tests/tool-line-length-save/random-ui.py | 62 +++ - tests/tool-line-length-save/test-ui.py | 116 ++++++ - tests/tool-line-length-save/test.sh | 12 + - tests/tool-wear-abort/.gitignore | 4 + - tests/tool-wear-abort/change-move.ngc | 5 + - tests/tool-wear-abort/change-then-end.ngc | 3 + - tests/tool-wear-abort/checkresult | 2 + - tests/tool-wear-abort/core_sim_handshake.hal | 18 + - tests/tool-wear-abort/interp-error-m6.ngc | 7 + - tests/tool-wear-abort/move-origin.ngc | 5 + - tests/tool-wear-abort/postgui.hal | 5 + - tests/tool-wear-abort/readahead-g43.ngc | 6 + - tests/tool-wear-abort/readahead-m61.ngc | 7 + - tests/tool-wear-abort/test-ui.py | 359 ++++++++++++++++++ - tests/tool-wear-abort/test.sh | 7 + - tests/tool-wear-abort/tool.tbl.original | 2 + - tests/tool-wear-common/lathe.ini.in | 84 ++++ - tests/tool-wear-common/make-ini.sh | 18 + - tests/tool-wear-restart/.gitignore | 5 + - tests/tool-wear-restart/checkresult | 2 + - tests/tool-wear-restart/common.py | 72 ++++ - tests/tool-wear-restart/run1.py | 10 + - tests/tool-wear-restart/run2.py | 18 + - tests/tool-wear-restart/test.sh | 14 + - tests/tool-wear-restart/tool.tbl.original | 2 + - tests/tool-wear-task/.gitignore | 4 + - tests/tool-wear-task/checkresult | 2 + - tests/tool-wear-task/remap.py | 15 + - tests/tool-wear-task/test-ui.py | 297 +++++++++++++++ - tests/tool-wear-task/test.sh | 10 + - tests/tool-wear-task/tool.tbl.original | 2 + - tests/tool-wear-task/toplevel.py | 1 + - tests/toolchanger/m61/test-ui.py | 28 +- + tests/toolchanger/m61/test-ui.py | 28 ++- .../nonrandom/expected-gcode-output | 12 +- .../random/expected-gcode-output | 12 +- - 112 files changed, 2368 insertions(+), 286 deletions(-) - create mode 100644 tests/interp/tool-line-length/expected - create mode 100644 tests/interp/tool-line-length/missing-t2.ngc - create mode 100644 tests/interp/tool-line-length/missing-t3.ngc - create mode 100644 tests/interp/tool-line-length/missing-t4.ngc - create mode 100644 tests/interp/tool-line-length/test.ngc - create mode 100755 tests/interp/tool-line-length/test.sh - create mode 100644 tests/interp/tool-line-length/test.tbl - 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-m61-comp.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 - create mode 100644 tests/tool-line-length-save/.gitignore - create mode 100755 tests/tool-line-length-save/checkresult - create mode 100755 tests/tool-line-length-save/make-table.py - create mode 100755 tests/tool-line-length-save/random-ui.py - create mode 100755 tests/tool-line-length-save/test-ui.py - create mode 100755 tests/tool-line-length-save/test.sh - create mode 100644 tests/tool-wear-abort/.gitignore - create mode 100644 tests/tool-wear-abort/change-move.ngc - create mode 100644 tests/tool-wear-abort/change-then-end.ngc - create mode 100755 tests/tool-wear-abort/checkresult - create mode 100644 tests/tool-wear-abort/core_sim_handshake.hal - create mode 100644 tests/tool-wear-abort/interp-error-m6.ngc - create mode 100644 tests/tool-wear-abort/move-origin.ngc - create mode 100644 tests/tool-wear-abort/postgui.hal - create mode 100644 tests/tool-wear-abort/readahead-g43.ngc - create mode 100644 tests/tool-wear-abort/readahead-m61.ngc - create mode 100755 tests/tool-wear-abort/test-ui.py - create mode 100755 tests/tool-wear-abort/test.sh - create mode 100644 tests/tool-wear-abort/tool.tbl.original - create mode 100644 tests/tool-wear-common/lathe.ini.in - create mode 100755 tests/tool-wear-common/make-ini.sh - create mode 100644 tests/tool-wear-restart/.gitignore - create mode 100755 tests/tool-wear-restart/checkresult - create mode 100644 tests/tool-wear-restart/common.py - create mode 100755 tests/tool-wear-restart/run1.py - create mode 100755 tests/tool-wear-restart/run2.py - create mode 100755 tests/tool-wear-restart/test.sh - create mode 100644 tests/tool-wear-restart/tool.tbl.original - create mode 100644 tests/tool-wear-task/.gitignore - create mode 100755 tests/tool-wear-task/checkresult - create mode 100644 tests/tool-wear-task/remap.py - create mode 100755 tests/tool-wear-task/test-ui.py - create mode 100755 tests/tool-wear-task/test.sh - create mode 100644 tests/tool-wear-task/tool.tbl.original - create mode 100644 tests/tool-wear-task/toplevel.py + 59 files changed, 937 insertions(+), 286 deletions(-) diff --git a/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini b/configs/sim/gmoccapy/gmoccapy_tool_sensor.ini index 37daf10..bbcdfc2 100644 @@ -2763,348 +2657,6 @@ index 488e01b..d94d652 100644 N..... SET_SPINDLE_SPEED(0, 800.0000) N..... START_SPINDLE_CLOCKWISE(0) N..... DWELL(1.0000) -diff --git a/tests/interp/tool-line-length/expected b/tests/interp/tool-line-length/expected -new file mode 100644 -index 0000000..43d9c1a ---- /dev/null -+++ b/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/tests/interp/tool-line-length/missing-t2.ngc b/tests/interp/tool-line-length/missing-t2.ngc -new file mode 100644 -index 0000000..a05d8bd ---- /dev/null -+++ b/tests/interp/tool-line-length/missing-t2.ngc -@@ -0,0 +1,3 @@ -+g21 -+g43 h2 -+m2 -diff --git a/tests/interp/tool-line-length/missing-t3.ngc b/tests/interp/tool-line-length/missing-t3.ngc -new file mode 100644 -index 0000000..c7e3b12 ---- /dev/null -+++ b/tests/interp/tool-line-length/missing-t3.ngc -@@ -0,0 +1,3 @@ -+g21 -+g43 h3 -+m2 -diff --git a/tests/interp/tool-line-length/missing-t4.ngc b/tests/interp/tool-line-length/missing-t4.ngc -new file mode 100644 -index 0000000..369efa7 ---- /dev/null -+++ b/tests/interp/tool-line-length/missing-t4.ngc -@@ -0,0 +1,3 @@ -+g21 -+g43 h4 -+m2 -diff --git a/tests/interp/tool-line-length/test.ngc b/tests/interp/tool-line-length/test.ngc -new file mode 100644 -index 0000000..aea66da ---- /dev/null -+++ b/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/tests/interp/tool-line-length/test.sh b/tests/interp/tool-line-length/test.sh -new file mode 100755 -index 0000000..0822c76 ---- /dev/null -+++ b/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/tests/interp/tool-line-length/test.tbl b/tests/interp/tool-line-length/test.tbl -new file mode 100644 -index 0000000..134455e ---- /dev/null -+++ b/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/tests/interp/tool-wear/expected b/tests/interp/tool-wear/expected -new file mode 100644 -index 0000000..e9e62dc ---- /dev/null -+++ b/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/tests/interp/tool-wear/invalid-i.ngc b/tests/interp/tool-wear/invalid-i.ngc -new file mode 100644 -index 0000000..3ee52a2 ---- /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 0000000..3613d39 ---- /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-m61-comp.ngc b/tests/interp/tool-wear/invalid-m61-comp.ngc -new file mode 100644 -index 0000000..1f2d11a ---- /dev/null -+++ b/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/tests/interp/tool-wear/invalid-missing-tool.ngc b/tests/interp/tool-wear/invalid-missing-tool.ngc -new file mode 100644 -index 0000000..c9cf799 ---- /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 0000000..c995e9b ---- /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 0000000..8ef7a87 ---- /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 0000000..3a172d8 ---- /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 0000000..fb5f4d5 ---- /dev/null -+++ b/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 tests/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/tests/interp/tool-wear/test.sh b/tests/interp/tool-wear/test.sh -new file mode 100755 -index 0000000..955dbcd ---- /dev/null -+++ b/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/tests/interp/tool-wear/test.tbl b/tests/interp/tool-wear/test.tbl -new file mode 100644 -index 0000000..1a6d140 ---- /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 2f33b4b..7655928 100644 --- a/tests/remap/introspect/expected @@ -3261,1413 +2813,6 @@ index 42fe939..2814fe0 100755 # if we get here it all worked! sys.exit(0) - -diff --git a/tests/tool-line-length-save/.gitignore b/tests/tool-line-length-save/.gitignore -new file mode 100644 -index 0000000..61ad1bd ---- /dev/null -+++ b/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/tests/tool-line-length-save/checkresult b/tests/tool-line-length-save/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/tool-line-length-save/make-table.py b/tests/tool-line-length-save/make-table.py -new file mode 100755 -index 0000000..624f03b ---- /dev/null -+++ b/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/tests/tool-line-length-save/random-ui.py b/tests/tool-line-length-save/random-ui.py -new file mode 100755 -index 0000000..35b3c18 ---- /dev/null -+++ b/tests/tool-line-length-save/random-ui.py -@@ -0,0 +1,62 @@ -+#!/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("*** all checks passed") -+sys.exit(0) -diff --git a/tests/tool-line-length-save/test-ui.py b/tests/tool-line-length-save/test-ui.py -new file mode 100755 -index 0000000..08ce5ff ---- /dev/null -+++ b/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/tests/tool-line-length-save/test.sh b/tests/tool-line-length-save/test.sh -new file mode 100755 -index 0000000..346c022 ---- /dev/null -+++ b/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/tests/tool-wear-abort/.gitignore b/tests/tool-wear-abort/.gitignore -new file mode 100644 -index 0000000..09798bf ---- /dev/null -+++ b/tests/tool-wear-abort/.gitignore -@@ -0,0 +1,4 @@ -+sim.var -+sim.var.bak -+tool.tbl -+lathe.ini -diff --git a/tests/tool-wear-abort/change-move.ngc b/tests/tool-wear-abort/change-move.ngc -new file mode 100644 -index 0000000..df79eee ---- /dev/null -+++ b/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/tests/tool-wear-abort/change-then-end.ngc b/tests/tool-wear-abort/change-then-end.ngc -new file mode 100644 -index 0000000..e02acfd ---- /dev/null -+++ b/tests/tool-wear-abort/change-then-end.ngc -@@ -0,0 +1,3 @@ -+G21 G90 -+T2 M6 -+M2 -diff --git a/tests/tool-wear-abort/checkresult b/tests/tool-wear-abort/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/tool-wear-abort/core_sim_handshake.hal b/tests/tool-wear-abort/core_sim_handshake.hal -new file mode 100644 -index 0000000..b1fdce4 ---- /dev/null -+++ b/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/tests/tool-wear-abort/interp-error-m6.ngc b/tests/tool-wear-abort/interp-error-m6.ngc -new file mode 100644 -index 0000000..ac36eff ---- /dev/null -+++ b/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/tests/tool-wear-abort/move-origin.ngc b/tests/tool-wear-abort/move-origin.ngc -new file mode 100644 -index 0000000..1d66847 ---- /dev/null -+++ b/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/tests/tool-wear-abort/postgui.hal b/tests/tool-wear-abort/postgui.hal -new file mode 100644 -index 0000000..114712d ---- /dev/null -+++ b/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/tests/tool-wear-abort/readahead-g43.ngc b/tests/tool-wear-abort/readahead-g43.ngc -new file mode 100644 -index 0000000..b0ab68c ---- /dev/null -+++ b/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/tests/tool-wear-abort/readahead-m61.ngc b/tests/tool-wear-abort/readahead-m61.ngc -new file mode 100644 -index 0000000..e9fa7e5 ---- /dev/null -+++ b/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/tests/tool-wear-abort/test-ui.py b/tests/tool-wear-abort/test-ui.py -new file mode 100755 -index 0000000..be0836e ---- /dev/null -+++ b/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/tests/tool-wear-abort/test.sh b/tests/tool-wear-abort/test.sh -new file mode 100755 -index 0000000..c7ee908 ---- /dev/null -+++ b/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/tests/tool-wear-abort/tool.tbl.original b/tests/tool-wear-abort/tool.tbl.original -new file mode 100644 -index 0000000..1026231 ---- /dev/null -+++ b/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/tests/tool-wear-common/lathe.ini.in b/tests/tool-wear-common/lathe.ini.in -new file mode 100644 -index 0000000..b4d12ae ---- /dev/null -+++ b/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/tests/tool-wear-common/make-ini.sh b/tests/tool-wear-common/make-ini.sh -new file mode 100755 -index 0000000..2e1b1f2 ---- /dev/null -+++ b/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/tests/tool-wear-restart/.gitignore b/tests/tool-wear-restart/.gitignore -new file mode 100644 -index 0000000..99ef76e ---- /dev/null -+++ b/tests/tool-wear-restart/.gitignore -@@ -0,0 +1,5 @@ -+sim.var -+sim.var.bak -+tool.tbl -+run1.ini -+run2.ini -diff --git a/tests/tool-wear-restart/checkresult b/tests/tool-wear-restart/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/tool-wear-restart/common.py b/tests/tool-wear-restart/common.py -new file mode 100644 -index 0000000..ed5a426 ---- /dev/null -+++ b/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/tests/tool-wear-restart/run1.py b/tests/tool-wear-restart/run1.py -new file mode 100755 -index 0000000..3523810 ---- /dev/null -+++ b/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/tests/tool-wear-restart/run2.py b/tests/tool-wear-restart/run2.py -new file mode 100755 -index 0000000..5feff1a ---- /dev/null -+++ b/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/tests/tool-wear-restart/test.sh b/tests/tool-wear-restart/test.sh -new file mode 100755 -index 0000000..72a85fd ---- /dev/null -+++ b/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/tests/tool-wear-restart/tool.tbl.original b/tests/tool-wear-restart/tool.tbl.original -new file mode 100644 -index 0000000..1026231 ---- /dev/null -+++ b/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/tests/tool-wear-task/.gitignore b/tests/tool-wear-task/.gitignore -new file mode 100644 -index 0000000..09798bf ---- /dev/null -+++ b/tests/tool-wear-task/.gitignore -@@ -0,0 +1,4 @@ -+sim.var -+sim.var.bak -+tool.tbl -+lathe.ini -diff --git a/tests/tool-wear-task/checkresult b/tests/tool-wear-task/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/tool-wear-task/remap.py b/tests/tool-wear-task/remap.py -new file mode 100644 -index 0000000..05e1a69 ---- /dev/null -+++ b/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/tests/tool-wear-task/test-ui.py b/tests/tool-wear-task/test-ui.py -new file mode 100755 -index 0000000..a6a6fd6 ---- /dev/null -+++ b/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/tests/tool-wear-task/test.sh b/tests/tool-wear-task/test.sh -new file mode 100755 -index 0000000..f5f4988 ---- /dev/null -+++ b/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/tests/tool-wear-task/tool.tbl.original b/tests/tool-wear-task/tool.tbl.original -new file mode 100644 -index 0000000..feb7fa0 ---- /dev/null -+++ b/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/tests/tool-wear-task/toplevel.py b/tests/tool-wear-task/toplevel.py -new file mode 100644 -index 0000000..0dc38fa ---- /dev/null -+++ b/tests/tool-wear-task/toplevel.py -@@ -0,0 +1 @@ -+import remap diff --git a/tests/toolchanger/m61/test-ui.py b/tests/toolchanger/m61/test-ui.py index 025cc58..8514d33 100755 --- a/tests/toolchanger/m61/test-ui.py diff --git a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch index e8a0369..69eb506 100644 --- a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch +++ b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch @@ -16,43 +16,13 @@ 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 | 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 + - tests/g76-tapered-pitch/README | 34 ++ - tests/g76-tapered-pitch/checkresult | 2 + - tests/g76-tapered-pitch/core_sim.hal | 18 + - tests/g76-tapered-pitch/test-ui.py | 173 +++++++ - tests/g76-tapered-pitch/test.ini | 67 +++ - tests/g76-tapered-pitch/test.sh | 3 + - tests/interp/g76-tapered/README | 14 + - .../g76-tapered/alternating-z-range.ngc | 31 ++ - tests/interp/g76-tapered/expected | 424 ++++++++++++++++++ - .../interp/g76-tapered/invalid-both-modes.ngc | 5 + - tests/interp/g76-tapered/invalid-d.ngc | 5 + - tests/interp/g76-tapered/invalid-y.ngc | 5 + - tests/interp/g76-tapered/invalid-zero-z.ngc | 5 + - tests/interp/g76-tapered/test.ngc | 67 +++ - tests/interp/g76-tapered/test.sh | 54 +++ - 21 files changed, 1200 insertions(+), 47 deletions(-) - create mode 100644 tests/g76-tapered-pitch/README - create mode 100755 tests/g76-tapered-pitch/checkresult - create mode 100644 tests/g76-tapered-pitch/core_sim.hal - create mode 100755 tests/g76-tapered-pitch/test-ui.py - create mode 100644 tests/g76-tapered-pitch/test.ini - create mode 100755 tests/g76-tapered-pitch/test.sh - create mode 100644 tests/interp/g76-tapered/README - create mode 100644 tests/interp/g76-tapered/alternating-z-range.ngc - create mode 100644 tests/interp/g76-tapered/expected - create mode 100644 tests/interp/g76-tapered/invalid-both-modes.ngc - create mode 100644 tests/interp/g76-tapered/invalid-d.ngc - create mode 100644 tests/interp/g76-tapered/invalid-y.ngc - create mode 100644 tests/interp/g76-tapered/invalid-zero-z.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 f8f9d01..6f196b6 100644 @@ -586,1000 +556,3 @@ index e834041..2fb074a 100644 int convert_tool_change(setup_pointer settings); int convert_tool_length_offset(int g_code, block_pointer block, setup_pointer settings); -diff --git a/tests/g76-tapered-pitch/README b/tests/g76-tapered-pitch/README -new file mode 100644 -index 0000000..ff9a863 ---- /dev/null -+++ b/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/tests/g76-tapered-pitch/checkresult b/tests/g76-tapered-pitch/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/g76-tapered-pitch/core_sim.hal b/tests/g76-tapered-pitch/core_sim.hal -new file mode 100644 -index 0000000..47884cf ---- /dev/null -+++ b/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/tests/g76-tapered-pitch/test-ui.py b/tests/g76-tapered-pitch/test-ui.py -new file mode 100755 -index 0000000..38ac4f5 ---- /dev/null -+++ b/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/tests/g76-tapered-pitch/test.ini b/tests/g76-tapered-pitch/test.ini -new file mode 100644 -index 0000000..8c04f36 ---- /dev/null -+++ b/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/tests/g76-tapered-pitch/test.sh b/tests/g76-tapered-pitch/test.sh -new file mode 100755 -index 0000000..411ae8c ---- /dev/null -+++ b/tests/g76-tapered-pitch/test.sh -@@ -0,0 +1,3 @@ -+#!/bin/bash -e -+ -+linuxcnc -r test.ini -diff --git a/tests/interp/g76-tapered/README b/tests/interp/g76-tapered/README -new file mode 100644 -index 0000000..14964ef ---- /dev/null -+++ b/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 tests/g76-tapered-pitch. -diff --git a/tests/interp/g76-tapered/alternating-z-range.ngc b/tests/interp/g76-tapered/alternating-z-range.ngc -new file mode 100644 -index 0000000..979eccd ---- /dev/null -+++ b/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/tests/interp/g76-tapered/expected b/tests/interp/g76-tapered/expected -new file mode 100644 -index 0000000..ab05650 ---- /dev/null -+++ b/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/tests/interp/g76-tapered/invalid-both-modes.ngc b/tests/interp/g76-tapered/invalid-both-modes.ngc -new file mode 100644 -index 0000000..110edb2 ---- /dev/null -+++ b/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/tests/interp/g76-tapered/invalid-d.ngc b/tests/interp/g76-tapered/invalid-d.ngc -new file mode 100644 -index 0000000..c6a6349 ---- /dev/null -+++ b/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/tests/interp/g76-tapered/invalid-y.ngc b/tests/interp/g76-tapered/invalid-y.ngc -new file mode 100644 -index 0000000..f79aa85 ---- /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/invalid-zero-z.ngc b/tests/interp/g76-tapered/invalid-zero-z.ngc -new file mode 100644 -index 0000000..9384803 ---- /dev/null -+++ b/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/tests/interp/g76-tapered/test.ngc b/tests/interp/g76-tapered/test.ngc -new file mode 100644 -index 0000000..46d331b ---- /dev/null -+++ b/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/tests/interp/g76-tapered/test.sh b/tests/interp/g76-tapered/test.sh -new file mode 100644 -index 0000000..73b58bc ---- /dev/null -+++ b/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-patches/0009-threading-stop-clear-and-pass-stepping.patch b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch index d5f3219..2e58c27 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -20,54 +20,30 @@ 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 | 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 | 203 ++++++++++- - src/emc/tp/tp.h | 3 +- - src/emc/tp/tp_types.h | 16 +- - tests/interp/compile/use-rs274.cc | 5 + - tests/resumable-stop/README | 16 + - .../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 + - tests/resumable-stop/g76-step/checkresult | 2 +- - tests/resumable-stop/g76-step/scenarios | 4 + - tests/resumable-stop/g76-stop/checkresult | 2 +- - tests/resumable-stop/g76-stop/scenarios | 3 + - .../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/run-scenarios.sh | 10 + - tests/resumable-stop/test-ui.py | 330 +++++++++++++++++- - tests/resumable-stop/test.ini | 1 + - tests/resumable-stop/threading/checkresult | 2 +- - tests/resumable-stop/threading/scenarios | 1 + - 40 files changed, 902 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 | 203 +++++++++++++++++++++++++++-- + src/emc/tp/tp.h | 3 +- + src/emc/tp/tp_types.h | 16 ++- + tests/interp/compile/use-rs274.cc | 5 + + 23 files changed, 496 insertions(+), 51 deletions(-) diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc index 6f196b6..3b3d18c 100644 @@ -1375,583 +1351,3 @@ index e30cc2f..6afd929 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 137bc85..a322d37 100644 ---- a/tests/resumable-stop/README -+++ b/tests/resumable-stop/README -@@ -70,3 +70,19 @@ barrier, and queued-g33 drops and restores at-speed after Resume as a - spindle would while spinning up. - 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. -+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/tests/resumable-stop/g33-followed-by-rapid.ngc b/tests/resumable-stop/g33-followed-by-rapid.ngc -new file mode 100644 -index 0000000..a12bcb3 ---- /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 0000000..5b04e69 ---- /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 0000000..01a62a2 ---- /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 0000000..c8ee28f ---- /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-step/checkresult b/tests/resumable-stop/g76-step/checkresult -index 55a8859..92d147c 100755 ---- a/tests/resumable-stop/g76-step/checkresult -+++ b/tests/resumable-stop/g76-step/checkresult -@@ -1,2 +1,2 @@ - #!/bin/sh --exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 1 -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 5 -diff --git a/tests/resumable-stop/g76-step/scenarios b/tests/resumable-stop/g76-step/scenarios -index f0a4053..576921d 100644 ---- a/tests/resumable-stop/g76-step/scenarios -+++ b/tests/resumable-stop/g76-step/scenarios -@@ -1 +1,5 @@ -+g76-single-step -+g76-tapered-single-step -+g76-exit-taper -+g76-tapered-exit-taper - trapezoidal:fperrev -diff --git a/tests/resumable-stop/g76-stop/checkresult b/tests/resumable-stop/g76-stop/checkresult -index 30bd373..92d147c 100755 ---- a/tests/resumable-stop/g76-stop/checkresult -+++ b/tests/resumable-stop/g76-stop/checkresult -@@ -1,2 +1,2 @@ - #!/bin/sh --exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 2 -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 5 -diff --git a/tests/resumable-stop/g76-stop/scenarios b/tests/resumable-stop/g76-stop/scenarios -index bea05471..e39cc37 100644 ---- a/tests/resumable-stop/g76-stop/scenarios -+++ b/tests/resumable-stop/g76-stop/scenarios -@@ -1,2 +1,5 @@ -+g76-handoff-stress - g76 -+g76-tapered -+g76-waiting-index - fperrev -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 0000000..488d2a9 ---- /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 0000000..241f777 ---- /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 0000000..b0eb997 ---- /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/run-scenarios.sh b/tests/resumable-stop/run-scenarios.sh -index c756dd3..f572282 100755 ---- a/tests/resumable-stop/run-scenarios.sh -+++ b/tests/resumable-stop/run-scenarios.sh -@@ -16,6 +16,16 @@ 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; } -diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index 4cf91ee..83dfcc5 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,32 @@ 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() if callable(message) else message) -+ 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): -@@ -480,6 +499,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) -@@ -544,9 +598,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] - ) - -@@ -565,6 +619,264 @@ 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_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") -@@ -1465,8 +1777,16 @@ SCENARIOS = { - "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-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 a422788..96b5a38 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/threading/checkresult b/tests/resumable-stop/threading/checkresult -index e619f41..0201d4f 100755 ---- a/tests/resumable-stop/threading/checkresult -+++ b/tests/resumable-stop/threading/checkresult -@@ -1,2 +1,2 @@ - #!/bin/sh --exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 8 -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 9 -diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios -index 9fdbe0c..0f41046 100644 ---- a/tests/resumable-stop/threading/scenarios -+++ b/tests/resumable-stop/threading/scenarios -@@ -5,4 +5,5 @@ g33-chain - trapezoidal:g33-chain - step-resume-stopping - g95-between-g33 -+g33-no-following-rapid - command-after-sync 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 4758657..1facc4b 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 @@ -11,37 +11,12 @@ 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 | 24 ++- - 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 | 12 ++ - tests/resumable-stop/after-tap-m5.ngc | 2 +- - tests/resumable-stop/after-thread-m5.ngc | 2 +- - tests/resumable-stop/after-thread-m9.ngc | 2 +- - tests/resumable-stop/after-thread-s.ngc | 2 +- - tests/resumable-stop/css.ngc | 2 +- - tests/resumable-stop/g76-step/checkresult | 2 +- - tests/resumable-stop/g76-step/scenarios | 1 + - tests/resumable-stop/general/checkresult | 2 +- - tests/resumable-stop/general/scenarios | 4 + - tests/resumable-stop/inflight-step.ngc | 7 + - tests/resumable-stop/multi-spindle.ngc | 2 +- - tests/resumable-stop/orient.ngc | 2 +- - tests/resumable-stop/rapid-then-feed.ngc | 2 +- - tests/resumable-stop/resume-s0.ngc | 7 + - tests/resumable-stop/tap.ngc | 6 +- - tests/resumable-stop/test-ui.py | 237 +++++++++++++++++++++ - tests/resumable-stop/test.ngc | 2 +- - tests/resumable-stop/thread-g95-thread.ngc | 2 +- - tests/resumable-stop/thread-then-steps.ngc | 4 +- - tests/resumable-stop/thread.ngc | 6 +- - tests/resumable-stop/threading/checkresult | 2 +- - tests/resumable-stop/threading/scenarios | 2 + - 28 files changed, 407 insertions(+), 72 deletions(-) - create mode 100644 tests/resumable-stop/inflight-step.ngc - create mode 100644 tests/resumable-stop/resume-s0.ngc + src/emc/motion/command.c | 24 +++++++---- + 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 ++- + 5 files changed, 116 insertions(+), 51 deletions(-) diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c index a8e8ae3..ff48890 100644 @@ -433,563 +408,3 @@ index 2963bcc..819f508 100644 } TP_STRUCT; -diff --git a/tests/resumable-stop/README b/tests/resumable-stop/README -index a322d37..6c8eb25 100644 ---- a/tests/resumable-stop/README -+++ b/tests/resumable-stop/README -@@ -68,6 +68,12 @@ 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 -@@ -82,6 +88,12 @@ 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/after-tap-m5.ngc b/tests/resumable-stop/after-tap-m5.ngc -index f8fa1b5..c6a6868 100644 ---- a/tests/resumable-stop/after-tap-m5.ngc -+++ b/tests/resumable-stop/after-tap-m5.ngc -@@ -3,5 +3,5 @@ G0 X0 Z0 - S300 M3 - G33.1 Z-5 K1 - M5 --G1 X5 F60 -+G1 X5 F300 - M2 -diff --git a/tests/resumable-stop/after-thread-m5.ngc b/tests/resumable-stop/after-thread-m5.ngc -index db6cb3d..e96d6e6 100644 ---- a/tests/resumable-stop/after-thread-m5.ngc -+++ b/tests/resumable-stop/after-thread-m5.ngc -@@ -3,5 +3,5 @@ G0 X0 Z0 - S300 M3 - G33 Z-10 K1 - M5 --G1 X5 F60 -+G1 X5 F300 - M2 -diff --git a/tests/resumable-stop/after-thread-m9.ngc b/tests/resumable-stop/after-thread-m9.ngc -index 30b558d..cfbf687 100644 ---- a/tests/resumable-stop/after-thread-m9.ngc -+++ b/tests/resumable-stop/after-thread-m9.ngc -@@ -4,5 +4,5 @@ M8 - S300 M3 - G33 Z-10 K1 - M9 --G1 X5 F60 -+G1 X5 F300 - M2 -diff --git a/tests/resumable-stop/after-thread-s.ngc b/tests/resumable-stop/after-thread-s.ngc -index 336d6be..6e468d1 100644 ---- a/tests/resumable-stop/after-thread-s.ngc -+++ b/tests/resumable-stop/after-thread-s.ngc -@@ -3,5 +3,5 @@ G0 X0 Z0 - S300 M3 - G33 Z-10 K1 - S500 --G1 X5 F60 -+G1 X5 F300 - M2 -diff --git a/tests/resumable-stop/css.ngc b/tests/resumable-stop/css.ngc -index 382aaff..8a70da2 100644 ---- a/tests/resumable-stop/css.ngc -+++ b/tests/resumable-stop/css.ngc -@@ -1,6 +1,6 @@ - G21 G18 G90 - G0 X20 Z0 - G96 D1000 S60 M3 --G1 X10 F60 -+G1 X10 F150 - M5 - M2 -diff --git a/tests/resumable-stop/g76-step/checkresult b/tests/resumable-stop/g76-step/checkresult -index 92d147c..0562404 100755 ---- a/tests/resumable-stop/g76-step/checkresult -+++ b/tests/resumable-stop/g76-step/checkresult -@@ -1,2 +1,2 @@ - #!/bin/sh --exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 5 -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 6 -diff --git a/tests/resumable-stop/g76-step/scenarios b/tests/resumable-stop/g76-step/scenarios -index 576921d..df2a2ab 100644 ---- a/tests/resumable-stop/g76-step/scenarios -+++ b/tests/resumable-stop/g76-step/scenarios -@@ -1,5 +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/tests/resumable-stop/general/checkresult b/tests/resumable-stop/general/checkresult -index 2d7e132..362de54 100755 ---- a/tests/resumable-stop/general/checkresult -+++ b/tests/resumable-stop/general/checkresult -@@ -1,2 +1,2 @@ - #!/bin/sh --exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 20 -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 24 -diff --git a/tests/resumable-stop/general/scenarios b/tests/resumable-stop/general/scenarios -index f3792d2..d8e2870 100644 ---- a/tests/resumable-stop/general/scenarios -+++ b/tests/resumable-stop/general/scenarios -@@ -3,6 +3,7 @@ ordinary - trapezoidal:ordinary - single-step - trapezoidal:single-step -+inflight-single-step - rapid-no-atspeed - paused-resume - paused-run -@@ -18,3 +19,6 @@ speed-change-atspeed - queued-feed-atspeed - spindle-state - resume-atspeed -+pause-starting -+resume-s0 -+pause-inflight-step -diff --git a/tests/resumable-stop/inflight-step.ngc b/tests/resumable-stop/inflight-step.ngc -new file mode 100644 -index 0000000..1f72544 ---- /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/tests/resumable-stop/multi-spindle.ngc b/tests/resumable-stop/multi-spindle.ngc -index ba2e66f..3811387 100644 ---- a/tests/resumable-stop/multi-spindle.ngc -+++ b/tests/resumable-stop/multi-spindle.ngc -@@ -1,4 +1,4 @@ - G21 G90 - G0 X0 --G1 X10 F60 -+G1 X10 F150 - M2 -diff --git a/tests/resumable-stop/orient.ngc b/tests/resumable-stop/orient.ngc -index bb08db3..6927a71 100644 ---- a/tests/resumable-stop/orient.ngc -+++ b/tests/resumable-stop/orient.ngc -@@ -2,5 +2,5 @@ G21 G90 - G0 X0 - M19 R90 P1 Q30 - M19 R180 P0 Q1 --G1 X20 F60 -+G1 X20 F600 - M2 -diff --git a/tests/resumable-stop/rapid-then-feed.ngc b/tests/resumable-stop/rapid-then-feed.ngc -index c562a57..531480c 100644 ---- a/tests/resumable-stop/rapid-then-feed.ngc -+++ b/tests/resumable-stop/rapid-then-feed.ngc -@@ -2,6 +2,6 @@ G21 G90 - F60 - S300 M3 - G0 X80 --G1 X90 -+G1 X90 F300 - M5 - M2 -diff --git a/tests/resumable-stop/resume-s0.ngc b/tests/resumable-stop/resume-s0.ngc -new file mode 100644 -index 0000000..69d6ce7 ---- /dev/null -+++ b/tests/resumable-stop/resume-s0.ngc -@@ -0,0 +1,7 @@ -+G21 G90 -+G0 X0 -+F60 -+S0 M3 -+G1 X4 -+M5 -+M2 -diff --git a/tests/resumable-stop/tap.ngc b/tests/resumable-stop/tap.ngc -index 3060ac4..2182f18 100644 ---- a/tests/resumable-stop/tap.ngc -+++ b/tests/resumable-stop/tap.ngc -@@ -1,7 +1,7 @@ - G21 G90 - G0 X0 Z0 --S6 M3 --G33.1 Z-5 K10 --G1 X10 F60 -+S60 M3 -+G33.1 Z-5 K1 -+G1 X10 F600 - M5 - M2 -diff --git a/tests/resumable-stop/test-ui.py b/tests/resumable-stop/test-ui.py -index 83dfcc5..ec9e072 100755 ---- a/tests/resumable-stop/test-ui.py -+++ b/tests/resumable-stop/test-ui.py -@@ -263,6 +263,74 @@ def run_stop_single_step_test(): - 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_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") -@@ -792,6 +860,48 @@ def run_tapered_g76_single_step_test(): - "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) -@@ -1288,6 +1398,124 @@ def run_resume_atspeed_wait_test(): - 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_cancel_latched_resume_test(label, cancel): -+ # Resume during STOPPING is latched until Stop completes; a Pause or a -+ # second Stop after it cancels the latched Resume, so the program stays -+ # STOPPED. -+ 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.auto(linuxcnc.AUTO_RESUME) -+ cancel() -+ s.poll() -+ if s.stop_state != linuxcnc.STOP_STOPPING: -+ fail("G33 finished before Resume and %s were sent" % label) -+ -+ wait_for( -+ lambda: s.stop_state == linuxcnc.STOP_STOPPED -+ and math.isclose(s.position[2], -5.0, abs_tol=0.01), -+ lambda: "%s after latched Resume did not leave the program " -+ "STOPPED: 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("%s after latched Resume: program left STOPPED" % label) -+ if hal.get_value("spindle.0.on"): -+ fail("%s after latched Resume: spindle on while STOPPED" % label) -+ if abs(s.position[0]) > 0.001: -+ fail("%s after latched Resume: 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) -@@ -1771,6 +1999,7 @@ 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), -@@ -1784,6 +2013,7 @@ SCENARIOS = { - "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, -@@ -1793,6 +2023,13 @@ SCENARIOS = { - "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, -+ "pause-latched-resume": lambda: run_cancel_latched_resume_test( -+ "Pause", lambda: c.auto(linuxcnc.AUTO_PAUSE)), -+ "stop-latched-resume": lambda: run_cancel_latched_resume_test( -+ "Stop", c.program_stop), -+ "pause-inflight-step": run_pause_inflight_single_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, -diff --git a/tests/resumable-stop/test.ngc b/tests/resumable-stop/test.ngc -index 416044b..c44a2cd 100644 ---- a/tests/resumable-stop/test.ngc -+++ b/tests/resumable-stop/test.ngc -@@ -1,6 +1,6 @@ - G21 G90 - G0 X0 --F60 -+F150 - S300 M3 - M8 - G1 X10 -diff --git a/tests/resumable-stop/thread-g95-thread.ngc b/tests/resumable-stop/thread-g95-thread.ngc -index d6630aa..2bc7489 100644 ---- a/tests/resumable-stop/thread-g95-thread.ngc -+++ b/tests/resumable-stop/thread-g95-thread.ngc -@@ -4,6 +4,6 @@ S60 M3 - G33 Z-2 K1 - G95 G1 X1 F0.5 - G33 Z-4 K1 --G94 G1 X10 F60 -+G94 G1 X10 F600 - M5 - M2 -diff --git a/tests/resumable-stop/thread-then-steps.ngc b/tests/resumable-stop/thread-then-steps.ngc -index e744543..44aa11e 100644 ---- a/tests/resumable-stop/thread-then-steps.ngc -+++ b/tests/resumable-stop/thread-then-steps.ngc -@@ -1,7 +1,7 @@ - G21 G90 - G0 X0 Z0 --S6 M3 --G33 Z-5 K10 -+S60 M3 -+G33 Z-5 K1 - G1 X5 F600 - M8 - G1 X10 -diff --git a/tests/resumable-stop/thread.ngc b/tests/resumable-stop/thread.ngc -index 5976979..c3ec6d0 100644 ---- a/tests/resumable-stop/thread.ngc -+++ b/tests/resumable-stop/thread.ngc -@@ -1,7 +1,7 @@ - G21 G90 - G0 X0 Z0 --S6 M3 --G33 Z-5 K10 --G1 X10 F60 -+S60 M3 -+G33 Z-5 K1 -+G1 X10 F600 - M5 - M2 -diff --git a/tests/resumable-stop/threading/checkresult b/tests/resumable-stop/threading/checkresult -index 0201d4f..664eed8 100755 ---- a/tests/resumable-stop/threading/checkresult -+++ b/tests/resumable-stop/threading/checkresult -@@ -1,2 +1,2 @@ - #!/bin/sh --exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 9 -+exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 11 -diff --git a/tests/resumable-stop/threading/scenarios b/tests/resumable-stop/threading/scenarios -index 0f41046..a4410d4 100644 ---- a/tests/resumable-stop/threading/scenarios -+++ b/tests/resumable-stop/threading/scenarios -@@ -7,3 +7,5 @@ step-resume-stopping - g95-between-g33 - g33-no-following-rapid - command-after-sync -+pause-latched-resume -+stop-latched-resume 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 61fd17d..187d3b3 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 @@ -32,49 +32,10 @@ tests/tooldb tests, which need a db program, are skipped. src/emc/tooldata/tooldata_common.cc | 386 ++++++++++++++---- src/emc/tooldata/tooldata_mmap.cc | 102 ++++- src/emc/tooldata/tooldata_nml.cc | 16 + - tests/tool-crud-refusal/.gitignore | 5 + - tests/tool-crud-refusal/README | 7 + - tests/tool-crud-refusal/checkresult | 2 + - tests/tool-crud-refusal/program.ngc | 2 + - tests/tool-crud-refusal/test-ui.py | 83 ++++ - tests/tool-crud-refusal/test.sh | 12 + - tests/tool-crud-refusal/tool-cmd.cc | 50 +++ - tests/tool-line-length-save/random-ui.py | 31 ++ - tests/tool-table-load/.gitignore | 6 + - tests/tool-table-load/checkresult | 2 + - tests/tool-table-load/common.py | 121 ++++++ - tests/tool-table-load/crlf-ui.py | 27 ++ - tests/tool-table-load/external-edit-ui.py | 74 ++++ - tests/tool-table-load/garbage-ui.py | 51 +++ - tests/tool-table-load/missing-ui.py | 52 +++ - tests/tool-table-load/other-table-ui.py | 33 ++ - tests/tool-table-load/random-start-ui.py | 36 ++ - tests/tool-table-load/reload-ui.py | 26 ++ - tests/tool-table-load/symlink-ui.py | 55 +++ - tests/tool-table-load/test.sh | 64 +++ .../reload-tool/non-random/test-ui.py | 14 + .../toolchanger/reload-tool/random/test-ui.py | 3 +- tests/tooldb/db-g10-offset/skip | 3 + - 33 files changed, 1685 insertions(+), 128 deletions(-) - create mode 100644 tests/tool-crud-refusal/.gitignore - create mode 100644 tests/tool-crud-refusal/README - create mode 100755 tests/tool-crud-refusal/checkresult - create mode 100644 tests/tool-crud-refusal/program.ngc - create mode 100755 tests/tool-crud-refusal/test-ui.py - create mode 100755 tests/tool-crud-refusal/test.sh - create mode 100644 tests/tool-crud-refusal/tool-cmd.cc - create mode 100644 tests/tool-table-load/.gitignore - create mode 100755 tests/tool-table-load/checkresult - create mode 100644 tests/tool-table-load/common.py - create mode 100755 tests/tool-table-load/crlf-ui.py - create mode 100755 tests/tool-table-load/external-edit-ui.py - create mode 100755 tests/tool-table-load/garbage-ui.py - create mode 100755 tests/tool-table-load/missing-ui.py - create mode 100755 tests/tool-table-load/other-table-ui.py - create mode 100755 tests/tool-table-load/random-start-ui.py - create mode 100755 tests/tool-table-load/reload-ui.py - create mode 100755 tests/tool-table-load/symlink-ui.py - create mode 100755 tests/tool-table-load/test.sh + 13 files changed, 946 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 @@ -1632,869 +1593,6 @@ index f333925..a7ee61e 100644 + memcpy(the_table, table, CANON_POCKETS_MAX * sizeof(*table)); + return 0; +} -diff --git a/tests/tool-crud-refusal/.gitignore b/tests/tool-crud-refusal/.gitignore -new file mode 100644 -index 0000000..89772f7 ---- /dev/null -+++ b/tests/tool-crud-refusal/.gitignore -@@ -0,0 +1,5 @@ -+sim.var -+sim.var.bak -+tool.tbl -+run.ini -+tool-cmd -diff --git a/tests/tool-crud-refusal/README b/tests/tool-crud-refusal/README -new file mode 100644 -index 0000000..1535c26 ---- /dev/null -+++ b/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/tests/tool-crud-refusal/checkresult b/tests/tool-crud-refusal/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/tool-crud-refusal/program.ngc b/tests/tool-crud-refusal/program.ngc -new file mode 100644 -index 0000000..1f0eacc ---- /dev/null -+++ b/tests/tool-crud-refusal/program.ngc -@@ -0,0 +1,2 @@ -+G0 X1 -+M2 -diff --git a/tests/tool-crud-refusal/test-ui.py b/tests/tool-crud-refusal/test-ui.py -new file mode 100755 -index 0000000..8d6ef70 ---- /dev/null -+++ b/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/tests/tool-crud-refusal/test.sh b/tests/tool-crud-refusal/test.sh -new file mode 100755 -index 0000000..bad1a01 ---- /dev/null -+++ b/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/tests/tool-crud-refusal/tool-cmd.cc b/tests/tool-crud-refusal/tool-cmd.cc -new file mode 100644 -index 0000000..226cf79 ---- /dev/null -+++ b/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/tests/tool-line-length-save/random-ui.py b/tests/tool-line-length-save/random-ui.py -index 35b3c18..4b2e267 100755 ---- a/tests/tool-line-length-save/random-ui.py -+++ b/tests/tool-line-length-save/random-ui.py -@@ -58,5 +58,36 @@ if s.tool_table[0].id != 1: - 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/tests/tool-table-load/.gitignore b/tests/tool-table-load/.gitignore -new file mode 100644 -index 0000000..ebe0144 ---- /dev/null -+++ b/tests/tool-table-load/.gitignore -@@ -0,0 +1,6 @@ -+sim.var -+sim.var.bak -+tool.tbl -+other.tbl -+linked/ -+run.ini -diff --git a/tests/tool-table-load/checkresult b/tests/tool-table-load/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/tool-table-load/common.py b/tests/tool-table-load/common.py -new file mode 100644 -index 0000000..fe72033 ---- /dev/null -+++ b/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/tests/tool-table-load/crlf-ui.py b/tests/tool-table-load/crlf-ui.py -new file mode 100755 -index 0000000..f2c8011 ---- /dev/null -+++ b/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/tests/tool-table-load/external-edit-ui.py b/tests/tool-table-load/external-edit-ui.py -new file mode 100755 -index 0000000..ce064c0 ---- /dev/null -+++ b/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/tests/tool-table-load/garbage-ui.py b/tests/tool-table-load/garbage-ui.py -new file mode 100755 -index 0000000..e390c5d ---- /dev/null -+++ b/tests/tool-table-load/garbage-ui.py -@@ -0,0 +1,51 @@ -+#!/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") -+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() -+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/tests/tool-table-load/missing-ui.py b/tests/tool-table-load/missing-ui.py -new file mode 100755 -index 0000000..0f44290 ---- /dev/null -+++ b/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/tests/tool-table-load/other-table-ui.py b/tests/tool-table-load/other-table-ui.py -new file mode 100755 -index 0000000..af9ba05 ---- /dev/null -+++ b/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/tests/tool-table-load/random-start-ui.py b/tests/tool-table-load/random-start-ui.py -new file mode 100755 -index 0000000..3b860d3 ---- /dev/null -+++ b/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/tests/tool-table-load/reload-ui.py b/tests/tool-table-load/reload-ui.py -new file mode 100755 -index 0000000..5e073f5 ---- /dev/null -+++ b/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/tests/tool-table-load/symlink-ui.py b/tests/tool-table-load/symlink-ui.py -new file mode 100755 -index 0000000..2e03fa7 ---- /dev/null -+++ b/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/tests/tool-table-load/test.sh b/tests/tool-table-load/test.sh -new file mode 100755 -index 0000000..c7295bc ---- /dev/null -+++ b/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/tests/toolchanger/reload-tool/non-random/test-ui.py b/tests/toolchanger/reload-tool/non-random/test-ui.py index fca46c3..445e5ee 100755 --- a/tests/toolchanger/reload-tool/non-random/test-ui.py diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index 5592078..d296327 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -25,19 +25,7 @@ instead of continuing the unwound call. src/emc/rs274ngc/interp_python.cc | 60 ++++- src/emc/rs274ngc/interp_python.hh | 7 + src/emc/rs274ngc/rs274ngc_pre.cc | 5 + - 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 ++ - 12 files changed, 816 insertions(+), 3 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 + 6 files changed, 461 insertions(+), 3 deletions(-) diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc index 75e2a09..410381a 100644 @@ -618,394 +606,3 @@ index 2ea3ba1..dea5749 100644 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 0000000..7fda879 ---- /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 0000000..0198feb ---- /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 0000000..fb9b77b ---- /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 0000000..c3ee45b ---- /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 0000000..4d496c4 ---- /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 0000000..4be91ba ---- /dev/null -+++ b/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-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 aa6fee0..cc57a7f4 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,25 +4,11 @@ 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 513c932..d6e8437 100644 @@ -77,182 +63,3 @@ index 8e91c88..f5cc454 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 0000000..66ad330 ---- /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 0000000..56f319c ---- /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 0000000..e244f00 ---- /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 0000000..2372f6c ---- /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 0000000..61ccf6b ---- /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 0000000..13436c1 ---- /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 0000000..e69de29 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 488f289..505c98e 100644 --- a/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch +++ b/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch @@ -4,27 +4,9 @@ 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 410381a..6027d2b 100644 @@ -106,144 +88,3 @@ index 286ee98..cf192c1 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 0000000..3758b4f ---- /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 0000000..518d1fe ---- /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 0000000..e5495df ---- /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 0000000..600c9a9 ---- /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 0000000..95f0e7b ---- /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 0000000..36abfcb ---- /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 0000000..b475564 ---- /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 0000000..7a38952 ---- /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 0000000..0dc38fa ---- /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 852e19c..133217a 100644 --- a/linuxcnc-patches/0016-motion-joint-target-preparation.patch +++ b/linuxcnc-patches/0016-motion-joint-target-preparation.patch @@ -4,20 +4,12 @@ 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 4cc5503..e814320 100644 @@ -286,118 +278,3 @@ index 26f1a64..c4b10cd 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 0000000..99955ca ---- /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 0000000..e69de29 -diff --git a/tests/motion-target-preparation/test.py b/tests/motion-target-preparation/test.py -new file mode 100644 -index 0000000..1fa2553 ---- /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 0000000..0cd44bb ---- /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 8529de7..dab33c3 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -54,99 +54,11 @@ other motion-logger tests. src/emc/task/task.hh | 1 + src/emc/task/taskintf.cc | 112 +++- src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + - tests/interp/g28.2/instant-home/README | 7 + - tests/interp/g28.2/instant-home/checkresult | 2 + - tests/interp/g28.2/instant-home/sim.tbl | 0 - tests/interp/g28.2/instant-home/test-ui.py | 80 +++ - tests/interp/g28.2/instant-home/test.ini | 103 ++++ - tests/interp/g28.2/instant-home/test.sh | 2 + .../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 | 22 + - .../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 | 81 +++ - .../joghome.ini.in | 6 + - .../record_abort.ngc | 6 + - .../sequence.ini.in | 6 + - .../slowtask.ini.in | 7 + - .../runtime-availability-regressions/tail.hal | 30 + - .../tail.ini.in | 7 + - .../test-ui.py | 198 ++++++ - .../test.ini.in | 3 + - .../runtime-availability-regressions/test.sh | 35 ++ - .../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 - 72 files changed, 3123 insertions(+), 103 deletions(-) - create mode 100644 tests/interp/g28.2/instant-home/README - create mode 100755 tests/interp/g28.2/instant-home/checkresult - create mode 100644 tests/interp/g28.2/instant-home/sim.tbl - create mode 100755 tests/interp/g28.2/instant-home/test-ui.py - create mode 100644 tests/interp/g28.2/instant-home/test.ini - create mode 100755 tests/interp/g28.2/instant-home/test.sh - 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/slowtask.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, 1703 insertions(+), 102 deletions(-) diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc index 2d7a99e..e93f55a 100644 @@ -3054,233 +2966,6 @@ index f5cc454..7733e39 100644 {"jog", (PyCFunction)jog, METH_VARARGS, "jog(JOG_CONTINUOUS, joint_flag, index, speed)\n" "jog(JOG_INCREMENT, joint_flag, index, speed, increment)\n" -diff --git a/tests/interp/g28.2/instant-home/README b/tests/interp/g28.2/instant-home/README -new file mode 100644 -index 0000000..277dcb5 ---- /dev/null -+++ b/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/tests/interp/g28.2/instant-home/checkresult b/tests/interp/g28.2/instant-home/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/interp/g28.2/instant-home/sim.tbl b/tests/interp/g28.2/instant-home/sim.tbl -new file mode 100644 -index 0000000..e69de29 -diff --git a/tests/interp/g28.2/instant-home/test-ui.py b/tests/interp/g28.2/instant-home/test-ui.py -new file mode 100755 -index 0000000..8643922 ---- /dev/null -+++ b/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/tests/interp/g28.2/instant-home/test.ini b/tests/interp/g28.2/instant-home/test.ini -new file mode 100644 -index 0000000..f1b2352 ---- /dev/null -+++ b/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/tests/interp/g28.2/instant-home/test.sh b/tests/interp/g28.2/instant-home/test.sh -new file mode 100755 -index 0000000..a16f6fa ---- /dev/null -+++ b/tests/interp/g28.2/instant-home/test.sh -@@ -0,0 +1,2 @@ -+#!/bin/bash -+exec linuxcnc -r test.ini 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 @@ -3664,1462 +3349,3 @@ index 8bef6b8..5741c00 100644 SS_ENABLE +ABORT DISABLE -diff --git a/tests/motion-target-preparation/README b/tests/motion-target-preparation/README -index 99955ca..7958c18 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 0000000..00099d2 ---- /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 0000000..dd4b2be ---- /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 1fa2553..8ac9a80 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 0000000..425d52b ---- /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 0000000..2a46151 ---- /dev/null -+++ b/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/tests/runtime-availability-regressions/base.ini b/tests/runtime-availability-regressions/base.ini -new file mode 100644 -index 0000000..71f455a ---- /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 0000000..153f94a ---- /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 0000000..7e0cffc ---- /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 0000000..b69d67a ---- /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 0000000..36c2c7e ---- /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 0000000..5048be9 ---- /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 0000000..b39d68b ---- /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 0000000..c4c8307 ---- /dev/null -+++ b/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/tests/runtime-availability-regressions/joghome.ini.in b/tests/runtime-availability-regressions/joghome.ini.in -new file mode 100644 -index 0000000..949adc1 ---- /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 0000000..5ca302f ---- /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 0000000..3786b15 ---- /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/slowtask.ini.in b/tests/runtime-availability-regressions/slowtask.ini.in -new file mode 100644 -index 0000000..75125d8 ---- /dev/null -+++ b/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/tests/runtime-availability-regressions/tail.hal b/tests/runtime-availability-regressions/tail.hal -new file mode 100644 -index 0000000..c9eea9d ---- /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 0000000..cdf6f94 ---- /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 0000000..c23405a ---- /dev/null -+++ b/tests/runtime-availability-regressions/test-ui.py -@@ -0,0 +1,198 @@ -+#!/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 == '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/tests/runtime-availability-regressions/test.ini.in b/tests/runtime-availability-regressions/test.ini.in -new file mode 100644 -index 0000000..67dab70 ---- /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 0000000..80bc7dd ---- /dev/null -+++ b/tests/runtime-availability-regressions/test.sh -@@ -0,0 +1,35 @@ -+#!/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 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 ;; -+ 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 0000000..a580019 ---- /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 0000000..5c7ef3f ---- /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 0000000..ada9398 ---- /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 0000000..425d52b ---- /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 0000000..bdfd8cc ---- /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 0000000..c8e0eab ---- /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 0000000..12624ae ---- /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 0000000..62edf53 ---- /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 0000000..1c30ffa ---- /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 0000000..3b9c37c ---- /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 0000000..3e7e61f ---- /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 0000000..c9e6f8a ---- /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 0000000..1f435da ---- /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 0000000..67dab70 ---- /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 0000000..9a17bf2 ---- /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 0000000..e69de29 diff --git a/linuxcnc-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index f066a68..1a25634 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -9,121 +9,21 @@ 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/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 | 12 + - 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 | 205 ++++++++++++++++++ - tests/availability-mcodes/test.ini.in | 3 + - 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 | 29 +++ - .../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 + - 64 files changed, 702 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 100644 tests/availability-mcodes/test.ini.in - 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 | 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/sai/saicanon.cc | 5 ++++ + src/emc/task/emccanon.cc | 18 +++++++++++++ + 14 files changed, 127 insertions(+), 7 deletions(-) diff --git a/docs/src/gcode/m-code.adoc b/docs/src/gcode/m-code.adoc index e74ef24..b3cdbd0 100644 @@ -481,877 +381,3 @@ index d6e8437..2276d89 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 0000000..425d52b ---- /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 0000000..3be13a3 ---- /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 0000000..14417ee ---- /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 0000000..a9bcd9e ---- /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 0000000..1cf2f53 ---- /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 0000000..bcbcb6c ---- /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 0000000..5ed42c8 ---- /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 0000000..425d52b ---- /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 0000000..bbb8ad6 ---- /dev/null -+++ b/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/tests/availability-mcodes/checkresult b/tests/availability-mcodes/checkresult -new file mode 100755 -index 0000000..1e0aa79 ---- /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 0000000..563a89b ---- /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 0000000..ca47f56 ---- /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 0000000..12b5b7a ---- /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 0000000..a180055 ---- /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 0000000..0f3d8df ---- /dev/null -+++ b/tests/availability-mcodes/test-ui.py -@@ -0,0 +1,205 @@ -+#!/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 ACK completes the -+# handshake, 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_STOPPED, 'Stop before ACK') -+ else: -+ wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED, 'Pause before ACK') -+ pin('joint.2.availability-ack', 1) -+ 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/tests/availability-mcodes/test.ini.in b/tests/availability-mcodes/test.ini.in -new file mode 100644 -index 0000000..fe357c0 ---- /dev/null -+++ b/tests/availability-mcodes/test.ini.in -@@ -0,0 +1,3 @@ -+# Uses the shared base unchanged. -+[FIXTURE] -+BASE = ../runtime-availability/base.ini -diff --git a/tests/availability-mcodes/test.sh b/tests/availability-mcodes/test.sh -new file mode 100755 -index 0000000..882b151 ---- /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 0000000..8a28c6f ---- /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 0000000..37d2571 ---- /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 0000000..e572890 ---- /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 0000000..6054ffd ---- /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 0000000..da0115c ---- /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 0000000..a851ea0 ---- /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 0000000..f2f707c ---- /dev/null -+++ b/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/tests/interp/availability-mcodes/execute-status.py b/tests/interp/availability-mcodes/execute-status.py -new file mode 100644 -index 0000000..145e482 ---- /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 0000000..e69de29 -diff --git a/tests/interp/availability-mcodes/fractional-joint.ngc b/tests/interp/availability-mcodes/fractional-joint.ngc -new file mode 100644 -index 0000000..e5488fb ---- /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 0000000..26ff05c ---- /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 0000000..3b2f3fb ---- /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 0000000..584fa3b ---- /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 0000000..6947d8a ---- /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 0000000..c48d1b9 ---- /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 0000000..96cb26c ---- /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 0000000..1a45e38 ---- /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 0000000..dd567c4 ---- /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 0000000..a52d2d4 ---- /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 0000000..1054e7e ---- /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 0000000..1d22b22 ---- /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 0000000..1cf09ae ---- /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 0000000..8fd4be9 ---- /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 0000000..6fc9e05 ---- /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 0000000..37e7a2e ---- /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 0000000..5153e91 ---- /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 0000000..dea8ef7 ---- /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 0000000..3a6b203 ---- /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 0000000..2412206 ---- /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 0000000..03afbfa ---- /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 0000000..c61548a ---- /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 0000000..d697df4 ---- /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 0000000..10632c2 ---- /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 8f4d3f7..d175c88 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -16,24 +16,12 @@ 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 | 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 +- - tests/homing-concurrent/checkresult | 3 + - tests/homing-concurrent/homing.hal | 16 ++ - tests/homing-concurrent/test-ui.py | 235 ++++++++++++++++++++++++++++ - tests/homing-concurrent/test.ini | 170 ++++++++++++++++++++ - tests/homing-concurrent/test.sh | 4 + - tests/homing-concurrent/tool.tbl | 0 - 11 files changed, 547 insertions(+), 78 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 9d6fb2c..e8a68ce 100644 @@ -509,464 +497,3 @@ index 9096469..ea04e05 100644 EXPORT_SYMBOL(get_index_enable); EXPORT_SYMBOL(read_homing_in_pins); EXPORT_SYMBOL(do_home_joint); -diff --git a/tests/homing-concurrent/checkresult b/tests/homing-concurrent/checkresult -new file mode 100755 -index 0000000..9c14eb3 ---- /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 0000000..5d4eaa3 ---- /dev/null -+++ b/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/tests/homing-concurrent/test-ui.py b/tests/homing-concurrent/test-ui.py -new file mode 100755 -index 0000000..3a0aac0 ---- /dev/null -+++ b/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/tests/homing-concurrent/test.ini b/tests/homing-concurrent/test.ini -new file mode 100644 -index 0000000..ffae470 ---- /dev/null -+++ b/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/tests/homing-concurrent/test.sh b/tests/homing-concurrent/test.sh -new file mode 100755 -index 0000000..3e0b516 ---- /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 0000000..e69de29 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 9456469..385f805 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 @@ -7,46 +7,32 @@ 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 | 29 ++++ + src/emc/motion/command.c | 29 ++++++ src/emc/motion/control.c | 9 +- src/emc/motion/mot_priv.h | 1 + - src/emc/motion/motion.c | 7 + + 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 | 128 ++++++++++++++++++++++++++ + 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 | 63 ++++++++ - 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, 796 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 | 63 +++++++++++++ + 22 files changed, 502 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 c172f57..003290e 100644 @@ -946,339 +932,3 @@ index 0000000..ad9e6e0 + previous_z = z; + } +}; -diff --git a/tests/power-jog/.gitignore b/tests/power-jog/.gitignore -new file mode 100644 -index 0000000..d070f21 ---- /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 0000000..305bdc4 ---- /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 0000000..80225af ---- /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 0000000..cc11940 ---- /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 0000000..98afc6f ---- /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 0000000..4397029 ---- /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 0000000..68840ea ---- /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 52e6ae4..4868588 100644 --- a/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch +++ b/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch @@ -4,18 +4,10 @@ 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 | 130 ++++++++++++-- - 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, 383 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 | 64 +++++++++++--- + src/hal/utils/halcompile.g | 130 ++++++++++++++++++++++++---- + 3 files changed, 201 insertions(+), 27 deletions(-) diff --git a/docs/src/man/man1/halcompile.1.adoc b/docs/src/man/man1/halcompile.1.adoc index 593be84..e688a75 100644 @@ -392,209 +384,3 @@ index 6bd2afa..2daaf56 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 0000000..b6e1624 ---- /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 0000000..367210b ---- /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 0000000..8265a4f ---- /dev/null -+++ b/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/tests/halcompile/cross-tools/test.sh b/tests/halcompile/cross-tools/test.sh -new file mode 100755 -index 0000000..13c1671 ---- /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/0023-hal-expose-native-thread-period-statistics.patch b/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch index c76d26b..ad546fc 100644 --- a/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch +++ b/linuxcnc-patches/0023-hal-expose-native-thread-period-statistics.patch @@ -9,26 +9,14 @@ 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 | 98 +++++++++++++++ - src/hal/hal_period_stats.h | 118 ++++++++++++++++++ - src/hal/hal_priv.h | 7 +- - tests/halmodule/halquery/expected | 16 +++ - tests/save.0/expected | 1 + - .../arithmetic.c | 109 ++++++++++++++++ - 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 ++ - 12 files changed, 424 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 5cf2078..667f4be 100644 @@ -410,198 +398,3 @@ index 6b849eb..cfbf203 100644 setp fast.tmax 0 setp sampler.0.tmax 0 setp stepgen.0.dirhold 0x0000000000000001 -diff --git a/tests/thread-period-stats-arithmetic/arithmetic.c b/tests/thread-period-stats-arithmetic/arithmetic.c -new file mode 100644 -index 0000000..1c0b04e ---- /dev/null -+++ b/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/tests/thread-period-stats-arithmetic/expected b/tests/thread-period-stats-arithmetic/expected -new file mode 100644 -index 0000000..e69de29 -diff --git a/tests/thread-period-stats-arithmetic/test.sh b/tests/thread-period-stats-arithmetic/test.sh -new file mode 100644 -index 0000000..09d59c2 ---- /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 -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/tests/thread-period-stats/README b/tests/thread-period-stats/README -new file mode 100644 -index 0000000..dd01bec ---- /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 0000000..753ff32 ---- /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] != "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/tests/thread-period-stats/test.hal b/tests/thread-period-stats/test.hal -new file mode 100644 -index 0000000..452dd58 ---- /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 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 index f3bc015..e3fb55c 100644 --- 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 @@ -31,26 +31,10 @@ 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 + - tests/remap/mdi-remap-abort/README | 18 +++ - tests/remap/mdi-remap-abort/checkresult | 2 + - tests/remap/mdi-remap-abort/m400.ngc | 5 + - tests/remap/mdi-remap-abort/remap.py | 9 ++ - tests/remap/mdi-remap-abort/test-ui.py | 161 ++++++++++++++++++++++++ - tests/remap/mdi-remap-abort/test.ini | 101 +++++++++++++++ - tests/remap/mdi-remap-abort/test.sh | 2 + - tests/remap/mdi-remap-abort/toplevel.py | 1 + - 11 files changed, 305 insertions(+), 1 deletion(-) - create mode 100644 tests/remap/mdi-remap-abort/README - create mode 100755 tests/remap/mdi-remap-abort/checkresult - create mode 100644 tests/remap/mdi-remap-abort/m400.ngc - create mode 100644 tests/remap/mdi-remap-abort/remap.py - create mode 100755 tests/remap/mdi-remap-abort/test-ui.py - create mode 100644 tests/remap/mdi-remap-abort/test.ini - create mode 100755 tests/remap/mdi-remap-abort/test.sh - create mode 100644 tests/remap/mdi-remap-abort/toplevel.py + 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 5a1e60e..67edc9b 100644 @@ -92,350 +76,3 @@ index 223886e..1a7a999 100644 void emcTaskCancelAvailability(); int emcTaskSetMode(EMC_TASK_MODE mode); int emcTaskSetState(EMC_TASK_STATE state); -diff --git a/tests/remap/mdi-remap-abort/README b/tests/remap/mdi-remap-abort/README -new file mode 100644 -index 0000000..03bb42d ---- /dev/null -+++ b/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/tests/remap/mdi-remap-abort/checkresult b/tests/remap/mdi-remap-abort/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/remap/mdi-remap-abort/m400.ngc b/tests/remap/mdi-remap-abort/m400.ngc -new file mode 100644 -index 0000000..b841fc7 ---- /dev/null -+++ b/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/tests/remap/mdi-remap-abort/remap.py b/tests/remap/mdi-remap-abort/remap.py -new file mode 100644 -index 0000000..b616b52 ---- /dev/null -+++ b/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/tests/remap/mdi-remap-abort/test-ui.py b/tests/remap/mdi-remap-abort/test-ui.py -new file mode 100755 -index 0000000..3341617 ---- /dev/null -+++ b/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/tests/remap/mdi-remap-abort/test.ini b/tests/remap/mdi-remap-abort/test.ini -new file mode 100644 -index 0000000..7a70763 ---- /dev/null -+++ b/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/tests/remap/mdi-remap-abort/test.sh b/tests/remap/mdi-remap-abort/test.sh -new file mode 100755 -index 0000000..a16f6fa ---- /dev/null -+++ b/tests/remap/mdi-remap-abort/test.sh -@@ -0,0 +1,2 @@ -+#!/bin/bash -+exec linuxcnc -r test.ini -diff --git a/tests/remap/mdi-remap-abort/toplevel.py b/tests/remap/mdi-remap-abort/toplevel.py -new file mode 100644 -index 0000000..0dc38fa ---- /dev/null -+++ b/tests/remap/mdi-remap-abort/toplevel.py -@@ -0,0 +1 @@ -+import remap 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 index 2f770a5..a61d65d 100644 --- 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 @@ -18,18 +18,8 @@ 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 | 50 ++++++ - tests/task/interp-reset-requires-idle/README | 5 + - .../interp-reset-requires-idle/checkresult | 2 + - .../interp-reset-requires-idle/test-ui.py | 153 ++++++++++++++++++ - .../task/interp-reset-requires-idle/test.ini | 93 +++++++++++ - tests/task/interp-reset-requires-idle/test.sh | 2 + - 6 files changed, 305 insertions(+) - create mode 100644 tests/task/interp-reset-requires-idle/README - create mode 100755 tests/task/interp-reset-requires-idle/checkresult - create mode 100755 tests/task/interp-reset-requires-idle/test-ui.py - create mode 100644 tests/task/interp-reset-requires-idle/test.ini - create mode 100755 tests/task/interp-reset-requires-idle/test.sh + src/emc/task/emctaskmain.cc | 50 +++++++++++++++++++++++++++++++++++++ + 1 file changed, 50 insertions(+) diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc index 65846a8..968fb84 100644 @@ -99,288 +89,3 @@ index 65846a8..968fb84 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -diff --git a/tests/task/interp-reset-requires-idle/README b/tests/task/interp-reset-requires-idle/README -new file mode 100644 -index 0000000..ef58eb2 ---- /dev/null -+++ b/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/tests/task/interp-reset-requires-idle/checkresult b/tests/task/interp-reset-requires-idle/checkresult -new file mode 100755 -index 0000000..24dc9aa ---- /dev/null -+++ b/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/tests/task/interp-reset-requires-idle/test-ui.py b/tests/task/interp-reset-requires-idle/test-ui.py -new file mode 100755 -index 0000000..d4e6742 ---- /dev/null -+++ b/tests/task/interp-reset-requires-idle/test-ui.py -@@ -0,0 +1,153 @@ -+#!/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") -+ -+# 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") -+ -+print("all scenarios passed") -+set_state(linuxcnc.STATE_ESTOP) -+sys.exit(0) -diff --git a/tests/task/interp-reset-requires-idle/test.ini b/tests/task/interp-reset-requires-idle/test.ini -new file mode 100644 -index 0000000..8cff916 ---- /dev/null -+++ b/tests/task/interp-reset-requires-idle/test.ini -@@ -0,0 +1,93 @@ -+[EMC] -+VERSION = 1.1 -+DEBUG = 0 -+ -+[DISPLAY] -+DISPLAY = ./test-ui.py -+ -+[RS274NGC] -+PARAMETER_FILE = sim.var -+RS274NGC_STARTUP_CODE = G21 G90 -+ -+[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/tests/task/interp-reset-requires-idle/test.sh b/tests/task/interp-reset-requires-idle/test.sh -new file mode 100755 -index 0000000..a16f6fa ---- /dev/null -+++ b/tests/task/interp-reset-requires-idle/test.sh -@@ -0,0 +1,2 @@ -+#!/bin/bash -+exec linuxcnc -r test.ini diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 731dfe3..0e34726 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -19,7 +19,7 @@ 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 a headless LinuxCNC in run-in-place mode, and runs the LinuxCNC regression suite with failure output enabled, @@ -29,6 +29,23 @@ and GUI tools (`tests/build/ui`, `tests/glcanon`, `tests/pyvcp`, `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 with the patched LinuxCNC's +`runtests`: + +```sh +cd /path/to/linuxcnc +scripts/runtests tests /path/to/linuxcnc-ctrl/linuxcnc-tests +``` + +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 From a clean checkout of the baseline revision: @@ -225,7 +242,7 @@ 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 `tests/resumable-stop` LinuxCNC regressions run as four tests +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 four re-runs with the trapezoidal planner. They cover @@ -310,7 +327,7 @@ 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. -`tests/tool-line-length-save` covers this. The G-code preview applies the same geometry-plus-wear offset +`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 @@ -431,7 +448,7 @@ 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. `tests/tool-table-load` covers this. +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 @@ -443,7 +460,7 @@ the spindle tool and `iocontrol.0.tool-number` from pocket 0. A refused tool update or delete tells the operator why and fails only that command: spindle, coolant and an open program are unaffected. -`tests/tool-crud-refusal` covers this. +`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 @@ -482,7 +499,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. @@ -497,7 +514,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 `^`. @@ -514,7 +531,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. @@ -554,7 +571,7 @@ 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 `tests/interp/g28.2/instant-home`), +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. Stop or Pause before the @@ -725,7 +742,7 @@ 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. -`tests/remap/mdi-remap-abort` interrupts a waiting NGC and Python remap with +`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. @@ -748,7 +765,7 @@ 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. -`tests/task/interp-reset-requires-idle` checks that resets are refused during +`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. The native server additionally refuses a reset while a command it wrote earlier is still in progress, because task may not have diff --git a/linuxcnc-tests/.gitignore b/linuxcnc-tests/.gitignore new file mode 100644 index 0000000..cfdfe07 --- /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 0000000..425d52b --- /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 0000000..3be13a3 --- /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 0000000..14417ee --- /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 0000000..a9bcd9e --- /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 0000000..1cf2f53 --- /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 0000000..bcbcb6c --- /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 0000000..5ed42c8 --- /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 0000000..425d52b --- /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 0000000..bbb8ad6 --- /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 0000000..1e0aa79 --- /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 0000000..563a89b --- /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 0000000..ca47f56 --- /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 0000000..12b5b7a --- /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 0000000..a180055 --- /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 0000000..0f3d8df --- /dev/null +++ b/linuxcnc-tests/availability-mcodes/test-ui.py @@ -0,0 +1,205 @@ +#!/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 ACK completes the +# handshake, 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_STOPPED, 'Stop before ACK') + else: + wait(lambda: s.interp_state == linuxcnc.INTERP_PAUSED, 'Pause before ACK') + pin('joint.2.availability-ack', 1) + 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 0000000..fe357c0 --- /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 0000000..882b151 --- /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 0000000..8a28c6f --- /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 0000000..37d2571 --- /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 0000000..e572890 --- /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 0000000..66ad330 --- /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 0000000..56f319c --- /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 0000000..e244f00 --- /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 0000000..2372f6c --- /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 0000000..61ccf6b --- /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 0000000..13436c1 --- /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 0000000..e69de29 diff --git a/linuxcnc-tests/g76-tapered-pitch/README b/linuxcnc-tests/g76-tapered-pitch/README new file mode 100644 index 0000000..ff9a863 --- /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 0000000..24dc9aa --- /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 0000000..47884cf --- /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 0000000..38ac4f5 --- /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 0000000..8c04f36 --- /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 0000000..411ae8c --- /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 0000000..b6e1624 --- /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 0000000..367210b --- /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 0000000..8265a4f --- /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 0000000..13c1671 --- /dev/null +++ b/linuxcnc-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-tests/homing-concurrent/checkresult b/linuxcnc-tests/homing-concurrent/checkresult new file mode 100755 index 0000000..9c14eb3 --- /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 0000000..5d4eaa3 --- /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 0000000..3a0aac0 --- /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 0000000..ffae470 --- /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 0000000..3e0b516 --- /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 0000000..e69de29 diff --git a/linuxcnc-tests/interp/availability-mcodes/README b/linuxcnc-tests/interp/availability-mcodes/README new file mode 100644 index 0000000..6054ffd --- /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 0000000..da0115c --- /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/double-selector.ngc b/linuxcnc-tests/interp/availability-mcodes/double-selector.ngc new file mode 100644 index 0000000..a851ea0 --- /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 0000000..f2f707c --- /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 0000000..8d42480 --- /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 0000000..e69de29 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 0000000..e5488fb --- /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 0000000..26ff05c --- /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 0000000..3b2f3fb --- /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 0000000..584fa3b --- /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 0000000..6947d8a --- /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 0000000..c48d1b9 --- /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 0000000..96cb26c --- /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 0000000..1a45e38 --- /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 0000000..dd567c4 --- /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 0000000..a52d2d4 --- /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 0000000..1054e7e --- /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 0000000..1d22b22 --- /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 0000000..1cf09ae --- /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 0000000..8fd4be9 --- /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 0000000..6fc9e05 --- /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 0000000..37e7a2e --- /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 0000000..5153e91 --- /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 0000000..dea8ef7 --- /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 0000000..3a6b203 --- /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 0000000..2412206 --- /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 0000000..03afbfa --- /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 0000000..c61548a --- /dev/null +++ b/linuxcnc-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/linuxcnc-tests/interp/availability-mcodes/valid-joint.ngc b/linuxcnc-tests/interp/availability-mcodes/valid-joint.ngc new file mode 100644 index 0000000..d697df4 --- /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 0000000..10632c2 --- /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 0000000..277dcb5 --- /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 0000000..24dc9aa --- /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 0000000..e69de29 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 0000000..8643922 --- /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 0000000..f1b2352 --- /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 0000000..a16f6fa --- /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 0000000..57dbfb9 --- /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 0000000..979eccd --- /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 0000000..ab05650 --- /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 0000000..110edb2 --- /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 0000000..c6a6349 --- /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 0000000..f79aa85 --- /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 0000000..9384803 --- /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 0000000..46d331b --- /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 0000000..73b58bc --- /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 0000000..43d9c1a --- /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 0000000..a05d8bd --- /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 0000000..c7e3b12 --- /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 0000000..369efa7 --- /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 0000000..aea66da --- /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 0000000..0822c76 --- /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 0000000..134455e --- /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 0000000..e9e62dc --- /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 0000000..3ee52a2 --- /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 0000000..3613d39 --- /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 0000000..1f2d11a --- /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 0000000..c9cf799 --- /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 0000000..c995e9b --- /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 0000000..8ef7a87 --- /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 0000000..3a172d8 --- /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 0000000..9568e63 --- /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 0000000..955dbcd --- /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 0000000..1a6d140 --- /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 0000000..7958c18 --- /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 0000000..00099d2 --- /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 0000000..dd4b2be --- /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 0000000..e69de29 diff --git a/linuxcnc-tests/motion-target-preparation/test.py b/linuxcnc-tests/motion-target-preparation/test.py new file mode 100644 index 0000000..3c78d02 --- /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 0000000..0cd44bb --- /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 0000000..d070f21 --- /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 0000000..305bdc4 --- /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 0000000..80225af --- /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 0000000..cc11940 --- /dev/null +++ b/linuxcnc-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/linuxcnc-tests/power-jog/test.ini b/linuxcnc-tests/power-jog/test.ini new file mode 100644 index 0000000..98afc6f --- /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 0000000..4397029 --- /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 0000000..68840ea --- /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 0000000..3758b4f --- /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 0000000..518d1fe --- /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 0000000..e5495df --- /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 0000000..600c9a9 --- /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 0000000..95f0e7b --- /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 0000000..36abfcb --- /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 0000000..b475564 --- /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 0000000..7a38952 --- /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 0000000..0dc38fa --- /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 0000000..cbaede8 --- /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 0000000..7fda879 --- /dev/null +++ b/linuxcnc-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/linuxcnc-tests/remap/executor/remap.py b/linuxcnc-tests/remap/executor/remap.py new file mode 100644 index 0000000..0198feb --- /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 0000000..fb9b77b --- /dev/null +++ b/linuxcnc-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/linuxcnc-tests/remap/executor/test.ini.in b/linuxcnc-tests/remap/executor/test.ini.in new file mode 100644 index 0000000..b9a4ee5 --- /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 0000000..37ec101 --- /dev/null +++ b/linuxcnc-tests/remap/executor/test.sh @@ -0,0 +1,12 @@ +#!/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; do + echo "Running executor remap scenario: ${scenario}" + EXECUTOR_SCENARIO="${scenario}" linuxcnc -r test.ini +done + +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 0000000..4be91ba --- /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 0000000..03bb42d --- /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 0000000..24dc9aa --- /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 0000000..b841fc7 --- /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 0000000..b616b52 --- /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 0000000..3341617 --- /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 0000000..7a70763 --- /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 0000000..a16f6fa --- /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 0000000..0dc38fa --- /dev/null +++ b/linuxcnc-tests/remap/mdi-remap-abort/toplevel.py @@ -0,0 +1 @@ +import remap diff --git a/linuxcnc-tests/resumable-stop/README b/linuxcnc-tests/resumable-stop/README new file mode 100644 index 0000000..6c8eb25 --- /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 0000000..df711f6 --- /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 0000000..c6a6868 --- /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 0000000..e96d6e6 --- /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 0000000..cfbf687 --- /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 0000000..6e468d1 --- /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 0000000..84280ec --- /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 0000000..bbc7166 --- /dev/null +++ b/linuxcnc-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/linuxcnc-tests/resumable-stop/css.ngc b/linuxcnc-tests/resumable-stop/css.ngc new file mode 100644 index 0000000..8a70da2 --- /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 0000000..be7e5af --- /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 0000000..f7a54f8 --- /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 0000000..8af98dc --- /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 0000000..92dbe87 --- /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 0000000..a12bcb3 --- /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 0000000..5b04e69 --- /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 0000000..01a62a2 --- /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 0000000..c8ee28f --- /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 0000000..0562404 --- /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 0000000..df2a2ab --- /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 0000000..713f576 --- /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 0000000..92d147c --- /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 0000000..e39cc37 --- /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 0000000..713f576 --- /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 0000000..488d2a9 --- /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 0000000..241f777 --- /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 0000000..b0eb997 --- /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 0000000..1c6a3ea --- /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 0000000..362de54 --- /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" 24 diff --git a/linuxcnc-tests/resumable-stop/general/scenarios b/linuxcnc-tests/resumable-stop/general/scenarios new file mode 100644 index 0000000..d8e2870 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/general/scenarios @@ -0,0 +1,24 @@ +idle-rejected +ordinary +trapezoidal:ordinary +single-step +trapezoidal:single-step +inflight-single-step +rapid-no-atspeed +paused-resume +paused-run +abort-empty +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 diff --git a/linuxcnc-tests/resumable-stop/general/test.sh b/linuxcnc-tests/resumable-stop/general/test.sh new file mode 100755 index 0000000..713f576 --- /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 0000000..2cc583c --- /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 0000000..4f214ea --- /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.ngc b/linuxcnc-tests/resumable-stop/inflight-step.ngc new file mode 100644 index 0000000..1f72544 --- /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 0000000..3811387 --- /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 0000000..6927a71 --- /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 0000000..6fe71e3 --- /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 0000000..531480c --- /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 0000000..cf66123 --- /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 0000000..69d6ce7 --- /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 0000000..4c52c4b --- /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 "$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/single-step.ngc b/linuxcnc-tests/resumable-stop/single-step.ngc new file mode 100644 index 0000000..8955e51 --- /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 0000000..927c3ca --- /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 0000000..c5f21ab --- /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/tap.ngc b/linuxcnc-tests/resumable-stop/tap.ngc new file mode 100644 index 0000000..2182f18 --- /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 0000000..ec9e072 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/test-ui.py @@ -0,0 +1,2051 @@ +#!/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_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_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") + + 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_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_cancel_latched_resume_test(label, cancel): + # Resume during STOPPING is latched until Stop completes; a Pause or a + # second Stop after it cancels the latched Resume, so the program stays + # STOPPED. + 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.auto(linuxcnc.AUTO_RESUME) + cancel() + s.poll() + if s.stop_state != linuxcnc.STOP_STOPPING: + fail("G33 finished before Resume and %s were sent" % label) + + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPED + and math.isclose(s.position[2], -5.0, abs_tol=0.01), + lambda: "%s after latched Resume did not leave the program " + "STOPPED: 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("%s after latched Resume: program left STOPPED" % label) + if hal.get_value("spindle.0.on"): + fail("%s after latched Resume: spindle on while STOPPED" % label) + if abs(s.position[0]) > 0.001: + fail("%s after latched Resume: 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_step_then_resume_while_stopping_test(): + # Step followed by Resume while Stop waits for G33 must resume the + # program normally rather than single-step it. + 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, + ) + + # Stop completes only on STOPPED, so do not wait for it here. + c.program_stop() + wait_for( + lambda: s.stop_state == linuxcnc.STOP_STOPPING, + "Stop did not wait for the active G33", + timeout=1.0, + ) + c.auto(linuxcnc.AUTO_STEP) + c.auto(linuxcnc.AUTO_RESUME) + s.poll() + if s.stop_state != linuxcnc.STOP_STOPPING: + fail("G33 finished before Step and Resume were sent") + + 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), + lambda: "program did not run to completion after Step and Resume: " + "X=%.3f interp=%d paused=%d stop=%d" + % (s.position[0], s.interp_state, s.task_paused, s.stop_state), + timeout=20.0, + ) + assert_outputs_stopped_after_program() + + +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, + "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, + "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, + "pause-latched-resume": lambda: run_cancel_latched_resume_test( + "Pause", lambda: c.auto(linuxcnc.AUTO_PAUSE)), + "stop-latched-resume": lambda: run_cancel_latched_resume_test( + "Stop", c.program_stop), + "pause-inflight-step": run_pause_inflight_single_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, + "step-resume-stopping": run_step_then_resume_while_stopping_test, + "g95-between-g33": run_g95_between_g33_stop_resume_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 0000000..96b5a38 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/test.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 = 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 0000000..c44a2cd --- /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.ngc b/linuxcnc-tests/resumable-stop/thread-chain.ngc new file mode 100644 index 0000000..ca80839 --- /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 0000000..2bc7489 --- /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 0000000..44aa11e --- /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 0000000..c3ec6d0 --- /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 0000000..664eed8 --- /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 0000000..a4410d4 --- /dev/null +++ b/linuxcnc-tests/resumable-stop/threading/scenarios @@ -0,0 +1,11 @@ +rigid-tap +g33 +queued-g33 +g33-chain +trapezoidal:g33-chain +step-resume-stopping +g95-between-g33 +g33-no-following-rapid +command-after-sync +pause-latched-resume +stop-latched-resume diff --git a/linuxcnc-tests/resumable-stop/threading/test.sh b/linuxcnc-tests/resumable-stop/threading/test.sh new file mode 100755 index 0000000..713f576 --- /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 0000000..68840ea --- /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 0000000..55233dc --- /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 0000000..b443927 --- /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 0000000..fffdf47 --- /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 0000000..dde6c2f --- /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/runtime-availability-regressions/.gitignore b/linuxcnc-tests/runtime-availability-regressions/.gitignore new file mode 100644 index 0000000..425d52b --- /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 0000000..2a46151 --- /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/base.ini b/linuxcnc-tests/runtime-availability-regressions/base.ini new file mode 100644 index 0000000..71f455a --- /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 0000000..153f94a --- /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 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 0000000..7e0cffc --- /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 0000000..b69d67a --- /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 0000000..36c2c7e --- /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 0000000..5048be9 --- /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 0000000..b39d68b --- /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 0000000..c4c8307 --- /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 0000000..949adc1 --- /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 0000000..5ca302f --- /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 0000000..3786b15 --- /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 0000000..75125d8 --- /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 0000000..c9eea9d --- /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 0000000..cdf6f94 --- /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 0000000..c23405a --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/test-ui.py @@ -0,0 +1,198 @@ +#!/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 == '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 0000000..67dab70 --- /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 0000000..80bc7dd --- /dev/null +++ b/linuxcnc-tests/runtime-availability-regressions/test.sh @@ -0,0 +1,35 @@ +#!/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 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 ;; + 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 0000000..a580019 --- /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 0000000..5c7ef3f --- /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 0000000..ada9398 --- /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 0000000..425d52b --- /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 0000000..bdfd8cc --- /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 0000000..c8e0eab --- /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 0000000..12624ae --- /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 0000000..62edf53 --- /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 0000000..1c30ffa --- /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 0000000..3b9c37c --- /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 0000000..3e7e61f --- /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 0000000..c9e6f8a --- /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 0000000..1f435da --- /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 0000000..67dab70 --- /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 0000000..9a17bf2 --- /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 0000000..e69de29 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 0000000..ef58eb2 --- /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 0000000..24dc9aa --- /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 0000000..d4e6742 --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py @@ -0,0 +1,153 @@ +#!/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") + +# 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") + +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 0000000..8cff916 --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test.ini @@ -0,0 +1,93 @@ +[EMC] +VERSION = 1.1 +DEBUG = 0 + +[DISPLAY] +DISPLAY = ./test-ui.py + +[RS274NGC] +PARAMETER_FILE = sim.var +RS274NGC_STARTUP_CODE = G21 G90 + +[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 0000000..a16f6fa --- /dev/null +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test.sh @@ -0,0 +1,2 @@ +#!/bin/bash +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 0000000..1c0b04e --- /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 0000000..e69de29 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 0000000..09d59c2 --- /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 0000000..dd01bec --- /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 0000000..753ff32 --- /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 0000000..452dd58 --- /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 0000000..89772f7 --- /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 0000000..1535c26 --- /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 0000000..24dc9aa --- /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 0000000..1f0eacc --- /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 0000000..8d6ef70 --- /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 0000000..bad1a01 --- /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 0000000..226cf79 --- /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 0000000..61ad1bd --- /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 0000000..24dc9aa --- /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 0000000..624f03b --- /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 0000000..4b2e267 --- /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 0000000..08ce5ff --- /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 0000000..346c022 --- /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 0000000..ebe0144 --- /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 0000000..24dc9aa --- /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 0000000..fe72033 --- /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 0000000..f2c8011 --- /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 0000000..ce064c0 --- /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 0000000..e390c5d --- /dev/null +++ b/linuxcnc-tests/tool-table-load/garbage-ui.py @@ -0,0 +1,51 @@ +#!/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") +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() +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 0000000..0f44290 --- /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 0000000..af9ba05 --- /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 0000000..3b860d3 --- /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 0000000..5e073f5 --- /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 0000000..2e03fa7 --- /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 0000000..c7295bc --- /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 0000000..09798bf --- /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 0000000..df79eee --- /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 0000000..e02acfd --- /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 0000000..24dc9aa --- /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 0000000..b1fdce4 --- /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 0000000..ac36eff --- /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 0000000..1d66847 --- /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 0000000..114712d --- /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 0000000..b0ab68c --- /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 0000000..e9fa7e5 --- /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 0000000..be0836e --- /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 0000000..c7ee908 --- /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 0000000..1026231 --- /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 0000000..b4d12ae --- /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 0000000..2e1b1f2 --- /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 0000000..99ef76e --- /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 0000000..24dc9aa --- /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 0000000..ed5a426 --- /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 0000000..3523810 --- /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 0000000..5feff1a --- /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 0000000..72a85fd --- /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 0000000..1026231 --- /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 0000000..09798bf --- /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 0000000..24dc9aa --- /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 0000000..05e1a69 --- /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 0000000..a6a6fd6 --- /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 0000000..f5f4988 --- /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 0000000..feb7fa0 --- /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 0000000..0dc38fa --- /dev/null +++ b/linuxcnc-tests/tool-wear-task/toplevel.py @@ -0,0 +1 @@ +import remap diff --git a/skills/patch-linuxcnc/SKILL.md b/skills/patch-linuxcnc/SKILL.md index 5bcd963..e259cf8 100644 --- a/skills/patch-linuxcnc/SKILL.md +++ b/skills/patch-linuxcnc/SKILL.md @@ -30,6 +30,11 @@ 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 them with `scripts/runtests ` from the + LinuxCNC checkout. ## Phase 1: fast development loop From 8dc3320c71f16ee7a13f045a6893c80114b8f0e0 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 19 Nov 2026 14:45:29 +0100 Subject: [PATCH 38/45] test(linuxcnc): share the regression test selection between CI and local runs linuxcnc-tests/run.sh selects the upstream and linuxcnc-tests tests, leaves out the out-of-scope GUI, remote-interface and tool-database tests, shards them when SHARD_INDEX and SHARD_COUNT are set, and runs them with runtests. CI calls it instead of carrying its own copy, so a local run reports the same set of tests as CI. --- .github/workflows/linuxcnc-patches.yml | 43 +------------------ linuxcnc-patches/README.md | 16 ++++--- linuxcnc-tests/run.sh | 59 ++++++++++++++++++++++++++ skills/patch-linuxcnc/SKILL.md | 3 +- 4 files changed, 72 insertions(+), 49 deletions(-) create mode 100755 linuxcnc-tests/run.sh diff --git a/.github/workflows/linuxcnc-patches.yml b/.github/workflows/linuxcnc-patches.yml index 77a6203..29e72f3 100644 --- a/.github/workflows/linuxcnc-patches.yml +++ b/.github/workflows/linuxcnc-patches.yml @@ -103,45 +103,4 @@ jobs: env: SHARD_COUNT: ${{ strategy.job-total }} SHARD_INDEX: ${{ matrix.shard }} - run: | - set -euo pipefail - - # Upstream tests run from the LinuxCNC tree, the patches' own tests - # from linuxcnc-tests/ in this repository. - # - # linuxcnc-tests/resumable-stop/* are the longest tests (about - # 2.5 minutes each); spread them one per shard. Everything else is - # hashed across all shards. - shard_tests=() - resumable_index=0 - while IFS= read -r -d '' test_path; do - relative_path="${test_path#"${GITHUB_WORKSPACE}/"}" - # LinuxCNC features that are out of scope for this repository. - case "${relative_path}" 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 [[ "${relative_path}" == linuxcnc-tests/resumable-stop/* ]]; then - test_shard=$((resumable_index % SHARD_COUNT)) - resumable_index=$((resumable_index + 1)) - else - checksum="$(printf '%s' "${relative_path}" | cksum)" - checksum="${checksum%% *}" - test_shard=$((checksum % SHARD_COUNT)) - fi - if (( test_shard == SHARD_INDEX )); then - shard_tests+=("${test_path}") - fi - done < <( - find tests "${GITHUB_WORKSPACE}/linuxcnc-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/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 0e34726..123a1ac 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -22,8 +22,9 @@ complete series. 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 a headless LinuxCNC in run-in-place mode, and runs the LinuxCNC regression suite with failure output enabled, -leaving out tests for features that are out of scope for this repository: GUIs +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 @@ -35,14 +36,17 @@ 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 with the patched LinuxCNC's -`runtests`: +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 -cd /path/to/linuxcnc -scripts/runtests tests /path/to/linuxcnc-ctrl/linuxcnc-tests +./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. diff --git a/linuxcnc-tests/run.sh b/linuxcnc-tests/run.sh new file mode 100755 index 0000000..76ed546 --- /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/skills/patch-linuxcnc/SKILL.md b/skills/patch-linuxcnc/SKILL.md index e259cf8..bceb3a1 100644 --- a/skills/patch-linuxcnc/SKILL.md +++ b/skills/patch-linuxcnc/SKILL.md @@ -33,7 +33,8 @@ validation into the ordinary edit-build-test loop. - 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 them with `scripts/runtests ` from the + Run the suite with `linuxcnc-tests/run.sh `, or one test with + `scripts/runtests ` from the LinuxCNC checkout. ## Phase 1: fast development loop From ca6ac20ed733172783a4f64ec95a32051a5a509d Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Tue, 24 Nov 2026 07:44:04 +0100 Subject: [PATCH 39/45] fix(linuxcnc): close pre2 round-5 findings and merge blockers - 0009: G76 approach endpoints stay exact so a prequeued Step stops on them. - 0011: in-flight Step stops at the first block end it can reach with the configured deceleration instead of braking hard on short blocks. - 0013: executor requests wait for earlier queued motion before starting, so AUTO read-ahead no longer sets HAL requests during previous moves. - 0018: M54/M55 are refused while cutter radius compensation is on. - 0020: out-of-range halui.power-feed.spindle values are refused instead of wrapping onto valid spindle indices. - 0025: a tool edit no longer leaves the plan wait set, which blocked interpreter resets on an idle machine. Tests cover each change; the executor test now checks the error policy. --- ...reading-stop-clear-and-pass-stepping.patch | 35 +-- ...-single-step-during-active-execution.patch | 210 ++++++++++++++---- ...4ngc-add-composable-executor-stdglue.patch | 27 ++- ...ngc-pass-spindle-selectors-to-remaps.patch | 2 +- .../0018-availability-mcodes.patch | 26 ++- ...otion-add-native-lathe-power-jogging.patch | 14 +- ...ter-reset-unless-the-machine-is-idle.patch | 27 ++- linuxcnc-patches/README.md | 41 +++- .../interp/availability-mcodes/comp-m54.ngc | 5 + .../interp/availability-mcodes/comp-m55.ngc | 5 + .../interp/availability-mcodes/test.sh | 4 + linuxcnc-tests/power-jog/test-ui.py | 8 + linuxcnc-tests/remap/executor/checkresult | 2 +- linuxcnc-tests/remap/executor/readahead.ngc | 4 + linuxcnc-tests/remap/executor/test-ui.py | 50 +++++ linuxcnc-tests/remap/executor/test.sh | 2 +- linuxcnc-tests/resumable-stop/core_sim.hal | 8 + .../resumable-stop/general/checkresult | 2 +- .../resumable-stop/general/scenarios | 1 + .../resumable-stop/inflight-step-short.ngc | 25 +++ linuxcnc-tests/resumable-stop/test-ui.py | 70 ++++++ .../interp-reset-requires-idle/.gitignore | 1 + .../interp-reset-requires-idle/test-ui.py | 25 +++ .../task/interp-reset-requires-idle/test.ini | 3 + .../task/interp-reset-requires-idle/test.sh | 2 + 25 files changed, 497 insertions(+), 102 deletions(-) create mode 100644 linuxcnc-tests/interp/availability-mcodes/comp-m54.ngc create mode 100644 linuxcnc-tests/interp/availability-mcodes/comp-m55.ngc create mode 100644 linuxcnc-tests/remap/executor/readahead.ngc create mode 100644 linuxcnc-tests/resumable-stop/inflight-step-short.ngc create mode 100644 linuxcnc-tests/task/interp-reset-requires-idle/.gitignore 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 2e58c27..d55160a 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -39,11 +39,11 @@ that adds in-flight stepping. src/emc/task/task.hh | 2 +- src/emc/task/taskintf.cc | 5 +- src/emc/tp/tc_types.h | 2 + - src/emc/tp/tp.c | 203 +++++++++++++++++++++++++++-- + 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, 496 insertions(+), 51 deletions(-) + 23 files changed, 497 insertions(+), 51 deletions(-) diff --git a/docs/src/gcode/g-code.adoc b/docs/src/gcode/g-code.adoc index 6f196b6..3b3d18c 100644 @@ -936,7 +936,7 @@ index 47018b2..bd8ad13 100644 // this segment (g64 mode) diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index 8ef21c3..c690207 100644 +index 8ef21c3..c9b271e 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c @@ -240,10 +240,12 @@ STATIC int tpGetMachineActiveLimit(double * const act_limit, PmCartesian const * @@ -1037,8 +1037,8 @@ index 8ef21c3..c690207 100644 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 && @@ -1048,8 +1048,8 @@ index 8ef21c3..c690207 100644 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) { @@ -1065,7 +1065,7 @@ index 8ef21c3..c690207 100644 { if (tpErrorCheck(tp) < 0) { return TP_ERR_FAIL; -@@ -2167,12 +2221,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,13 +1077,14 @@ index 8ef21c3..c690207 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, -@@ -3370,7 +3429,7 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) +@@ -3370,7 +3430,7 @@ STATIC void tpHandleEmptyQueue(TP_STRUCT * const tp) tpUpdateMovementStatus(tp, NULL); @@ -1092,7 +1093,7 @@ index 8ef21c3..c690207 100644 tpResume(tp); } } -@@ -3432,6 +3491,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); @@ -1110,7 +1111,7 @@ index 8ef21c3..c690207 100644 //TODO make progress to match target? // done with this move if (tp->reverse_run) { -@@ -4303,6 +4373,10 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4303,6 +4374,10 @@ int tpRunCycle(TP_STRUCT * const tp, long period) if(!tc) { if (tp->stopping) { tpHandleEmptyQueue(tp); @@ -1121,7 +1122,7 @@ index 8ef21c3..c690207 100644 if (tp->stopping) { tp->stop_sync_run = 0; tp->pausing = 1; -@@ -4310,6 +4384,11 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4310,6 +4385,11 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -1133,7 +1134,7 @@ index 8ef21c3..c690207 100644 tpHandleEmptyQueue(tp); return TP_ERR_WAITING; } -@@ -4458,6 +4537,42 @@ int tpSetSpindleSync(TP_STRUCT * const tp, int spindle, double sync, int mode) { +@@ -4458,6 +4538,42 @@ int tpSetSpindleSync(TP_STRUCT * const tp, int spindle, double sync, int mode) { return TP_ERR_OK; } @@ -1176,7 +1177,7 @@ index 8ef21c3..c690207 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4465,22 +4580,75 @@ int tpPause(TP_STRUCT * const tp) +@@ -4465,22 +4581,75 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -1258,7 +1259,7 @@ index 8ef21c3..c690207 100644 } else { tp->pausing = 1; } -@@ -4495,6 +4663,17 @@ int tpResume(TP_STRUCT * const tp) +@@ -4495,6 +4664,17 @@ int tpResume(TP_STRUCT * const tp) tp->pausing = 0; tp->stopping = 0; tp->stop_sync_run = 0; @@ -1276,7 +1277,7 @@ index 8ef21c3..c690207 100644 emcmotStatus->stopped = 0; return TP_ERR_OK; } -@@ -4507,6 +4686,10 @@ int tpAbort(TP_STRUCT * const tp) +@@ -4507,6 +4687,10 @@ int tpAbort(TP_STRUCT * const tp) if (!tp->aborting) { /* const to abort, signal a pause and set our abort flag */ 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 1facc4b..ae19b95 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 @@ -11,12 +11,13 @@ 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 | 24 +++++++---- - 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 ++- - 5 files changed, 116 insertions(+), 51 deletions(-) + src/emc/motion/command.c | 24 +++-- + src/emc/motion/control.c | 9 +- + src/emc/task/emctaskmain.cc | 48 ++++----- + src/emc/tp/tc_types.h | 3 + + src/emc/tp/tp.c | 192 +++++++++++++++++++++++++++++++++--- + src/emc/tp/tp_types.h | 5 +- + 6 files changed, 230 insertions(+), 51 deletions(-) diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c index a8e8ae3..ff48890 100644 @@ -200,8 +201,22 @@ index e2a7209..f69fcbb 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_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 c690207..dac694f 100644 +index c9b271e..c42d4f1 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c @@ -357,9 +357,9 @@ STATIC inline double tpGetRealFinalVel(TP_STRUCT const * const tp, @@ -216,20 +231,18 @@ index c690207..dac694f 100644 tc->term_cond != TC_TERM_COND_TANGENT || tp->reverse_run) { return 0.0; } -@@ -497,7 +497,11 @@ int tpClear(TP_STRUCT * const tp) +@@ -497,7 +497,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; -@@ -1595,7 +1599,7 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc +@@ -1595,7 +1597,7 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc tp->stop_pass_id); return TP_ERR_FAIL; } @@ -238,7 +251,7 @@ index c690207..dac694f 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, -@@ -1621,12 +1625,11 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc +@@ -1621,12 +1623,11 @@ STATIC inline int tpAddSegmentToQueue(TP_STRUCT * const tp, TC_STRUCT * const tc } } if (queued_tc && queued_tc->g76_pass_clearance && @@ -252,7 +265,7 @@ index c690207..dac694f 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) { -@@ -3496,10 +3499,11 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, +@@ -3497,10 +3498,11 @@ STATIC int tpCompleteSegment(TP_STRUCT * const tp, tp->stop_tc = 0; tp->stop_pass_id = 0; } @@ -265,7 +278,7 @@ index c690207..dac694f 100644 } //TODO make progress to match target? -@@ -4384,7 +4388,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4385,7 +4387,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -274,7 +287,7 @@ index c690207..dac694f 100644 tp->step_pass_id && !tp->step_tc) { tpHandleEmptyQueue(tp); return TP_ERR_WAITING; -@@ -4573,6 +4577,30 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) +@@ -4574,6 +4576,146 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) return tc ? tc->g76_pass_id : 0; } @@ -293,19 +306,135 @@ index c690207..dac694f 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) { ++ dist += 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; ++ } ++ 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) { -@@ -4580,10 +4608,12 @@ int tpPause(TP_STRUCT * const tp) +@@ -4581,10 +4723,12 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -319,7 +448,7 @@ index c690207..dac694f 100644 TC_STRUCT *tc = tcqItem(&tp->queue, 0); /* * A G76 cut that has passed spindle index, or its explicitly marked -@@ -4630,7 +4660,7 @@ int tpPause(TP_STRUCT * const tp) +@@ -4631,7 +4775,7 @@ int tpPause(TP_STRUCT * const tp) tp->pausing = 1; } } else if (emcmotStatus->stepping && @@ -328,7 +457,7 @@ index c690207..dac694f 100644 /* * EMCMOT_STEP requests default-TP pass targeting through the existing * tpPause ABI. Alternate planners leave step_target_pending clear and -@@ -4639,15 +4669,25 @@ int tpPause(TP_STRUCT * const tp) +@@ -4640,15 +4784,27 @@ int tpPause(TP_STRUCT * const tp) int pass_id = tpGetQueuedG76PassId(tp); if (pass_id) { tp->step_pass_id = pass_id; @@ -344,21 +473,23 @@ index c690207..dac694f 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; keep the ++ * established end of its source block. */ ++ tp->step_tc = tpFindSourceBlockTarget(tp, tp->step_motion_id); ++ 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; -@@ -4660,6 +4700,7 @@ int tpResume(TP_STRUCT * const tp) +@@ -4661,6 +4817,7 @@ int tpResume(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -366,44 +497,39 @@ index c690207..dac694f 100644 tp->pausing = 0; tp->stopping = 0; tp->stop_sync_run = 0; -@@ -4669,7 +4710,10 @@ int tpResume(TP_STRUCT * const tp) +@@ -4670,7 +4827,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; -@@ -4689,7 +4733,11 @@ int tpAbort(TP_STRUCT * const tp) +@@ -4690,7 +4848,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 2963bcc..819f508 100644 +index 2963bcc..0d3f164 100644 --- a/src/emc/tp/tp_types.h +++ b/src/emc/tp/tp_types.h -@@ -171,7 +171,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/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index d296327..b730b02 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -19,19 +19,19 @@ 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 | 129 +++++++++ - nc_files/remap_lib/python-stdglue/stdglue.py | 260 ++++++++++++++++++- + docs/src/remap/remap.adoc | 130 +++++++++ + nc_files/remap_lib/python-stdglue/stdglue.py | 268 ++++++++++++++++++- src/emc/rs274ngc/interp_internal.hh | 3 + src/emc/rs274ngc/interp_python.cc | 60 ++++- src/emc/rs274ngc/interp_python.hh | 7 + src/emc/rs274ngc/rs274ngc_pre.cc | 5 + - 6 files changed, 461 insertions(+), 3 deletions(-) + 6 files changed, 470 insertions(+), 3 deletions(-) diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index 75e2a09..410381a 100644 +index 75e2a09..642e4c7 100644 --- a/docs/src/remap/remap.adoc +++ b/docs/src/remap/remap.adoc -@@ -1576,6 +1576,135 @@ 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: @@ -44,7 +44,8 @@ index 75e2a09..410381a 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 @@ -168,7 +169,7 @@ index 75e2a09..410381a 100644 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 8457e40..f7d7d47 100644 +index 8457e40..3cd13d2 100644 --- a/nc_files/remap_lib/python-stdglue/stdglue.py +++ b/nc_files/remap_lib/python-stdglue/stdglue.py @@ -16,6 +16,9 @@ @@ -181,7 +182,7 @@ index 8457e40..f7d7d47 100644 import emccanon from interpreter import * from emccanon import MESSAGE -@@ -40,6 +43,261 @@ def build_hal(self): +@@ -40,6 +43,269 @@ def build_hal(self): except Exception as e: print(e) @@ -250,6 +251,14 @@ index 8457e40..f7d7d47 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: @@ -443,7 +452,7 @@ index 8457e40..f7d7d47 100644 # REMAP=S prolog=setspeed_prolog ngc=setspeed epilog=setspeed_epilog # exposed parameter: # -@@ -655,5 +913,3 @@ def tool_probe_m6(self, **words): +@@ -655,5 +921,3 @@ def tool_probe_m6(self, **words): self.set_errormsg("tool_probe_m6 remap error." ) yield INTERP_ERROR 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 505c98e..fd1f0ed 100644 --- a/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch +++ b/linuxcnc-patches/0015-rs274ngc-pass-spindle-selectors-to-remaps.patch @@ -9,7 +9,7 @@ Subject: [PATCH] rs274ngc: pass spindle selectors to remaps 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index 410381a..6027d2b 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 <> | Set Current Tool Number |<> | Output Control |<> | Input Control -@@ -411,6 +412,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. @@ -65,6 +65,7 @@ index e74ef24..b3cdbd0 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. @@ -84,10 +85,10 @@ index e74ef24..b3cdbd0 100644 == M61 Set Current Tool diff --git a/docs/src/remap/remap.adoc b/docs/src/remap/remap.adoc -index 6027d2b..e796ebb 100644 +index e332924..46b68ef 100644 --- a/docs/src/remap/remap.adoc +++ b/docs/src/remap/remap.adoc -@@ -1930,6 +1930,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) @@ -95,7 +96,7 @@ index 6027d2b..e796ebb 100644 - M60 (exchange pallet shuttles and then pause a running program temporarily) - M62 .. M65 (digital output control) - M66 (wait on input) -@@ -2119,7 +2120,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 | | @@ -104,7 +105,7 @@ index 6027d2b..e796ebb 100644 |60-69 | | | | | | | | | | |70-79 | | | | |M74 |M75 |M76 |M77 |M78 |M79 |80-89 |M80 |M81 |M82 |M83 |M84 |M85 |M86 |M87 |M88 |M89 -@@ -2128,6 +2129,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. @@ -216,15 +217,18 @@ index c65a3b2..219a007 100644 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 a02c025..cb7f482 100644 +index a02c025..6cdf203 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -4443,6 +4443,17 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ +@@ -4443,6 +4443,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); 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 385f805..ed2895a 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 @@ -28,8 +28,8 @@ other halui u32 pins. 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 | 63 +++++++++++++ - 22 files changed, 502 insertions(+), 4 deletions(-) + src/emc/usr_intf/halui_power_feed.hh | 67 ++++++++++++++ + 22 files changed, 506 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 @@ -865,12 +865,14 @@ index 65b890a..d59b478 100644 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 0000000..ad9e6e0 +index 0000000..c0024ad --- /dev/null +++ b/src/emc/usr_intf/halui_power_feed.hh -@@ -0,0 +1,63 @@ +@@ -0,0 +1,67 @@ +#pragma once + ++#include ++ +#include "hal.h" +#include "nml_intf/emc_nml.hh" + @@ -922,7 +924,9 @@ index 0000000..ad9e6e0 + command.x_direction = x; + command.z_direction = z; + command.feed_per_rev = hal_get_real(pins->feed); -+ command.spindle = spindle; ++ // 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; 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 index a61d65d..5e76a04 100644 --- 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 @@ -18,11 +18,11 @@ 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 | 50 +++++++++++++++++++++++++++++++++++++ - 1 file changed, 50 insertions(+) + 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 65846a8..968fb84 100644 +index 65846a8..f7db2f0 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1216,6 +1216,45 @@ static void emcTaskStopProgress() @@ -71,7 +71,26 @@ index 65846a8..968fb84 100644 /* emcTaskPlan() -@@ -1273,6 +1312,17 @@ static int emcTaskPlan(void) +@@ -1235,6 +1274,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: +@@ -1273,6 +1324,17 @@ static int emcTaskPlan(void) return retval; } diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 123a1ac..cb55920 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -372,8 +372,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. @@ -411,14 +413,22 @@ compensation being switched on and off through the existing canon calls, and `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. A Step that is canceled restores every segment it +changed. 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, Stop or Pause; Pause during an in-flight Step is an ordinary Pause. 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; +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 @@ -479,7 +489,9 @@ 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. The supplied `HalExecutor` endpoint adds namespaced request and response pins to a HAL component provided and owned by the machine configuration. It neither @@ -491,7 +503,8 @@ endpoint and an in-memory endpoint. 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, and a request +read ahead of a running AUTO move. Headless installs now include the curated `stdglue`. ### 0014 — Publish modal CSS maximum in spindle status @@ -610,7 +623,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. @@ -665,6 +680,8 @@ 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. Includes simulator coverage and HALUI pin documentation. ### 0021 — Cross-compile external HAL components @@ -767,11 +784,15 @@ 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. +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. The native server additionally refuses a reset while +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. 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 0000000..d6d1cc8 --- /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 0000000..91bba27 --- /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/test.sh b/linuxcnc-tests/interp/availability-mcodes/test.sh index c61548a..367dd32 100755 --- a/linuxcnc-tests/interp/availability-mcodes/test.sh +++ b/linuxcnc-tests/interp/availability-mcodes/test.sh @@ -62,6 +62,10 @@ check_rejected fractional-spindle.ngc '$ selector must be a non-negative integer 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" diff --git a/linuxcnc-tests/power-jog/test-ui.py b/linuxcnc-tests/power-jog/test-ui.py index cc11940..dbdd465 100755 --- a/linuxcnc-tests/power-jog/test-ui.py +++ b/linuxcnc-tests/power-jog/test-ui.py @@ -98,6 +98,14 @@ def origin(): 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) diff --git a/linuxcnc-tests/remap/executor/checkresult b/linuxcnc-tests/remap/executor/checkresult index 7fda879..d23add7 100755 --- a/linuxcnc-tests/remap/executor/checkresult +++ b/linuxcnc-tests/remap/executor/checkresult @@ -1,5 +1,5 @@ #!/bin/sh set -e -test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 4 +test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 5 grep -q '^executor remap scenarios complete$' "$1" diff --git a/linuxcnc-tests/remap/executor/readahead.ngc b/linuxcnc-tests/remap/executor/readahead.ngc new file mode 100644 index 0000000..c7ec232 --- /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/test-ui.py b/linuxcnc-tests/remap/executor/test-ui.py index fb9b77b..1ca48c7 100755 --- a/linuxcnc-tests/remap/executor/test-ui.py +++ b/linuxcnc-tests/remap/executor/test-ui.py @@ -51,6 +51,24 @@ def wait_request(executor, opcode): 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)) @@ -68,6 +86,7 @@ def assert_released(prefix): command = linuxcnc.command() status = linuxcnc.stat() +errors = linuxcnc.error_channel() test_component = hal.component("executor-test-ui") test_component.ready() @@ -136,6 +155,9 @@ def assert_released(prefix): ) 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") @@ -146,6 +168,8 @@ def assert_released(prefix): "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") @@ -170,6 +194,32 @@ def assert_released(prefix): "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") + else: fail("unknown executor scenario %s" % scenario) diff --git a/linuxcnc-tests/remap/executor/test.sh b/linuxcnc-tests/remap/executor/test.sh index 37ec101..1ee6126 100755 --- a/linuxcnc-tests/remap/executor/test.sh +++ b/linuxcnc-tests/remap/executor/test.sh @@ -4,7 +4,7 @@ # 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; do +for scenario in success failure timeout abort readahead; do echo "Running executor remap scenario: ${scenario}" EXECUTOR_SCENARIO="${scenario}" linuxcnc -r test.ini done diff --git a/linuxcnc-tests/resumable-stop/core_sim.hal b/linuxcnc-tests/resumable-stop/core_sim.hal index bbc7166..5723428 100644 --- a/linuxcnc-tests/resumable-stop/core_sim.hal +++ b/linuxcnc-tests/resumable-stop/core_sim.hal @@ -40,3 +40,11 @@ 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/general/checkresult b/linuxcnc-tests/resumable-stop/general/checkresult index 362de54..9bf048f 100755 --- a/linuxcnc-tests/resumable-stop/general/checkresult +++ b/linuxcnc-tests/resumable-stop/general/checkresult @@ -1,2 +1,2 @@ #!/bin/sh -exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 24 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 25 diff --git a/linuxcnc-tests/resumable-stop/general/scenarios b/linuxcnc-tests/resumable-stop/general/scenarios index d8e2870..f9d65ac 100644 --- a/linuxcnc-tests/resumable-stop/general/scenarios +++ b/linuxcnc-tests/resumable-stop/general/scenarios @@ -22,3 +22,4 @@ resume-atspeed pause-starting resume-s0 pause-inflight-step +trapezoidal:inflight-step-short 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 0000000..090a7b9 --- /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/test-ui.py b/linuxcnc-tests/resumable-stop/test-ui.py index ec9e072..2c77536 100755 --- a/linuxcnc-tests/resumable-stop/test-ui.py +++ b/linuxcnc-tests/resumable-stop/test-ui.py @@ -300,6 +300,61 @@ def run_inflight_single_step_test(): 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. @@ -898,6 +953,20 @@ def run_inflight_g76_single_step_test(): ): 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() @@ -2029,6 +2098,7 @@ def run_stopped_spindle_s_word_test(): "stop-latched-resume": lambda: run_cancel_latched_resume_test( "Stop", c.program_stop), "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, 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 0000000..f7f21f1 --- /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/test-ui.py b/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py index d4e6742..f6c85cc 100755 --- a/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py @@ -148,6 +148,31 @@ def abort_and_settle(name): 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 index 8cff916..2b489c0 100644 --- a/linuxcnc-tests/task/interp-reset-requires-idle/test.ini +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test.ini @@ -9,6 +9,9 @@ DISPLAY = ./test-ui.py PARAMETER_FILE = sim.var RS274NGC_STARTUP_CODE = G21 G90 +[EMCIO] +TOOL_TABLE = tool.tbl + [EMCMOT] EMCMOT = motmod COMM_TIMEOUT = 4.0 diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/test.sh b/linuxcnc-tests/task/interp-reset-requires-idle/test.sh index a16f6fa..f3f52ec 100755 --- a/linuxcnc-tests/task/interp-reset-requires-idle/test.sh +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test.sh @@ -1,2 +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 From 86b17c1c2b9c09945037a28b8b458a9a3cbd4220 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Tue, 24 Nov 2026 11:55:06 +0100 Subject: [PATCH 40/45] feat(linuxcnc): let Stop and Pause finish operations already under way Stop and Pause now wait for an operation task has already handed to another subsystem before the machine holds, as an M function runs to its completion signal on other controls: G28.2 homing, tool changes and other I/O commands, user M100-M199 programs, executor requests that have started, and M54/M55 handshakes waiting for their acknowledgment. Stop keeps spindle and coolant on until then. Abort ends the wait. - 0004: hold wait check and EMC_TASK_STAT.holdWait; Resume, Run and Step during STOPPING are refused instead of being remembered. - 0013: an executor request keeps being polled while held; a failure or timeout while held ends the program and clears the Stop. - 0017: Stop waits for an availability handshake's acknowledgment. - proto/native: TaskStat.hold_wait with delta support. --- docs/status-delta-boundaries.md | 3 +- linuxcnc-patches/0004-resumable-stop.patch | 206 ++++++++----- .../0007-native-automatic-tool-wear.patch | 52 ++-- ...reading-stop-clear-and-pass-stepping.patch | 44 +-- ...-single-step-during-active-execution.patch | 16 +- ...-own-transactional-tool-CRUD-in-task.patch | 28 +- ...4ngc-add-composable-executor-stdglue.patch | 276 +++++++++++++++++- ...-publish-modal-CSS-maximum-in-status.patch | 8 +- ...ntime-joint-and-spindle-availability.patch | 140 ++++++--- .../0018-availability-mcodes.patch | 2 +- ...otion-add-native-lathe-power-jogging.patch | 14 +- ...te-whenever-the-interpreter-is-reset.patch | 8 +- ...ter-reset-unless-the-machine-is-idle.patch | 8 +- linuxcnc-patches/README.md | 42 ++- linuxcnc-tests/availability-mcodes/test-ui.py | 18 +- linuxcnc-tests/remap/executor/checkresult | 2 +- .../remap/executor/hold-timeout.ngc | 4 + linuxcnc-tests/remap/executor/hold.ngc | 4 + linuxcnc-tests/remap/executor/test-ui.py | 65 +++++ linuxcnc-tests/remap/executor/test.sh | 2 +- linuxcnc-tests/resumable-stop/M101 | 4 + .../resumable-stop/general/checkresult | 2 +- .../resumable-stop/general/scenarios | 1 + .../resumable-stop/run-scenarios.sh | 2 +- .../resumable-stop/system-command.ngc | 7 + linuxcnc-tests/resumable-stop/test-ui.py | 122 ++++---- linuxcnc-tests/resumable-stop/test.ini | 1 + .../resumable-stop/threading/checkresult | 2 +- .../resumable-stop/threading/scenarios | 5 +- .../linuxcnc_grpc/linuxcnc/nml_adapter.hpp | 1 + native/server/src/linuxcnc/nml_adapter.cc | 1 + .../server/src/machine/grpc/status_codec.cc | 2 + .../tests/machine_status_codec_tests.cc | 2 + proto/linuxcnc/v1/machine.proto | 19 ++ 34 files changed, 802 insertions(+), 311 deletions(-) create mode 100644 linuxcnc-tests/remap/executor/hold-timeout.ngc create mode 100644 linuxcnc-tests/remap/executor/hold.ngc create mode 100755 linuxcnc-tests/resumable-stop/M101 create mode 100644 linuxcnc-tests/resumable-stop/system-command.ngc diff --git a/docs/status-delta-boundaries.md b/docs/status-delta-boundaries.md index e2e9527..f89e2d1 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/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index e45c509..243ff80 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -20,7 +20,7 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: - 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/python-interface.adoc | 12 + + docs/src/config/python-interface.adoc | 20 + docs/src/gui/halui.adoc | 3 +- docs/src/man/man1/halui.1.adoc | 5 +- src/emc/motion-logger/motion-logger.c | 4 + @@ -28,34 +28,42 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: src/emc/motion/control.c | 21 + src/emc/motion/motion.c | 1 + src/emc/motion/motion.h | 7 + - src/emc/nml_intf/emc.cc | 24 + - src/emc/nml_intf/emc.hh | 14 + - src/emc/nml_intf/emc_nml.hh | 22 + - src/emc/nml_intf/emcops.cc | 4 + - src/emc/task/emctaskmain.cc | 440 +++++++++++++++++- + 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 | 462 +++++++++++++++++- src/emc/task/taskintf.cc | 67 ++- - src/emc/tp/tp.c | 133 +++++- + src/emc/tp/tp.c | 133 ++++- src/emc/tp/tp_types.h | 12 + - src/emc/usr_intf/axis/extensions/emcmodule.cc | 14 + + src/emc/usr_intf/axis/extensions/emcmodule.cc | 19 + src/emc/usr_intf/halui.cc | 9 +- - 18 files changed, 812 insertions(+), 25 deletions(-) + 18 files changed, 860 insertions(+), 25 deletions(-) diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc -index 25d5762..fa546b7 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,14 @@ 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. @@ -293,7 +301,7 @@ index b98bfc0..1915616 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 ec54d4e..25e5f5a 100644 +index ec54d4e..27f5172 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc @@ -179,6 +179,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) @@ -362,15 +370,16 @@ index ec54d4e..25e5f5a 100644 cms->update(homed); } -@@ -1388,6 +1405,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); // 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 +1761,7 @@ void EMC_TRAJ_STAT::update(CMS * cms) +@@ -1743,6 +1762,7 @@ void EMC_TRAJ_STAT::update(CMS * cms) cms->update(queueFull); cms->update(id); cms->update(paused); @@ -378,7 +387,7 @@ index ec54d4e..25e5f5a 100644 cms->update(single_stepping); cms->update(scale); cms->update(rapid_scale); -@@ -1905,6 +1924,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); } @@ -391,7 +400,7 @@ index ec54d4e..25e5f5a 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 c2f4d1b..f28481b 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; @@ -410,7 +419,7 @@ index c2f4d1b..f28481b 100644 #define EMC_TASK_ABORT_TYPE ((NMLTYPE) 503) #define EMC_TASK_SET_MODE_TYPE ((NMLTYPE) 504) #define EMC_TASK_SET_STATE_TYPE ((NMLTYPE) 505) -@@ -228,6 +230,13 @@ enum class EMC_TASK_INTERP { +@@ -228,6 +230,22 @@ enum class EMC_TASK_INTERP { WAITING = 4 }; @@ -420,11 +429,20 @@ index c2f4d1b..f28481b 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, -@@ -369,6 +378,7 @@ extern int emcTrajEnable(); +@@ -369,6 +387,7 @@ extern int emcTrajEnable(); extern int emcTrajDisable(); extern int emcTrajAbort(); extern int emcTrajPause(); @@ -432,7 +450,7 @@ index c2f4d1b..f28481b 100644 extern int emcTrajReverse(); extern int emcTrajForward(); extern int emcTrajStep(); -@@ -436,6 +446,10 @@ extern int emcSpindleSpeed(int spindle, double speed, double factor, double xoff +@@ -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); @@ -444,7 +462,7 @@ index c2f4d1b..f28481b 100644 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 3d8c617..0d4ab6c 100644 +index 3d8c617..239d812 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh @@ -704,6 +704,15 @@ class EMC_TRAJ_PAUSE:public EMC_TRAJ_CMD_MSG { @@ -503,16 +521,18 @@ index 3d8c617..0d4ab6c 100644 class EMC_TASK_ABORT:public EMC_TASK_CMD_MSG { public: EMC_TASK_ABORT() -@@ -1516,6 +1537,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; ++ // 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 ed6a962..a6b2345 100644 +index ed6a962..6010ecb 100644 --- a/src/emc/nml_intf/emcops.cc +++ b/src/emc/nml_intf/emcops.cc @@ -78,6 +78,7 @@ EMC_TRAJ_STAT::EMC_TRAJ_STAT() @@ -523,15 +543,16 @@ index ed6a962..a6b2345 100644 single_stepping(false), scale(0.0), rapid_scale(0.0), -@@ -137,6 +138,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), -@@ -203,6 +205,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), @@ -539,7 +560,7 @@ index ed6a962..a6b2345 100644 state(0), direction(0), brake(1), -@@ -211,6 +214,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), @@ -548,10 +569,10 @@ index ed6a962..a6b2345 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a3b5256..15aac38 100644 +index a3b5256..8fff91d 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -124,6 +124,40 @@ 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 @@ -580,7 +601,6 @@ index a3b5256..15aac38 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; @@ -592,7 +612,7 @@ index a3b5256..15aac38 100644 // delay counter static double taskExecDelayTimeout = 0.0; -@@ -414,6 +448,10 @@ static double homingIssueTime = 0.0; // etime() when issued, for the start-t +@@ -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 @@ -603,7 +623,7 @@ index a3b5256..15aac38 100644 // 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 +560,9 @@ extern int emcTaskMopup(); +@@ -522,6 +559,9 @@ extern int emcTaskMopup(); void readahead_reading(void) { @@ -613,7 +633,7 @@ index a3b5256..15aac38 100644 int readRetval; int execRetval; -@@ -737,6 +778,9 @@ static void mdi_execute_hook(void) +@@ -737,6 +777,9 @@ static void mdi_execute_hook(void) void readahead_waiting(void) { @@ -623,7 +643,7 @@ index a3b5256..15aac38 100644 // now handle call logic // check for subsystems done if (interp_list.len() == 0 && -@@ -781,6 +825,275 @@ static bool allow_while_idle_type() { +@@ -781,6 +824,289 @@ static bool allow_while_idle_type() { return 0; } @@ -692,7 +712,6 @@ index a3b5256..15aac38 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; @@ -724,14 +743,12 @@ index a3b5256..15aac38 100644 +} + +/* -+ * A second Stop, or a Pause, while Resume is pending cancels it: a Resume -+ * latched during STOPPING is dropped, and 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. ++ * 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_resume_latched = false; + stop_single_step = false; + if (emcStatus->task.stopState == EMC_TASK_STOP_STATE::STARTING) { + emcTaskStopDisableSavedOutputs(); @@ -741,7 +758,6 @@ index a3b5256..15aac38 100644 + +static void emcTaskStopResume() +{ -+ stop_resume_latched = false; + if (!stop_outputs_saved) { + return; + } @@ -777,19 +793,40 @@ index a3b5256..15aac38 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: { -+ /* -+ * A queued G28.2 homing cycle cannot be paused and resumed part way, -+ * so, like position-synchronized motion, it runs to completion before -+ * Stop is reached. 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. -+ */ -+ if (emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_HOMING || ++ // 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; + } @@ -839,9 +876,6 @@ index a3b5256..15aac38 100644 + return; + } + emcStatus->task.stopState = EMC_TASK_STOP_STATE::STOPPED; -+ if (stop_resume_latched) { -+ emcTaskStopResume(); -+ } + return; + } + @@ -899,7 +933,7 @@ index a3b5256..15aac38 100644 /* emcTaskPlan() -@@ -809,6 +1122,29 @@ static int emcTaskPlan(void) +@@ -809,6 +1135,33 @@ static int emcTaskPlan(void) return retval; } @@ -911,6 +945,12 @@ index a3b5256..15aac38 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(); @@ -918,9 +958,7 @@ index a3b5256..15aac38 100644 + // 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; @@ -929,7 +967,7 @@ index a3b5256..15aac38 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1734,6 +2070,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1734,6 +2087,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; @@ -937,7 +975,7 @@ index a3b5256..15aac38 100644 if (homingPriorMode != EMC_TRAJ_MODE::FREE) { emcTrajSetMode(EMC_TRAJ_MODE::FREE); } -@@ -1937,6 +2274,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1937,6 +2291,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcTrajPause(); break; @@ -949,7 +987,7 @@ index a3b5256..15aac38 100644 case EMC_TRAJ_RESUME_TYPE: emcStatus->task.task_paused = 0; retval = emcTrajResume(); -@@ -2039,6 +2381,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2039,6 +2398,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE: wait_spindle_orient_complete_msg = reinterpret_cast(cmd); @@ -961,7 +999,7 @@ index a3b5256..15aac38 100644 taskExecDelayTimeout = etime() + wait_spindle_orient_complete_msg->timeout; break; -@@ -2099,6 +2446,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2099,6 +2463,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_ORIENT_TYPE: spindle_orient_msg = reinterpret_cast(cmd); @@ -976,7 +1014,7 @@ index a3b5256..15aac38 100644 retval = emcSpindleOrient(spindle_orient_msg->spindle, spindle_orient_msg->orientation, spindle_orient_msg->mode); break; -@@ -2191,7 +2546,50 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2191,7 +2563,49 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // task commands @@ -1003,7 +1041,6 @@ index a3b5256..15aac38 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; @@ -1027,7 +1064,7 @@ index a3b5256..15aac38 100644 // abort everything emcTaskAbort(); // KLUDGE call motion abort before state restore to make absolutely sure no -@@ -2215,6 +2613,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2215,6 +2629,9 @@ 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 @@ -1037,7 +1074,7 @@ index a3b5256..15aac38 100644 if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { // leaving auto or mdi mode for manual -@@ -2259,6 +2660,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2259,6 +2676,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_SET_STATE_TYPE: state_msg = reinterpret_cast(cmd); @@ -1047,7 +1084,7 @@ index a3b5256..15aac38 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2451,6 +2855,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2451,6 +2871,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_PAUSE_TYPE: @@ -1055,7 +1092,7 @@ index a3b5256..15aac38 100644 emcTrajPause(); if (emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED) { interpResumeState = emcStatus->task.interpState; -@@ -2484,11 +2889,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2484,11 +2905,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -1068,7 +1105,7 @@ index a3b5256..15aac38 100644 retval = 0; break; -@@ -2701,6 +3103,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3119,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -1076,7 +1113,7 @@ index a3b5256..15aac38 100644 /*! \todo FIXME-- duplicate code for abort, also near end of main, when aborting on subordinate errors, -@@ -2746,7 +3149,9 @@ static int emcTaskExecute(void) +@@ -2746,7 +3165,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -1087,7 +1124,7 @@ index a3b5256..15aac38 100644 if (NULL == emcTaskCommand) { // need a new command emcTaskCommand = interp_list.get(); -@@ -2767,7 +3172,7 @@ static int emcTaskExecute(void) +@@ -2767,7 +3188,7 @@ static int emcTaskExecute(void) emcStatus->task.execState = emcTaskCheckPreconditions(emcTaskCommand.get()); } } @@ -1096,7 +1133,7 @@ index a3b5256..15aac38 100644 // have an outstanding command // This is the one emcTaskIssueCommand() call site followed by // emcTaskCheckPostconditions(), i.e. the only one whose commands -@@ -3040,6 +3445,18 @@ static int emcTaskExecute(void) +@@ -3040,6 +3461,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -1115,7 +1152,7 @@ index a3b5256..15aac38 100644 // check if delay has passed emcStatus->task.delayLeft = taskExecDelayTimeout - etime(); if (etime() >= taskExecDelayTimeout) { -@@ -3626,6 +4043,7 @@ int main(int argc, char *argv[]) +@@ -3626,6 +4059,7 @@ int main(int argc, char *argv[]) prev_traj_enabled = emcStatus->motion.traj.enabled; // synchronize subordinate states if (emcStatus->io.aux.estop) { @@ -1123,7 +1160,7 @@ index a3b5256..15aac38 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3707,6 +4125,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4141,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -1131,7 +1168,7 @@ index a3b5256..15aac38 100644 // abort everything emcTaskAbort(); emcIoAbort(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); -@@ -3742,6 +4161,12 @@ int main(int argc, char *argv[]) +@@ -3742,6 +4177,18 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -1140,11 +1177,17 @@ index a3b5256..15aac38 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); -@@ -3762,6 +4187,9 @@ int main(int argc, char *argv[]) +@@ -3762,6 +4209,9 @@ int main(int argc, char *argv[]) emcStatus->io.status == RCS_STATUS::ERROR) { emcStatus->status = RCS_STATUS::ERROR; emcStatus->task.status = RCS_STATUS::ERROR; @@ -1504,18 +1547,19 @@ index 0e9ab84..d11e695 100644 diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc -index d242bd5..13069fb 100644 +index d242bd5..9261f61 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1138,6 +1138,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}, -@@ -2003,6 +2004,13 @@ static PyObject *emcabort(pyCommandChannel *s, PyObject * /*o*/) { +@@ -2003,6 +2005,13 @@ static PyObject *emcabort(pyCommandChannel *s, PyObject * /*o*/) { return Py_None; } @@ -1529,7 +1573,7 @@ index d242bd5..13069fb 100644 static PyObject *override_limits(pyCommandChannel *s, PyObject * /*o*/) { EMC_JOINT_OVERRIDE_LIMITS m; m.joint = 0; // same number for all -@@ -2405,6 +2413,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}, @@ -1537,11 +1581,15 @@ index d242bd5..13069fb 100644 {"task_plan_synch", (PyCFunction)task_plan_synch, METH_NOARGS, NULL}, {"override_limits", (PyCFunction)override_limits, METH_NOARGS, NULL}, {"home", (PyCFunction)home, METH_VARARGS, -@@ -3383,6 +3392,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); diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index 7a3859e..7efd114 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -153,10 +153,10 @@ index a99a87e..2d7a99e 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 fa546b7..5355172 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, @@ -166,7 +166,7 @@ index fa546b7..5355172 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', @@ -576,7 +576,7 @@ index 96e558d..68cf5d4 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 25e5f5a..d8d1d9d 100644 +index 27f5172..7a02127 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc @@ -780,6 +780,8 @@ void EMC_COOLANT_CMD_MSG::update(CMS * /*cms*/) @@ -615,10 +615,10 @@ index 25e5f5a..d8d1d9d 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 f28481b..4c8ebac 100644 +index d8b6a4b..fb1faa8 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh -@@ -430,9 +430,18 @@ 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); @@ -640,10 +640,10 @@ index f28481b..4c8ebac 100644 // 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 0d4ab6c..89aba60 100644 +index 239d812..b41c212 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -1637,13 +1637,22 @@ class EMC_TOOL_PREPARE: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() @@ -667,7 +667,7 @@ index 0d4ab6c..89aba60 100644 }; class EMC_TOOL_UNLOAD:public EMC_TOOL_CMD_MSG { -@@ -1680,6 +1689,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { +@@ -1682,6 +1691,8 @@ class EMC_TOOL_SET_OFFSET:public EMC_TOOL_CMD_MSG { pocket(0), toolno(0), offset{}, @@ -676,7 +676,7 @@ index 0d4ab6c..89aba60 100644 diameter(0.0), frontangle(0.0), backangle(0.0), -@@ -1694,6 +1705,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; @@ -685,7 +685,7 @@ index 0d4ab6c..89aba60 100644 double diameter; double frontangle; double backangle; -@@ -1704,7 +1717,9 @@ class EMC_TOOL_SET_NUMBER:public EMC_TOOL_CMD_MSG { +@@ -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)), @@ -696,7 +696,7 @@ index 0d4ab6c..89aba60 100644 {}; // For internal NML/CMS use only. -@@ -1713,6 +1728,10 @@ class EMC_TOOL_SET_NUMBER:public EMC_TOOL_CMD_MSG { +@@ -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 @@ -1471,10 +1471,10 @@ index 7620a30..55fb417 100644 // 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 15aac38..6025a96 100644 +index 8fff91d..9e21ff7 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -613,6 +613,9 @@ interpret_again: +@@ -612,6 +612,9 @@ interpret_again: emcStatus->task.interpState = EMC_TASK_INTERP::WAITING; interp_list.clear(); @@ -1484,7 +1484,7 @@ index 15aac38..6025a96 100644 emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, "interpreter error"); } else if (execRetval == -1 -@@ -1935,6 +1938,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1952,6 +1955,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) break; case EMC_TOOL_SET_NUMBER_TYPE: @@ -1496,7 +1496,7 @@ index 15aac38..6025a96 100644 return EMC_TASK_EXEC::WAITING_FOR_IO; break; -@@ -2012,6 +2020,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) +@@ -2029,6 +2037,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) } // issues command immediately @@ -1509,7 +1509,7 @@ index 15aac38..6025a96 100644 static int emcTaskIssueCommand(NMLmsg * cmd) { int retval = 0; -@@ -2515,9 +2529,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2532,9 +2546,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcToolPrepare(tool_prepare_msg->tool); break; @@ -1524,7 +1524,7 @@ index 15aac38..6025a96 100644 case EMC_TOOL_UNLOAD_TYPE: retval = emcToolUnload(); -@@ -2533,6 +2551,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2550,6 +2568,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, @@ -1533,7 +1533,7 @@ index 15aac38..6025a96 100644 emc_tool_set_offset_msg->diameter, emc_tool_set_offset_msg->frontangle, emc_tool_set_offset_msg->backangle, -@@ -2542,6 +2562,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2559,6 +2579,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); @@ -1544,7 +1544,7 @@ index 15aac38..6025a96 100644 break; // task commands -@@ -3130,6 +3154,7 @@ static int emcTaskExecute(void) +@@ -3146,6 +3170,7 @@ static int emcTaskExecute(void) // clear out pending command emcTaskCommand = NULL; interp_list.clear(); @@ -1552,7 +1552,7 @@ index 15aac38..6025a96 100644 emcAbortCleanup(EMC_ABORT::TASK_EXEC_ERROR); emcStatus->task.currentLine = 0; -@@ -3696,7 +3721,8 @@ static int emctask_startup() +@@ -3712,7 +3737,8 @@ static int emctask_startup() } // initialize the subsystems @@ -1562,7 +1562,7 @@ index 15aac38..6025a96 100644 if (emcIoInit() != 0) { rcs_print_error("can't initialize IO\n"); return -1; -@@ -4146,6 +4172,7 @@ int main(int argc, char *argv[]) +@@ -4162,6 +4188,7 @@ int main(int argc, char *argv[]) // clear out the pending command emcTaskCommand = NULL; interp_list.clear(); @@ -2295,7 +2295,7 @@ index 4a5f885..963f4a5 100644 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 13069fb..8e91c88 100644 +index 9261f61..6a0b6d7 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc @@ -1098,6 +1098,15 @@ static PyObject *toolinfo(pyStatChannel * /*s*/, PyObject *o) { @@ -2314,7 +2314,7 @@ index 13069fb..8e91c88 100644 PyDict_SetItemString(res, "comment", o= PyUnicode_FromString(tdata.comment)); Py_DECREF(o); -@@ -1485,6 +1494,15 @@ static PyStructSequence_Field tool_fields[] = { +@@ -1486,6 +1495,15 @@ static PyStructSequence_Field tool_fields[] = { {(char*)"frontangle", NULL}, {(char*)"backangle", NULL}, {(char*)"orientation", NULL}, @@ -2330,7 +2330,7 @@ index 13069fb..8e91c88 100644 {}, }; -@@ -1492,7 +1510,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, @@ -2339,7 +2339,7 @@ index 13069fb..8e91c88 100644 }; static PyTypeObject ToolResultType; -@@ -1530,6 +1548,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)); 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 d55160a..1491d38 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -234,7 +234,7 @@ index 68cf5d4..ee99e8e 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 d8d1d9d..ded71c3 100644 +index 7a02127..891516e 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc @@ -212,6 +212,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) @@ -278,7 +278,7 @@ index d8d1d9d..ded71c3 100644 /* diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index 4c8ebac..6b3f9d9 100644 +index fb1faa8..c98adba 100644 --- a/src/emc/nml_intf/emc.hh +++ b/src/emc/nml_intf/emc.hh @@ -145,6 +145,7 @@ struct PM_CARTESIAN; @@ -289,7 +289,7 @@ index 4c8ebac..6b3f9d9 100644 #define EMC_TASK_STAT_TYPE ((NMLTYPE) 599) -@@ -386,7 +387,8 @@ 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, @@ -300,7 +300,7 @@ index 4c8ebac..6b3f9d9 100644 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 89aba60..cf8bc14 100644 +index b41c212..6a5632c 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh @@ -752,7 +752,9 @@ class EMC_TRAJ_LINEAR_MOVE:public EMC_TRAJ_CMD_MSG { @@ -684,10 +684,10 @@ index 55fb417..90cc136 100644 } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 6025a96..e2a7209 100644 +index 9e21ff7..e2bdf62 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -504,6 +504,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; @@ -710,7 +710,7 @@ index 6025a96..e2a7209 100644 // Variables to handle MDI call interrupts // Depth of call level before interrupted MDI call -@@ -874,8 +890,7 @@ static void emcTaskResumeInterpreter() +@@ -873,8 +889,7 @@ static void emcTaskResumeInterpreter() emcStatus->task.interpState = interpResumeState; } emcStatus->motion.traj.single_stepping = 0; @@ -720,7 +720,7 @@ index 6025a96..e2a7209 100644 } static void emcTaskStepInterpreter() -@@ -1554,6 +1569,10 @@ static int emcTaskPlan(void) +@@ -1571,6 +1586,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 @@ -731,7 +731,7 @@ index 6025a96..e2a7209 100644 break; // otherwise we can't handle it -@@ -1706,6 +1725,10 @@ static int emcTaskPlan(void) +@@ -1723,6 +1742,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 @@ -742,7 +742,7 @@ index 6025a96..e2a7209 100644 break; // otherwise we can't handle it -@@ -1963,6 +1986,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1980,6 +2003,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; @@ -754,7 +754,7 @@ index 6025a96..e2a7209 100644 case EMC_TRAJ_DELAY_TYPE: return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2268,7 +2296,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2285,7 +2313,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajLinearMoveMsg->type, emcTrajLinearMoveMsg->vel, emcTrajLinearMoveMsg->ini_maxvel, emcTrajLinearMoveMsg->acc, emcTrajLinearMoveMsg->ini_maxjerk, emcTrajLinearMoveMsg->vlimit_scale, @@ -765,7 +765,7 @@ index 6025a96..e2a7209 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2639,6 +2669,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2655,6 +2685,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } else { // we can honour the modeswitch if (mode_msg->mode != emcStatus->task.mode) { emcTaskStopClear(); @@ -774,7 +774,7 @@ index 6025a96..e2a7209 100644 } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { -@@ -2672,8 +2704,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2688,8 +2720,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; @@ -784,7 +784,7 @@ index 6025a96..e2a7209 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2686,6 +2717,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2702,6 +2733,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) state_msg = reinterpret_cast(cmd); if (state_msg->state != EMC_TASK_STATE::ON) { emcTaskStopClear(); @@ -793,7 +793,7 @@ index 6025a96..e2a7209 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2770,8 +2803,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2786,8 +2819,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_EXECUTE_TYPE: emcStatus->motion.traj.single_stepping = 0; @@ -803,7 +803,7 @@ index 6025a96..e2a7209 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")); -@@ -2866,8 +2898,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2882,8 +2914,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -813,7 +813,7 @@ index 6025a96..e2a7209 100644 if (!taskplanopen && emcStatus->task.file[0] != 0) { emcTaskPlanOpen(emcStatus->task.file); } -@@ -2936,6 +2967,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2952,6 +2983,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -824,7 +824,7 @@ index 6025a96..e2a7209 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: os_msg = reinterpret_cast(cmd); emcTaskPlanSetOptionalStop(os_msg->state); -@@ -3044,6 +3079,7 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3060,6 +3095,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: @@ -832,7 +832,7 @@ index 6025a96..e2a7209 100644 case EMC_TASK_PLAN_EXECUTE_TYPE: case EMC_TASK_PLAN_OPTIONAL_STOP_TYPE: return EMC_TASK_EXEC::DONE; -@@ -3096,11 +3132,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3112,11 +3148,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) #define STEPPING_CHECK() \ if (stepping) { \ if (! steppingWait) { \ @@ -854,7 +854,7 @@ index 6025a96..e2a7209 100644 break; \ } \ } \ -@@ -3162,8 +3205,7 @@ static int emcTaskExecute(void) +@@ -3178,8 +3221,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; @@ -864,7 +864,7 @@ index 6025a96..e2a7209 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -3185,6 +3227,7 @@ static int emcTaskExecute(void) +@@ -3201,6 +3243,7 @@ static int emcTaskExecute(void) if (NULL != emcTaskCommand) { emcTaskEager = 1; emcStatus->task.currentLine = interp_list.get_line_number(); @@ -872,7 +872,7 @@ index 6025a96..e2a7209 100644 // 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. -@@ -4181,8 +4224,7 @@ int main(int argc, char *argv[]) +@@ -4197,8 +4240,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; 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 ae19b95..0c240ef 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 @@ -99,10 +99,10 @@ index e347bf1..75a9f1c 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index e2a7209..f69fcbb 100644 +index e2bdf62..7185ec7 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -504,6 +504,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; @@ -110,7 +110,7 @@ index e2a7209..f69fcbb 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 -@@ -519,6 +520,7 @@ void emcTaskResetSteppingState() +@@ -518,6 +519,7 @@ void emcTaskResetSteppingState() steppedLine = 0; currentPassGroup = 0; steppedPassGroup = 0; @@ -118,7 +118,7 @@ index e2a7209..f69fcbb 100644 } // Variables to handle MDI call interrupts -@@ -904,6 +906,22 @@ static void emcTaskStepInterpreter() +@@ -903,6 +905,22 @@ static void emcTaskStepInterpreter() emcStatus->task.task_paused = 1; } @@ -141,7 +141,7 @@ index e2a7209..f69fcbb 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1566,13 +1584,7 @@ static int emcTaskPlan(void) +@@ -1583,13 +1601,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -156,7 +156,7 @@ index e2a7209..f69fcbb 100644 break; // otherwise we can't handle it -@@ -1646,17 +1658,9 @@ static int emcTaskPlan(void) +@@ -1663,17 +1675,9 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -175,7 +175,7 @@ index e2a7209..f69fcbb 100644 break; // otherwise we can't handle it -@@ -1722,13 +1726,7 @@ static int emcTaskPlan(void) +@@ -1739,13 +1743,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -190,7 +190,7 @@ index e2a7209..f69fcbb 100644 break; // otherwise we can't handle it -@@ -4102,6 +4100,10 @@ int main(int argc, char *argv[]) +@@ -4118,6 +4116,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); 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 187d3b3..14c7fd8 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 @@ -39,7 +39,7 @@ tests/tooldb tests, which need a db program, are skipped. 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 ded71c3..ce4110e 100644 +index 891516e..61fa3b6 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc @@ -254,6 +254,12 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) @@ -97,7 +97,7 @@ index ded71c3..ce4110e 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 6b3f9d9..d445ee8 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; @@ -117,7 +117,7 @@ index 6b3f9d9..d445ee8 100644 #define EMC_TOOL_STAT_TYPE ((NMLTYPE) 1199) -@@ -444,6 +447,8 @@ extern void emcToolSetChangeOffset(bool apply, const EmcPose& offset); +@@ -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&)); @@ -127,10 +127,10 @@ index 6b3f9d9..d445ee8 100644 // 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 cf8bc14..b40c76d 100644 +index 6a5632c..e4a04b1 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh -@@ -1730,6 +1730,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; }; @@ -182,10 +182,10 @@ index cf8bc14..b40c76d 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index f69fcbb..bb43b9c 100644 +index 7185ec7..f483726 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1263,7 +1263,18 @@ static int emcTaskPlan(void) +@@ -1280,7 +1280,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -205,7 +205,7 @@ index f69fcbb..bb43b9c 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO emcTaskQueueCommand(std::make_unique(*static_cast(emcCommand))); -@@ -1392,6 +1403,18 @@ static int emcTaskPlan(void) +@@ -1409,6 +1420,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -224,7 +224,7 @@ index f69fcbb..bb43b9c 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO -@@ -1517,6 +1540,18 @@ static int emcTaskPlan(void) +@@ -1534,6 +1557,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -243,7 +243,7 @@ index f69fcbb..bb43b9c 100644 // otherwise we can't handle it default: -@@ -1852,6 +1887,18 @@ static int emcTaskPlan(void) +@@ -1869,6 +1904,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -262,7 +262,7 @@ index f69fcbb..bb43b9c 100644 // otherwise we can't handle it default: -@@ -1955,6 +2002,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1972,6 +2019,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) case EMC_TOOL_LOAD_TOOL_TABLE_TYPE: case EMC_TOOL_SET_OFFSET_TYPE: @@ -271,7 +271,7 @@ index f69fcbb..bb43b9c 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2587,6 +2636,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2604,6 +2653,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emc_tool_set_offset_msg->orientation); break; @@ -286,7 +286,7 @@ index f69fcbb..bb43b9c 100644 case EMC_TOOL_SET_NUMBER_TYPE: emc_tool_set_number_msg = reinterpret_cast(cmd); retval = emcToolSetNumber(emc_tool_set_number_msg->tool); -@@ -3060,6 +3117,8 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3076,6 +3133,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: @@ -295,7 +295,7 @@ index f69fcbb..bb43b9c 100644 case EMC_TOOL_SET_NUMBER_TYPE: case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: -@@ -3244,10 +3303,18 @@ static int emcTaskExecute(void) +@@ -3260,10 +3319,18 @@ static int emcTaskExecute(void) // emcTaskCheckPostconditions(), i.e. the only one whose commands // can reach a WAITING_FOR_* state. See issuingQueuedCommand. issuingQueuedCommand = true; diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index b730b02..f7d23b5 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -19,14 +19,36 @@ 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 | 130 +++++++++ - nc_files/remap_lib/python-stdglue/stdglue.py | 268 ++++++++++++++++++- - src/emc/rs274ngc/interp_internal.hh | 3 + - src/emc/rs274ngc/interp_python.cc | 60 ++++- - src/emc/rs274ngc/interp_python.hh | 7 + - src/emc/rs274ngc/rs274ngc_pre.cc | 5 + - 6 files changed, 470 insertions(+), 3 deletions(-) + docs/src/config/python-interface.adoc | 3 +- + docs/src/remap/remap.adoc | 130 +++++++++ + nc_files/remap_lib/python-stdglue/stdglue.py | 271 +++++++++++++++++- + src/emc/nml_intf/emc.hh | 3 +- + src/emc/rs274ngc/interp_internal.hh | 7 + + src/emc/rs274ngc/interp_python.cc | 60 +++- + 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 | 43 ++- + src/emc/task/task.hh | 4 + + src/emc/usr_intf/axis/extensions/emcmodule.cc | 1 + + 14 files changed, 548 insertions(+), 10 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 75e2a09..642e4c7 100644 --- a/docs/src/remap/remap.adoc @@ -169,7 +191,7 @@ index 75e2a09..642e4c7 100644 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 8457e40..3cd13d2 100644 +index 8457e40..be54d1a 100644 --- a/nc_files/remap_lib/python-stdglue/stdglue.py +++ b/nc_files/remap_lib/python-stdglue/stdglue.py @@ -16,6 +16,9 @@ @@ -182,7 +204,7 @@ index 8457e40..3cd13d2 100644 import emccanon from interpreter import * from emccanon import MESSAGE -@@ -40,6 +43,269 @@ def build_hal(self): +@@ -40,6 +43,272 @@ def build_hal(self): except Exception as e: print(e) @@ -286,6 +308,9 @@ index 8457e40..3cd13d2 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: @@ -452,14 +477,28 @@ index 8457e40..3cd13d2 100644 # REMAP=S prolog=setspeed_prolog ngc=setspeed epilog=setspeed_epilog # exposed parameter: # -@@ -655,5 +921,3 @@ def tool_probe_m6(self, **words): +@@ -655,5 +924,3 @@ def tool_probe_m6(self, **words): self.set_errormsg("tool_probe_m6 remap error." ) yield INTERP_ERROR - - +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) + }; + + // types for motion control diff --git a/src/emc/rs274ngc/interp_internal.hh b/src/emc/rs274ngc/interp_internal.hh -index 210b4db..65197e8 100644 +index 210b4db..692b6e9 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh @@ -620,6 +620,9 @@ struct pycontext { @@ -472,6 +511,17 @@ index 210b4db..65197e8 100644 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 e3f8b60..34f6fbc 100644 --- a/src/emc/rs274ngc/interp_python.cc @@ -592,11 +642,48 @@ index 3fcf26b..baedeab 100644 // 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 2ea3ba1..dea5749 100644 +index 2ea3ba1..85dd055 100644 --- a/src/emc/rs274ngc/rs274ngc_pre.cc +++ b/src/emc/rs274ngc/rs274ngc_pre.cc -@@ -1246,6 +1246,10 @@ int Interp::init() +@@ -1246,7 +1246,12 @@ int Interp::init() //_setup.feed_hold set in Interp::synch // initialization stuff for subroutines and control structures @@ -605,9 +692,17 @@ index 2ea3ba1..dea5749 100644 + 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; -@@ -1760,6 +1764,7 @@ int Interp::unwind_call(int status, const char *file, int line, const char *func + _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; @@ -615,3 +710,156 @@ index 2ea3ba1..dea5749 100644 free_named_parameters(&_setup.sub_context[_setup.call_level]); if(sub->subName) { logDebug("unwind_call leaving sub '%s'", sub->subName); +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; ++ } ++} ++ + int emcTaskPlanClearWait() + { + waitFlag = 0; +diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc +index f483726..7156924 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 = +@@ -880,6 +900,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; + } +@@ -1021,6 +1045,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; + } +@@ -1723,6 +1750,9 @@ static int emcTaskPlan(void) + + } // switch (type) in ON, AUTO, PAUSED + ++ // an executor request under way is polled while paused ++ readahead_reading(); ++ + break; // EMC_TASK_INTERP::PAUSED + + case EMC_TASK_INTERP::WAITING: +@@ -3289,7 +3319,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) { +@@ -3594,7 +3625,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 cc57a7f4..e115ca9 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 @@ -26,10 +26,10 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index bb43b9c..ee88562 100644 +index 7156924..76e3cf8 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1035,7 +1035,7 @@ static void emcTaskStopProgress() +@@ -1078,7 +1078,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]; @@ -52,10 +52,10 @@ index 3328659..aa63ab4 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 8e91c88..f5cc454 100644 +index 74edfa0..af63368 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1462,6 +1462,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); diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index dab33c3..89f32a2 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -32,7 +32,7 @@ gain the availability configuration and reordered ABORT, as in the other motion-logger tests. --- docs/src/config/ini-config.adoc | 33 + - docs/src/config/python-interface.adoc | 26 + + 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 + @@ -46,19 +46,19 @@ other motion-logger tests. 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 | 16 + + 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 | 295 ++++++++- + src/emc/task/emctaskmain.cc | 308 +++++++++- src/emc/task/task.hh | 1 + src/emc/task/taskintf.cc | 112 +++- - src/emc/usr_intf/axis/extensions/emcmodule.cc | 24 + + 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 +- - 27 files changed, 1703 insertions(+), 102 deletions(-) + 27 files changed, 1721 insertions(+), 104 deletions(-) diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc index 2d7a99e..e93f55a 100644 @@ -112,10 +112,20 @@ index 2d7a99e..e93f55a 100644 [[sub:ini:sec:emcio]] === [EMCIO] Section(((INI File,Sections,[EMCIO] Section))) diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc -index 5355172..82db3c9 100644 +index 2131b07..08e75bd 100644 --- a/docs/src/config/python-interface.adoc +++ b/docs/src/config/python-interface.adoc -@@ -446,6 +446,9 @@ print("Joint 1 homed: ", s.joint[1]["homed"]) +@@ -220,7 +220,8 @@ see <> 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: @@ -125,7 +135,7 @@ index 5355172..82db3c9 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 @@ -135,7 +145,7 @@ index 5355172..82db3c9 100644 *brake*:: '(returns integer)' - value of the spindle brake flag. -@@ -765,6 +771,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 @@ -1994,7 +2004,7 @@ index ad391e1..bed4351 100644 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 ce4110e..f70a5e0 100644 +index 61fa3b6..54d973c 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc @@ -59,6 +59,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) @@ -2076,7 +2086,7 @@ index ce4110e..f70a5e0 100644 /* diff --git a/src/emc/nml_intf/emc.hh b/src/emc/nml_intf/emc.hh -index d445ee8..ba2bd2f 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; @@ -2095,7 +2105,17 @@ index d445ee8..ba2bd2f 100644 #define EMC_SPINDLE_STAT_TYPE ((NMLTYPE) 1399) -@@ -332,6 +334,11 @@ extern int emcJointSetMaxAcceleration(int joint, double acc); +@@ -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); @@ -2107,7 +2127,7 @@ index d445ee8..ba2bd2f 100644 extern int emcJointUnhome(int joint); extern int emcJointActivate(int joint); extern int emcJointDeactivate(int joint); -@@ -344,6 +351,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); +@@ -354,6 +362,10 @@ extern int emcJogAbs(int nr, double pos, double vel, int jjogmode); extern int emcJointUpdate(EMC_JOINT_STAT stat[], int numJoints); @@ -2118,7 +2138,7 @@ index d445ee8..ba2bd2f 100644 extern int emcJointSetMaxJerk(int joint, double jerk); -@@ -473,6 +484,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); @@ -2131,7 +2151,7 @@ index d445ee8..ba2bd2f 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 b40c76d..c03bfc3 100644 +index e4a04b1..feab3fb 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh @@ -356,6 +356,17 @@ class EMC_JOINT_UNHOME:public EMC_JOINT_CMD_MSG { @@ -2172,7 +2192,7 @@ index b40c76d..c03bfc3 100644 }; class EMC_MOTION_STAT:public EMC_MOTION_STAT_MSG { -@@ -2000,6 +2017,18 @@ class EMC_SPINDLE_OFF:public EMC_SPINDLE_CMD_MSG { +@@ -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 }; @@ -2192,7 +2212,7 @@ index b40c76d..c03bfc3 100644 public: EMC_SPINDLE_INCREASE() diff --git a/src/emc/nml_intf/emcops.cc b/src/emc/nml_intf/emcops.cc -index a6b2345..2e672de 100644 +index 6010ecb..72fd7d4 100644 --- a/src/emc/nml_intf/emcops.cc +++ b/src/emc/nml_intf/emcops.cc @@ -58,7 +58,10 @@ EMC_JOINT_STAT::EMC_JOINT_STAT() @@ -2207,7 +2227,7 @@ index a6b2345..2e672de 100644 { } -@@ -215,7 +218,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), @@ -2220,7 +2240,7 @@ index a6b2345..2e672de 100644 } diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index 90cc136..5a1e60e 100644 +index d2634e9..f889dd3 100644 --- a/src/emc/task/emctask.cc +++ b/src/emc/task/emctask.cc @@ -245,6 +245,7 @@ void emcTaskQueueTaskPlanSynchCmd() @@ -2232,10 +2252,10 @@ index 90cc136..5a1e60e 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index ee88562..b0ece8e 100644 +index 76e3cf8..86385c3 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -172,6 +172,61 @@ 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 @@ -2297,7 +2317,7 @@ index ee88562..b0ece8e 100644 static int joints = 0; uint64_t task_beat = 0; // Task's main loop heartbeat counter -@@ -183,8 +238,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++) { @@ -2313,7 +2333,7 @@ index ee88562..b0ece8e 100644 } return 1; } -@@ -437,21 +497,27 @@ static EMC_TRAJ_SET_SPINDLESYNC *emcTrajSetSpindlesyncMsg; +@@ -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 @@ -2345,7 +2365,7 @@ index ee88562..b0ece8e 100644 // 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 -@@ -463,6 +529,19 @@ static EMC_TASK_MODE homingPriorTaskMode = EMC_TASK_MODE::MANUAL; +@@ -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; @@ -2365,7 +2385,7 @@ index ee88562..b0ece8e 100644 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; -@@ -922,6 +1001,13 @@ static bool emcTaskArmSingleStep() +@@ -945,6 +1024,13 @@ static bool emcTaskArmSingleStep() return true; } @@ -2379,7 +2399,27 @@ index ee88562..b0ece8e 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1162,6 +1248,31 @@ static int emcTaskPlan(void) +@@ -1057,6 +1143,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; + } + +@@ -1202,6 +1301,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2411,7 +2451,7 @@ index ee88562..b0ece8e 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -@@ -1181,6 +1292,36 @@ static int emcTaskPlan(void) +@@ -1225,6 +1349,36 @@ static int emcTaskPlan(void) return 0; } @@ -2448,7 +2488,7 @@ index ee88562..b0ece8e 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1693,9 +1834,7 @@ static int emcTaskPlan(void) +@@ -1737,9 +1891,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2459,7 +2499,7 @@ index ee88562..b0ece8e 100644 break; // otherwise we can't handle it -@@ -1958,6 +2097,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -2005,6 +2157,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: @@ -2468,7 +2508,7 @@ index ee88562..b0ece8e 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2164,10 +2305,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2211,10 +2365,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajSetMode(EMC_TRAJ_MODE::FREE); } homingWaitJoint = target_joint; @@ -2481,7 +2521,7 @@ index ee88562..b0ece8e 100644 if (retval != 0) { // emcJointHome() rejected the request outright (e.g. an // invalid joint number) -- homing will never start, so the -@@ -2177,9 +2320,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2224,9 +2380,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // from it) stays stuck at FREE/MANUAL until the operator // manually cycles mode again. homingWaiting = false; @@ -2492,7 +2532,7 @@ index ee88562..b0ece8e 100644 } } break; -@@ -2193,6 +2334,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2240,6 +2394,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2517,7 +2557,7 @@ index ee88562..b0ece8e 100644 case EMC_JOG_CONT_TYPE: jog_cont_msg = reinterpret_cast(cmd); retval = emcJogCont(jog_cont_msg->joint_or_axis, -@@ -2560,6 +2719,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2607,6 +2779,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcSpindleOff(spindle_off_msg->spindle, spindle_off_msg->wait_for_spindle_at_speed); break; @@ -2544,7 +2584,7 @@ index ee88562..b0ece8e 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -3016,7 +3195,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3062,7 +3254,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2559,7 +2599,7 @@ index ee88562..b0ece8e 100644 if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -3131,6 +3317,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3177,6 +3376,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2571,7 +2611,7 @@ index ee88562..b0ece8e 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -3213,6 +3404,12 @@ static int emcTaskExecute(void) +@@ -3259,6 +3463,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2584,7 +2624,7 @@ index ee88562..b0ece8e 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3339,11 +3536,59 @@ static int emcTaskExecute(void) +@@ -3386,11 +3596,59 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: @@ -2644,7 +2684,7 @@ index ee88562..b0ece8e 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } -@@ -3471,12 +3716,17 @@ static int emcTaskExecute(void) +@@ -3518,12 +3776,17 @@ static int emcTaskExecute(void) homingStarted = true; break; // still running; no timeout once started (see HOMING_START_TIMEOUT comment) } @@ -2667,7 +2707,7 @@ index ee88562..b0ece8e 100644 // HOMING_START_TIMEOUT before concluding it was rejected. if (etime() - homingIssueTime < HOMING_START_TIMEOUT) { break; -@@ -3488,11 +3738,8 @@ static int emcTaskExecute(void) +@@ -3535,11 +3798,8 @@ static int emcTaskExecute(void) emcTaskEager = 1; homingWaiting = false; // Nothing physically moved, so it's safe to restore the @@ -2681,7 +2721,7 @@ index ee88562..b0ece8e 100644 break; } // It ran and has now stopped; did it reach the expected end state? -@@ -3558,7 +3805,9 @@ static int emcTaskExecute(void) +@@ -3605,7 +3865,9 @@ static int emcTaskExecute(void) "coordinated motion until every joint is homed")); emcStatus->task.execState = EMC_TASK_EXEC::ERROR; } else if (success) { @@ -2693,7 +2733,7 @@ index ee88562..b0ece8e 100644 emcTrajSetMode(homingPriorMode); } diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh -index 79dbeb6..223886e 100644 +index ea3bdc8..4a7089e 100644 --- a/src/emc/task/task.hh +++ b/src/emc/task/task.hh @@ -34,6 +34,7 @@ int emcTaskInit(); @@ -2911,10 +2951,10 @@ index aa63ab4..27418ce 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 f5cc454..7733e39 100644 +index af63368..25b240e 100644 --- a/src/emc/usr_intf/axis/extensions/emcmodule.cc +++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc -@@ -1418,6 +1418,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); @@ -2924,7 +2964,7 @@ index f5cc454..7733e39 100644 return res; } #undef F -@@ -1467,6 +1470,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); @@ -2934,7 +2974,7 @@ index f5cc454..7733e39 100644 return res; } #undef F -@@ -2063,6 +2069,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { +@@ -2064,6 +2070,20 @@ static PyObject *unhome(pyCommandChannel *s, PyObject *o) { return Py_None; } @@ -2955,7 +2995,7 @@ index f5cc454..7733e39 100644 // jog(JOG_STOP, jjogmode, ja_value) // jog(JOG_CONTINUOUS, jjogmode, ja_value, speed) // jog(JOG_INCREMENT, jjogmode, ja_value, speed, increment) -@@ -2449,6 +2469,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}, @@ -2966,6 +3006,14 @@ index f5cc454..7733e39 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 diff --git a/linuxcnc-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index 972f15d..93bfdb7 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -269,7 +269,7 @@ index e08e4a6..21edbb7 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 65197e8..ddae1dc 100644 +index 692b6e9..8ffadca 100644 --- a/src/emc/rs274ngc/interp_internal.hh +++ b/src/emc/rs274ngc/interp_internal.hh @@ -479,12 +479,19 @@ struct block_struct 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 ed2895a..cef7275 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 @@ -600,7 +600,7 @@ index 0000000..293e1d0 + +#endif diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc -index f70a5e0..b2b729a 100644 +index 54d973c..133869b 100644 --- a/src/emc/nml_intf/emc.cc +++ b/src/emc/nml_intf/emc.cc @@ -65,6 +65,9 @@ int emcFormat(NMLTYPE type, void *buffer, CMS * cms) @@ -639,7 +639,7 @@ index f70a5e0..b2b729a 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 ba2bd2f..c33ee96 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; @@ -650,7 +650,7 @@ index ba2bd2f..c33ee96 100644 #define EMC_JOINT_STAT_TYPE ((NMLTYPE) 198) #define EMC_AXIS_STAT_TYPE ((NMLTYPE) 199) -@@ -346,6 +347,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); @@ -659,7 +659,7 @@ index ba2bd2f..c33ee96 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 c03bfc3..05a29fe 100644 +index feab3fb..a9fc353 100644 --- a/src/emc/nml_intf/emc_nml.hh +++ b/src/emc/nml_intf/emc_nml.hh @@ -367,6 +367,17 @@ class EMC_JOINT_SET_AVAILABILITY:public EMC_JOINT_CMD_MSG { @@ -681,10 +681,10 @@ index c03bfc3..05a29fe 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index b0ece8e..9097f40 100644 +index 86385c3..20092fb 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1464,6 +1464,7 @@ static int emcTaskPlan(void) +@@ -1521,6 +1521,7 @@ static int emcTaskPlan(void) case EMC_JOINT_HOME_TYPE: case EMC_JOINT_UNHOME_TYPE: case EMC_JOG_CONT_TYPE: @@ -692,7 +692,7 @@ index b0ece8e..9097f40 100644 case EMC_JOG_INCR_TYPE: case EMC_JOG_ABS_TYPE: case EMC_JOG_STOP_TYPE: -@@ -2365,6 +2366,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2425,6 +2426,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; 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 index e3fb55c..eefdbd5 100644 --- 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 @@ -37,7 +37,7 @@ MDI works afterwards. 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/emc/task/emctask.cc b/src/emc/task/emctask.cc -index 5a1e60e..67edc9b 100644 +index f889dd3..b6793d2 100644 --- a/src/emc/task/emctask.cc +++ b/src/emc/task/emctask.cc @@ -282,6 +282,10 @@ int emcTaskAbort() @@ -52,10 +52,10 @@ index 5a1e60e..67edc9b 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 9097f40..65846a8 100644 +index 20092fb..b2d4a91 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -798,7 +798,7 @@ interpret_again: +@@ -817,7 +817,7 @@ interpret_again: } // if interp len is less than max } @@ -65,7 +65,7 @@ index 9097f40..65846a8 100644 int queued_mdi_commands; diff --git a/src/emc/task/task.hh b/src/emc/task/task.hh -index 223886e..1a7a999 100644 +index 4a7089e..4220b67 100644 --- a/src/emc/task/task.hh +++ b/src/emc/task/task.hh @@ -34,6 +34,7 @@ int emcTaskInit(); 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 index 5e76a04..3d451dc 100644 --- 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 @@ -22,10 +22,10 @@ and accepted again once the machine is idle. 1 file changed, 62 insertions(+) diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 65846a8..f7db2f0 100644 +index b2d4a91..42f985ac 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1216,6 +1216,45 @@ static void emcTaskStopProgress() +@@ -1269,6 +1269,45 @@ static void emcTaskStopProgress() } } @@ -71,7 +71,7 @@ index 65846a8..f7db2f0 100644 /* emcTaskPlan() -@@ -1235,6 +1274,18 @@ static int emcTaskPlan(void) +@@ -1288,6 +1327,18 @@ static int emcTaskPlan(void) type = 0; } @@ -90,7 +90,7 @@ index 65846a8..f7db2f0 100644 // Always display messages switch (type) { case EMC_OPERATOR_ERROR_TYPE: -@@ -1273,6 +1324,17 @@ static int emcTaskPlan(void) +@@ -1326,6 +1377,17 @@ static int emcTaskPlan(void) return retval; } diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index cb55920..c35cefa 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -210,6 +210,15 @@ reaches `STOPPED`: - 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. @@ -230,9 +239,10 @@ 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. -A second Stop or a Pause while Resume is pending (in `STARTING`, or a Resume -latched during `STOPPING`) cancels it: the program stays in or returns to -`STOPPED` with the restored outputs off. A spindle restored at commanded speed 0 does not +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 @@ -249,10 +259,11 @@ 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 four re-runs with the trapezoidal planner. They cover +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, Stop and Pause while Resume is pending, Pause during an in-flight Step, Resume of a spindle restored at S0, commands queued behind a thread, `G33` threading including a chain of +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, 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. @@ -493,6 +504,13 @@ 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. +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. 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 constructs the component nor calls `ready()`, allowing multiple endpoints and @@ -503,8 +521,9 @@ endpoint and an in-memory endpoint. 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, cancellation, and a request -read ahead of a running AUTO move. Headless +responses, monotonic request IDs, request release, cancellation, a request +read ahead of a running AUTO move, Stop and Pause during a request, and a +timeout while stopping. Headless installs now include the curated `stdglue`. ### 0014 — Publish modal CSS maximum in spindle status @@ -591,10 +610,11 @@ 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. Stop or Pause before the -hardware acknowledgment of an unhomed joint does not hold `STOPPING`: the -acknowledgment completes the handshake and the acquisition home starts only -after Resume. Once acknowledged, the home must start within +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. diff --git a/linuxcnc-tests/availability-mcodes/test-ui.py b/linuxcnc-tests/availability-mcodes/test-ui.py index 0f3d8df..36ce873 100755 --- a/linuxcnc-tests/availability-mcodes/test-ui.py +++ b/linuxcnc-tests/availability-mcodes/test-ui.py @@ -165,9 +165,10 @@ def idle(): wait(lambda: s.interp_state == linuxcnc.INTERP_IDLE and s.exec_state 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 ACK completes the -# handshake, but like a queued G28.2 the acquisition home starts only after -# Resume. Time held exceeds AVAILABILITY_TIMEOUT, which does not run then. +# 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') @@ -179,10 +180,17 @@ def idle(): wait(lambda: s.interp_state == linuxcnc.INTERP_IDLE and s.exec_state 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_STOPPED, 'Stop before ACK') + 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, 'Pause before ACK') + 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' diff --git a/linuxcnc-tests/remap/executor/checkresult b/linuxcnc-tests/remap/executor/checkresult index d23add7..b3f6a2c 100755 --- a/linuxcnc-tests/remap/executor/checkresult +++ b/linuxcnc-tests/remap/executor/checkresult @@ -1,5 +1,5 @@ #!/bin/sh set -e -test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 5 +test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 8 grep -q '^executor remap scenarios complete$' "$1" diff --git a/linuxcnc-tests/remap/executor/hold-timeout.ngc b/linuxcnc-tests/remap/executor/hold-timeout.ngc new file mode 100644 index 0000000..73e9722 --- /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 0000000..f87cbff --- /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/test-ui.py b/linuxcnc-tests/remap/executor/test-ui.py index 1ca48c7..59542e6 100755 --- a/linuxcnc-tests/remap/executor/test-ui.py +++ b/linuxcnc-tests/remap/executor/test-ui.py @@ -220,6 +220,71 @@ def assert_released(prefix): 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 == "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") + else: fail("unknown executor scenario %s" % scenario) diff --git a/linuxcnc-tests/remap/executor/test.sh b/linuxcnc-tests/remap/executor/test.sh index 1ee6126..e2e3e8f 100755 --- a/linuxcnc-tests/remap/executor/test.sh +++ b/linuxcnc-tests/remap/executor/test.sh @@ -4,7 +4,7 @@ # 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; do +for scenario in success failure timeout abort readahead stop pause stop-timeout; do echo "Running executor remap scenario: ${scenario}" EXECUTOR_SCENARIO="${scenario}" linuxcnc -r test.ini done diff --git a/linuxcnc-tests/resumable-stop/M101 b/linuxcnc-tests/resumable-stop/M101 new file mode 100755 index 0000000..5ffe22d --- /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/general/checkresult b/linuxcnc-tests/resumable-stop/general/checkresult index 9bf048f..a81b33d 100755 --- a/linuxcnc-tests/resumable-stop/general/checkresult +++ b/linuxcnc-tests/resumable-stop/general/checkresult @@ -1,2 +1,2 @@ #!/bin/sh -exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 25 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 26 diff --git a/linuxcnc-tests/resumable-stop/general/scenarios b/linuxcnc-tests/resumable-stop/general/scenarios index f9d65ac..37ac880 100644 --- a/linuxcnc-tests/resumable-stop/general/scenarios +++ b/linuxcnc-tests/resumable-stop/general/scenarios @@ -23,3 +23,4 @@ pause-starting resume-s0 pause-inflight-step trapezoidal:inflight-step-short +system-command diff --git a/linuxcnc-tests/resumable-stop/run-scenarios.sh b/linuxcnc-tests/resumable-stop/run-scenarios.sh index 4c52c4b..a304399 100755 --- a/linuxcnc-tests/resumable-stop/run-scenarios.sh +++ b/linuxcnc-tests/resumable-stop/run-scenarios.sh @@ -34,7 +34,7 @@ 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 "$config"/ + "$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" diff --git a/linuxcnc-tests/resumable-stop/system-command.ngc b/linuxcnc-tests/resumable-stop/system-command.ngc new file mode 100644 index 0000000..7ba66fb --- /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/test-ui.py b/linuxcnc-tests/resumable-stop/test-ui.py index 2c77536..41e67f0 100755 --- a/linuxcnc-tests/resumable-stop/test-ui.py +++ b/linuxcnc-tests/resumable-stop/test-ui.py @@ -1225,6 +1225,43 @@ def run_dwell_stop_resume_test(): 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_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 @@ -1505,10 +1542,10 @@ def run_pause_while_starting_test(): assert_outputs_stopped_after_program() -def run_cancel_latched_resume_test(label, cancel): - # Resume during STOPPING is latched until Stop completes; a Pause or a - # second Stop after it cancels the latched Resume, so the program stays - # STOPPED. +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( @@ -1518,34 +1555,44 @@ def run_cancel_latched_resume_test(label, cancel): "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, ) - c.auto(linuxcnc.AUTO_RESUME) - cancel() + 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 Resume and %s were sent" % label) + 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: "%s after latched Resume did not leave the program " - "STOPPED: X=%.3f Z=%.3f stop=%d" - % (label, s.position[0], s.position[2], s.stop_state), + 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("%s after latched Resume: program left STOPPED" % label) + fail("refused %s: program left STOPPED" % label) if hal.get_value("spindle.0.on"): - fail("%s after latched Resume: spindle on while STOPPED" % label) + fail("refused %s: spindle on while STOPPED" % label) if abs(s.position[0]) > 0.001: - fail("%s after latched Resume: feed after G33 moved" % label) + fail("refused %s: feed after G33 moved" % label) c.auto(linuxcnc.AUTO_RESUME) wait_for( @@ -1557,7 +1604,6 @@ def run_cancel_latched_resume_test(label, cancel): ) 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. @@ -1948,44 +1994,6 @@ def run_threading_chain_stop_resume_test(): ) -def run_step_then_resume_while_stopping_test(): - # Step followed by Resume while Stop waits for G33 must resume the - # program normally rather than single-step it. - 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, - ) - - # Stop completes only on STOPPED, so do not wait for it here. - c.program_stop() - wait_for( - lambda: s.stop_state == linuxcnc.STOP_STOPPING, - "Stop did not wait for the active G33", - timeout=1.0, - ) - c.auto(linuxcnc.AUTO_STEP) - c.auto(linuxcnc.AUTO_RESUME) - s.poll() - if s.stop_state != linuxcnc.STOP_STOPPING: - fail("G33 finished before Step and Resume were sent") - - 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), - lambda: "program did not run to completion after Step and Resume: " - "X=%.3f interp=%d paused=%d stop=%d" - % (s.position[0], s.interp_state, s.task_paused, s.stop_state), - timeout=20.0, - ) - assert_outputs_stopped_after_program() - - 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 @@ -2089,14 +2097,15 @@ def run_stopped_spindle_s_word_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, "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, - "pause-latched-resume": lambda: run_cancel_latched_resume_test( - "Pause", lambda: c.auto(linuxcnc.AUTO_PAUSE)), - "stop-latched-resume": lambda: run_cancel_latched_resume_test( - "Stop", c.program_stop), + "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, @@ -2107,7 +2116,6 @@ def run_stopped_spindle_s_word_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, - "step-resume-stopping": run_step_then_resume_while_stopping_test, "g95-between-g33": run_g95_between_g33_stop_resume_test, "spindle-state": run_stopped_spindle_s_word_test, } diff --git a/linuxcnc-tests/resumable-stop/test.ini b/linuxcnc-tests/resumable-stop/test.ini index 96b5a38..6c0370f 100644 --- a/linuxcnc-tests/resumable-stop/test.ini +++ b/linuxcnc-tests/resumable-stop/test.ini @@ -7,6 +7,7 @@ DISPLAY = ./test-ui.py [RS274NGC] PARAMETER_FILE = sim.var +USER_M_PATH = . [EMCMOT] EMCMOT = motmod diff --git a/linuxcnc-tests/resumable-stop/threading/checkresult b/linuxcnc-tests/resumable-stop/threading/checkresult index 664eed8..3b2acd1 100755 --- a/linuxcnc-tests/resumable-stop/threading/checkresult +++ b/linuxcnc-tests/resumable-stop/threading/checkresult @@ -1,2 +1,2 @@ #!/bin/sh -exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 11 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 10 diff --git a/linuxcnc-tests/resumable-stop/threading/scenarios b/linuxcnc-tests/resumable-stop/threading/scenarios index a4410d4..7391ffb 100644 --- a/linuxcnc-tests/resumable-stop/threading/scenarios +++ b/linuxcnc-tests/resumable-stop/threading/scenarios @@ -3,9 +3,8 @@ g33 queued-g33 g33-chain trapezoidal:g33-chain -step-resume-stopping g95-between-g33 g33-no-following-rapid command-after-sync -pause-latched-resume -stop-latched-resume +resume-stopping-refused +step-stopping-refused diff --git a/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp b/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp index 7a65bbb..56c698f 100644 --- a/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp +++ b/native/server/include/linuxcnc_grpc/linuxcnc/nml_adapter.hpp @@ -144,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 { diff --git a/native/server/src/linuxcnc/nml_adapter.cc b/native/server/src/linuxcnc/nml_adapter.cc index 853edf0..35c00ac 100644 --- a/native/server/src/linuxcnc/nml_adapter.cc +++ b/native/server/src/linuxcnc/nml_adapter.cc @@ -400,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; diff --git a/native/server/src/machine/grpc/status_codec.cc b/native/server/src/machine/grpc/status_codec.cc index 018e67b..868b2d9 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/tests/machine_status_codec_tests.cc b/native/server/tests/machine_status_codec_tests.cc index a77ba5d..e1a0dd7 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/proto/linuxcnc/v1/machine.proto b/proto/linuxcnc/v1/machine.proto index c4d6763..9481bda 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 { From 51f61e2d7021f1ba2e449ac50625ca677a66bfd7 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Tue, 24 Nov 2026 14:20:32 +0100 Subject: [PATCH 41/45] fix(linuxcnc): close pre2 review round 6 - 0004: setting AUTO or MDI ends a Stop, as the abort it causes does; document that threading and rigid tapping use the trapezoidal planner. - 0013: executor requests are refused under cutter radius compensation. - 0017: a released spindle counts as at speed for the other spindles. - 0020: a power jog stops just inside a soft limit, like an ordinary jog. - 0021: a SYSROOT exported by a cross SDK no longer turns a native halcompile build into a cross build. --- linuxcnc-patches/0004-resumable-stop.patch | 60 +++++++++----- .../0007-native-automatic-tool-wear.patch | 8 +- ...reading-stop-clear-and-pass-stepping.patch | 42 +++++----- ...-single-step-during-active-execution.patch | 22 ++--- ...-own-transactional-tool-CRUD-in-task.patch | 6 +- ...4ngc-add-composable-executor-stdglue.patch | 25 ++++-- ...-publish-modal-CSS-maximum-in-status.patch | 2 +- ...ntime-joint-and-spindle-availability.patch | 83 +++++++++++-------- ...w-concurrent-individual-joint-homing.patch | 4 +- ...otion-add-native-lathe-power-jogging.patch | 31 ++++--- ...-cross-compiling-external-components.patch | 17 ++-- ...te-whenever-the-interpreter-is-reset.patch | 2 +- ...ter-reset-unless-the-machine-is-idle.patch | 2 +- linuxcnc-patches/README.md | 31 +++++-- linuxcnc-tests/halcompile/cross-tools/test.sh | 5 +- linuxcnc-tests/power-jog/test-ui.py | 6 ++ linuxcnc-tests/remap/executor/checkresult | 2 +- linuxcnc-tests/remap/executor/comp.ngc | 6 ++ linuxcnc-tests/remap/executor/test-ui.py | 13 +++ linuxcnc-tests/remap/executor/test.sh | 2 +- .../resumable-stop/general/checkresult | 2 +- .../resumable-stop/general/scenarios | 1 + linuxcnc-tests/resumable-stop/set-auto.ngc | 7 ++ linuxcnc-tests/resumable-stop/test-ui.py | 62 ++++++++++++++ .../atspeed.hal | 20 +++++ .../atspeed.ini.in | 6 ++ .../atspeed.ngc | 5 ++ .../checkresult | 2 +- .../test-ui.py | 8 ++ .../runtime-availability-regressions/test.sh | 3 +- 30 files changed, 344 insertions(+), 141 deletions(-) create mode 100644 linuxcnc-tests/remap/executor/comp.ngc create mode 100644 linuxcnc-tests/resumable-stop/set-auto.ngc create mode 100644 linuxcnc-tests/runtime-availability-regressions/atspeed.hal create mode 100644 linuxcnc-tests/runtime-availability-regressions/atspeed.ini.in create mode 100644 linuxcnc-tests/runtime-availability-regressions/atspeed.ngc diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 243ff80..d8137a1 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -32,13 +32,13 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: 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 | 462 +++++++++++++++++- + src/emc/task/emctaskmain.cc | 465 +++++++++++++++++- src/emc/task/taskintf.cc | 67 ++- - src/emc/tp/tp.c | 133 ++++- + 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 +- - 18 files changed, 860 insertions(+), 25 deletions(-) + 18 files changed, 874 insertions(+), 25 deletions(-) diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc index 25d5762..5153f11 100644 @@ -569,7 +569,7 @@ index ed6a962..6010ecb 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a3b5256..8fff91d 100644 +index a3b5256..60ae9b4 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -124,6 +124,39 @@ static int emcTaskEager = 0; @@ -1064,17 +1064,20 @@ index a3b5256..8fff91d 100644 // abort everything emcTaskAbort(); // KLUDGE call motion abort before state restore to make absolutely sure no -@@ -2215,6 +2629,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2215,6 +2629,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 -@@ -2259,6 +2676,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2259,6 +2679,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_SET_STATE_TYPE: state_msg = reinterpret_cast(cmd); @@ -1084,7 +1087,7 @@ index a3b5256..8fff91d 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2451,6 +2871,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2451,6 +2874,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_PAUSE_TYPE: @@ -1092,7 +1095,7 @@ index a3b5256..8fff91d 100644 emcTrajPause(); if (emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED) { interpResumeState = emcStatus->task.interpState; -@@ -2484,11 +2905,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2484,11 +2908,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -1105,7 +1108,7 @@ index a3b5256..8fff91d 100644 retval = 0; break; -@@ -2701,6 +3119,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3122,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -1113,7 +1116,7 @@ index a3b5256..8fff91d 100644 /*! \todo FIXME-- duplicate code for abort, also near end of main, when aborting on subordinate errors, -@@ -2746,7 +3165,9 @@ static int emcTaskExecute(void) +@@ -2746,7 +3168,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -1124,7 +1127,7 @@ index a3b5256..8fff91d 100644 if (NULL == emcTaskCommand) { // need a new command emcTaskCommand = interp_list.get(); -@@ -2767,7 +3188,7 @@ static int emcTaskExecute(void) +@@ -2767,7 +3191,7 @@ static int emcTaskExecute(void) emcStatus->task.execState = emcTaskCheckPreconditions(emcTaskCommand.get()); } } @@ -1133,7 +1136,7 @@ index a3b5256..8fff91d 100644 // have an outstanding command // This is the one emcTaskIssueCommand() call site followed by // emcTaskCheckPostconditions(), i.e. the only one whose commands -@@ -3040,6 +3461,18 @@ static int emcTaskExecute(void) +@@ -3040,6 +3464,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -1152,7 +1155,7 @@ index a3b5256..8fff91d 100644 // check if delay has passed emcStatus->task.delayLeft = taskExecDelayTimeout - etime(); if (etime() >= taskExecDelayTimeout) { -@@ -3626,6 +4059,7 @@ int main(int argc, char *argv[]) +@@ -3626,6 +4062,7 @@ int main(int argc, char *argv[]) prev_traj_enabled = emcStatus->motion.traj.enabled; // synchronize subordinate states if (emcStatus->io.aux.estop) { @@ -1160,7 +1163,7 @@ index a3b5256..8fff91d 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3707,6 +4141,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4144,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -1168,7 +1171,7 @@ index a3b5256..8fff91d 100644 // abort everything emcTaskAbort(); emcIoAbort(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); -@@ -3742,6 +4177,18 @@ int main(int argc, char *argv[]) +@@ -3742,6 +4180,18 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -1187,7 +1190,7 @@ index a3b5256..8fff91d 100644 // update task-specific status emcTaskUpdate(&emcStatus->task); -@@ -3762,6 +4209,9 @@ int main(int argc, char *argv[]) +@@ -3762,6 +4212,9 @@ int main(int argc, char *argv[]) emcStatus->io.status == RCS_STATUS::ERROR) { emcStatus->status = RCS_STATUS::ERROR; emcStatus->task.status = RCS_STATUS::ERROR; @@ -1310,7 +1313,7 @@ index 4215d22..3f66a0b 100644 return 0; } diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index c75c795..8ef21c3 100644 +index c75c795..e481a43 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c @@ -229,6 +229,31 @@ STATIC int tpGetMachineActiveLimit(double * const act_limit, PmCartesian const * @@ -1406,17 +1409,28 @@ index c75c795..8ef21c3 100644 } /** Wrapper function to unlock rotary axes */ -@@ -3812,6 +3857,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 -@@ -4253,10 +4301,48 @@ 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) { @@ -1465,7 +1479,7 @@ index c75c795..8ef21c3 100644 tc_debug_print("-------------------\n"); -@@ -4270,6 +4356,18 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4270,6 +4367,18 @@ int tpRunCycle(TP_STRUCT * const tp, long period) return TP_ERR_STOPPED; } @@ -1484,7 +1498,7 @@ index c75c795..8ef21c3 100644 //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 +4463,27 @@ int tpPause(TP_STRUCT * const tp) +@@ -4365,7 +4474,27 @@ int tpPause(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -1513,7 +1527,7 @@ index c75c795..8ef21c3 100644 return TP_ERR_OK; } -@@ -4375,6 +4493,9 @@ int tpResume(TP_STRUCT * const tp) +@@ -4375,6 +4504,9 @@ int tpResume(TP_STRUCT * const tp) return TP_ERR_FAIL; } tp->pausing = 0; diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index 7efd114..2a39227 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -1471,7 +1471,7 @@ index 7620a30..55fb417 100644 // 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 8fff91d..9e21ff7 100644 +index 60ae9b4..eb0dda6 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -612,6 +612,9 @@ interpret_again: @@ -1544,7 +1544,7 @@ index 8fff91d..9e21ff7 100644 break; // task commands -@@ -3146,6 +3170,7 @@ static int emcTaskExecute(void) +@@ -3149,6 +3173,7 @@ static int emcTaskExecute(void) // clear out pending command emcTaskCommand = NULL; interp_list.clear(); @@ -1552,7 +1552,7 @@ index 8fff91d..9e21ff7 100644 emcAbortCleanup(EMC_ABORT::TASK_EXEC_ERROR); emcStatus->task.currentLine = 0; -@@ -3712,7 +3737,8 @@ static int emctask_startup() +@@ -3715,7 +3740,8 @@ static int emctask_startup() } // initialize the subsystems @@ -1562,7 +1562,7 @@ index 8fff91d..9e21ff7 100644 if (emcIoInit() != 0) { rcs_print_error("can't initialize IO\n"); return -1; -@@ -4162,6 +4188,7 @@ int main(int argc, char *argv[]) +@@ -4165,6 +4191,7 @@ int main(int argc, char *argv[]) // clear out the pending command emcTaskCommand = NULL; interp_list.clear(); 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 1491d38..c32aebf 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -684,7 +684,7 @@ index 55fb417..90cc136 100644 } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 9e21ff7..e2bdf62 100644 +index eb0dda6..3f7e971 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -503,6 +503,22 @@ static int programStartLine = 0; // which line to run program from @@ -765,16 +765,16 @@ index 9e21ff7..e2bdf62 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2655,6 +2685,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) - } else { // we can honour the modeswitch - if (mode_msg->mode != emcStatus->task.mode) { +@@ -2658,6 +2688,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) { -@@ -2688,8 +2720,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2691,8 +2723,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; @@ -784,7 +784,7 @@ index 9e21ff7..e2bdf62 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2702,6 +2733,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2705,6 +2736,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) state_msg = reinterpret_cast(cmd); if (state_msg->state != EMC_TASK_STATE::ON) { emcTaskStopClear(); @@ -793,7 +793,7 @@ index 9e21ff7..e2bdf62 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2786,8 +2819,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2789,8 +2822,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_EXECUTE_TYPE: emcStatus->motion.traj.single_stepping = 0; @@ -803,7 +803,7 @@ index 9e21ff7..e2bdf62 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")); -@@ -2882,8 +2914,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2885,8 +2917,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -813,7 +813,7 @@ index 9e21ff7..e2bdf62 100644 if (!taskplanopen && emcStatus->task.file[0] != 0) { emcTaskPlanOpen(emcStatus->task.file); } -@@ -2952,6 +2983,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2955,6 +2986,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -824,7 +824,7 @@ index 9e21ff7..e2bdf62 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: os_msg = reinterpret_cast(cmd); emcTaskPlanSetOptionalStop(os_msg->state); -@@ -3060,6 +3095,7 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3063,6 +3098,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: @@ -832,7 +832,7 @@ index 9e21ff7..e2bdf62 100644 case EMC_TASK_PLAN_EXECUTE_TYPE: case EMC_TASK_PLAN_OPTIONAL_STOP_TYPE: return EMC_TASK_EXEC::DONE; -@@ -3112,11 +3148,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3115,11 +3151,18 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) #define STEPPING_CHECK() \ if (stepping) { \ if (! steppingWait) { \ @@ -854,7 +854,7 @@ index 9e21ff7..e2bdf62 100644 break; \ } \ } \ -@@ -3178,8 +3221,7 @@ static int emcTaskExecute(void) +@@ -3181,8 +3224,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; @@ -864,7 +864,7 @@ index 9e21ff7..e2bdf62 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -3201,6 +3243,7 @@ static int emcTaskExecute(void) +@@ -3204,6 +3246,7 @@ static int emcTaskExecute(void) if (NULL != emcTaskCommand) { emcTaskEager = 1; emcStatus->task.currentLine = interp_list.get_line_number(); @@ -872,7 +872,7 @@ index 9e21ff7..e2bdf62 100644 // 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. -@@ -4197,8 +4240,7 @@ int main(int argc, char *argv[]) +@@ -4200,8 +4243,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; @@ -936,7 +936,7 @@ index 47018b2..bd8ad13 100644 // this segment (g64 mode) diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index 8ef21c3..c9b271e 100644 +index e481a43..a9dfacc 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c @@ -240,10 +240,12 @@ STATIC int tpGetMachineActiveLimit(double * const act_limit, PmCartesian const * @@ -1111,7 +1111,7 @@ index 8ef21c3..c9b271e 100644 //TODO make progress to match target? // done with this move if (tp->reverse_run) { -@@ -4303,6 +4374,10 @@ 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); @@ -1122,7 +1122,7 @@ index 8ef21c3..c9b271e 100644 if (tp->stopping) { tp->stop_sync_run = 0; tp->pausing = 1; -@@ -4310,6 +4385,11 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4321,6 +4396,11 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -1134,7 +1134,7 @@ index 8ef21c3..c9b271e 100644 tpHandleEmptyQueue(tp); return TP_ERR_WAITING; } -@@ -4458,6 +4538,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; } @@ -1177,7 +1177,7 @@ index 8ef21c3..c9b271e 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4465,22 +4581,75 @@ int tpPause(TP_STRUCT * const tp) +@@ -4476,22 +4592,75 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -1259,7 +1259,7 @@ index 8ef21c3..c9b271e 100644 } else { tp->pausing = 1; } -@@ -4495,6 +4664,17 @@ int tpResume(TP_STRUCT * const tp) +@@ -4506,6 +4675,17 @@ int tpResume(TP_STRUCT * const tp) tp->pausing = 0; tp->stopping = 0; tp->stop_sync_run = 0; @@ -1277,7 +1277,7 @@ index 8ef21c3..c9b271e 100644 emcmotStatus->stopped = 0; return TP_ERR_OK; } -@@ -4507,6 +4687,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 */ 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 0c240ef..2c78c47 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 @@ -99,7 +99,7 @@ index e347bf1..75a9f1c 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index e2bdf62..7185ec7 100644 +index 3f7e971..7335937 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -503,6 +503,7 @@ static int programStartLine = 0; // which line to run program from @@ -190,7 +190,7 @@ index e2bdf62..7185ec7 100644 break; // otherwise we can't handle it -@@ -4118,6 +4116,10 @@ int main(int argc, char *argv[]) +@@ -4121,6 +4119,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); @@ -216,7 +216,7 @@ index bd8ad13..5d6e0b4 100644 // this segment (g64 mode) diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index c9b271e..c42d4f1 100644 +index a9dfacc..85ee681 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c @@ -357,9 +357,9 @@ STATIC inline double tpGetRealFinalVel(TP_STRUCT const * const tp, @@ -278,7 +278,7 @@ index c9b271e..c42d4f1 100644 } //TODO make progress to match target? -@@ -4385,7 +4387,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) +@@ -4396,7 +4398,7 @@ int tpRunCycle(TP_STRUCT * const tp, long period) } return TP_ERR_WAITING; } @@ -287,7 +287,7 @@ index c9b271e..c42d4f1 100644 tp->step_pass_id && !tp->step_tc) { tpHandleEmptyQueue(tp); return TP_ERR_WAITING; -@@ -4574,6 +4576,146 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) +@@ -4585,6 +4587,146 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) return tc ? tc->g76_pass_id : 0; } @@ -434,7 +434,7 @@ index c9b271e..c42d4f1 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4581,10 +4723,12 @@ int tpPause(TP_STRUCT * const tp) +@@ -4592,10 +4734,12 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -448,7 +448,7 @@ index c9b271e..c42d4f1 100644 TC_STRUCT *tc = tcqItem(&tp->queue, 0); /* * A G76 cut that has passed spindle index, or its explicitly marked -@@ -4631,7 +4775,7 @@ int tpPause(TP_STRUCT * const tp) +@@ -4642,7 +4786,7 @@ int tpPause(TP_STRUCT * const tp) tp->pausing = 1; } } else if (emcmotStatus->stepping && @@ -457,7 +457,7 @@ index c9b271e..c42d4f1 100644 /* * EMCMOT_STEP requests default-TP pass targeting through the existing * tpPause ABI. Alternate planners leave step_target_pending clear and -@@ -4640,15 +4784,27 @@ int tpPause(TP_STRUCT * const tp) +@@ -4651,15 +4795,27 @@ int tpPause(TP_STRUCT * const tp) int pass_id = tpGetQueuedG76PassId(tp); if (pass_id) { tp->step_pass_id = pass_id; @@ -489,7 +489,7 @@ index c9b271e..c42d4f1 100644 } } else { tp->pausing = 1; -@@ -4661,6 +4817,7 @@ int tpResume(TP_STRUCT * const tp) +@@ -4672,6 +4828,7 @@ int tpResume(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -497,7 +497,7 @@ index c9b271e..c42d4f1 100644 tp->pausing = 0; tp->stopping = 0; tp->stop_sync_run = 0; -@@ -4670,7 +4827,8 @@ int tpResume(TP_STRUCT * const tp) +@@ -4681,7 +4838,8 @@ int tpResume(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; @@ -507,7 +507,7 @@ index c9b271e..c42d4f1 100644 if (MOTION_ID_VALID(tp->spindle.waiting_for_index)) { emcmotStatus->spindle_status[ tp->spindle.spindle_num].spindle_index_enable = 1; -@@ -4690,7 +4848,9 @@ int tpAbort(TP_STRUCT * const tp) +@@ -4701,7 +4859,9 @@ int tpAbort(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; 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 14c7fd8..5e4220b 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 @@ -182,7 +182,7 @@ index 6a5632c..e4a04b1 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 7185ec7..f483726 100644 +index 7335937..a8ee5a6 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1280,7 +1280,18 @@ static int emcTaskPlan(void) @@ -286,7 +286,7 @@ index 7185ec7..f483726 100644 case EMC_TOOL_SET_NUMBER_TYPE: emc_tool_set_number_msg = reinterpret_cast(cmd); retval = emcToolSetNumber(emc_tool_set_number_msg->tool); -@@ -3076,6 +3133,8 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3079,6 +3136,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: @@ -295,7 +295,7 @@ index 7185ec7..f483726 100644 case EMC_TOOL_SET_NUMBER_TYPE: case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: -@@ -3260,10 +3319,18 @@ static int emcTaskExecute(void) +@@ -3263,10 +3322,18 @@ static int emcTaskExecute(void) // emcTaskCheckPostconditions(), i.e. the only one whose commands // can reach a WAITING_FOR_* state. See issuingQueuedCommand. issuingQueuedCommand = true; diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index f7d23b5..3602410 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -20,8 +20,8 @@ pycall() then returns the unwind status (INTERP_EXIT or an error) instead of continuing the unwound call. --- docs/src/config/python-interface.adoc | 3 +- - docs/src/remap/remap.adoc | 130 +++++++++ - nc_files/remap_lib/python-stdglue/stdglue.py | 271 +++++++++++++++++- + docs/src/remap/remap.adoc | 130 ++++++++ + nc_files/remap_lib/python-stdglue/stdglue.py | 278 +++++++++++++++++- src/emc/nml_intf/emc.hh | 3 +- src/emc/rs274ngc/interp_internal.hh | 7 + src/emc/rs274ngc/interp_python.cc | 60 +++- @@ -33,7 +33,7 @@ instead of continuing the unwound call. src/emc/task/emctaskmain.cc | 43 ++- src/emc/task/task.hh | 4 + src/emc/usr_intf/axis/extensions/emcmodule.cc | 1 + - 14 files changed, 548 insertions(+), 10 deletions(-) + 14 files changed, 555 insertions(+), 10 deletions(-) diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc index 1c871cf..2131b07 100644 @@ -191,7 +191,7 @@ index 75e2a09..642e4c7 100644 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 8457e40..be54d1a 100644 +index 8457e40..7c4efca 100644 --- a/nc_files/remap_lib/python-stdglue/stdglue.py +++ b/nc_files/remap_lib/python-stdglue/stdglue.py @@ -16,6 +16,9 @@ @@ -204,7 +204,7 @@ index 8457e40..be54d1a 100644 import emccanon from interpreter import * from emccanon import MESSAGE -@@ -40,6 +43,272 @@ def build_hal(self): +@@ -40,6 +43,279 @@ def build_hal(self): except Exception as e: print(e) @@ -263,6 +263,13 @@ index 8457e40..be54d1a 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) + @@ -477,7 +484,7 @@ index 8457e40..be54d1a 100644 # REMAP=S prolog=setspeed_prolog ngc=setspeed epilog=setspeed_epilog # exposed parameter: # -@@ -655,5 +924,3 @@ def tool_probe_m6(self, **words): +@@ -655,5 +931,3 @@ def tool_probe_m6(self, **words): self.set_errormsg("tool_probe_m6 remap error." ) yield INTERP_ERROR @@ -734,7 +741,7 @@ index 90cc136..d2634e9 100644 { waitFlag = 0; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index f483726..7156924 100644 +index a8ee5a6..9133a28 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -577,7 +577,12 @@ extern int emcTaskMopup(); @@ -815,7 +822,7 @@ index f483726..7156924 100644 break; // EMC_TASK_INTERP::PAUSED case EMC_TASK_INTERP::WAITING: -@@ -3289,7 +3319,8 @@ static int emcTaskExecute(void) +@@ -3292,7 +3322,8 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::DONE: STEPPING_CHECK(); if (!emcStatus->motion.traj.queueFull && @@ -825,7 +832,7 @@ index f483726..7156924 100644 emcStatus->task.stopState != EMC_TASK_STOP_STATE::STOPPED && emcStatus->task.stopState != EMC_TASK_STOP_STATE::STARTING) { if (NULL == emcTaskCommand) { -@@ -3594,7 +3625,9 @@ static int emcTaskExecute(void) +@@ -3597,7 +3628,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); 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 e115ca9..4a792c3 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 @@ -26,7 +26,7 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 7156924..76e3cf8 100644 +index 9133a28..bae7266 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1078,7 +1078,7 @@ static void emcTaskStopProgress() diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index 89f32a2..e558f59 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -40,7 +40,7 @@ other motion-logger tests. src/emc/motion-logger/motion-logger.c | 22 + src/emc/motion/axis.c | 2 +- src/emc/motion/command.c | 376 +++++++++++- - src/emc/motion/control.c | 568 ++++++++++++++++-- + src/emc/motion/control.c | 575 ++++++++++++++++-- src/emc/motion/homing.h | 4 +- src/emc/motion/mot_priv.h | 21 + src/emc/motion/motion.c | 19 + @@ -58,7 +58,7 @@ other motion-logger tests. .../basic/expected.builtin-startup.in | 16 +- .../mountaindew/expected.motion-logger | 11 +- .../expected.motion-logger.in | 9 +- - 27 files changed, 1721 insertions(+), 104 deletions(-) + 27 files changed, 1728 insertions(+), 104 deletions(-) diff --git a/docs/src/config/ini-config.adoc b/docs/src/config/ini-config.adoc index 2d7a99e..e93f55a 100644 @@ -987,7 +987,7 @@ index ff48890..9d6fb2c 100644 } break; diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index f22ab9b..31c4284 100644 +index f22ab9b..7f55169 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c @@ -45,6 +45,9 @@ static int switchkins_type = 0; @@ -1051,7 +1051,22 @@ index f22ab9b..31c4284 100644 /* 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. */ -@@ -518,8 +539,29 @@ static void process_inputs(void) +@@ -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]; @@ -1082,7 +1097,7 @@ index f22ab9b..31c4284 100644 continue; } /* copy data from HAL to joint structure */ -@@ -567,25 +609,7 @@ static void process_inputs(void) +@@ -567,25 +616,7 @@ static void process_inputs(void) SET_JOINT_FERROR_FLAG(joint, 0); } @@ -1109,7 +1124,7 @@ index f22ab9b..31c4284 100644 } // a fault was signalled during a spindle-orient in progress -@@ -629,6 +653,401 @@ static void process_inputs(void) +@@ -629,6 +660,401 @@ static void process_inputs(void) } } @@ -1511,7 +1526,7 @@ index f22ab9b..31c4284 100644 static void joint_jog_abort_all(bool immediate) { int jNum; -@@ -691,7 +1110,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,}; @@ -1520,7 +1535,7 @@ index f22ab9b..31c4284 100644 emcmot_joint_t *joint; /* copy joint position feedback to local array */ -@@ -873,7 +1292,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++){ @@ -1531,7 +1546,7 @@ index f22ab9b..31c4284 100644 reportError(_("spindle %d amplifier fault"), spindle_num); emcmotInternal->enabling = 0; } -@@ -945,6 +1366,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()) { @@ -1539,7 +1554,7 @@ index f22ab9b..31c4284 100644 /* clear out the motion emcmotInternal->coord_tp and interpolators */ tpClear(&emcmotInternal->coord_tp); for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -999,8 +1421,9 @@ static void set_operating_mode(void) +@@ -999,8 +1428,9 @@ static void set_operating_mode(void) } } SET_MOTION_ENABLE_FLAG(1); @@ -1551,7 +1566,7 @@ index f22ab9b..31c4284 100644 } /* check for entering teleop mode */ -@@ -1028,7 +1451,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); @@ -1560,7 +1575,7 @@ index f22ab9b..31c4284 100644 kinematicsForward(positions, &emcmotStatus->carte_pos_cmd, &fflags, &iflags); // entering teleop (INPOS), remove ext offsets -@@ -1072,7 +1495,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); @@ -1569,7 +1584,7 @@ index f22ab9b..31c4284 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1092,7 +1515,7 @@ static void set_operating_mode(void) +@@ -1092,7 +1522,7 @@ static void set_operating_mode(void) } SET_MOTION_COORD_FLAG(0); SET_MOTION_TELEOP_FLAG(0); @@ -1578,7 +1593,7 @@ index f22ab9b..31c4284 100644 } else { /* not in position-- defer the mode change; the request stays pending and is honored when motion comes to rest */ -@@ -1127,10 +1550,17 @@ static void handle_jjogwheels(void) +@@ -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]; @@ -1600,7 +1615,7 @@ index f22ab9b..31c4284 100644 // disallow accel bogus fractions rtapi_real jjog_accel_fraction = hal_get_real(joint_data->jjog_accel_fraction); -@@ -1145,6 +1575,7 @@ static void handle_jjogwheels(void) +@@ -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; @@ -1608,7 +1623,7 @@ index f22ab9b..31c4284 100644 /* initialization complete */ if ( first_pass ) { continue; -@@ -1276,6 +1707,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; } @@ -1625,7 +1640,7 @@ index f22ab9b..31c4284 100644 cubics[n] = joints[n].cubic; if (cubicNeedNextPoint(&cubics[n]) && cubicAddPoint(&cubics[n], positions[n]) != 0) { -@@ -1365,7 +1806,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]; @@ -1637,7 +1652,7 @@ index f22ab9b..31c4284 100644 /* if joint is not active, skip it */ continue; } -@@ -1521,8 +1965,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) { @@ -1647,7 +1662,7 @@ index f22ab9b..31c4284 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1583,8 +2026,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) { @@ -1657,7 +1672,7 @@ index f22ab9b..31c4284 100644 break; } for (joint_num = 0; joint_num < NO_OF_KINS_JOINTS; joint_num++) { -@@ -1595,6 +2037,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); } @@ -1666,7 +1681,7 @@ index f22ab9b..31c4284 100644 /* END OF OUTPUT KINS */ -@@ -1611,10 +2055,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 */ @@ -1681,7 +1696,7 @@ index f22ab9b..31c4284 100644 /* save old command */ joint->pos_cmd = joint->pos_fb; /* set joint velocity and acceleration to zero */ -@@ -2002,8 +2449,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; @@ -1690,7 +1705,7 @@ index f22ab9b..31c4284 100644 /* output machine info to HAL for scoping, etc */ hal_set_bool(emcmot_hal_data->motion_enabled, GET_MOTION_ENABLE_FLAG()); -@@ -2045,6 +2490,9 @@ static void output_to_hal(void) +@@ -2045,6 +2497,9 @@ static void output_to_hal(void) for (spindle_num = 0; spindle_num < emcmotConfig->numSpindles; spindle_num++){ double speed; @@ -1700,7 +1715,7 @@ index f22ab9b..31c4284 100644 if(emcmotStatus->spindle_status[spindle_num].css_factor) { double denom = fabs(emcmotStatus->spindle_status[spindle_num].xoffset - emcmotStatus->carte_pos_cmd.tran.x); -@@ -2079,14 +2527,22 @@ static void output_to_hal(void) +@@ -2079,14 +2534,22 @@ static void output_to_hal(void) } } @@ -1727,7 +1742,7 @@ index f22ab9b..31c4284 100644 // What is this for? Docs don't say hal_set_real(emcmot_hal_data->spindle[spindle_num].spindle_speed_cmd_rps, emcmotStatus->spindle_status[spindle_num].speed / 60.); -@@ -2147,6 +2603,13 @@ static void output_to_hal(void) +@@ -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++){ @@ -1741,7 +1756,7 @@ index f22ab9b..31c4284 100644 if(emcmotStatus->spindle_status[spindle_num].spindle_index_enable && !old_motion_index[spindle_num]) { hal_set_bool(emcmot_hal_data->spindle[spindle_num].spindle_index_enable, 1); -@@ -2189,7 +2652,14 @@ static void output_to_hal(void) +@@ -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); @@ -2252,7 +2267,7 @@ index d2634e9..f889dd3 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 76e3cf8..86385c3 100644 +index bae7266..2a76c92 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -171,6 +171,61 @@ volatile int done; @@ -2584,7 +2599,7 @@ index 76e3cf8..86385c3 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -3062,7 +3254,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3065,7 +3257,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2599,7 +2614,7 @@ index 76e3cf8..86385c3 100644 if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -3177,6 +3376,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) +@@ -3180,6 +3379,11 @@ static EMC_TASK_EXEC emcTaskCheckPostconditions(NMLmsg * cmd) return EMC_TASK_EXEC::DONE; break; @@ -2611,7 +2626,7 @@ index 76e3cf8..86385c3 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -3259,6 +3463,12 @@ static int emcTaskExecute(void) +@@ -3262,6 +3466,12 @@ static int emcTaskExecute(void) int status; // status of child from EMC_SYSTEM_CMD pid_t pid; // pid returned from waitpid() @@ -2624,7 +2639,7 @@ index 76e3cf8..86385c3 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3386,11 +3596,59 @@ static int emcTaskExecute(void) +@@ -3389,11 +3599,59 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: @@ -2684,7 +2699,7 @@ index 76e3cf8..86385c3 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } -@@ -3518,12 +3776,17 @@ static int emcTaskExecute(void) +@@ -3521,12 +3779,17 @@ static int emcTaskExecute(void) homingStarted = true; break; // still running; no timeout once started (see HOMING_START_TIMEOUT comment) } @@ -2707,7 +2722,7 @@ index 76e3cf8..86385c3 100644 // HOMING_START_TIMEOUT before concluding it was rejected. if (etime() - homingIssueTime < HOMING_START_TIMEOUT) { break; -@@ -3535,11 +3798,8 @@ static int emcTaskExecute(void) +@@ -3538,11 +3801,8 @@ static int emcTaskExecute(void) emcTaskEager = 1; homingWaiting = false; // Nothing physically moved, so it's safe to restore the @@ -2721,7 +2736,7 @@ index 76e3cf8..86385c3 100644 break; } // It ran and has now stopped; did it reach the expected end state? -@@ -3605,7 +3865,9 @@ static int emcTaskExecute(void) +@@ -3608,7 +3868,9 @@ static int emcTaskExecute(void) "coordinated motion until every joint is homed")); emcStatus->task.execState = EMC_TASK_EXEC::ERROR; } else if (success) { 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 d175c88..b45517a 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -60,10 +60,10 @@ index 9d6fb2c..e8a68ce 100644 break; } diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c -index 31c4284..babce73 100644 +index 7f55169..c75c227 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2735,18 +2735,13 @@ static void update_status(void) +@@ -2742,18 +2742,13 @@ static void update_status(void) } #endif joint_status->flag = joint->flag; 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 cef7275..9626292 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 @@ -11,25 +11,25 @@ other halui u32 pins. 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/axis.c | 68 ++++++++++++- src/emc/motion/axis.h | 5 +- src/emc/motion/command.c | 29 ++++++ src/emc/motion/control.c | 9 +- src/emc/motion/mot_priv.h | 1 + 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/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/task/emctaskmain.cc | 8 ++ src/emc/task/taskintf.cc | 12 +++ - src/emc/tp/sp_scurve.c | 52 +++++++++++ + 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, 506 insertions(+), 4 deletions(-) + 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 @@ -339,10 +339,10 @@ index e8a68ce..554c1b5 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 babce73..cb1b2cb 100644 +index c75c227..f0e6a18 100644 --- a/src/emc/motion/control.c +++ b/src/emc/motion/control.c -@@ -2006,7 +2006,14 @@ static void get_pos_cmds(long period) +@@ -2013,7 +2013,14 @@ static void get_pos_cmds(long period) break; case EMCMOT_MOTION_TELEOP: @@ -424,16 +424,19 @@ index bed4351..51719c1 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 0000000..2303950 +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) || @@ -516,7 +519,11 @@ index 0000000..2303950 + 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) { @@ -681,7 +688,7 @@ index feab3fb..a9fc353 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 86385c3..20092fb 100644 +index 2a76c92..57b8240 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1521,6 +1521,7 @@ static int emcTaskPlan(void) 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 4868588..98e0610 100644 --- a/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch +++ b/linuxcnc-patches/0021-hal-support-cross-compiling-external-components.patch @@ -5,9 +5,9 @@ Subject: [PATCH] hal: support cross-compiling external components --- docs/src/man/man1/halcompile.1.adoc | 34 ++++++++ - src/Makefile.modinc.in | 64 +++++++++++--- + src/Makefile.modinc.in | 69 ++++++++++++--- src/hal/utils/halcompile.g | 130 ++++++++++++++++++++++++---- - 3 files changed, 201 insertions(+), 27 deletions(-) + 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 593be84..e688a75 100644 @@ -55,10 +55,10 @@ index 593be84..e688a75 100644 *halcompile* performs many different functions: diff --git a/src/Makefile.modinc.in b/src/Makefile.modinc.in -index 85bc79d..fd55cf3 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@ @@ -66,6 +66,11 @@ index 85bc79d..fd55cf3 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=...) @@ -155,7 +160,7 @@ index 85bc79d..fd55cf3 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 $@ @@ -166,7 +171,7 @@ index 85bc79d..fd55cf3 100644 | awk 'BEGIN{print "{ global :"} /rtapi_exported_/{printf("%s;\n", substr($$6,16))} END{print "local : * ; };"}' \ > $*.ver $(Q)$(CC) -shared -Wl,-Bsymbolic $(LDFLAGS) -Wl,--version-script,$*.ver -o $@ $^ -lm $(EXTRA_LDFLAGS) -@@ -130,4 +171,3 @@ endif +@@ -130,4 +176,3 @@ endif ifeq ($(BUILDSYS),normal) $(error Makefile.modinc is only suitable for 'kbuild' kernels and 'uspace' systems) endif 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 index eefdbd5..12a593d 100644 --- 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 @@ -52,7 +52,7 @@ index f889dd3..b6793d2 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 20092fb..b2d4a91 100644 +index 57b8240..3e8c047 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -817,7 +817,7 @@ interpret_again: 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 index 3d451dc..19b16a9 100644 --- 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 @@ -22,7 +22,7 @@ and accepted again once the machine is idle. 1 file changed, 62 insertions(+) diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index b2d4a91..42f985ac 100644 +index 3e8c047..2a975eb 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1269,6 +1269,45 @@ static void emcTaskStopProgress() diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index c35cefa..54e5377 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -223,6 +223,16 @@ timeout of their own; Abort, E-stop and Machine Off end them. While Stop is 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`) @@ -239,6 +249,8 @@ 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. 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 @@ -502,7 +514,9 @@ 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. 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. +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 @@ -522,8 +536,9 @@ 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, cancellation, a request -read ahead of a running AUTO move, Stop and Pause during a request, and a -timeout while stopping. Headless +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 @@ -619,6 +634,8 @@ Resume. Once acknowledged, the home must start within 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 @@ -701,7 +718,9 @@ 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. +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 @@ -732,8 +751,8 @@ 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 diff --git a/linuxcnc-tests/halcompile/cross-tools/test.sh b/linuxcnc-tests/halcompile/cross-tools/test.sh index 13c1671..a2677b7 100755 --- a/linuxcnc-tests/halcompile/cross-tools/test.sh +++ b/linuxcnc-tests/halcompile/cross-tools/test.sh @@ -113,9 +113,10 @@ if halcompile --compile --sysroot="$sysroot" cross_tools.comp \ 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. +# A native build ignores target tools and a sysroot exported by a cross SDK +# environment. rm -f cross_tools.so -LD=false OBJDUMP=false halcompile --compile cross_tools.comp +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. diff --git a/linuxcnc-tests/power-jog/test-ui.py b/linuxcnc-tests/power-jog/test-ui.py index dbdd465..463e5c3 100755 --- a/linuxcnc-tests/power-jog/test-ui.py +++ b/linuxcnc-tests/power-jog/test-ui.py @@ -153,6 +153,12 @@ def origin(): 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) diff --git a/linuxcnc-tests/remap/executor/checkresult b/linuxcnc-tests/remap/executor/checkresult index b3f6a2c..bbdfe51 100755 --- a/linuxcnc-tests/remap/executor/checkresult +++ b/linuxcnc-tests/remap/executor/checkresult @@ -1,5 +1,5 @@ #!/bin/sh set -e -test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 8 +test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 9 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 0000000..1b8267e --- /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/test-ui.py b/linuxcnc-tests/remap/executor/test-ui.py index 59542e6..95fccbc 100755 --- a/linuxcnc-tests/remap/executor/test-ui.py +++ b/linuxcnc-tests/remap/executor/test-ui.py @@ -285,6 +285,19 @@ def assert_released(prefix): 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) diff --git a/linuxcnc-tests/remap/executor/test.sh b/linuxcnc-tests/remap/executor/test.sh index e2e3e8f..29c462d 100755 --- a/linuxcnc-tests/remap/executor/test.sh +++ b/linuxcnc-tests/remap/executor/test.sh @@ -4,7 +4,7 @@ # 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; do +for scenario in success failure timeout abort readahead stop pause stop-timeout comp; do echo "Running executor remap scenario: ${scenario}" EXECUTOR_SCENARIO="${scenario}" linuxcnc -r test.ini done diff --git a/linuxcnc-tests/resumable-stop/general/checkresult b/linuxcnc-tests/resumable-stop/general/checkresult index a81b33d..c3dac55 100755 --- a/linuxcnc-tests/resumable-stop/general/checkresult +++ b/linuxcnc-tests/resumable-stop/general/checkresult @@ -1,2 +1,2 @@ #!/bin/sh -exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 26 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 27 diff --git a/linuxcnc-tests/resumable-stop/general/scenarios b/linuxcnc-tests/resumable-stop/general/scenarios index 37ac880..faa5b75 100644 --- a/linuxcnc-tests/resumable-stop/general/scenarios +++ b/linuxcnc-tests/resumable-stop/general/scenarios @@ -24,3 +24,4 @@ resume-s0 pause-inflight-step trapezoidal:inflight-step-short system-command +set-auto-stopped diff --git a/linuxcnc-tests/resumable-stop/set-auto.ngc b/linuxcnc-tests/resumable-stop/set-auto.ngc new file mode 100644 index 0000000..a3b0082 --- /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/test-ui.py b/linuxcnc-tests/resumable-stop/test-ui.py index 41e67f0..fa7d105 100755 --- a/linuxcnc-tests/resumable-stop/test-ui.py +++ b/linuxcnc-tests/resumable-stop/test-ui.py @@ -1262,6 +1262,67 @@ def run_system_command_stop_test(): 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_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 @@ -2098,6 +2159,7 @@ def run_stopped_spindle_s_word_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, "dwell-atspeed": run_dwell_atspeed_barrier_test, "command-after-sync": run_command_after_sync_motion_test, "resume-atspeed": run_resume_atspeed_wait_test, diff --git a/linuxcnc-tests/runtime-availability-regressions/atspeed.hal b/linuxcnc-tests/runtime-availability-regressions/atspeed.hal new file mode 100644 index 0000000..218d2bc --- /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 0000000..f1e6f3e --- /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 0000000..1099c4f --- /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/checkresult b/linuxcnc-tests/runtime-availability-regressions/checkresult index 153f94a..65ed2d7 100755 --- a/linuxcnc-tests/runtime-availability-regressions/checkresult +++ b/linuxcnc-tests/runtime-availability-regressions/checkresult @@ -1,5 +1,5 @@ #!/bin/sh set -eu -for scenario in ${AVAILABILITY_REGRESSION_CASES:-fault wheel tail amp power index jogstop joghome extra sequence}; do +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/test-ui.py b/linuxcnc-tests/runtime-availability-regressions/test-ui.py index c23405a..62770f3 100755 --- a/linuxcnc-tests/runtime-availability-regressions/test-ui.py +++ b/linuxcnc-tests/runtime-availability-regressions/test-ui.py @@ -187,6 +187,14 @@ 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 diff --git a/linuxcnc-tests/runtime-availability-regressions/test.sh b/linuxcnc-tests/runtime-availability-regressions/test.sh index 80bc7dd..9ce4700 100755 --- a/linuxcnc-tests/runtime-availability-regressions/test.sh +++ b/linuxcnc-tests/runtime-availability-regressions/test.sh @@ -1,7 +1,7 @@ #!/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 extra sequence}; do +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 ;; @@ -9,6 +9,7 @@ for scenario in ${AVAILABILITY_REGRESSION_CASES:-fault wheel jointwheel tail amp 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 From a8ef581da5045463568a084bc0c8dbc63b8edf07 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 26 Nov 2026 12:12:31 +0100 Subject: [PATCH 42/45] fix(linuxcnc): close the final pre2 review's simple findings Step resume state, MDI pause, tool table load during a tool change, wear on the changed tool, executor StopIteration and poll flag, saved term cond and sync run target for Step, with tests. --- linuxcnc-patches/0004-resumable-stop.patch | 49 ++++++----- .../0007-native-automatic-tool-wear.patch | 62 +++++++------- .../0008-tapered-g76-drive-lines.patch | 14 +-- ...reading-stop-clear-and-pass-stepping.patch | 48 +++++------ ...0-rs274-support-native-gcode-preview.patch | 2 +- ...-single-step-during-active-execution.patch | 69 ++++++++++----- ...-own-transactional-tool-CRUD-in-task.patch | 40 +++++---- ...4ngc-add-composable-executor-stdglue.patch | 85 +++++++++++++++---- ...-publish-modal-CSS-maximum-in-status.patch | 4 +- ...ntime-joint-and-spindle-availability.patch | 36 ++++---- .../0018-availability-mcodes.patch | 4 +- ...otion-add-native-lathe-power-jogging.patch | 6 +- ...te-whenever-the-interpreter-is-reset.patch | 2 +- ...ter-reset-unless-the-machine-is-idle.patch | 8 +- linuxcnc-patches/README.md | 26 ++++-- linuxcnc-tests/remap/executor/checkresult | 3 +- linuxcnc-tests/remap/executor/preview.ngc | 7 ++ linuxcnc-tests/remap/executor/test-ui.py | 35 ++++++++ linuxcnc-tests/remap/executor/test.sh | 13 ++- .../resumable-stop/general/checkresult | 2 +- .../resumable-stop/general/scenarios | 1 + linuxcnc-tests/resumable-stop/test-ui.py | 61 +++++++++++++ .../resumable-stop/thread-chain-g64.ngc | 8 ++ .../resumable-stop/threading/checkresult | 2 +- .../resumable-stop/threading/scenarios | 1 + linuxcnc-tests/tool-table-load/garbage-ui.py | 9 ++ 26 files changed, 417 insertions(+), 180 deletions(-) create mode 100644 linuxcnc-tests/remap/executor/preview.ngc create mode 100644 linuxcnc-tests/resumable-stop/thread-chain-g64.ngc diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index d8137a1..8bf8243 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -32,13 +32,13 @@ Ported to v2.10.0-pre2. Differences from the patch on the old base: 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 | 465 +++++++++++++++++- + 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 +- - 18 files changed, 874 insertions(+), 25 deletions(-) + 18 files changed, 877 insertions(+), 25 deletions(-) diff --git a/docs/src/config/python-interface.adoc b/docs/src/config/python-interface.adoc index 25d5762..5153f11 100644 @@ -569,7 +569,7 @@ index ed6a962..6010ecb 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a3b5256..60ae9b4 100644 +index a3b5256..3b544e1 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -124,6 +124,39 @@ static int emcTaskEager = 0; @@ -643,7 +643,7 @@ index a3b5256..60ae9b4 100644 // now handle call logic // check for subsystems done if (interp_list.len() == 0 && -@@ -781,6 +824,289 @@ static bool allow_while_idle_type() { +@@ -781,6 +824,292 @@ static bool allow_while_idle_type() { return 0; } @@ -702,7 +702,10 @@ index a3b5256..60ae9b4 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; @@ -933,7 +936,7 @@ index a3b5256..60ae9b4 100644 /* emcTaskPlan() -@@ -809,6 +1135,33 @@ static int emcTaskPlan(void) +@@ -809,6 +1138,33 @@ static int emcTaskPlan(void) return retval; } @@ -967,7 +970,7 @@ index a3b5256..60ae9b4 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1734,6 +2087,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1734,6 +2090,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; @@ -975,7 +978,7 @@ index a3b5256..60ae9b4 100644 if (homingPriorMode != EMC_TRAJ_MODE::FREE) { emcTrajSetMode(EMC_TRAJ_MODE::FREE); } -@@ -1937,6 +2291,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1937,6 +2294,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcTrajPause(); break; @@ -987,7 +990,7 @@ index a3b5256..60ae9b4 100644 case EMC_TRAJ_RESUME_TYPE: emcStatus->task.task_paused = 0; retval = emcTrajResume(); -@@ -2039,6 +2398,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2039,6 +2401,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_WAIT_ORIENT_COMPLETE_TYPE: wait_spindle_orient_complete_msg = reinterpret_cast(cmd); @@ -999,7 +1002,7 @@ index a3b5256..60ae9b4 100644 taskExecDelayTimeout = etime() + wait_spindle_orient_complete_msg->timeout; break; -@@ -2099,6 +2463,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2099,6 +2466,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_SPINDLE_ORIENT_TYPE: spindle_orient_msg = reinterpret_cast(cmd); @@ -1014,7 +1017,7 @@ index a3b5256..60ae9b4 100644 retval = emcSpindleOrient(spindle_orient_msg->spindle, spindle_orient_msg->orientation, spindle_orient_msg->mode); break; -@@ -2191,7 +2563,49 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2191,7 +2566,49 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // task commands @@ -1064,7 +1067,7 @@ index a3b5256..60ae9b4 100644 // abort everything emcTaskAbort(); // KLUDGE call motion abort before state restore to make absolutely sure no -@@ -2215,6 +2629,12 @@ 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 @@ -1077,7 +1080,7 @@ index a3b5256..60ae9b4 100644 if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { // leaving auto or mdi mode for manual -@@ -2259,6 +2679,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); @@ -1087,7 +1090,7 @@ index a3b5256..60ae9b4 100644 retval = emcTaskSetState(state_msg->state); break; -@@ -2451,6 +2874,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2451,6 +2877,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_PAUSE_TYPE: @@ -1095,7 +1098,7 @@ index a3b5256..60ae9b4 100644 emcTrajPause(); if (emcStatus->task.interpState != EMC_TASK_INTERP::PAUSED) { interpResumeState = emcStatus->task.interpState; -@@ -2484,11 +2908,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2484,11 +2911,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) case EMC_TASK_PLAN_RESUME_TYPE: emcTrajResume(); @@ -1108,7 +1111,7 @@ index a3b5256..60ae9b4 100644 retval = 0; break; -@@ -2701,6 +3122,7 @@ static int emcTaskExecute(void) +@@ -2701,6 +3125,7 @@ static int emcTaskExecute(void) switch (emcStatus->task.execState) { case EMC_TASK_EXEC::ERROR: @@ -1116,7 +1119,7 @@ index a3b5256..60ae9b4 100644 /*! \todo FIXME-- duplicate code for abort, also near end of main, when aborting on subordinate errors, -@@ -2746,7 +3168,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 && @@ -1127,7 +1130,7 @@ index a3b5256..60ae9b4 100644 if (NULL == emcTaskCommand) { // need a new command emcTaskCommand = interp_list.get(); -@@ -2767,7 +3191,7 @@ static int emcTaskExecute(void) +@@ -2767,7 +3194,7 @@ static int emcTaskExecute(void) emcStatus->task.execState = emcTaskCheckPreconditions(emcTaskCommand.get()); } } @@ -1136,7 +1139,7 @@ index a3b5256..60ae9b4 100644 // have an outstanding command // This is the one emcTaskIssueCommand() call site followed by // emcTaskCheckPostconditions(), i.e. the only one whose commands -@@ -3040,6 +3464,18 @@ static int emcTaskExecute(void) +@@ -3040,6 +3467,18 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); @@ -1155,7 +1158,7 @@ index a3b5256..60ae9b4 100644 // check if delay has passed emcStatus->task.delayLeft = taskExecDelayTimeout - etime(); if (etime() >= taskExecDelayTimeout) { -@@ -3626,6 +4062,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) { @@ -1163,7 +1166,7 @@ index a3b5256..60ae9b4 100644 if (emcStatus->motion.traj.enabled) { emcTrajDisable(); emcTaskAbort(); -@@ -3707,6 +4144,7 @@ int main(int argc, char *argv[]) +@@ -3707,6 +4147,7 @@ int main(int argc, char *argv[]) // emcOperatorError("wait for orient complete timed out"); // } @@ -1171,7 +1174,7 @@ index a3b5256..60ae9b4 100644 // abort everything emcTaskAbort(); emcIoAbort(EMC_ABORT::MOTION_OR_IO_RCS_ERROR); -@@ -3742,6 +4180,18 @@ int main(int argc, char *argv[]) +@@ -3742,6 +4183,18 @@ int main(int argc, char *argv[]) emcTaskQueueTaskPlanSynchCmd(); } @@ -1190,7 +1193,7 @@ index a3b5256..60ae9b4 100644 // update task-specific status emcTaskUpdate(&emcStatus->task); -@@ -3762,6 +4212,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; diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index 2a39227..d5adcb1 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -79,7 +79,7 @@ Fixes from review of the port: 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 | 171 ++++++++++------ + 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/pyemctypes.cc | 2 + @@ -116,7 +116,7 @@ Fixes from review of the port: tests/toolchanger/m61/test-ui.py | 28 ++- .../nonrandom/expected-gcode-output | 12 +- .../random/expected-gcode-output | 12 +- - 59 files changed, 937 insertions(+), 286 deletions(-) + 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 37daf10..bbcdfc2 100644 @@ -869,7 +869,7 @@ index fc5ae57..c65a3b2 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 450922e..10bf98d 100644 +index 450922e..ab502ad 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -4013,6 +4013,8 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 @@ -881,16 +881,20 @@ index 450922e..10bf98d 100644 double timeout; // timeout for M66 /* The M62-65 commands are used for DIO */ -@@ -4148,6 +4150,8 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 +@@ -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)); + builtin_tool_change = true; -+ changed_toolno = settings->selected_tool; ++ // 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; -@@ -4160,6 +4164,10 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 +@@ -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"))); @@ -901,7 +905,7 @@ index 450922e..10bf98d 100644 int idx; -@@ -4169,6 +4177,8 @@ int Interp::convert_m(block_pointer block, //!< pointer to a block of RS27 +@@ -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(); @@ -910,7 +914,7 @@ index 450922e..10bf98d 100644 } break; -@@ -4180,22 +4190,31 @@ 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 } } @@ -958,7 +962,7 @@ index 450922e..10bf98d 100644 } if (is_user_defined_m_code(block, settings, 7) && ONCE_M(7)) { -@@ -4464,7 +4483,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) { @@ -967,7 +971,7 @@ index 450922e..10bf98d 100644 CHP(convert_setup_tool(block, settings)); else if (block->l_number == 0) { int tno = settings->tool_table[0].toolno; -@@ -4731,7 +4750,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; @@ -977,7 +981,7 @@ index 450922e..10bf98d 100644 is_near_int(&toolno, block->p_number); -@@ -4742,9 +4762,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), @@ -1011,7 +1015,7 @@ index 450922e..10bf98d 100644 if(block->x_flag) settings->tool_table[idx].offset.tran.x = PROGRAM_TO_USER_LEN(block->x_number); if(block->y_flag) -@@ -4844,10 +4886,10 @@ int Interp::convert_setup_tool(block_pointer block, setup_pointer settings) { +@@ -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); } @@ -1026,7 +1030,7 @@ index 450922e..10bf98d 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; -@@ -4856,6 +4898,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, @@ -1034,7 +1038,7 @@ index 450922e..10bf98d 100644 settings->tool_table[idx].diameter, settings->tool_table[idx].frontangle, settings->tool_table[idx].backangle, -@@ -4910,6 +4953,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; @@ -1050,7 +1054,7 @@ index 450922e..10bf98d 100644 // if the modified tool is currently in the spindle, then copy its // information to index 0 of the tool table (which signifies the -@@ -4919,6 +4971,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, @@ -1058,7 +1062,7 @@ index 450922e..10bf98d 100644 settings->tool_table[idx].diameter, settings->tool_table[idx].frontangle, settings->tool_table[idx].backangle, -@@ -6438,11 +6491,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. @@ -1073,7 +1077,7 @@ index 450922e..10bf98d 100644 */ -@@ -6662,15 +6713,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); @@ -1098,7 +1102,7 @@ index 450922e..10bf98d 100644 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 || -@@ -6697,15 +6748,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))); @@ -1123,7 +1127,7 @@ index 450922e..10bf98d 100644 } 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 +6800,7 @@ int Interp::convert_tool_length_offset(int g_code, //!< g_code being execu +@@ -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. @@ -1140,7 +1144,7 @@ index 450922e..10bf98d 100644 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 +6851,22 @@ int Interp::convert_tool_select(block_pointer block, //!< pointer to a block +@@ -6808,6 +6855,22 @@ int Interp::convert_tool_select(block_pointer block, //!< pointer to a block return INTERP_OK; } @@ -1471,7 +1475,7 @@ index 7620a30..55fb417 100644 // 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 60ae9b4..eb0dda6 100644 +index 3b544e1..fafc18c 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -612,6 +612,9 @@ interpret_again: @@ -1484,7 +1488,7 @@ index 60ae9b4..eb0dda6 100644 emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, "interpreter error"); } else if (execRetval == -1 -@@ -1952,6 +1955,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1955,6 +1958,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) break; case EMC_TOOL_SET_NUMBER_TYPE: @@ -1496,7 +1500,7 @@ index 60ae9b4..eb0dda6 100644 return EMC_TASK_EXEC::WAITING_FOR_IO; break; -@@ -2029,6 +2037,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) +@@ -2032,6 +2040,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) } // issues command immediately @@ -1509,7 +1513,7 @@ index 60ae9b4..eb0dda6 100644 static int emcTaskIssueCommand(NMLmsg * cmd) { int retval = 0; -@@ -2532,9 +2546,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2535,9 +2549,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcToolPrepare(tool_prepare_msg->tool); break; @@ -1524,7 +1528,7 @@ index 60ae9b4..eb0dda6 100644 case EMC_TOOL_UNLOAD_TYPE: retval = emcToolUnload(); -@@ -2550,6 +2568,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2553,6 +2571,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, @@ -1533,7 +1537,7 @@ index 60ae9b4..eb0dda6 100644 emc_tool_set_offset_msg->diameter, emc_tool_set_offset_msg->frontangle, emc_tool_set_offset_msg->backangle, -@@ -2559,6 +2579,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2562,6 +2582,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); @@ -1544,7 +1548,7 @@ index 60ae9b4..eb0dda6 100644 break; // task commands -@@ -3149,6 +3173,7 @@ static int emcTaskExecute(void) +@@ -3152,6 +3176,7 @@ static int emcTaskExecute(void) // clear out pending command emcTaskCommand = NULL; interp_list.clear(); @@ -1552,7 +1556,7 @@ index 60ae9b4..eb0dda6 100644 emcAbortCleanup(EMC_ABORT::TASK_EXEC_ERROR); emcStatus->task.currentLine = 0; -@@ -3715,7 +3740,8 @@ static int emctask_startup() +@@ -3718,7 +3743,8 @@ static int emctask_startup() } // initialize the subsystems @@ -1562,7 +1566,7 @@ index 60ae9b4..eb0dda6 100644 if (emcIoInit() != 0) { rcs_print_error("can't initialize IO\n"); return -1; -@@ -4165,6 +4191,7 @@ int main(int argc, char *argv[]) +@@ -4168,6 +4194,7 @@ int main(int argc, char *argv[]) // clear out the pending command emcTaskCommand = NULL; interp_list.clear(); diff --git a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch index 69eb506..856870f 100644 --- a/linuxcnc-patches/0008-tapered-g76-drive-lines.patch +++ b/linuxcnc-patches/0008-tapered-g76-drive-lines.patch @@ -144,10 +144,10 @@ index f8f9d01..6f196b6 100644 [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 10bf98d..560748a 100644 +index ab502ad..6d051a2 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -5940,7 +5940,8 @@ int Interp::issue_straight_index(int axis, int jnum, double target, int lineno, +@@ -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, @@ -157,7 +157,7 @@ index 10bf98d..560748a 100644 int entry_taper, int exit_taper, double taper_pitch, double pitch, double full_threadheight, double target_z) { STRAIGHT_TRAVERSE(block->line_number, boring? -@@ -5966,24 +5967,171 @@ threading_pass(setup_pointer settings, block_pointer block, +@@ -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 @@ -333,7 +333,7 @@ index 10bf98d..560748a 100644 int Interp::convert_threading_cycle(block_pointer block, setup_pointer settings, double end_x, double end_y, double end_z) { -@@ -5991,6 +6139,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"))); @@ -342,7 +342,7 @@ index 10bf98d..560748a 100644 CHKS((block->i_number == 0), (_("In G76, I must not be 0"))); -@@ -6030,7 +6180,17 @@ 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; @@ -361,7 +361,7 @@ index 10bf98d..560748a 100644 int spring_cuts = block->h_flag ? block->h_number: 0; -@@ -6042,7 +6202,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; @@ -371,7 +371,7 @@ index 10bf98d..560748a 100644 int taper_flags = block->l_number; if(taper_flags < 0) taper_flags = 0; -@@ -6053,44 +6214,86 @@ 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; 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 c32aebf..0a6070a 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -450,10 +450,10 @@ index 91d4b7b..109cf46 100644 void PALLET_SHUTTLE() {} 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 560748a..47f2509 100644 +index 6d051a2..663668a 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -5944,11 +5944,13 @@ threading_pass(setup_pointer settings, block_pointer block, +@@ -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) { @@ -467,7 +467,7 @@ index 560748a..47f2509 100644 DISABLE_FEED_OVERRIDE(); START_SPEED_FEED_SYNCH(settings->active_spindle, taper_pitch, 0); STRAIGHT_FEED(block->line_number, boring? -@@ -5959,6 +5961,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 { @@ -475,7 +475,7 @@ index 560748a..47f2509 100644 STRAIGHT_TRAVERSE(block->line_number, boring? safe_x + depth: safe_x - depth, start_y, start_z - zoff, AABBCC); //in DISABLE_FEED_OVERRIDE(); -@@ -5978,11 +5981,13 @@ threading_pass(setup_pointer settings, block_pointer block, +@@ -5982,11 +5985,13 @@ threading_pass(setup_pointer settings, block_pointer block, start_y, target_z - end_zoff, AABBCC); //over } STOP_SPEED_FEED_SYNCH(); @@ -489,7 +489,7 @@ index 560748a..47f2509 100644 } // Geometry of one threading pass along a tapered XZ drive line. X coordinates -@@ -6056,10 +6061,12 @@ tapered_pass(int boring, double start_x, double start_z, +@@ -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) { @@ -502,7 +502,7 @@ index 560748a..47f2509 100644 DISABLE_FEED_OVERRIDE(); START_SPEED_FEED_SYNCH(settings->active_spindle, g.entry_pitch, 0); STRAIGHT_FEED(block->line_number, g.crest_start_x, -@@ -6068,6 +6075,7 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, +@@ -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 { @@ -510,7 +510,7 @@ index 560748a..47f2509 100644 STRAIGHT_TRAVERSE(block->line_number, g.cut_start_x, start_y, g.pass_start_z, AABBCC); // in DISABLE_FEED_OVERRIDE(); -@@ -6085,9 +6093,11 @@ tapered_threading_pass(setup_pointer settings, block_pointer block, +@@ -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(); @@ -522,7 +522,7 @@ index 560748a..47f2509 100644 } int Interp::check_tapered_threading_pass(setup_pointer settings, -@@ -6283,9 +6293,13 @@ int Interp::convert_threading_cycle(block_pointer block, +@@ -6287,9 +6297,13 @@ int Interp::convert_threading_cycle(block_pointer block, } } @@ -684,7 +684,7 @@ index 55fb417..90cc136 100644 } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index eb0dda6..3f7e971 100644 +index fafc18c..cff0805 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -503,6 +503,22 @@ static int programStartLine = 0; // which line to run program from @@ -720,7 +720,7 @@ index eb0dda6..3f7e971 100644 } static void emcTaskStepInterpreter() -@@ -1571,6 +1586,10 @@ static int emcTaskPlan(void) +@@ -1574,6 +1589,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 @@ -731,7 +731,7 @@ index eb0dda6..3f7e971 100644 break; // otherwise we can't handle it -@@ -1723,6 +1742,10 @@ static int emcTaskPlan(void) +@@ -1726,6 +1745,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 @@ -742,7 +742,7 @@ index eb0dda6..3f7e971 100644 break; // otherwise we can't handle it -@@ -1980,6 +2003,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1983,6 +2006,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; @@ -754,7 +754,7 @@ index eb0dda6..3f7e971 100644 case EMC_TRAJ_DELAY_TYPE: return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2285,7 +2313,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2288,7 +2316,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajLinearMoveMsg->type, emcTrajLinearMoveMsg->vel, emcTrajLinearMoveMsg->ini_maxvel, emcTrajLinearMoveMsg->acc, emcTrajLinearMoveMsg->ini_maxjerk, emcTrajLinearMoveMsg->vlimit_scale, @@ -765,7 +765,7 @@ index eb0dda6..3f7e971 100644 break; case EMC_TRAJ_CIRCULAR_MOVE_TYPE: -@@ -2658,6 +2688,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2661,6 +2691,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) if (mode_msg->mode != emcStatus->task.mode || mode_msg->mode != EMC_TASK_MODE::MANUAL) { emcTaskStopClear(); @@ -774,7 +774,7 @@ index eb0dda6..3f7e971 100644 } if (mode_msg->mode == EMC_TASK_MODE::MANUAL && emcStatus->task.mode != EMC_TASK_MODE::MANUAL) { -@@ -2691,8 +2723,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; @@ -784,7 +784,7 @@ index eb0dda6..3f7e971 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -2705,6 +2736,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(); @@ -793,7 +793,7 @@ index eb0dda6..3f7e971 100644 } retval = emcTaskSetState(state_msg->state); break; -@@ -2789,8 +2822,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; @@ -803,7 +803,7 @@ index eb0dda6..3f7e971 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")); -@@ -2885,8 +2917,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2888,8 +2920,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; } emcStatus->motion.traj.single_stepping = 0; @@ -813,7 +813,7 @@ index eb0dda6..3f7e971 100644 if (!taskplanopen && emcStatus->task.file[0] != 0) { emcTaskPlanOpen(emcStatus->task.file); } -@@ -2955,6 +2986,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2958,6 +2989,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) } break; @@ -824,7 +824,7 @@ index eb0dda6..3f7e971 100644 case EMC_TASK_PLAN_SET_OPTIONAL_STOP_TYPE: os_msg = reinterpret_cast(cmd); emcTaskPlanSetOptionalStop(os_msg->state); -@@ -3063,6 +3098,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: @@ -832,7 +832,7 @@ index eb0dda6..3f7e971 100644 case EMC_TASK_PLAN_EXECUTE_TYPE: case EMC_TASK_PLAN_OPTIONAL_STOP_TYPE: return EMC_TASK_EXEC::DONE; -@@ -3115,11 +3151,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) { \ @@ -854,7 +854,7 @@ index eb0dda6..3f7e971 100644 break; \ } \ } \ -@@ -3181,8 +3224,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; @@ -864,7 +864,7 @@ index eb0dda6..3f7e971 100644 // now queue up command to resynch interpreter emcTaskQueueTaskPlanSynchCmd(); -@@ -3204,6 +3246,7 @@ static int emcTaskExecute(void) +@@ -3207,6 +3249,7 @@ static int emcTaskExecute(void) if (NULL != emcTaskCommand) { emcTaskEager = 1; emcStatus->task.currentLine = interp_list.get_line_number(); @@ -872,7 +872,7 @@ index eb0dda6..3f7e971 100644 // 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. -@@ -4200,8 +4243,7 @@ int main(int argc, char *argv[]) +@@ -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; diff --git a/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch b/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch index eeb55a2..eef8da4 100644 --- a/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch +++ b/linuxcnc-patches/0010-rs274-support-native-gcode-preview.patch @@ -24,7 +24,7 @@ keeps upstream's record of the mapping descriptor (8c8e048). 11 files changed, 160 insertions(+) diff --git a/src/emc/rs274ngc/interp_convert.cc b/src/emc/rs274ngc/interp_convert.cc -index 47f2509..a02c025 100644 +index 663668a..a823ac5 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc @@ -2528,6 +2528,7 @@ Called by: convert_cutter_compensation 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 2c78c47..93cf829 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 @@ -14,10 +14,11 @@ feature and its program. src/emc/motion/command.c | 24 +++-- 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 | 192 +++++++++++++++++++++++++++++++++--- + src/emc/tp/tp.c | 197 +++++++++++++++++++++++++++++++++--- src/emc/tp/tp_types.h | 5 +- - 6 files changed, 230 insertions(+), 51 deletions(-) + 7 files changed, 244 insertions(+), 52 deletions(-) diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c index a8e8ae3..ff48890 100644 @@ -99,7 +100,7 @@ index e347bf1..75a9f1c 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 3f7e971..7335937 100644 +index cff0805..f95b3b0 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -503,6 +503,7 @@ static int programStartLine = 0; // which line to run program from @@ -118,7 +119,7 @@ index 3f7e971..7335937 100644 } // Variables to handle MDI call interrupts -@@ -903,6 +905,22 @@ static void emcTaskStepInterpreter() +@@ -906,6 +908,22 @@ static void emcTaskStepInterpreter() emcStatus->task.task_paused = 1; } @@ -141,7 +142,7 @@ index 3f7e971..7335937 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1583,13 +1601,7 @@ static int emcTaskPlan(void) +@@ -1586,13 +1604,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -156,7 +157,7 @@ index 3f7e971..7335937 100644 break; // otherwise we can't handle it -@@ -1663,17 +1675,9 @@ static int emcTaskPlan(void) +@@ -1666,17 +1678,9 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -175,7 +176,7 @@ index 3f7e971..7335937 100644 break; // otherwise we can't handle it -@@ -1739,13 +1743,7 @@ static int emcTaskPlan(void) +@@ -1742,13 +1746,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -190,7 +191,7 @@ index 3f7e971..7335937 100644 break; // otherwise we can't handle it -@@ -4121,6 +4119,10 @@ int main(int argc, char *argv[]) +@@ -4124,6 +4122,10 @@ int main(int argc, char *argv[]) // update subordinate status emcMotionUpdate(&emcStatus->motion); @@ -201,6 +202,27 @@ index 3f7e971..7335937 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 @@ -216,7 +238,7 @@ index bd8ad13..5d6e0b4 100644 // this segment (g64 mode) diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index a9dfacc..85ee681 100644 +index a9dfacc..2a488d8 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c @@ -357,9 +357,9 @@ STATIC inline double tpGetRealFinalVel(TP_STRUCT const * const tp, @@ -287,16 +309,21 @@ index a9dfacc..85ee681 100644 tp->step_pass_id && !tp->step_tc) { tpHandleEmptyQueue(tp); return TP_ERR_WAITING; -@@ -4585,6 +4587,146 @@ STATIC int tpGetQueuedG76PassId(TP_STRUCT * const tp) +@@ -4585,6 +4587,151 @@ 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; @@ -434,7 +461,7 @@ index a9dfacc..85ee681 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4592,10 +4734,12 @@ int tpPause(TP_STRUCT * const tp) +@@ -4592,10 +4739,12 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -448,7 +475,7 @@ index a9dfacc..85ee681 100644 TC_STRUCT *tc = tcqItem(&tp->queue, 0); /* * A G76 cut that has passed spindle index, or its explicitly marked -@@ -4642,7 +4786,7 @@ int tpPause(TP_STRUCT * const tp) +@@ -4642,7 +4791,7 @@ int tpPause(TP_STRUCT * const tp) tp->pausing = 1; } } else if (emcmotStatus->stepping && @@ -457,7 +484,7 @@ index a9dfacc..85ee681 100644 /* * EMCMOT_STEP requests default-TP pass targeting through the existing * tpPause ABI. Alternate planners leave step_target_pending clear and -@@ -4651,15 +4795,27 @@ int tpPause(TP_STRUCT * const tp) +@@ -4651,15 +4800,27 @@ int tpPause(TP_STRUCT * const tp) int pass_id = tpGetQueuedG76PassId(tp); if (pass_id) { tp->step_pass_id = pass_id; @@ -474,9 +501,9 @@ index a9dfacc..85ee681 100644 - tp->pausing = 1; + tp->step_motion_id = tc ? tc->id : 0; + if (tc && tc->synchronized == TC_SYNC_POSITION) { -+ /* A spindle-synchronized move cannot change speed; keep the -+ * established end of its source block. */ -+ tp->step_tc = tpFindSourceBlockTarget(tp, tp->step_motion_id); ++ /* 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); @@ -489,7 +516,7 @@ index a9dfacc..85ee681 100644 } } else { tp->pausing = 1; -@@ -4672,6 +4828,7 @@ int tpResume(TP_STRUCT * const tp) +@@ -4672,6 +4833,7 @@ int tpResume(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -497,7 +524,7 @@ index a9dfacc..85ee681 100644 tp->pausing = 0; tp->stopping = 0; tp->stop_sync_run = 0; -@@ -4681,7 +4838,8 @@ int tpResume(TP_STRUCT * const tp) +@@ -4681,7 +4843,8 @@ int tpResume(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; @@ -507,7 +534,7 @@ index a9dfacc..85ee681 100644 if (MOTION_ID_VALID(tp->spindle.waiting_for_index)) { emcmotStatus->spindle_status[ tp->spindle.spindle_num].spindle_index_enable = 1; -@@ -4701,7 +4859,9 @@ int tpAbort(TP_STRUCT * const tp) +@@ -4701,7 +4864,9 @@ int tpAbort(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; 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 5e4220b..62c9814 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 @@ -25,8 +25,8 @@ tests/tooldb tests, which need a db program, are skipped. 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 | 71 +++- - src/emc/task/taskclass.cc | 369 ++++++++++++++++- + 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 ++++++++++++++---- @@ -35,7 +35,7 @@ tests/tooldb tests, which need a db program, are skipped. .../reload-tool/non-random/test-ui.py | 14 + .../toolchanger/reload-tool/random/test-ui.py | 3 +- tests/tooldb/db-g10-offset/skip | 3 + - 13 files changed, 946 insertions(+), 128 deletions(-) + 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 @@ -182,10 +182,10 @@ index 6a5632c..e4a04b1 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 7335937..a8ee5a6 100644 +index f95b3b0..c5aec97 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1280,7 +1280,18 @@ static int emcTaskPlan(void) +@@ -1283,7 +1283,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -205,7 +205,7 @@ index 7335937..a8ee5a6 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO emcTaskQueueCommand(std::make_unique(*static_cast(emcCommand))); -@@ -1409,6 +1420,18 @@ static int emcTaskPlan(void) +@@ -1412,6 +1423,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -224,7 +224,7 @@ index 7335937..a8ee5a6 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO -@@ -1534,6 +1557,18 @@ static int emcTaskPlan(void) +@@ -1537,6 +1560,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -243,7 +243,7 @@ index 7335937..a8ee5a6 100644 // otherwise we can't handle it default: -@@ -1869,6 +1904,18 @@ static int emcTaskPlan(void) +@@ -1872,6 +1907,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -262,7 +262,7 @@ index 7335937..a8ee5a6 100644 // otherwise we can't handle it default: -@@ -1972,6 +2019,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1975,6 +2022,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) case EMC_TOOL_LOAD_TOOL_TABLE_TYPE: case EMC_TOOL_SET_OFFSET_TYPE: @@ -271,7 +271,7 @@ index 7335937..a8ee5a6 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2604,6 +2653,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2607,6 +2656,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emc_tool_set_offset_msg->orientation); break; @@ -286,7 +286,7 @@ index 7335937..a8ee5a6 100644 case EMC_TOOL_SET_NUMBER_TYPE: emc_tool_set_number_msg = reinterpret_cast(cmd); retval = emcToolSetNumber(emc_tool_set_number_msg->tool); -@@ -3079,6 +3136,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: @@ -295,7 +295,7 @@ index 7335937..a8ee5a6 100644 case EMC_TOOL_SET_NUMBER_TYPE: case EMC_SPINDLE_SPEED_TYPE: case EMC_SPINDLE_ON_TYPE: -@@ -3263,10 +3322,18 @@ static int emcTaskExecute(void) +@@ -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; @@ -310,13 +310,14 @@ index 7335937..a8ee5a6 100644 + // carries on. Everything else aborts. + emcStatus->task.execState = + issued_type == EMC_TOOL_UPDATE_TYPE || -+ issued_type == EMC_TOOL_DELETE_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 0d076c8..3bac973 100644 +index 0d076c8..b4ec501 100644 --- a/src/emc/task/taskclass.cc +++ b/src/emc/task/taskclass.cc @@ -17,6 +17,7 @@ @@ -438,7 +439,7 @@ index 0d076c8..3bac973 100644 reload_tool_number(emcioStatus.tool.toolInSpindle); if (0 != iniTool(emc_inifile)) { -@@ -589,10 +612,70 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE +@@ -589,10 +612,73 @@ int Task::emcToolUnload()//EMC_TOOL_UNLOAD_TYPE return 0; } @@ -459,7 +460,10 @@ index 0d076c8..3bac973 100644 { if(!strlen(file)) file = tooltable_filename;//use filename from ini if none is provided - tooldata_load(file); -+ if (hal_get_bool(iocontrol_data->tool_prepare) || hal_get_bool(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; + bool refused_lines = false; @@ -510,7 +514,7 @@ index 0d076c8..3bac973 100644 reload_tool_number(emcioStatus.tool.toolInSpindle); return 0; } -@@ -634,9 +717,10 @@ 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)); @@ -522,7 +526,7 @@ index 0d076c8..3bac973 100644 int pno = idx; // for random_toolchanger if (!random_toolchanger) { pno = tdata.pocketno; } if (tooldata_db_notify(TOOL_OFFSET,toolno,pno,tdata)) { -@@ -656,6 +740,247 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, +@@ -656,6 +743,247 @@ int Task::emcToolSetOffset(int idx, int toolno, const EmcPose& offset, return 0; } diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index 3602410..88ea8e8 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -21,19 +21,19 @@ instead of continuing the unwound call. --- docs/src/config/python-interface.adoc | 3 +- docs/src/remap/remap.adoc | 130 ++++++++ - nc_files/remap_lib/python-stdglue/stdglue.py | 278 +++++++++++++++++- + 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 | 60 +++- + 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 | 43 ++- + src/emc/task/emctaskmain.cc | 55 +++- src/emc/task/task.hh | 4 + src/emc/usr_intf/axis/extensions/emcmodule.cc | 1 + - 14 files changed, 555 insertions(+), 10 deletions(-) + 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 @@ -191,7 +191,7 @@ index 75e2a09..642e4c7 100644 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 8457e40..7c4efca 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 @@ @@ -204,7 +204,7 @@ index 8457e40..7c4efca 100644 import emccanon from interpreter import * from emccanon import MESSAGE -@@ -40,6 +43,279 @@ def build_hal(self): +@@ -40,6 +43,281 @@ def build_hal(self): except Exception as e: print(e) @@ -321,6 +321,8 @@ index 8457e40..7c4efca 100644 + 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() @@ -484,7 +486,7 @@ index 8457e40..7c4efca 100644 # REMAP=S prolog=setspeed_prolog ngc=setspeed epilog=setspeed_epilog # exposed parameter: # -@@ -655,5 +931,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 @@ -530,7 +532,7 @@ index 210b4db..692b6e9 100644 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 e3f8b60..34f6fbc 100644 +index e3f8b60..ffcbf6f 100644 --- a/src/emc/rs274ngc/interp_python.cc +++ b/src/emc/rs274ngc/interp_python.cc @@ -99,6 +99,19 @@ bool Interp::is_pycallable(setup_pointer /*settings*/, @@ -574,7 +576,7 @@ index e3f8b60..34f6fbc 100644 ERS("exception during generator call: %s", msg.c_str()); } } else -@@ -193,6 +212,7 @@ int Interp::pycall(setup_pointer /*settings*/, +@@ -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. @@ -582,7 +584,26 @@ index e3f8b60..34f6fbc 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'. -@@ -264,6 +284,11 @@ int Interp::pycall(setup_pointer /*settings*/, +- 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(); } @@ -594,7 +615,7 @@ index e3f8b60..34f6fbc 100644 if (py_exception) { ERM("pycall: %s.%s:\n%s", module ? module:"", funcname, msg.c_str()); status = INTERP_ERROR; -@@ -298,3 +323,36 @@ pycontext &pycontext::operator=(const pycontext &other) { +@@ -298,3 +335,36 @@ pycontext &pycontext::operator=(const pycontext &other) { impl = new pycontext_impl(*other.impl); return *this; } @@ -741,7 +762,7 @@ index 90cc136..d2634e9 100644 { waitFlag = 0; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a8ee5a6..9133a28 100644 +index c5aec97..a93574e 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -577,7 +577,12 @@ extern int emcTaskMopup(); @@ -791,7 +812,23 @@ index a8ee5a6..9133a28 100644 } else if (execRetval == -1 || execRetval == INTERP_EXIT ) { emcStatus->task.interpState = -@@ -880,6 +900,10 @@ static bool emcTaskStopAllowsIssue(const NMLmsg *cmd) +@@ -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; @@ -802,7 +839,7 @@ index a8ee5a6..9133a28 100644 default: return false; } -@@ -1021,6 +1045,9 @@ static void emcTaskStopResume() +@@ -1024,6 +1051,9 @@ static void emcTaskStopResume() */ static EMC_TASK_HOLD_WAIT emcTaskHoldWait() { @@ -812,7 +849,7 @@ index a8ee5a6..9133a28 100644 if (emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_HOMING) { return EMC_TASK_HOLD_WAIT::HOMING; } -@@ -1723,6 +1750,9 @@ static int emcTaskPlan(void) +@@ -1726,6 +1756,9 @@ static int emcTaskPlan(void) } // switch (type) in ON, AUTO, PAUSED @@ -822,7 +859,21 @@ index a8ee5a6..9133a28 100644 break; // EMC_TASK_INTERP::PAUSED case EMC_TASK_INTERP::WAITING: -@@ -3292,7 +3322,8 @@ static int emcTaskExecute(void) +@@ -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 && @@ -832,7 +883,7 @@ index a8ee5a6..9133a28 100644 emcStatus->task.stopState != EMC_TASK_STOP_STATE::STOPPED && emcStatus->task.stopState != EMC_TASK_STOP_STATE::STARTING) { if (NULL == emcTaskCommand) { -@@ -3597,7 +3628,9 @@ static int emcTaskExecute(void) +@@ -3601,7 +3638,9 @@ static int emcTaskExecute(void) case EMC_TASK_EXEC::WAITING_FOR_DELAY: STEPPING_CHECK(); 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 4a792c3..c65b246 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 @@ -26,10 +26,10 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 9133a28..bae7266 100644 +index a93574e..5880f9a 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1078,7 +1078,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]; diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index e558f59..b7030ef 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -2267,7 +2267,7 @@ index d2634e9..f889dd3 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index bae7266..2a76c92 100644 +index 5880f9a..418bcd5 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -171,6 +171,61 @@ volatile int done; @@ -2400,7 +2400,7 @@ index bae7266..2a76c92 100644 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; -@@ -945,6 +1024,13 @@ static bool emcTaskArmSingleStep() +@@ -951,6 +1030,13 @@ static bool emcTaskArmSingleStep() return true; } @@ -2414,7 +2414,7 @@ index bae7266..2a76c92 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1057,6 +1143,19 @@ static EMC_TASK_HOLD_WAIT emcTaskHoldWait() +@@ -1063,6 +1149,19 @@ static EMC_TASK_HOLD_WAIT emcTaskHoldWait() if (emcStatus->io.status == RCS_STATUS::EXEC) { return EMC_TASK_HOLD_WAIT::IO; } @@ -2434,7 +2434,7 @@ index bae7266..2a76c92 100644 return EMC_TASK_HOLD_WAIT::NONE; } -@@ -1202,6 +1301,31 @@ static int emcTaskPlan(void) +@@ -1208,6 +1307,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2466,7 +2466,7 @@ index bae7266..2a76c92 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -@@ -1225,6 +1349,36 @@ static int emcTaskPlan(void) +@@ -1231,6 +1355,36 @@ static int emcTaskPlan(void) return 0; } @@ -2503,7 +2503,7 @@ index bae7266..2a76c92 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1737,9 +1891,7 @@ static int emcTaskPlan(void) +@@ -1743,9 +1897,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2514,7 +2514,7 @@ index bae7266..2a76c92 100644 break; // otherwise we can't handle it -@@ -2005,6 +2157,8 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -2011,6 +2163,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: @@ -2523,7 +2523,7 @@ index bae7266..2a76c92 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2211,10 +2365,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2217,10 +2371,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajSetMode(EMC_TRAJ_MODE::FREE); } homingWaitJoint = target_joint; @@ -2536,7 +2536,7 @@ index bae7266..2a76c92 100644 if (retval != 0) { // emcJointHome() rejected the request outright (e.g. an // invalid joint number) -- homing will never start, so the -@@ -2224,9 +2380,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2230,9 +2386,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) // from it) stays stuck at FREE/MANUAL until the operator // manually cycles mode again. homingWaiting = false; @@ -2547,7 +2547,7 @@ index bae7266..2a76c92 100644 } } break; -@@ -2240,6 +2394,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2246,6 +2400,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2572,7 +2572,7 @@ index bae7266..2a76c92 100644 case EMC_JOG_CONT_TYPE: jog_cont_msg = reinterpret_cast(cmd); retval = emcJogCont(jog_cont_msg->joint_or_axis, -@@ -2607,6 +2779,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2613,6 +2785,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcSpindleOff(spindle_off_msg->spindle, spindle_off_msg->wait_for_spindle_at_speed); break; @@ -2599,7 +2599,7 @@ index bae7266..2a76c92 100644 case EMC_SPINDLE_BRAKE_RELEASE_TYPE: spindle_brake_release_msg = reinterpret_cast(cmd); retval = emcSpindleBrakeRelease(spindle_brake_release_msg->spindle); -@@ -3065,7 +3257,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -3074,7 +3266,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) break; case EMC_TASK_PLAN_SYNCH_TYPE: @@ -2614,7 +2614,7 @@ index bae7266..2a76c92 100644 if (retval > INTERP_MIN_ERROR) { retval = -1; } -@@ -3180,6 +3379,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; @@ -2626,7 +2626,7 @@ index bae7266..2a76c92 100644 case EMC_TASK_PLAN_RUN_TYPE: case EMC_TASK_PLAN_PAUSE_TYPE: case EMC_TASK_PLAN_END_TYPE: -@@ -3262,6 +3466,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() @@ -2639,7 +2639,7 @@ index bae7266..2a76c92 100644 // first check for an abandoned system command and abort it if (emcSystemCmdPid != 0 && emcStatus->task.execState != -@@ -3389,11 +3599,59 @@ static int emcTaskExecute(void) +@@ -3399,11 +3609,59 @@ static int emcTaskExecute(void) break; case EMC_TASK_EXEC::WAITING_FOR_MOTION: @@ -2699,7 +2699,7 @@ index bae7266..2a76c92 100644 emcStatus->task.execState = EMC_TASK_EXEC::DONE; emcTaskEager = 1; } -@@ -3521,12 +3779,17 @@ static int emcTaskExecute(void) +@@ -3531,12 +3789,17 @@ static int emcTaskExecute(void) homingStarted = true; break; // still running; no timeout once started (see HOMING_START_TIMEOUT comment) } @@ -2722,7 +2722,7 @@ index bae7266..2a76c92 100644 // HOMING_START_TIMEOUT before concluding it was rejected. if (etime() - homingIssueTime < HOMING_START_TIMEOUT) { break; -@@ -3538,11 +3801,8 @@ static int emcTaskExecute(void) +@@ -3548,11 +3811,8 @@ static int emcTaskExecute(void) emcTaskEager = 1; homingWaiting = false; // Nothing physically moved, so it's safe to restore the @@ -2736,7 +2736,7 @@ index bae7266..2a76c92 100644 break; } // It ran and has now stopped; did it reach the expected end state? -@@ -3608,7 +3868,9 @@ static int emcTaskExecute(void) +@@ -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) { diff --git a/linuxcnc-patches/0018-availability-mcodes.patch b/linuxcnc-patches/0018-availability-mcodes.patch index 93bfdb7..d9580f1 100644 --- a/linuxcnc-patches/0018-availability-mcodes.patch +++ b/linuxcnc-patches/0018-availability-mcodes.patch @@ -217,10 +217,10 @@ index c65a3b2..219a007 100644 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 a02c025..6cdf203 100644 +index a823ac5..354433e 100644 --- a/src/emc/rs274ngc/interp_convert.cc +++ b/src/emc/rs274ngc/interp_convert.cc -@@ -4443,6 +4443,20 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ +@@ -4447,6 +4447,20 @@ if ((block->m_modes[9] == 53) && ONCE_M(9)){ } } 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 9626292..62249a2 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 @@ -688,10 +688,10 @@ index feab3fb..a9fc353 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 2a76c92..57b8240 100644 +index 418bcd5..d2e57f0 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1521,6 +1521,7 @@ static int emcTaskPlan(void) +@@ -1527,6 +1527,7 @@ static int emcTaskPlan(void) case EMC_JOINT_HOME_TYPE: case EMC_JOINT_UNHOME_TYPE: case EMC_JOG_CONT_TYPE: @@ -699,7 +699,7 @@ index 2a76c92..57b8240 100644 case EMC_JOG_INCR_TYPE: case EMC_JOG_ABS_TYPE: case EMC_JOG_STOP_TYPE: -@@ -2425,6 +2426,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2431,6 +2432,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; 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 index 12a593d..78afd32 100644 --- 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 @@ -52,7 +52,7 @@ index f889dd3..b6793d2 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 57b8240..3e8c047 100644 +index d2e57f0..9da1e97 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -817,7 +817,7 @@ interpret_again: 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 index 19b16a9..8933414 100644 --- 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 @@ -22,10 +22,10 @@ and accepted again once the machine is idle. 1 file changed, 62 insertions(+) diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 3e8c047..2a975eb 100644 +index 9da1e97..76ad4cd 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1269,6 +1269,45 @@ static void emcTaskStopProgress() +@@ -1275,6 +1275,45 @@ static void emcTaskStopProgress() } } @@ -71,7 +71,7 @@ index 3e8c047..2a975eb 100644 /* emcTaskPlan() -@@ -1288,6 +1327,18 @@ static int emcTaskPlan(void) +@@ -1294,6 +1333,18 @@ static int emcTaskPlan(void) type = 0; } @@ -90,7 +90,7 @@ index 3e8c047..2a975eb 100644 // Always display messages switch (type) { case EMC_OPERATOR_ERROR_TYPE: -@@ -1326,6 +1377,17 @@ static int emcTaskPlan(void) +@@ -1332,6 +1383,17 @@ static int emcTaskPlan(void) return retval; } diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index 54e5377..a93355d 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -251,6 +251,8 @@ 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. 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 @@ -327,7 +329,10 @@ 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. On v2.10.0-pre2, @@ -441,8 +446,12 @@ 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. A Step that is canceled restores every segment it -changed. Later motion remains queued and does not +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. 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. @@ -495,8 +504,8 @@ 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 or delete tells the operator why and fails only that -command: spindle, coolant and an open program are unaffected. +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 @@ -521,7 +530,8 @@ 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. Its timeout keeps counting, and a failure +`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. @@ -532,6 +542,10 @@ 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 diff --git a/linuxcnc-tests/remap/executor/checkresult b/linuxcnc-tests/remap/executor/checkresult index bbdfe51..bfa99e9 100755 --- a/linuxcnc-tests/remap/executor/checkresult +++ b/linuxcnc-tests/remap/executor/checkresult @@ -1,5 +1,6 @@ #!/bin/sh set -e -test "$(grep -c '^executor remap scenario ok:' "$1")" -eq 9 +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/preview.ngc b/linuxcnc-tests/remap/executor/preview.ngc new file mode 100644 index 0000000..bf3931c --- /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/test-ui.py b/linuxcnc-tests/remap/executor/test-ui.py index 95fccbc..c673858 100755 --- a/linuxcnc-tests/remap/executor/test-ui.py +++ b/linuxcnc-tests/remap/executor/test-ui.py @@ -266,6 +266,41 @@ def assert_released(prefix): "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. diff --git a/linuxcnc-tests/remap/executor/test.sh b/linuxcnc-tests/remap/executor/test.sh index 29c462d..9ffc590 100755 --- a/linuxcnc-tests/remap/executor/test.sh +++ b/linuxcnc-tests/remap/executor/test.sh @@ -4,9 +4,20 @@ # 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; do +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/resumable-stop/general/checkresult b/linuxcnc-tests/resumable-stop/general/checkresult index c3dac55..8869f3b 100755 --- a/linuxcnc-tests/resumable-stop/general/checkresult +++ b/linuxcnc-tests/resumable-stop/general/checkresult @@ -1,2 +1,2 @@ #!/bin/sh -exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 27 +exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 28 diff --git a/linuxcnc-tests/resumable-stop/general/scenarios b/linuxcnc-tests/resumable-stop/general/scenarios index faa5b75..3749334 100644 --- a/linuxcnc-tests/resumable-stop/general/scenarios +++ b/linuxcnc-tests/resumable-stop/general/scenarios @@ -25,3 +25,4 @@ pause-inflight-step trapezoidal:inflight-step-short system-command set-auto-stopped +step-after-dwell-stop diff --git a/linuxcnc-tests/resumable-stop/test-ui.py b/linuxcnc-tests/resumable-stop/test-ui.py index fa7d105..b37cafe 100755 --- a/linuxcnc-tests/resumable-stop/test-ui.py +++ b/linuxcnc-tests/resumable-stop/test-ui.py @@ -1323,6 +1323,35 @@ def run_set_auto_while_stopped_test(): 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) + 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 @@ -2055,6 +2084,36 @@ def run_threading_chain_stop_resume_test(): ) +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 @@ -2160,6 +2219,7 @@ def run_stopped_spindle_s_word_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, @@ -2179,6 +2239,7 @@ def run_stopped_spindle_s_word_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, } 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 0000000..a9f4865 --- /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/threading/checkresult b/linuxcnc-tests/resumable-stop/threading/checkresult index 3b2acd1..664eed8 100755 --- a/linuxcnc-tests/resumable-stop/threading/checkresult +++ b/linuxcnc-tests/resumable-stop/threading/checkresult @@ -1,2 +1,2 @@ #!/bin/sh -exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 10 +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 index 7391ffb..36e8cc9 100644 --- a/linuxcnc-tests/resumable-stop/threading/scenarios +++ b/linuxcnc-tests/resumable-stop/threading/scenarios @@ -8,3 +8,4 @@ g33-no-following-rapid command-after-sync resume-stopping-refused step-stopping-refused +inflight-step-g33-chain diff --git a/linuxcnc-tests/tool-table-load/garbage-ui.py b/linuxcnc-tests/tool-table-load/garbage-ui.py index e390c5d..d1323f5 100755 --- a/linuxcnc-tests/tool-table-load/garbage-ui.py +++ b/linuxcnc-tests/tool-table-load/garbage-ui.py @@ -24,11 +24,20 @@ 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: From 5f550d9d05584e87f2bcfca1ac6f7ee99623d2f5 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 26 Nov 2026 12:20:02 +0100 Subject: [PATCH 43/45] fix(linuxcnc): close the final pre2 review's Stop and Step findings Step from STOPPED with nothing queued resumes motion, motion's abort drops an armed Step, Stop needs a running program, a Step on a synchronized run follows the run as it is queued, and a blend under way at Step arm is finished. --- linuxcnc-patches/0004-resumable-stop.patch | 28 +++--- .../0007-native-automatic-tool-wear.patch | 12 +-- ...reading-stop-clear-and-pass-stepping.patch | 10 +- ...-single-step-during-active-execution.patch | 96 ++++++++++++++----- ...-own-transactional-tool-CRUD-in-task.patch | 14 +-- ...4ngc-add-composable-executor-stdglue.patch | 4 +- ...-publish-modal-CSS-maximum-in-status.patch | 2 +- ...ntime-joint-and-spindle-availability.patch | 62 ++++++------ ...w-concurrent-individual-joint-homing.patch | 4 +- ...otion-add-native-lathe-power-jogging.patch | 10 +- ...te-whenever-the-interpreter-is-reset.patch | 2 +- ...ter-reset-unless-the-machine-is-idle.patch | 8 +- linuxcnc-patches/README.md | 19 ++-- .../resumable-stop/general/checkresult | 2 +- .../resumable-stop/general/scenarios | 1 + linuxcnc-tests/resumable-stop/test-ui.py | 38 ++++++++ 16 files changed, 201 insertions(+), 111 deletions(-) diff --git a/linuxcnc-patches/0004-resumable-stop.patch b/linuxcnc-patches/0004-resumable-stop.patch index 8bf8243..54bdb67 100644 --- a/linuxcnc-patches/0004-resumable-stop.patch +++ b/linuxcnc-patches/0004-resumable-stop.patch @@ -569,7 +569,7 @@ index ed6a962..6010ecb 100644 { } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a3b5256..3b544e1 100644 +index a3b5256..3e73c7b 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -124,6 +124,39 @@ static int emcTaskEager = 0; @@ -643,7 +643,7 @@ index a3b5256..3b544e1 100644 // now handle call logic // check for subsystems done if (interp_list.len() == 0 && -@@ -781,6 +824,292 @@ static bool allow_while_idle_type() { +@@ -781,6 +824,294 @@ static bool allow_while_idle_type() { return 0; } @@ -917,7 +917,9 @@ index a3b5256..3b544e1 100644 + return; + } + } -+ if (stop_single_step) { ++ // 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(); @@ -936,7 +938,7 @@ index a3b5256..3b544e1 100644 /* emcTaskPlan() -@@ -809,6 +1138,33 @@ static int emcTaskPlan(void) +@@ -809,6 +1140,33 @@ static int emcTaskPlan(void) return retval; } @@ -970,7 +972,7 @@ index a3b5256..3b544e1 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1734,6 +2090,7 @@ 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; @@ -978,7 +980,7 @@ index a3b5256..3b544e1 100644 if (homingPriorMode != EMC_TRAJ_MODE::FREE) { emcTrajSetMode(EMC_TRAJ_MODE::FREE); } -@@ -1937,6 +2294,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -1937,6 +2296,11 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcTrajPause(); break; @@ -990,7 +992,7 @@ index a3b5256..3b544e1 100644 case EMC_TRAJ_RESUME_TYPE: emcStatus->task.task_paused = 0; retval = emcTrajResume(); -@@ -2039,6 +2401,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); @@ -1002,7 +1004,7 @@ index a3b5256..3b544e1 100644 taskExecDelayTimeout = etime() + wait_spindle_orient_complete_msg->timeout; break; -@@ -2099,6 +2466,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); @@ -1017,17 +1019,15 @@ index a3b5256..3b544e1 100644 retval = emcSpindleOrient(spindle_orient_msg->spindle, spindle_orient_msg->orientation, spindle_orient_msg->mode); break; -@@ -2191,7 +2566,49 @@ 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 = diff --git a/linuxcnc-patches/0007-native-automatic-tool-wear.patch b/linuxcnc-patches/0007-native-automatic-tool-wear.patch index d5adcb1..d6cc1cd 100644 --- a/linuxcnc-patches/0007-native-automatic-tool-wear.patch +++ b/linuxcnc-patches/0007-native-automatic-tool-wear.patch @@ -1475,7 +1475,7 @@ index 7620a30..55fb417 100644 // 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 3b544e1..fafc18c 100644 +index 3e73c7b..ec76402 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -612,6 +612,9 @@ interpret_again: @@ -1488,7 +1488,7 @@ index 3b544e1..fafc18c 100644 emcAbortCleanup(EMC_ABORT::INTERPRETER_ERROR, "interpreter error"); } else if (execRetval == -1 -@@ -1955,6 +1958,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) +@@ -1957,6 +1960,11 @@ static EMC_TASK_EXEC emcTaskCheckPreconditions(NMLmsg * cmd) break; case EMC_TOOL_SET_NUMBER_TYPE: @@ -1500,7 +1500,7 @@ index 3b544e1..fafc18c 100644 return EMC_TASK_EXEC::WAITING_FOR_IO; break; -@@ -2032,6 +2040,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) +@@ -2034,6 +2042,12 @@ int emcTaskQueueCommand(std::unique_ptr &&cmd) } // issues command immediately @@ -1513,7 +1513,7 @@ index 3b544e1..fafc18c 100644 static int emcTaskIssueCommand(NMLmsg * cmd) { int retval = 0; -@@ -2535,9 +2549,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2537,9 +2551,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcToolPrepare(tool_prepare_msg->tool); break; @@ -1528,7 +1528,7 @@ index 3b544e1..fafc18c 100644 case EMC_TOOL_UNLOAD_TYPE: retval = emcToolUnload(); -@@ -2553,6 +2571,8 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -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, @@ -1537,7 +1537,7 @@ index 3b544e1..fafc18c 100644 emc_tool_set_offset_msg->diameter, emc_tool_set_offset_msg->frontangle, emc_tool_set_offset_msg->backangle, -@@ -2562,6 +2582,10 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -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); 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 0a6070a..ba56823 100644 --- a/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch +++ b/linuxcnc-patches/0009-threading-stop-clear-and-pass-stepping.patch @@ -684,7 +684,7 @@ index 55fb417..90cc136 100644 } - diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index fafc18c..cff0805 100644 +index ec76402..14f26b5 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -503,6 +503,22 @@ static int programStartLine = 0; // which line to run program from @@ -720,7 +720,7 @@ index fafc18c..cff0805 100644 } static void emcTaskStepInterpreter() -@@ -1574,6 +1589,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 @@ -731,7 +731,7 @@ index fafc18c..cff0805 100644 break; // otherwise we can't handle it -@@ -1726,6 +1745,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 @@ -742,7 +742,7 @@ index fafc18c..cff0805 100644 break; // otherwise we can't handle it -@@ -1983,6 +2006,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; @@ -754,7 +754,7 @@ index fafc18c..cff0805 100644 case EMC_TRAJ_DELAY_TYPE: return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2288,7 +2316,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2290,7 +2318,9 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajLinearMoveMsg->type, emcTrajLinearMoveMsg->vel, emcTrajLinearMoveMsg->ini_maxvel, emcTrajLinearMoveMsg->acc, emcTrajLinearMoveMsg->ini_maxjerk, emcTrajLinearMoveMsg->vlimit_scale, 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 93cf829..ebbad87 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 @@ -11,20 +11,30 @@ 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 | 24 +++-- + src/emc/motion/command.c | 27 +++-- src/emc/motion/control.c | 9 +- - src/emc/task/emctaskmain.cc | 48 ++++----- + src/emc/task/emctaskmain.cc | 48 ++++---- src/emc/tp/tc.c | 10 +- src/emc/tp/tc_types.h | 3 + - src/emc/tp/tp.c | 197 +++++++++++++++++++++++++++++++++--- + src/emc/tp/tp.c | 224 +++++++++++++++++++++++++++++++++--- src/emc/tp/tp_types.h | 5 +- - 7 files changed, 244 insertions(+), 52 deletions(-) + 7 files changed, 274 insertions(+), 52 deletions(-) diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index a8e8ae3..ff48890 100644 +index a8e8ae3..0347123 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -1334,6 +1334,13 @@ 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"); @@ -38,7 +48,7 @@ index a8e8ae3..ff48890 100644 tpPause(&emcmotInternal->coord_tp); emcmotStatus->paused = 1; break; -@@ -1381,26 +1388,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1381,26 +1391,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; case EMCMOT_STEP: @@ -100,7 +110,7 @@ index e347bf1..75a9f1c 100644 emcmotStatus->stepping = 0; emcmotStatus->paused = 1; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index cff0805..f95b3b0 100644 +index 14f26b5..635418d 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -503,6 +503,7 @@ static int programStartLine = 0; // which line to run program from @@ -142,7 +152,7 @@ index cff0805..f95b3b0 100644 static void emcTaskStopClear() { bool was_active = emcStatus && -@@ -1586,13 +1604,7 @@ static int emcTaskPlan(void) +@@ -1588,13 +1606,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -157,7 +167,7 @@ index cff0805..f95b3b0 100644 break; // otherwise we can't handle it -@@ -1666,17 +1678,9 @@ static int emcTaskPlan(void) +@@ -1668,17 +1680,9 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -176,7 +186,7 @@ index cff0805..f95b3b0 100644 break; // otherwise we can't handle it -@@ -1742,13 +1746,7 @@ static int emcTaskPlan(void) +@@ -1744,13 +1748,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -238,10 +248,19 @@ index bd8ad13..5d6e0b4 100644 // this segment (g64 mode) diff --git a/src/emc/tp/tp.c b/src/emc/tp/tp.c -index a9dfacc..2a488d8 100644 +index a9dfacc..63c138c 100644 --- a/src/emc/tp/tp.c +++ b/src/emc/tp/tp.c -@@ -357,9 +357,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 */ @@ -253,7 +272,7 @@ index a9dfacc..2a488d8 100644 tc->term_cond != TC_TERM_COND_TANGENT || tp->reverse_run) { return 0.0; } -@@ -497,7 +497,9 @@ 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; @@ -264,7 +283,7 @@ index a9dfacc..2a488d8 100644 tp->reverse_run = 0; tp->synchronized = 0; tp->uu_per_rev = 0.0; -@@ -1595,7 +1597,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; } @@ -273,7 +292,7 @@ index a9dfacc..2a488d8 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, -@@ -1621,12 +1623,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 && @@ -284,10 +303,28 @@ index a9dfacc..2a488d8 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) { -@@ -3497,10 +3498,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; } @@ -300,7 +337,7 @@ index a9dfacc..2a488d8 100644 } //TODO make progress to match target? -@@ -4396,7 +4398,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; } @@ -309,7 +346,7 @@ index a9dfacc..2a488d8 100644 tp->step_pass_id && !tp->step_tc) { tpHandleEmptyQueue(tp); return TP_ERR_WAITING; -@@ -4585,6 +4587,151 @@ 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; } @@ -406,7 +443,9 @@ index a9dfacc..2a488d8 100644 + for (int i = 0; i < len; ++i) { + TC_STRUCT *tc = tcqItem(&tp->queue, i); + if (i > 0) { -+ dist += tc->target; ++ // 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)); + } @@ -414,6 +453,11 @@ index a9dfacc..2a488d8 100644 + 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; + } @@ -461,7 +505,7 @@ index a9dfacc..2a488d8 100644 int tpPause(TP_STRUCT * const tp) { if (0 == tp) { -@@ -4592,10 +4739,12 @@ int tpPause(TP_STRUCT * const tp) +@@ -4592,10 +4766,12 @@ int tpPause(TP_STRUCT * const tp) } if (tp->stopping) { @@ -475,7 +519,7 @@ index a9dfacc..2a488d8 100644 TC_STRUCT *tc = tcqItem(&tp->queue, 0); /* * A G76 cut that has passed spindle index, or its explicitly marked -@@ -4642,7 +4791,7 @@ int tpPause(TP_STRUCT * const tp) +@@ -4642,7 +4818,7 @@ int tpPause(TP_STRUCT * const tp) tp->pausing = 1; } } else if (emcmotStatus->stepping && @@ -484,7 +528,7 @@ index a9dfacc..2a488d8 100644 /* * EMCMOT_STEP requests default-TP pass targeting through the existing * tpPause ABI. Alternate planners leave step_target_pending clear and -@@ -4651,15 +4800,27 @@ 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; @@ -516,7 +560,7 @@ index a9dfacc..2a488d8 100644 } } else { tp->pausing = 1; -@@ -4672,6 +4833,7 @@ int tpResume(TP_STRUCT * const tp) +@@ -4672,6 +4860,7 @@ int tpResume(TP_STRUCT * const tp) if (0 == tp) { return TP_ERR_FAIL; } @@ -524,7 +568,7 @@ index a9dfacc..2a488d8 100644 tp->pausing = 0; tp->stopping = 0; tp->stop_sync_run = 0; -@@ -4681,7 +4843,8 @@ int tpResume(TP_STRUCT * const tp) +@@ -4681,7 +4870,8 @@ int tpResume(TP_STRUCT * const tp) tp->step_tc = 0; tp->step_target_pending = 0; tp->step_pass_id = 0; @@ -534,7 +578,7 @@ index a9dfacc..2a488d8 100644 if (MOTION_ID_VALID(tp->spindle.waiting_for_index)) { emcmotStatus->spindle_status[ tp->spindle.spindle_num].spindle_index_enable = 1; -@@ -4701,7 +4864,9 @@ 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; 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 62c9814..15b17d3 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 @@ -182,10 +182,10 @@ index 6a5632c..e4a04b1 100644 public: EMC_TOOL_SET_NUMBER() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index f95b3b0..c5aec97 100644 +index 635418d..6c57192 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1283,7 +1283,18 @@ static int emcTaskPlan(void) +@@ -1285,7 +1285,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -205,7 +205,7 @@ index f95b3b0..c5aec97 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO emcTaskQueueCommand(std::make_unique(*static_cast(emcCommand))); -@@ -1412,6 +1423,18 @@ static int emcTaskPlan(void) +@@ -1414,6 +1425,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -224,7 +224,7 @@ index f95b3b0..c5aec97 100644 case EMC_TOOL_SET_NUMBER_TYPE: { // send to IO -@@ -1537,6 +1560,18 @@ static int emcTaskPlan(void) +@@ -1539,6 +1562,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -243,7 +243,7 @@ index f95b3b0..c5aec97 100644 // otherwise we can't handle it default: -@@ -1872,6 +1907,18 @@ static int emcTaskPlan(void) +@@ -1874,6 +1909,18 @@ static int emcTaskPlan(void) emcTaskQueueTaskPlanSynchCmd(); break; } @@ -262,7 +262,7 @@ index f95b3b0..c5aec97 100644 // otherwise we can't handle it default: -@@ -1975,6 +2022,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: @@ -271,7 +271,7 @@ index f95b3b0..c5aec97 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2607,6 +2656,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2609,6 +2658,14 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emc_tool_set_offset_msg->orientation); break; diff --git a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch index 88ea8e8..b53a173 100644 --- a/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch +++ b/linuxcnc-patches/0013-rs274ngc-add-composable-executor-stdglue.patch @@ -762,7 +762,7 @@ index 90cc136..d2634e9 100644 { waitFlag = 0; diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index c5aec97..a93574e 100644 +index 6c57192..0d3448c 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -577,7 +577,12 @@ extern int emcTaskMopup(); @@ -849,7 +849,7 @@ index c5aec97..a93574e 100644 if (emcStatus->task.execState == EMC_TASK_EXEC::WAITING_FOR_HOMING) { return EMC_TASK_HOLD_WAIT::HOMING; } -@@ -1726,6 +1756,9 @@ static int emcTaskPlan(void) +@@ -1728,6 +1758,9 @@ static int emcTaskPlan(void) } // switch (type) in ON, AUTO, PAUSED 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 c65b246..963e57a 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 @@ -26,7 +26,7 @@ index 513c932..d6e8437 100644 template diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index a93574e..5880f9a 100644 +index 0d3448c..fd0335e 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -1084,7 +1084,7 @@ static void emcTaskStopProgress() diff --git a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch index b7030ef..029ef87 100644 --- a/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch +++ b/linuxcnc-patches/0017-runtime-joint-and-spindle-availability.patch @@ -414,7 +414,7 @@ index e814320..029af60 100644 if (!motion_enable_flag) { 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 ff48890..9d6fb2c 100644 +index 0347123..072bb70 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -80,6 +80,16 @@ extern int motion_num_spindles; @@ -533,7 +533,7 @@ index ff48890..9d6fb2c 100644 SET_MOTION_ERROR_FLAG(0); /* clear joint errors (regardless of mode) */ for (joint_num = 0; joint_num < ALL_JOINTS; joint_num++) { -@@ -610,6 +691,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); @@ -545,7 +545,7 @@ index ff48890..9d6fb2c 100644 if (GET_MOTION_TELEOP_FLAG()) { /* tell teleop planner to stop */ if ((emcmotCommand->axis >= 0) && (emcmotCommand->axis < EMCMOT_MAX_AXIS)) { -@@ -644,6 +730,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: @@ -556,7 +556,7 @@ index ff48890..9d6fb2c 100644 /* change the mode to coordinated axis motion */ /* can be done at any time */ /* this code doesn't actually make the transition, it merely -@@ -666,6 +756,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: @@ -567,7 +567,7 @@ index ff48890..9d6fb2c 100644 rtapi_print_msg(RTAPI_MSG_DBG, "TELEOP"); switch_to_teleop_mode(); break; -@@ -740,10 +834,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); @@ -586,7 +586,7 @@ index ff48890..9d6fb2c 100644 update_joint_homing_params(joint_num, emcmotCommand->offset, emcmotCommand->home, -@@ -856,6 +957,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; } @@ -601,7 +601,7 @@ index ff48890..9d6fb2c 100644 // cannot jog if jog-inhibit is TRUE if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); -@@ -925,6 +1034,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; } @@ -616,7 +616,7 @@ index ff48890..9d6fb2c 100644 // cannot jog if jog-inhibit is TRUE if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); -@@ -1005,6 +1122,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; } @@ -631,7 +631,7 @@ index ff48890..9d6fb2c 100644 // cannot jog if jog-inhibit is TRUE if (hal_get_bool(emcmot_hal_data->jog_inhibit)){ reportError(_("Cannot jog while jog-inhibit is active.")); -@@ -1068,6 +1193,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: @@ -649,7 +649,7 @@ index ff48890..9d6fb2c 100644 tpSetSpindleSync(&emcmotInternal->coord_tp, emcmotCommand->spindle, emcmotCommand->spindlesync, emcmotCommand->flags); break; -@@ -1508,6 +1644,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; @@ -657,7 +657,7 @@ index ff48890..9d6fb2c 100644 if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { emcmotInternal->teleoperating = 0; emcmotInternal->coordinating = 0; -@@ -1520,10 +1657,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"); @@ -675,7 +675,7 @@ index ff48890..9d6fb2c 100644 if (emcmotConfig->kinType == KINEMATICS_INVERSE_ONLY) { emcmotInternal->teleoperating = 0; emcmotInternal->coordinating = 0; -@@ -1540,6 +1683,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; } @@ -689,7 +689,7 @@ index ff48890..9d6fb2c 100644 SET_JOINT_ACTIVE_FLAG(joint, 1); break; -@@ -1552,6 +1702,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; } @@ -703,7 +703,7 @@ index ff48890..9d6fb2c 100644 SET_JOINT_ACTIVE_FLAG(joint, 0); break; -@@ -1563,6 +1720,14 @@ 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); @@ -718,7 +718,7 @@ index ff48890..9d6fb2c 100644 /* 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 -@@ -1595,9 +1760,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1598,9 +1763,17 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) if (!GET_MOTION_ENABLE_FLAG()) { break; } @@ -736,7 +736,7 @@ index ff48890..9d6fb2c 100644 break; case EMCMOT_JOINT_UNHOME: -@@ -1611,6 +1784,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1614,6 +1787,26 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) return; } @@ -763,7 +763,7 @@ index ff48890..9d6fb2c 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'. -@@ -1629,6 +1822,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1632,6 +1825,160 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) break; @@ -924,7 +924,7 @@ index ff48890..9d6fb2c 100644 case EMCMOT_CLEAR_PROBE_FLAGS: rtapi_print_msg(RTAPI_MSG_DBG, "CLEAR_PROBE_FLAGS"); emcmotStatus->probing = 0; -@@ -1825,6 +2172,11 @@ 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,7 +936,7 @@ index ff48890..9d6fb2c 100644 for (n = s0; n<=s1; n++){ if (hal_get_bool(emcmot_hal_data->spindle[n].spindle_orient)) -@@ -1930,8 +2282,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1933,8 +2285,12 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) s0 = 0; s1 = motion_num_spindles - 1; } @@ -950,7 +950,7 @@ index ff48890..9d6fb2c 100644 if (n > emcmotConfig->numSpindles){ rtapi_print_msg(RTAPI_MSG_ERR, "spindle number <%d> too high in M19",n); break; -@@ -1981,6 +2337,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; } @@ -961,7 +961,7 @@ index ff48890..9d6fb2c 100644 for (n = s0; n<=s1; n++){ if (emcmotStatus->spindle_status[n].speed > 0) { emcmotStatus->spindle_status[n].speed += emcmotStatus->spindle_status[n].increment; -@@ -2005,6 +2365,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; } @@ -972,7 +972,7 @@ index ff48890..9d6fb2c 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; -@@ -2051,8 +2415,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; } @@ -2267,7 +2267,7 @@ index d2634e9..f889dd3 100644 // clear out the pending command diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 5880f9a..418bcd5 100644 +index fd0335e..900c430 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -171,6 +171,61 @@ volatile int done; @@ -2434,7 +2434,7 @@ index 5880f9a..418bcd5 100644 return EMC_TASK_HOLD_WAIT::NONE; } -@@ -1208,6 +1307,31 @@ static int emcTaskPlan(void) +@@ -1210,6 +1309,31 @@ static int emcTaskPlan(void) return emcTaskIssueCommand(emcCommand); } @@ -2466,7 +2466,7 @@ index 5880f9a..418bcd5 100644 if (emcStatus->task.stopState != EMC_TASK_STOP_STATE::IDLE && (type == EMC_TASK_PLAN_RUN_TYPE || type == EMC_TASK_PLAN_RESUME_TYPE || -@@ -1231,6 +1355,36 @@ static int emcTaskPlan(void) +@@ -1233,6 +1357,36 @@ static int emcTaskPlan(void) return 0; } @@ -2503,7 +2503,7 @@ index 5880f9a..418bcd5 100644 // handle any new command switch (emcStatus->task.state) { case EMC_TASK_STATE::OFF: -@@ -1743,9 +1897,7 @@ static int emcTaskPlan(void) +@@ -1745,9 +1899,7 @@ static int emcTaskPlan(void) break; case EMC_TASK_PLAN_STEP_TYPE: @@ -2514,7 +2514,7 @@ index 5880f9a..418bcd5 100644 break; // otherwise we can't handle it -@@ -2011,6 +2163,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: @@ -2523,7 +2523,7 @@ index 5880f9a..418bcd5 100644 return EMC_TASK_EXEC::WAITING_FOR_MOTION_AND_IO; break; -@@ -2217,10 +2371,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2219,10 +2373,12 @@ static int emcTaskIssueCommand(NMLmsg * cmd) emcTrajSetMode(EMC_TRAJ_MODE::FREE); } homingWaitJoint = target_joint; @@ -2536,7 +2536,7 @@ index 5880f9a..418bcd5 100644 if (retval != 0) { // emcJointHome() rejected the request outright (e.g. an // invalid joint number) -- homing will never start, so the -@@ -2230,9 +2386,7 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -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; @@ -2547,7 +2547,7 @@ index 5880f9a..418bcd5 100644 } } break; -@@ -2246,6 +2400,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2248,6 +2402,24 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcJointUnhome(unhome_msg->joint); break; @@ -2572,7 +2572,7 @@ index 5880f9a..418bcd5 100644 case EMC_JOG_CONT_TYPE: jog_cont_msg = reinterpret_cast(cmd); retval = emcJogCont(jog_cont_msg->joint_or_axis, -@@ -2613,6 +2785,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2615,6 +2787,26 @@ static int emcTaskIssueCommand(NMLmsg * cmd) retval = emcSpindleOff(spindle_off_msg->spindle, spindle_off_msg->wait_for_spindle_at_speed); break; 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 b45517a..aa731f4 100644 --- a/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch +++ b/linuxcnc-patches/0019-motion-allow-concurrent-individual-joint-homing.patch @@ -24,10 +24,10 @@ so the new concurrency checks never refuse it. 5 files changed, 119 insertions(+), 78 deletions(-) diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index 9d6fb2c..e8a68ce 100644 +index 072bb70..b96b098 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c -@@ -1753,10 +1753,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) +@@ -1756,10 +1756,29 @@ void emcmotCommandHandler_locked(void *arg, long servo_period) joint_num); return; } 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 62249a2..64ca089 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 @@ -292,7 +292,7 @@ index 5d61f0b..f1ce1d7 100644 #ifdef __cplusplus diff --git a/src/emc/motion/command.c b/src/emc/motion/command.c -index e8a68ce..554c1b5 100644 +index b96b098..3f5a562 100644 --- a/src/emc/motion/command.c +++ b/src/emc/motion/command.c @@ -157,6 +157,19 @@ STATIC int spindle_range_is_available(int first, int last) @@ -315,7 +315,7 @@ index e8a68ce..554c1b5 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) -@@ -946,6 +959,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; @@ -688,10 +688,10 @@ index feab3fb..a9fc353 100644 public: EMC_JOG_CONT() diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 418bcd5..d2e57f0 100644 +index 900c430..db1e711 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1527,6 +1527,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: @@ -699,7 +699,7 @@ index 418bcd5..d2e57f0 100644 case EMC_JOG_INCR_TYPE: case EMC_JOG_ABS_TYPE: case EMC_JOG_STOP_TYPE: -@@ -2431,6 +2432,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) +@@ -2433,6 +2434,13 @@ static int emcTaskIssueCommand(NMLmsg * cmd) jog_stop_msg->jjogmode); break; 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 index 78afd32..c008019 100644 --- 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 @@ -52,7 +52,7 @@ index f889dd3..b6793d2 100644 } diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index d2e57f0..9da1e97 100644 +index db1e711..f318c1e 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc @@ -817,7 +817,7 @@ interpret_again: 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 index 8933414..1cc55f2 100644 --- 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 @@ -22,10 +22,10 @@ and accepted again once the machine is idle. 1 file changed, 62 insertions(+) diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc -index 9da1e97..76ad4cd 100644 +index f318c1e..758ed70 100644 --- a/src/emc/task/emctaskmain.cc +++ b/src/emc/task/emctaskmain.cc -@@ -1275,6 +1275,45 @@ static void emcTaskStopProgress() +@@ -1277,6 +1277,45 @@ static void emcTaskStopProgress() } } @@ -71,7 +71,7 @@ index 9da1e97..76ad4cd 100644 /* emcTaskPlan() -@@ -1294,6 +1333,18 @@ static int emcTaskPlan(void) +@@ -1296,6 +1335,18 @@ static int emcTaskPlan(void) type = 0; } @@ -90,7 +90,7 @@ index 9da1e97..76ad4cd 100644 // Always display messages switch (type) { case EMC_OPERATOR_ERROR_TYPE: -@@ -1332,6 +1383,17 @@ static int emcTaskPlan(void) +@@ -1334,6 +1385,17 @@ static int emcTaskPlan(void) return retval; } diff --git a/linuxcnc-patches/README.md b/linuxcnc-patches/README.md index a93355d..cb861c7 100644 --- a/linuxcnc-patches/README.md +++ b/linuxcnc-patches/README.md @@ -195,8 +195,9 @@ 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. @@ -252,7 +253,9 @@ 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. +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 @@ -277,7 +280,7 @@ 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, Resume of a spindle restored at S0, commands queued behind a thread, `G33` threading including a chain of +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. @@ -448,7 +451,10 @@ 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. A Step that is canceled +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 @@ -456,7 +462,8 @@ 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, Stop or -Pause; Pause during an in-flight Step is an ordinary Pause. Existing paused source-line stepping and two-stage G76 stepping remain intact. +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 diff --git a/linuxcnc-tests/resumable-stop/general/checkresult b/linuxcnc-tests/resumable-stop/general/checkresult index 8869f3b..f5ef75d 100755 --- a/linuxcnc-tests/resumable-stop/general/checkresult +++ b/linuxcnc-tests/resumable-stop/general/checkresult @@ -1,2 +1,2 @@ #!/bin/sh -exec "$(dirname "$0")/../check-result.sh" "$1" "$(dirname "$0")/scenarios" 28 +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 index 3749334..d184309 100644 --- a/linuxcnc-tests/resumable-stop/general/scenarios +++ b/linuxcnc-tests/resumable-stop/general/scenarios @@ -8,6 +8,7 @@ rapid-no-atspeed paused-resume paused-run abort-empty +abort-armed-step orientation dwell dwell-atspeed diff --git a/linuxcnc-tests/resumable-stop/test-ui.py b/linuxcnc-tests/resumable-stop/test-ui.py index b37cafe..74dcbf1 100755 --- a/linuxcnc-tests/resumable-stop/test-ui.py +++ b/linuxcnc-tests/resumable-stop/test-ui.py @@ -478,6 +478,37 @@ def run_stop_while_program_paused_test(restart_with_run): 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") @@ -1340,6 +1371,12 @@ def run_step_after_dwell_stop_test(): "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: @@ -2201,6 +2238,7 @@ def run_stopped_spindle_s_word_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, From d4d871fd387f7b34e4c24b514889a3edcb610896 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 26 Nov 2026 12:24:38 +0100 Subject: [PATCH 44/45] feat(linuxcnc): port patch 0026 to v2.10.0-pre2 Main added the operator error serial patch (0024 there, 0026 here, after this branch's own 0024 and 0025) against the old base. Port it onto the pre2 series; readahead keeps the zero stamp next to pre2's Stop hold. --- ...he-command-an-operator-error-rejects.patch | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/linuxcnc-patches/0026-task-identify-the-command-an-operator-error-rejects.patch b/linuxcnc-patches/0026-task-identify-the-command-an-operator-error-rejects.patch index 7617802..9cf5a0f 100644 --- a/linuxcnc-patches/0026-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); From 9b24f0f888eefa090f33bcd8f55c9683e35380e3 Mon Sep 17 00:00:00 2001 From: Dariusz Majnert Date: Thu, 26 Nov 2026 12:54:30 +0100 Subject: [PATCH 45/45] test(linuxcnc): retry the first interpreter reset after startup Task's startup synch is not visible in status, and on a loaded runner it can still refuse the first reset. --- .../task/interp-reset-requires-idle/test-ui.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py b/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py index f6c85cc..d7b2092 100755 --- a/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py +++ b/linuxcnc-tests/task/interp-reset-requires-idle/test-ui.py @@ -105,6 +105,20 @@ def abort_and_settle(name): # 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")