From 0a679b5eeb3e8185be8b2644692aa58f47ab35f4 Mon Sep 17 00:00:00 2001 From: wangdequan Date: Mon, 7 Sep 2026 13:47:10 +0800 Subject: [PATCH] Align AXIS Web control lifecycle with LinuxCNC --- coverage/runtime-mapping.report.json | 2 +- docs/linuxcnc-axis-complete-parity-spec.md | 1 + ...cnc-axis-web-control-panel-source-logic.md | 394 ++++++++ docs/linuxcnc-submodule-local-changes.md | 18 + patches/linuxcnc-working-tree.patch | 944 ++++++++++++++++++ scripts/test_axis_control_contract.mjs | 40 + ...test_xyzac_live_path_lifecycle_browser.mjs | 122 +++ .../test_xyzac_multi_program_load_browser.mjs | 112 +++ scripts/test_xyzac_panel_buttons_browser.mjs | 26 +- ...xyzac_program_execution_browser_strict.mjs | 143 +++ ...t_xyzac_refresh_single_program_browser.mjs | 99 ++ wasm-core/CMakeLists.txt | 2 +- wasm-core/include/sim_program.h | 1 + wasm-core/src/sim_program.c | 39 +- wasm-core/tests/sim_xyzac_trace_test.c | 8 + web/react/src/App.tsx | 209 ++-- web/react/src/XyzacToolPreview.tsx | 53 +- web/react/src/XyzacTrtPanel.tsx | 9 +- web/react/src/protocol.ts | 1 + web/react/src/store.ts | 21 +- web/react/src/test_store_visual_clear.mjs | 27 +- web/react/src/test_xyzac_tool_preview.mjs | 5 +- web/react/src/xyzac-visual-adapter.ts | 4 +- web/worker/sim-session.mjs | 147 ++- web/worker/test_xyzac_3d_chips.mjs | 23 +- web/worker/test_xyzac_live_path_lifecycle.mjs | 76 ++ web/worker/test_xyzac_multi_program_load.mjs | 86 ++ web/worker/test_xyzac_panel_buttons.mjs | 4 +- web/worker/test_xyzac_program_rerun.mjs | 66 ++ web/worker/test_xyzac_protocol_react.mjs | 7 +- .../test_xyzac_touch_off_source_flow.mjs | 56 ++ web/worker/wasm-program-runtime.mjs | 23 + web/worker/wasm-xyzac-io.mjs | 1 + web/worker/xyzac-session.mjs | 6 +- 34 files changed, 2598 insertions(+), 177 deletions(-) create mode 100644 docs/linuxcnc-axis-web-control-panel-source-logic.md create mode 100644 docs/linuxcnc-submodule-local-changes.md create mode 100644 patches/linuxcnc-working-tree.patch create mode 100644 scripts/test_axis_control_contract.mjs create mode 100644 scripts/test_xyzac_live_path_lifecycle_browser.mjs create mode 100644 scripts/test_xyzac_multi_program_load_browser.mjs create mode 100644 scripts/test_xyzac_program_execution_browser_strict.mjs create mode 100644 scripts/test_xyzac_refresh_single_program_browser.mjs create mode 100644 web/worker/test_xyzac_live_path_lifecycle.mjs create mode 100644 web/worker/test_xyzac_multi_program_load.mjs create mode 100644 web/worker/test_xyzac_program_rerun.mjs create mode 100644 web/worker/test_xyzac_touch_off_source_flow.mjs diff --git a/coverage/runtime-mapping.report.json b/coverage/runtime-mapping.report.json index df83762..2ceca0f 100644 --- a/coverage/runtime-mapping.report.json +++ b/coverage/runtime-mapping.report.json @@ -2,7 +2,7 @@ "schema": "runtime-mapping-report.v1", "status": "passed", "mapped_error_codes": 18, - "commands": 50, + "commands": 52, "limits": 6, "real_exclusions": 3 } diff --git a/docs/linuxcnc-axis-complete-parity-spec.md b/docs/linuxcnc-axis-complete-parity-spec.md index d2ed326..39e4352 100644 --- a/docs/linuxcnc-axis-complete-parity-spec.md +++ b/docs/linuxcnc-axis-complete-parity-spec.md @@ -7,6 +7,7 @@ **原始 AXIS 入口**:[`linuxcnc/share/axis/tcl/axis.tcl`](../linuxcnc/share/axis/tcl/axis.tcl) **配套通信契约**:[前端与通信详细设计](linuxcnc-web-wasm-frontend-communication-design.md) **配套案例契约**:[案例对标计划](linuxcnc-web-wasm-case-parity-plan.md) +**控制面板逻辑契约**:[LinuxCNC AXIS Web 控制面板源程序对照逻辑](linuxcnc-axis-web-control-panel-source-logic.md) 本文件是“Web 主界面完全对标 LinuxCNC 原始 AXIS”的唯一执行规范。它把原始 AXIS 的功能、界面结构、状态门控、快捷键、图标、绘图和外部集成拆成可追溯任务;没有来源、命令序列、状态结果和验收证据的功能,不得标记为完成。 diff --git a/docs/linuxcnc-axis-web-control-panel-source-logic.md b/docs/linuxcnc-axis-web-control-panel-source-logic.md new file mode 100644 index 0000000..6b05060 --- /dev/null +++ b/docs/linuxcnc-axis-web-control-panel-source-logic.md @@ -0,0 +1,394 @@ +# LinuxCNC AXIS Web Control Panel Source Logic + +Status: active implementation contract +Scope: the selected `XYZAC TRT` Web/WASM panel and its LinuxCNC-compatible +Worker command path +Source baseline: LinuxCNC submodule `239dcf4284762ad7e9c65d390bc5524d855c2f8e` + +This document is the control-flow authority for the Web panel. A button is +implemented only when its complete path is defined here: + +```text +browser gesture + -> React handler + -> AxisOperationController operation + -> SimSession command gate + -> LinuxCNC/WASM task, interpreter, TP or IO authority + -> canonical snapshot + -> React projection +``` + +The React state is never an authority. A rejected Worker command must remain +rejected in the UI, with the source gate reason visible as the disabled-button +title and in Diagnostics. + +The panel does not add a startup/run alias. The source-defined machine sequence +is explicit: release E-stop when needed, power on, home, then press the single +toolbar Run control (or the source `R` shortcut). + +On browser startup, the selected INI is the only program-selection authority. +For `xyzac-trt.ini`, `[DISPLAY] OPEN_FILE` selects +`./demos/xyzac_switchkins.ngc`, matching `axis.py` startup around +`initialfile`/`open_file_guts`. Browser UI persistence must not restore a +different G-code source or path and must never schedule a hidden second +`PROGRAM_LOAD` after the configured file appears. + +AXIS has both Machine/View menu bindings and toolbar/notebook bindings. The Web +surface keeps the toolbar as the single machine-command entry point and the +notebook tabs as the single view entry point. This removes duplicate buttons; +the command, gate and source symbol for each retained entry are unchanged. + +## Source References + +The primary GUI source is +`linuxcnc/src/emc/usr_intf/axis/scripts/axis.py`. The accepted command and +post-completion/abort behavior are also checked against +`linuxcnc/src/emc/task/emctaskmain.cc`; the Web panel must not stop at the +Python button handler when the LinuxCNC task layer defines an additional +transition. + +| AXIS source symbol | Role | +| --- | --- | +| `manual_ok`, `ensure_mode` | Polling, task-state and mode preconditions | +| `estop_clicked`, `onoff_clicked` | E-stop and machine power edges | +| `open_file_guts` | File replacement transaction and mode restoration | +| `task_run`, `task_run_line`, `task_step`, `task_pause`, `task_resume`, `task_pauseresume`, `task_stop` | Program execution lifecycle | +| `send_mdi`, `send_mdi_command` | MDI history, mode and command submission | +| `home_all_joints`, `home_joint` | Homing and joint/kinematics restrictions | +| `touch_off_system`, `touch_off_tool` | Coordinate/tool offset dialogs and `G10`/`G43` sequence | +| `spindle`, `spindle_forward_toggle`, `spindle_backward_toggle`, `spindle_increase`, `spindle_decrease`, `spindle_constant` | Spindle direction, speed and brake controls | +| `mist_toggle`, `flood_toggle`, `brake_on`, `brake_off` | Auxiliary IO controls | +| `toggle_override_limits`, `cycle_view` | Limit override and preview view selection | + +The widget wiring is in `linuxcnc/share/axis/tcl/axis.tcl`: machine menu and +toolbar bindings are around lines 105-170 and 490-669; manual jog, home, +touch-off, spindle and coolant bindings are around lines 893-1087. + +## Source Surface Inventory + +This inventory separates source controls from the smaller Web surface. A +source-only or host-bound entry is documented explicitly rather than silently +replaced by a different action. + +| Source surface | Source entries | Web treatment | +| --- | --- | --- | +| File menu | Open, Recent Files, Edit, Reload, Save As, Properties, Edit Tool Data, Reload Tool Data, Ladder Editor, Quit | Open/Reload/Load are Worker-backed; editor text is the Web file source; save, external editors, Ladder and Quit are host-boundary status/disabled entries. | +| Machine menu | E-stop, Power, Run, Run from selected line, Step, Pause, Resume, Stop, Optional Stop, Block Delete, MDI history, Calibration/HAL tools, Homing, Unhoming, Zero coordinate system, Tool touch-off target | E-stop/Power/Run/Step/Pause/Resume/Stop/Home/Touch Off are represented by documented commands; Run-from-line, MDI clipboard/file actions, calibration/HAL desktop tools and Unhoming are not exposed; Optional Stop, Block Delete, Override Limits and Tool Touch Off remain ABI-blocked. | +| View menu | Six preset views, inches/mm, show program/rapids/live plot/tool/extents/offsets/limits/velocity/DTG, grid, DRO font, PyVCP, commanded/actual, machine/relative, joint/world, clear plot | Preset view/zoom/rotate, units, commanded/actual, machine/relative and supported visual layers are Web projections; unsupported teleop, grid/DTG/font/PyVCP settings are not aliased to motion state. | +| Toolbar | E-stop, Power, Open, Reload, Run, Step, Pause/Resume, Stop, Block Delete, Optional Stop, zoom, six views, rotate, Clear Plot | Same source order and icon assets are retained for supported controls; unsupported controls are disabled with a source/ABI reason. | +| Manual notebook | Axis/joint selector, continuous/increment jog, Home Axis, Touch Off, Tool Touch Off, Override Limits, spindle direction/stop/speed/brake, coolant, tool/probe | XYZAC axis selector, jog, Home Axis, Touch Off, spindle, coolant, tool and probe are represented; joint selector, Tool Touch Off and Override Limits are explicitly bounded by the selected configuration/ABI. | +| Web case strip | no AXIS equivalent | `Load exact XYZAC TRT case` is a Web workspace/bootstrap control, not an AXIS source button. It may only call the same documented `LOAD_WORKSPACE` + `PROGRAM_LOAD` transaction and must not introduce a second Run/Power/Home flow. | +| MDI notebook | MDI entry, Go, history selection/double-click, Up/Down history, Ctrl-M/H/Shift-H clipboard operations | Entry, Go and local history are represented; clipboard/file history operations are host/UI-only and are not sent as machine commands. | +| Browser UI persistence | AXIS preferences do not override `[DISPLAY] OPEN_FILE` with executable source text | OPFS may persist presentation preferences such as view, zoom, tabs, units and selected axis. It must not persist or automatically load G-code source/path. | + +The Web surface may remove duplicate menu entries, but it may not change the +meaning of a retained command. This is why Machine/View menus are not rendered +when the same source action already has a toolbar or notebook entry. + +## Source Keyboard Contract + +The following bindings are copied from `axis.py` lines 3109-3171. Keys that +would require an unavailable command are listed as blocked instead of being +silently mapped to another operation. + +| Key | Source handler | Web treatment | +| --- | --- | --- | +| `F1`, `F2`, lowercase `r`, `T`, `P`, `S`, `Esc`, `Ctrl-R`, `O`, `F7`-`F12` | E-stop, power, run, step, pause, resume, stop, reload, open, coolant and spindle handlers | Worker-backed commands with the same gate and ordering rules. | +| uppercase `R`, `F` | `task_reverse`, `task_forward` | Source controls are recorded as blocked because the selected WASM program ABI has no reverse/forward command; they are never mapped to Run. | +| `Home`, `Ctrl-Home`, `End`, `Ctrl-End` | `home_joint`, `home_all_joints`, `touch_off_system`, `touch_off_tool` | Home and system Touch Off are implemented; Tool Touch Off reports the documented ABI blocker. | +| `x`, `y`, `z`, `a`, `c`, `-`, `=`, Shift jog keys | Axis selection and `jog_on`/`jog_off` | Axis selection and pointer jog are implemented; browser key-jog remains limited to the visible selected axes. | +| `c`, `i`, `I` | Continuous/incremental jog mode | Represented by the jog increment selector; no second local mode state is created. | +| `v`, `d`, `!`, `@`, `#`, `$` | Cycle view, rotate, units, display type, coordinate type, teleop mode | View/rotate/units/display/coordinate actions are projected; teleop mode is explicitly unavailable. | +| `Ctrl-K` | `clear_live_plot` | Worker visual-only `VISUAL_CLEAR`. | +| `Ctrl-S`, Ctrl-M/H/Shift-H, `F4` | Save G-code, MDI clipboard/history, next tab | Save/clipboard operations are host/UI-boundary; `F4` notebook cycling is a Web navigation action and does not alter machine state. | + +## State Gates + +Every motion or interpreter operation is evaluated against the canonical task, +IO and trajectory state before the handler runs. + +| State | Meaning in the panel | +| --- | --- | +| `ESTOP` | E-stop input asserted. Only the reset edge and diagnostic-safe actions are available. | +| `ESTOP_RESET` | E-stop released but power is not on. `POWER(active=true)` is the next machine edge. | +| `OFF` | Machine power is off. File inspection/loading is allowed by LinuxCNC, but motion and MDI are not. | +| `ON` | IO is ready. Manual operations still require an idle interpreter and the correct task mode. | +| `RUNNING`/`PAUSED` | AUTO execution owns the interpreter. Manual, MDI, home, spindle and tool operations are blocked. | +| `STOPPED` | A stopped taskfile remains recoverable; the next source-defined transition is `IO_RECOVER`, power or restart as applicable. | + +`manual_ok()` is equivalent to: poll, task state ON, not running, and either +an idle interpreter or an MDI queue below its limit. `ensure_mode()` is a +command transaction, not a React state assignment. + +## Control Matrix + +| Panel control | React command | Source flow and required result | +| --- | --- | --- | +| Emergency Stop / Cancel | `ESTOP {active}` | `estop_clicked` toggles `STATE_ESTOP` and `STATE_ESTOP_RESET`; active E-stop aborts the interpreter and TP, then keeps the loaded taskfile. | +| Power on / off | `POWER {active}` | `onoff_clicked` toggles `STATE_ON` and `STATE_OFF`; power-off aborts motion but preserves the loaded file. | +| Open G-code file | browser file + `PROGRAM_LOAD` | `open_file_guts`: poll, save mode, enter MANUAL, restore the saved tab mode before `PLAN_OPEN/program_open`, set first line, synchronize, parse/preview, then `set_mode_from_tab` after refresh. | +| Load case / Load editor | `PROGRAM_LOAD` | Same replacement transaction as `open_file_guts`; old preview is cleared before parsing and never reused after a failed replacement. | +| Switchkins Identity / TCP: XYZAC / User K | `KINEMATICS_SELECT {type}` | Selected-case remap equivalent for `M429`/`M428`/`M430` from `xyzac-trt.ini`; requires homed, idle, empty TP queue and canonical HAL switchkins state. | +| Run | `PROGRAM_RUN` | `run_warn`, `ensure_mode(AUTO)`, `AUTO_RUN` from the selected start line, then periodic task/TP ticks. Normal AXIS Run uses line 0. In `emctaskmain.cc`, an ended or aborted task plan is closed; the next `EMC_TASK_PLAN_RUN` reopens the current taskfile and runs from line 0. Therefore Run after `completed` or `aborted` must work directly and must not require a separate Reload/Restart click. | +| Run from selected line | not exposed | AXIS `task_run_line` requires an editor highlight and source `AUTO_RUN` start line. The Web editor has no source-line selection command yet, so no partial/fake button is rendered. | +| Reverse / Forward | not exposed | AXIS `task_reverse`/`task_forward` are keyboard-only source actions; the selected WASM program ABI has no corresponding command and Web preserves the distinction from Run. | +| Step | `PROGRAM_STEP` | `ensure_mode(AUTO)` when needed, issue `AUTO_STEP`, and keep the interpreter at the source line boundary. | +| Pause / Resume | `PROGRAM_PAUSE` / `PROGRAM_RESUME` | Pause only while AUTO is reading/waiting; resume only from the paused state. Polling ticks stop around the edge so a servo sample cannot race it. | +| Stop | `PROGRAM_ABORT` | AXIS enables Stop only while the interpreter is non-idle; then it highlights the active line, issues `c.abort()`, waits for completion, and clears the abort edge. The Worker may accept an internal abort edge in more states, but the Web button follows the AXIS UI gate. | +| Block delete / optional pause | disabled | LinuxCNC source has these controls, but the selected WASM ABI does not expose their canonical state. They are visible as disabled, with `blocked_by_abi`, and never emulate a local toggle. | +| Preview view, zoom, rotate, clear plot | local view or `VISUAL_CLEAR` | Visual-only operations do not change task, interpreter, TP or IO state. `Ctrl-K` maps AXIS `clear_live_plot()` and clears only the accumulated execution Live Plot; it must not delete the loaded program's static preview. | +| DRO coordinate/display/units | local projection | Maps AXIS `coord_type`, `display_type` and `metric` variables; values remain Worker snapshot projections. | +| Preview layers | local projection | Maps source `show_live_plot`, `show_machine_limits`, `show_machine_speed`, `show_offsets` and `show_extents` where the selected visual adapter has data; toggling a layer never changes motion. | +| Manual / MDI tabs | `SET_MODE` | The tab gesture sends an explicit Worker mode command. No background effect may change MANUAL after AUTO has started. | +| Joint/World (teleop) mode | not exposed | AXIS View menu calls `set_teleop_mode`/`c.teleop_enable`; the selected WASM motion ABI has no canonical teleop setter, so Web does not pretend its coordinate mode is a joint/world toggle. | +| Jog `-` / `+` | `JOG_START`, repeated `SIM_STEP`, `JOG_STOP` | `jog_on`/`jog_off` semantics. Incremental mode submits one TP segment; Continuous mode samples the source TP jog velocity until pointer release. | +| Home Axis | `HOME {axis}` | `manual_ok`, `ensure_mode(MANUAL)`, then source joint-home command. Individual axis home is rejected outside identity kinematics, matching `home_joint`. | +| Home All / Re-home All | `HOME {all:true}` | `manual_ok`, `ensure_mode(MANUAL)`, then home all joints. Once the canonical homed mask is complete, the Web label changes to `RE-HOME ALL` so loading another program is not mistaken for a requirement to home again. Activating Re-home retains the source `home_all_joints` confirmation. `PROGRAM_LOAD` never clears the homed mask and never invokes HOME. | +| Touch Off | `TOUCH_OFF {axis,value,system,units}` | Prompt for value and one of AXIS's `all_systems` entries (`P0 Current`, `P1 G54` ... `P9 G59.3`), enter MDI, issue `G10 L20 `, wait/synchronize, reload the active interpreter state and restore the saved mode. | +| Tool Touch Off | `TOOL_TOUCH_OFF {axis,value,system,units}` | LinuxCNC source requires `G10 L10/L11` plus `G43`, but the selected WASM interpreter does not expose canonical tool-offset storage. The control is therefore disabled with `blocked_by_abi_tool_offsets`; it never sends a fake fixed `G43`. | +| Override limits | disabled | Source requires an active limit and an idle interpreter; the selected WASM limit override ABI is unavailable, so no unsafe local emulation is provided. | +| Spindle CCW / stop / CW | `SPINDLE_COMMAND` | `manual_ok`, `ensure_mode(MANUAL)`, then source direction/stop command. The displayed pressed state is derived from canonical signed RPM. | +| Spindle - / + | `SPINDLE_COMMAND {delta}` → `SPINDLE_CONSTANT` on release | AXIS binds Button-1 to `spindle_decrease`/`spindle_increase` and ButtonRelease to `spindle_constant`; Web preserves this press/release sequence. | +| Brake | `SPINDLE_BRAKE` | Source brake command, gated by `manual_ok`. | +| Mist / Flood | `COOLANT_COMMAND` | Independent source coolant toggles; canonical device IO is returned after every edge. | +| Prepare / Change tool | `TOOL_PREPARE` / `TOOL_CHANGE` | Source tool IO authority and acknowledgement path; no simulated completion is reported before the Worker verifies it. | +| Arm / Disarm probe | `PROBE_CONFIG` | Source probe IO authority; faults and E-stop remain Worker-owned. | +| Jog Speed | `SET_JOG_SCALE` | `update_jog_slider_vel` writes the source linear jog scale. | +| Angular Jog Speed | not exposed | AXIS has a separate `ajogspeed` control for rotary joints; the selected WASM TP exposes one shared jog scale only, so the Web panel does not alias linear Jog Speed to this control. | +| Feed Override | `SET_OVERRIDE` | `set_feedrate` writes the source feed override; updates are debounced but ordered in the Worker queue. | +| Spindle Override | `SET_SPINDLE_OVERRIDE` | `set_spindlerate` writes canonical spindle override. | +| Max Velocity | `SET_MAX_VELOCITY` | AXIS `set_maxvel` calls `c.maxvel` and changes the trajectory velocity limit. The selected WASM TP exposes this as its velocity scale. | +| Rapid Override | disabled | AXIS `set_rapidrate` calls `c.rapidrate` and is distinct from Max Velocity. The selected WASM TP has no rapid-scale setter, so the Web control is disabled with `blocked_by_abi_rapidrate`. | +| MDI command/history | `MDI_EXECUTE` | `send_mdi` validates `manual_ok`, enters MDI, de-duplicates adjacent history entries and submits `c.mdi`. | +| File edit/tool data/quit and desktop diagnostics | disabled or status-only | AXIS source launches external editor, tool editor, Ladder, HAL tools, LinuxCNC status and process quit. These are host-boundary operations and are not represented as browser controls. | + +## Button Dependency Matrix + +The following matrix describes the side effects that determine the next set of +enabled controls. The right-hand column is an observable Worker state change; +React must derive its button gates from that state on the next snapshot. + +| Action | Must be true before the click | State change after acceptance | Controls affected next | +| --- | --- | --- | --- | +| `ESTOP(active=true)` | Always accepted by the task state machine | IO `estop=1`, `ready=0`; interpreter and TP aborted; task `ESTOP`; loaded source retained | Disable power-on, home, jog, MDI, spindle, tool, probe and all program controls except E-stop reset/recovery-safe actions | +| `ESTOP(active=false)` | E-stop input is asserted | IO estop clears; task becomes `STOPPED`/`ESTOP_RESET`; power remains off | Enable Power On; keep all motion/interpreter operations disabled | +| `POWER(active=true)` | E-stop clear, interpreter idle, task not running | IO `ready=1`; task `READY`/machine `ON` | Enable Home and source-gated manual/program controls; Run still requires homed and a taskfile | +| `POWER(active=false)` | Machine on (source accepts the immediate off edge) | Abort motion/interpreter, IO `ready=0`, loaded taskfile retained | Disable motion, MDI, home and Run; allow Power On after the off edge | +| `HOME(all/axis)` | Machine on, interpreter idle, homing gate true | Home-limit authority sets homed mask; individual non-identity home is rejected | Enables Run/MDI/jog only after the canonical homed result is published | +| `PROGRAM_LOAD` | Interpreter idle, TP/MDI motion queue empty, source file/path valid | Enters MANUAL for replacement setup, captures the current canonical TP pose, restores the saved mode before PLAN_OPEN-equivalent parsing, replaces the interpreter source, applies the `task_plan_synch` pose before preview/subroutine processing, then reapplies the selected tab mode | Run/Step/Restart gates are recalculated from the new taskfile; old preview/trace is unavailable during parse and incremental coordinates start from the synchronized machine pose | +| `KINEMATICS_SELECT` | Machine on, homed, idle, TP queue empty, valid type 0/1/2 | M429/M428/M430 selection updates canonical kinematics and the HAL switchkins type | Identity is required for individual coordinate-axis homing; a non-empty queue blocks selection | +| `SET_MODE(MANUAL)` | Machine on, no active AUTO/MDI motion | Task mode becomes `MANUAL` | Enables manual jog/home/spindle/tool gates when idle; disables AUTO-only pause/resume | +| `SET_MODE(MDI)` | Machine on, interpreter idle or MDI queue below limit | Task mode becomes `MDI` | Enables MDI submission; manual controls follow `manual_ok` and queue policy | +| `PROGRAM_RUN` | AXIS toolbar projection: machine ON and interpreter IDLE. Task acceptance additionally requires a current taskfile and, unless `NO_FORCE_HOMING` is configured, all required joints homed. `completed` and `aborted` are valid idle starting states. | If the previous task plan ended or was aborted, reopen/rewind the current taskfile at line 0; set mode `AUTO`, program `RUNNING`, and begin TP samples. A short program may pass through RUNNING and reach `completed` before the next UI paint; that is successful execution, not a blocked Run. | Disable Load, MDI, Home, Jog, spindle and tool operations while active; enable Pause and Stop. On completion, Run becomes available again for another line-0 execution. | +| `PROGRAM_PAUSE` | AUTO program is reading/waiting | Program/task `PAUSED`; run polling is stopped around the edge | Disable Pause and Stop-as-new-run; enable Resume; keep E-stop and Power Off available | +| `PROGRAM_RESUME` | Program/task is paused | Program/task `RUNNING`; TP polling resumes | Re-enable Pause and Stop; keep manual/MDI/home disabled | +| `PROGRAM_ABORT` | AXIS exposes Stop while machine ON and interpreter non-IDLE; the task abort command itself is immediate | Interpreter aborts, TP queue is cleared, current taskfile/path remains selected, and the open task plan is closed | Stop periodic run polling; direct Run is enabled again when the task is idle and reopens the same taskfile from line 0. Reload is not a prerequisite. | +| `JOG_START` | Machine on, idle/manual gate, homed | One incremental segment or repeated continuous TP segments are queued | While held, another jog direction is not started; release/cancel must issue `JOG_STOP` | +| `JOG_STOP` | An active jog gesture exists | Active jog is aborted/stopped; TP remains runnable | Allows a subsequent jog, MDI or source-gated manual command | +| `TOUCH_OFF` | Machine on, homed, idle/manual gate and valid dialog value | MDI `G10 L20` updates the selected coordinate system, then the saved mode is restored | Position/DRO and offsets refresh; program run state is unchanged | +| `SET_MAX_VELOCITY` | Machine powered and the override gate permits the update | Source TP velocity limit is changed | Motion duration/velocity changes; jog and feed overrides remain independent | +| Rapid Override control | Not available in the selected WASM TP | No state change | Rapid Override remains disabled; Max Velocity must not be used as a substitute | +| Spindle/Coolant/Tool/Probe | Machine on, idle, source-specific manual gate | Canonical device IO changes only after Worker verification | Their pressed/checked states update from device IO; no React-only optimistic state is allowed | + +### Dependency Flow + +```text +ESTOP ──release──> ESTOP_RESET ──POWER ON──> ON + │ + ├──HOME ALL──> homed ON + │ │ + │ ├──RUN──> AUTO/RUNNING + │ │ ├──PAUSE──> PAUSED + │ │ │ └──RESUME──> RUNNING + │ │ └──STOP/ESTOP/POWER OFF──> idle loaded taskfile + │ └──MANUAL/MDI──> jog/home/offset/device gates + └──PROGRAM LOAD──> loaded taskfile (idle only) +``` + +Any E-stop or power-off edge invalidates the downstream branch immediately. +The UI must not leave a stale enabled button visible while it waits for the +next canonical snapshot; the Worker gate remains the final authority even if a +click races a state transition. + +## Required Transactions + +### Startup program selection + +```text +read selected INI + -> resolve [DISPLAY] OPEN_FILE + -> keep preview/program controls in loading state + -> LOAD_WORKSPACE + -> exactly one PROGRAM_LOAD for the configured OPEN_FILE + -> publish the configured program, source hash and preview atomically + -> enable source-gated controls +``` + +The UI cache is read only for presentation preferences. A stale cached program +from an earlier Web version is ignored and replaced on the next UI preference +save. No default-preview-then-cached-preview transition is permitted. + +### File replacement + +```text +poll + -> reject if AUTO is running/paused + -> save task mode + -> ensure MANUAL + -> clear previous preview and pending TP/interpreter edges + -> restore saved task mode before PLAN_OPEN-equivalent parsing + -> capture current canonical TP pose + -> set first line / PROGRAM_LOAD + -> task_plan_synch equivalent: initialize the new interpreter from that TP pose + -> subroutine load + preview from the same synchronized pose + -> reapply selected tab mode after the UI refresh + -> publish one canonical replacement snapshot +``` + +The replacement is rejected while the TP or an MDI move still has a queued or +active segment. Loading program B after program A has moved the machine must +never reset the interpreter to the origin. For example, if A ends at `X10`, a +new B program beginning with `G91 G1 X5` previews and executes from `X10` to +`X15`, not from `X0` to `X5`. + +### E-stop recovery and startup + +```text +ESTOP(active=true) + -> abort interpreter and TP + -> task ESTOP, IO estop=1, ready=0 +ESTOP(active=false) + -> IO estop=0, task STOPPED (ESTOP_RESET) +POWER(active=true) + -> IO ready=1, task READY/ON +HOME(all=true) + -> MANUAL mode, all joints homed +PROGRAM_RUN + -> if the previous plan is completed/aborted: reopen current taskfile at line 0 + -> AUTO mode, RUNNING, periodic SIM_STEP until completion +``` + +### Run after completion or Stop + +```text +RUNNING -> M2/end-of-file -> WAITING -> queue/IO drained -> IDLE/completed + -> press Run + -> reopen current taskfile + -> AUTO_RUN line 0 + +RUNNING -> Stop/abort -> abort interpreter + TP -> close task plan -> IDLE/aborted + -> press Run + -> reopen current taskfile + -> AUTO_RUN line 0 +``` + +This is the source behavior in `emctaskmain.cc`: closing the task plan avoids +resuming at an aborted line, and `EMC_TASK_PLAN_RUN_TYPE` opens the selected +file again when no plan is open. The Web runtime may expose `PROGRAM_RESTART` +internally for recovery/testing, but it is not a required user step and is not +a second visible Run control. After the reopen/synchronization, a positioning +block whose target already equals the current canonical pose is a zero-motion +block: it advances the interpreter line but must not enqueue an invalid +zero-length TP segment. + +### Touch-off command encoding + +AXIS's `all_systems` list is `P0 Current`, `P1 G54` through `P9 G59.3`. +`touch_off_system` passes the first token from the selected entry to +`G10 L20`, so the source command is `G10 L20 P1 X...` for G54 (and `P0` for +the current system). The Worker accepts the same P-token or a G54..G59.3 +display token, records the normalized `source_system`, and executes the same +canonical P form. This keeps the source command and the interpreter encoding +auditable without changing the UI behavior. + +### Continuous jog + +AXIS binds Button-1 to continuous jog and ButtonRelease to `jog_stop`. +The Web equivalent keeps a single active `{axis,direction}` gesture, issues +one source-TP jog segment per 50 ms sample using the canonical jog velocity, +advances one servo sample, and sends `JOG_STOP` exactly once on release, +cancel, leave or E-stop. + +### Toolpath display lifecycle + +The panel renders two different path layers. They must never share an implicit +clear condition: + +| Layer | Source owner | Visible/retained | Cleared or replaced | +| --- | --- | --- | --- | +| Static program preview | `open_file_guts` creates `AxisCanon`; Gremlin renders the parsed canon | Remains visible during Run, Pause, Resume, Stop and normal completion | A new `PROGRAM_LOAD` hides the old preview while parsing, then replaces it atomically with the newly parsed program. A failed replacement must not relabel the old path as the new program. | +| Machining Live Plot | `LivePlotter`/`linuxcnc.positionlogger`; `show_live_plot` controls visibility | Accumulates during motion. Pause freezes and retains it. Resume continues the same trace. Stop and normal completion retain the accumulated trace. Hiding the Live layer changes visibility only and does not delete data. | AXIS `clear_live_plot()` explicitly calls `logger.clear()`. The Web panel additionally starts a documented new machining epoch for an accepted `PROGRAM_RUN`, `PROGRAM_RESTART`, or `PROGRAM_LOAD`, as required for this panel: the previous machining trace is cleared without changing the static preview or any task/TP state. | + +The Worker publishes a monotonic `visual.live_path_epoch`. React may clear the +machining Live Plot only when this value changes. Array identity, a full versus +delta snapshot, Pause, Resume, Stop, task mode, queue depth and completion are +not clear signals. + +```text +PROGRAM_LOAD accepted -> increment live_path_epoch -> clear old live trace + -> hide old static preview while parsing + -> publish new static preview + +PROGRAM_RUN accepted -> increment live_path_epoch -> begin a new live trace +PROGRAM_PAUSE -> epoch unchanged -> retain/freeze live trace +PROGRAM_RESUME -> epoch unchanged -> continue live trace +PROGRAM_ABORT/STOP -> epoch unchanged -> retain live trace +program completed -> epoch unchanged -> retain live trace +VISUAL_CLEAR -> increment live_path_epoch -> clear live trace only +PROGRAM_RESTART -> increment live_path_epoch -> clear live trace +``` + +If Clear Plot is used while motion is still active, history before the clear +edge is removed and `positionlogger` semantics immediately begin accumulating +the subsequent motion in the new epoch. At IDLE, the cleared trace stays empty. + +The additional Web epoch at a new Run/load boundary is a presentation +lifecycle rule requested for this panel. It does not pretend that AXIS calls +`positionlogger.clear()` from `task_run` or `open_file_guts`: the native source +does not. Pause/completion retention and explicit Clear Plot behavior remain +direct source matches. + +## Implementation Invariants + +1. `web/worker/sim-session.mjs` is the command gate and transaction boundary. +2. `web/worker/wasm-linuxcnc-tp.mjs`, `wasm-program-runtime.mjs`, + `wasm-xyzac-io.mjs` and `wasm-xyzac-device-io.mjs` are the only authorities + for selected-case motion, interpreter and device state. +3. `web/react/src/App.tsx` may render a button disabled from a gate snapshot, + but a Worker gate is still mandatory because UI state can be stale. +4. Every accepted operation produces a ledger entry and canonical snapshot; + every rejected operation produces a stable source/gate reason. +5. A feature that cannot be represented by the selected ABI is disabled with + an explicit reason. It must not be approximated with `G92`, a fixed `G43`, + local booleans or a second JavaScript state machine. +6. New controls must be added to this matrix, the source symbol inventory and + a focused Worker/browser regression test before deployment. +7. Executable program source/path is never part of UI preference persistence; + refresh performs one INI-authorized startup load. +8. Live Plot clearing is controlled only by the Worker `live_path_epoch`; + React object/array replacement is never a lifecycle signal. + +## Change Procedure + +Focused evidence for this contract is kept in +`web/worker/test_xyzac_touch_off_source_flow.mjs`, +`web/worker/test_xyzac_panel_buttons.mjs` and +`scripts/test_xyzac_panel_buttons_browser.mjs`. The completed/aborted direct +rerun contract is covered by `web/worker/test_xyzac_program_rerun.mjs` and the +published-site execution sequence is covered by +`scripts/test_xyzac_program_execution_browser_strict.mjs`. +The source-surface audit is enforced by `scripts/test_axis_control_contract.mjs`. + +When LinuxCNC source behavior or the selected machine configuration changes: + +1. Update the source baseline and the affected matrix row/transaction above. +2. Update the Worker gate/authority path. +3. Update the React handler only after the Worker contract is verified. +4. Add normal, blocked and recovery assertions to the focused test. +5. Run the panel browser test, build the React bundle, and publish a new + release directory without replacing the previous rollback target. + +The document deliberately records ABI blockers and source boundaries. A +`verified` Web slice means the implemented path matches this contract; it does +not claim that an unavailable LinuxCNC host or official native oracle has been +silently reproduced in the browser. diff --git a/docs/linuxcnc-submodule-local-changes.md b/docs/linuxcnc-submodule-local-changes.md new file mode 100644 index 0000000..4b51a11 --- /dev/null +++ b/docs/linuxcnc-submodule-local-changes.md @@ -0,0 +1,18 @@ +# LinuxCNC Submodule Local Changes + +The root repository pins the `linuxcnc` submodule at +`239dcf4284762ad7e9c65d390bc5524d855c2f8e`. + +Local source-oracle and simulation configuration changes that cannot be +represented by the unchanged submodule pointer are archived in +`patches/linuxcnc-working-tree.patch`. + +From the repository root, restore them to a clean submodule checkout with: + +```sh +git submodule update --init linuxcnc +git -C linuxcnc apply ../patches/linuxcnc-working-tree.patch +``` + +The patch includes tracked modifications and the untracked configuration files +present when the root project was saved. diff --git a/patches/linuxcnc-working-tree.patch b/patches/linuxcnc-working-tree.patch new file mode 100644 index 0000000..19a5abc --- /dev/null +++ b/patches/linuxcnc-working-tree.patch @@ -0,0 +1,944 @@ +diff --git a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.ini b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.ini +index cc4ad63..fcee728 100644 +--- a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.ini ++++ b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.ini +@@ -11,7 +11,7 @@ + + + # Version of this INI file +-VERSION = 1.0 ++VERSION = 1.1 + + # Name of machine, for use with display, etc. + MACHINE = 3axis-tutorial +@@ -43,6 +43,7 @@ MAX_FEED_OVERRIDE = 1.2 + MAX_SPINDLE_OVERRIDE = 1.0 + # Prefix to be used + PROGRAM_PREFIX =/home/rolf/linuxcnc/nc_files #need to change ++OPEN_FILE = configs/nc_files/3dtest.ngc + + # Introductory graphic + INTRO_GRAPHIC = linuxcnc.gif +diff --git a/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzac-trt.ini b/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzac-trt.ini +index 957336f..41ebee0 100644 +--- a/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzac-trt.ini ++++ b/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzac-trt.ini +@@ -18,7 +18,7 @@ MAX_ANGULAR_VELOCITY = 360 + POSITION_FEEDBACK = ACTUAL + MAX_FEED_OVERRIDE = 2 + PROGRAM_PREFIX = ../../nc_files +- INTRO_GRAPHIC = emc2.gif ++ INTRO_GRAPHIC = linuxcnc.gif + INTRO_TIME = 1 + #EDITOR = geany + TOOL_EDITOR = tooledit z diam +diff --git a/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzbc-trt.ini b/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzbc-trt.ini +index f49430b..29ac1a6 100644 +--- a/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzbc-trt.ini ++++ b/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzbc-trt.ini +@@ -18,7 +18,7 @@ MAX_ANGULAR_VELOCITY = 360 + POSITION_FEEDBACK = ACTUAL + MAX_FEED_OVERRIDE = 2 + PROGRAM_PREFIX = ../../nc_files +- INTRO_GRAPHIC = emc2.gif ++ INTRO_GRAPHIC = linuxcnc.gif + INTRO_TIME = 1 + #EDITOR = geany + TOOL_EDITOR = tooledit z diam +diff --git a/lib/hallib/sim_lib.tcl b/lib/hallib/sim_lib.tcl +index 7d98add..27f1270 100644 +--- a/lib/hallib/sim_lib.tcl ++++ b/lib/hallib/sim_lib.tcl +@@ -108,6 +108,8 @@ proc setup_kins {axes} { + # set up axis indices for known kins + switch $kins_module { + trivkins {indices_for_trivkins $axes} ++ xyzac-trt-kins {indices_for_trivkins $axes} ++ xyzbc-trt-kins {indices_for_trivkins $axes} + default { + puts stderr "setup_kins: unknown \[KINS\]KINEMATICS=<$::KINS(KINEMATICS)>" + } +diff --git a/src/emc/motion/control.c b/src/emc/motion/control.c +index 8c9ce66..0ab0f5f 100644 +--- a/src/emc/motion/control.c ++++ b/src/emc/motion/control.c +@@ -19,6 +19,9 @@ + #ifdef SWITCHKINS_DEBUG + #include // rtpreempt only, consolidate to stderr + #endif ++#include ++#include ++#include + + #include "posemath.h" + #include "rtapi.h" +@@ -67,6 +70,46 @@ extern struct emcmot_status_t *emcmotStatus; + // etc. + static double *pcmd_p[EMCMOT_MAX_AXIS]; + ++/* Optional simulation-only servo oracle. It is disabled unless the caller ++ * provides a file path, so normal LinuxCNC motion timing is unchanged. */ ++static FILE *xyzac_trace_stream; ++static void xyzac_trace_tick(void) { ++ const char *path; ++ int joint; ++ struct timespec now; ++ clock_gettime(CLOCK_MONOTONIC, &now); ++ if (xyzac_trace_stream == NULL) { ++ path = getenv("LINUXCNC_XYZAC_TRACE_FILE"); ++ if (path == NULL || path[0] == '\0') return; ++ xyzac_trace_stream = fopen(path, "w"); ++ if (xyzac_trace_stream == NULL) return; ++ setvbuf(xyzac_trace_stream, NULL, _IOLBF, 0); ++ } ++ fprintf(xyzac_trace_stream, ++ "{\"wall_ns\":%llu,\"motion_heartbeat\":%u,\"position\":[%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g],\"actual_position\":[%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g,%.17g],\"velocity\":%.17g,\"acceleration\":%.17g,\"queue_depth\":%d,\"active_depth\":%d,\"motion_id\":%d,\"motion_type\":%d,\"paused\":%d,\"queue_full\":%d,\"joints\":[", ++ (unsigned long long)now.tv_sec * 1000000000ull + (unsigned long long)now.tv_nsec, ++ emcmotStatus->heartbeat, ++ emcmotStatus->carte_pos_cmd.tran.x, emcmotStatus->carte_pos_cmd.tran.y, emcmotStatus->carte_pos_cmd.tran.z, ++ emcmotStatus->carte_pos_cmd.a, emcmotStatus->carte_pos_cmd.b, emcmotStatus->carte_pos_cmd.c, ++ emcmotStatus->carte_pos_cmd.u, emcmotStatus->carte_pos_cmd.v, emcmotStatus->carte_pos_cmd.w, ++ emcmotStatus->carte_pos_fb.tran.x, emcmotStatus->carte_pos_fb.tran.y, emcmotStatus->carte_pos_fb.tran.z, ++ emcmotStatus->carte_pos_fb.a, emcmotStatus->carte_pos_fb.b, emcmotStatus->carte_pos_fb.c, ++ emcmotStatus->carte_pos_fb.u, emcmotStatus->carte_pos_fb.v, emcmotStatus->carte_pos_fb.w, ++ emcmotStatus->current_vel, emcmotStatus->acc, emcmotStatus->depth, ++ emcmotStatus->activeDepth, emcmotStatus->id, emcmotStatus->motionType, ++ emcmotStatus->paused, emcmotStatus->queueFull); ++ for (joint = 0; joint < EMCMOT_MAX_JOINTS; ++joint) { ++ if (joint != 0) fputc(',', xyzac_trace_stream); ++ fprintf(xyzac_trace_stream, "{\"cmd\":%.17g,\"fb\":%.17g,\"vel\":%.17g,\"acc\":%.17g,\"homed\":%d}", ++ emcmotStatus->joint_status[joint].pos_cmd, ++ emcmotStatus->joint_status[joint].pos_fb, ++ emcmotStatus->joint_status[joint].vel_cmd, ++ emcmotStatus->joint_status[joint].acc_cmd, ++ emcmotStatus->joint_status[joint].homed); ++ } ++ fputs("]}\n", xyzac_trace_stream); ++} ++ + /*********************************************************************** + * LOCAL FUNCTION PROTOTYPES * + ************************************************************************/ +@@ -271,6 +314,7 @@ void emcmotController(void *arg, long period) + update_status(); + /* here ends the core of the controller */ + emcmotStatus->heartbeat++; ++ xyzac_trace_tick(); + /* set tail to head, to indicate work complete */ + emcmotStatus->tail = emcmotStatus->head; + /* end of controller function */ +diff --git a/src/emc/nml_intf/emc.cc b/src/emc/nml_intf/emc.cc +index 59fdabe..cdba7ed 100644 +--- a/src/emc/nml_intf/emc.cc ++++ b/src/emc/nml_intf/emc.cc +@@ -1838,6 +1838,7 @@ void EMC_TRAJ_STAT::update(CMS * cms) + cms->update(probeval); + cms->update(kinematics_type); + cms->update(motion_type); ++ cms->update(motion_heartbeat); + + } + +@@ -2261,4 +2262,4 @@ void EMC_MOTION_ADAPTIVE::update(CMS * cms) + void EMC_MOTION_CMD_MSG::update(CMS * cms) + { + +-} +\ No newline at end of file ++} +diff --git a/src/emc/nml_intf/emc_nml.hh b/src/emc/nml_intf/emc_nml.hh +index 2d5e61e..8c713b7 100644 +--- a/src/emc/nml_intf/emc_nml.hh ++++ b/src/emc/nml_intf/emc_nml.hh +@@ -834,6 +834,7 @@ class EMC_TRAJ_STAT:public EMC_TRAJ_STAT_MSG { + //bool spindle_override_enabled; moved to SPINDLE_STAT + bool adaptive_feed_enabled; + bool feed_hold_enabled; ++ uint32_t motion_heartbeat; // native motion-controller servo-cycle counter + StateTag tag; + }; + +diff --git a/src/emc/task/emctaskmain.cc b/src/emc/task/emctaskmain.cc +index 6d5ebd5..d215e2e 100644 +--- a/src/emc/task/emctaskmain.cc ++++ b/src/emc/task/emctaskmain.cc +@@ -3490,6 +3490,11 @@ int main(int argc, char *argv[]) + // since emcStatus was passed to the WM init functions, it + // will be updated in the _update() functions above. There's + // no need to call the individual functions on all WM items. ++ // EMC_TASK_STAT_MSG::heartbeat is the native task-cycle oracle used by ++ // external clients. Keep it monotonic and publish it with this cycle's ++ // status image so a reader can identify every task tick without relying on ++ // wall-clock sampling. ++ emcStatus->task.heartbeat++; + emcStatusBuffer->write(emcStatus); + + // wait on timer cycle, if specified, or calculate actual +diff --git a/src/emc/task/taskintf.cc b/src/emc/task/taskintf.cc +index 36fbd97..b3ae2aa 100644 +--- a/src/emc/task/taskintf.cc ++++ b/src/emc/task/taskintf.cc +@@ -1612,6 +1612,7 @@ int emcTrajUpdate(EMC_TRAJ_STAT * stat) + stat->feed_override_enabled = enables & FS_ENABLED; + stat->adaptive_feed_enabled = enables & AF_ENABLED; + stat->feed_hold_enabled = enables & FH_ENABLED; ++ stat->motion_heartbeat = emcmotStatus.heartbeat; + + if (new_config) { + stat->cycleTime = emcmotConfig.trajCycleTime; +diff --git a/src/emc/usr_intf/axis/extensions/emcmodule.cc b/src/emc/usr_intf/axis/extensions/emcmodule.cc +index b43f041..96f12a2 100644 +--- a/src/emc/usr_intf/axis/extensions/emcmodule.cc ++++ b/src/emc/usr_intf/axis/extensions/emcmodule.cc +@@ -409,6 +409,9 @@ static PyMemberDef Stat_members[] = { + {(char*)"echo_serial_number", T_INT, O(echo_serial_number), READONLY}, + {(char*)"echo_serial_number", T_INT, O(echo_serial_number), READONLY}, + {(char*)"state", T_INT, O(status), READONLY}, ++ {(char*)"task_heartbeat", T_UINT, O(task.heartbeat), READONLY, ++ "Native EMC task-loop heartbeat. This counter is incremented by the " ++ "LinuxCNC task thread and is suitable for identifying native status ticks."}, + + // task + {(char*)"task_mode", T_INT, O(task.mode), READONLY}, +@@ -473,6 +476,8 @@ static PyMemberDef Stat_members[] = { + {(char*)"feed_override_enabled", T_BOOL, O(motion.traj.feed_override_enabled), READONLY}, + {(char*)"adaptive_feed_enabled", T_BOOL, O(motion.traj.adaptive_feed_enabled), READONLY}, + {(char*)"feed_hold_enabled", T_BOOL, O(motion.traj.feed_hold_enabled), READONLY}, ++ {(char*)"motion_heartbeat", T_UINT, O(motion.traj.motion_heartbeat), READONLY, ++ "Native motion-controller servo-cycle counter."}, + {(char*)"num_extrajoints", T_INT, O(motion.numExtraJoints), READONLY}, + + +diff --git a/configs/sim/axis/corexy/tool.tbl b/configs/sim/axis/corexy/tool.tbl +new file mode 100644 +index 0000000..6239879 +--- /dev/null ++++ b/configs/sim/axis/corexy/tool.tbl +@@ -0,0 +1,5 @@ ++T1 P1 Z0.511 D0.125 ;1/8 end mill ++T2 P2 Z0.1 D0.0625 ;1/16 end mill ++T3 P3 Z1.273 D0.201 ;#7 tap drill ++T99999 P99999 Z0.1 ;big tool number ++T4 P4 Z0 D.005 ;Added 20131029 +diff --git a/configs/sim/axis/rotate/rotatekins.hal b/configs/sim/axis/rotate/rotatekins.hal +new file mode 100644 +index 0000000..f42bec6 +--- /dev/null ++++ b/configs/sim/axis/rotate/rotatekins.hal +@@ -0,0 +1,6 @@ ++# Workspace-derived rotatekins candidate. The runtime integration remains a ++# later K2-HAL task; this file is intentionally limited to module registration. ++loadrt [KINS]KINEMATICS ++loadrt [EMCMOT]EMCMOT servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS ++addf motion-command-handler servo-thread ++addf motion-controller servo-thread +diff --git a/configs/sim/axis/rotate/rotatekins.ini b/configs/sim/axis/rotate/rotatekins.ini +new file mode 100644 +index 0000000..40e40a8 +--- /dev/null ++++ b/configs/sim/axis/rotate/rotatekins.ini +@@ -0,0 +1,27 @@ ++# Workspace-derived simulation candidate for the rotatekins source module. ++# LinuxCNC ships the module and man-page example but no dedicated configs/sim ++# entry; this fixture keeps that absence explicit in the coupled report. ++ ++[EMC] ++MACHINE = rotatekins_candidate ++VERSION = 1.1 ++ ++[KINS] ++JOINTS = 6 ++KINEMATICS = rotatekins ++ ++[TRAJ] ++COORDINATES = XYZABC ++LINEAR_UNITS = mm ++ANGULAR_UNITS = degree ++ ++[HAL] ++HALFILE = rotatekins.hal ++ ++[EMCMOT] ++EMCMOT = motmod ++SERVO_PERIOD = 1000000 ++ ++[TASK] ++TASK = milltask ++CYCLE_TIME = 0.010 +diff --git a/configs/sim/axis/tool.tbl b/configs/sim/axis/tool.tbl +new file mode 100644 +index 0000000..6239879 +--- /dev/null ++++ b/configs/sim/axis/tool.tbl +@@ -0,0 +1,5 @@ ++T1 P1 Z0.511 D0.125 ;1/8 end mill ++T2 P2 Z0.1 D0.0625 ;1/16 end mill ++T3 P3 Z1.273 D0.201 ;#7 tap drill ++T99999 P99999 Z0.1 ;big tool number ++T4 P4 Z0 D.005 ;Added 20131029 +diff --git a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial +new file mode 100755 +index 0000000..2b374b9 +--- /dev/null ++++ b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial +@@ -0,0 +1,284 @@ ++#!/usr/bin/env python3 ++ ++# Rolf Redford, Nov 2018 ++ ++#import libraries ++from vismach import * ++import hal ++import math ++import sys ++ ++#---------------------------------------------------------------------------------------------------------------------------------- ++# Starting and defining ++ ++# used for diameter for versions less than 2.8. ++# it gives us way to access variable values from vismach script. ++import linuxcnc ++s = linuxcnc.stat() ++s.poll() ++ ++# Here is where we define pins that linuxcnc will send ++# data to, in order to make movements. ++# We will need 5 pins, 3 for motion and 2 for tool stats. ++# tooldiameter isn't really used but if you are using 2.8 you can make couple changes ++# in this file, and uncomment last line in HAL file. ++# add joints. Mill has 3. ++c = hal.component("3axis-tutorial") ++c.newpin("jointX", hal.HAL_FLOAT, hal.HAL_IN) ++c.newpin("jointY", hal.HAL_FLOAT, hal.HAL_IN) ++c.newpin("jointZ", hal.HAL_FLOAT, hal.HAL_IN) ++ ++# tool length and diameter pins? ++c.newpin("toollength", hal.HAL_FLOAT, hal.HAL_IN) ++c.newpin("tooldiameter", hal.HAL_FLOAT, hal.HAL_IN) ++ ++# tells loadusr pins is ready ++c.ready() ++ ++# Used for tool cylinder ++# it will be updated in shape and length by function below. ++toolshape = CylinderZ(0) ++toolshape = Color([1, .5, .5, .5],[toolshape]) ++ ++# updates tool cylinder shape. ++class HalToolCylinder(CylinderZ): ++ def __init__(self, comp, *args): ++ # get machine access so it can ++ # change itself as it runs ++ # specifically tool cylinder in this case. ++ CylinderZ.__init__(self, *args) ++ self.comp = c ++ def coords(self): ++ # update data - not needed if using 2.8 and self.comp["tooldiameter"] ++ # 2.7 does not have direct pin for diameter so this is workaround. commented out code is direct way to do it. ++ # s.poll() # 2.8 don't need this, comment out if using 2.8. ++ # get diameter and divide by 2 to get radius. ++ # rad = ( s.tool_table[s.tool_in_spindle].diameter ) # 2.7 workaround ++ rad = ( self.comp["tooldiameter"] ) # 2.8 only ++ rad = rad / 2 # change to rad ++ # this instantly updates tool model but tooltip doesn't move till - ++ # tooltip, the drawing point will NOT move till g43h(tool number) is called, however. ++ # Tool will "crash" if h and tool length does not match. ++ leng = s.tool_table[s.tool_in_spindle].zoffset ++ # Update tool length when g43h(toolnumber) is called, otherwise stays at 0 or previous size. ++ # commented out as I prefer machine to show actual tool size right away. ++ #leng = self.comp["toollength"] ++ return (-leng, rad, 0, rad) ++ ++ ++#---------------------------------------------------------------------------------------------------------------------------------- ++# Concept of machine design ++ ++# The model follows logical tree design - picture the tree, with branch and smaller branches off it ++# if you move the larger branch, smaller branches will move with it, but if you move smaller branch larger will not. ++# ++# Machine design follows that conceptal design, so for example if you move X, it can move on its own, but if you move Y, ++# it will also move X assembly, as it is attached to Y assembly. ++# so for this machine, tree looks like this: ++ ++# model ++# | ++# |---frame ++# | | ++# | |---base ++# | | ++# | |---column ++# | | ++# | |---top ++# | ++# | ++# |---yassembly ++# | | ++# | | ++# | |---xassembly ++# | | | ++# | | | ++# | | |---xbase ++# | | | ++# | | |---work ++# | | ++# | | ++# | |---ybase ++# | ++# | ++# |---zassembly ++# | ++# | ++# |---zframe ++# | | ++# | |---zbody ++# | | ++# | |---spindle ++# | ++# | ++# |---toolassembly ++# | ++# |---cat30 ++# | ++# |---tool ++# | ++# |---tooltip ++# | ++# |---(tool cylinder function) ++ ++# As you can see, lowest parts must exist first before it can be grouped with others into assembly. ++# So you build upwards from lowest point in tree and assembly them together. ++# Same is applicable for any design of machine. Look at machine arm example and you will see that it starts ++# with tip and adds to larger part of arm then it finally groups with base. ++ ++ ++#---------------------------------------------------------------------------------------------------------------------------------- ++# Starting with fixed frame ++ ++# start creating base itself, floor and column for z. box is centered on 0,0,0 ++base = BoxCentered(200, 560, 20) ++# translate it so top of base is at zero ++base = Translate([base], 0,0,-10) ++ ++# column, attached to base on side. ++# Box() accepts extents ++# ie -100 to 100 is 200 wide, and rightmost is at -100 on coord. ++# Box(x rightmost, y futherest, z lowest, x leftmost, y nearest, z highest) ++column = Box( -60, -260, 0, 60, -200, 400) ++ ++# add block on top ++# not really needed, but I like how it looks with it. ++# bare column looks little bit strange for some reason. ++top = Box(-80,-280,400, 80,-160,440) ++ ++# now fuse it into "frame" ++frame = Collection([base, column, top]) ++# color it grayish ++frame = Color([.8,.8,.8,1],[frame]) ++ ++ ++#---------------------------------------------------------------------------------------------------------------------------------- ++# Moving parts section ++ ++# Start with X, Y then finally Z with tool and spindle. ++ ++# X table addition ++xbase = BoxCentered(1000,200,30) ++# let's color it blue ++xbase = Color([0,0,1,1], [xbase]) ++# Move table so top is at zero for now, ++# so work (default 0,0,0) is on top of table. ++xbase = Translate([xbase], 0,0, -15) ++ ++# now create work which would be defined by Linuxcnc. ++# I suspect we would need to define shape but not enough is known. ++# for now just create an point that would be bottom center of stock. ++work = Capture() ++ ++# group work and xbase together so they move together. ++xassembly = Collection([xbase, work]) ++# work is now defined and grouped, and default at 0,0,0, or ++# currently on top of x part table. ++# so we move table group upwards, taking work with it. ++xassembly = Translate([xassembly], 0,0, 35) ++ ++# Must define part motion before it becomes part of collection. ++# Must have arguments, object itself, c (defined above), then finally scale from the pin to x y z. ++# since this moves solely on X axis, only x is 1, rest is zero. ++# you could use fractions for say axis that moves in compound like arm for example ++# but this machine is very simple, so all axis will be purely full on axis and zero on other axis. ++xassembly = HalTranslate([xassembly], c, "jointX", 1, 0, 0) ++ ++# Y assembly creation ++ybase = BoxCentered(200, 200, 10) ++# colorize it green so we can see it separate from frame. ++ybase = Color([0,1,0,1], [ybase]) ++# don't define translation for this one, as y also moves X table. ++# translating this would move itself alone. You want it to move X parts also. ++ ++# X table is moved by Y base, so we have to make X child of Y. ++# now define collection of ybase and xassembly. ++yassembly = Collection([ybase, xassembly]) ++# define its motion first before translate. ++yassembly = HalTranslate([yassembly], c, "jointY", 0, 1, 0) ++# Now that translate is locked with part, ++# move it upwards so its on frame base. ++yassembly = Translate([yassembly], 0,0,5) ++ ++# spindle head ++# define small cylinder where tool will be attached to. ++# It is shallow, basically exposed end of "cat30" toolholder. ++# let's pretend machine uses cat30. ++cat30 = CylinderZ(0, 30, 20, 40) # cone wider top smaller bottom ++# color it red, as in danger, tool! ++cat30 = Color([1,0,0,1], [cat30]) ++ ++# Define tool and grab such model information from linuxcnc ++# tooltip is initially in vismach "world" 0,0,0. ++# what it does is place where line drawing is in world, so ++# you can see where machine think tip of tool is. ++# first capture it, so we can use it and move it to where ++# defined end of tool is. ++tooltip = Capture() ++ ++# Now that we have tooltip, let's attach it to cylinder function (see above) ++# it creates cylinder then translates tooltip to end of it. ++tool = Collection([ ++ Translate([HalTranslate([tooltip], c, "toollength", 0, 0, -1)], 0, 0, 0), ++ HalToolCylinder(toolshape) ++ ]) ++ ++# Since tool is defined, lets attach it to cat30 ++# Group cat30 and tooltip ++toolassembly = Collection([cat30, tool]) ++# now that tool is properly attached, we can move it ++# and tool will "move" with it now. ++# BUT we need to build rest of head in such way that TOP of head is defined as Z zero. ++# Move it so it attaches to bottom of spindle body. ++toolassembly = Translate([toolassembly],0,0,-120) ++ ++# Start building Z assembly head, including spindle and support ++# top is at zero as I want top to be defined as Z home top. ++spindle = CylinderZ(-100, 60, 0, 60) # top is at zero ++# define rest of head using Box ++zbody = Box(-30, -200, 0, 30, 0, -100) ++ ++# fuse into z assembly ++zframe = Collection([zbody, spindle]) ++# color it yellow ++zframe = Color([1,1,0,1], [zframe]) ++ ++# Now that all parts are created, let's group it and finally make Z motion ++zassembly = Collection([zframe, toolassembly]) ++# define Z motion ++zassembly = HalTranslate([zassembly], c, "jointZ", 0, 0, 1) ++# Now that motion is defined, ++# we can now move it to Z home position. ++zassembly = Translate([zassembly], 0,0, 400) ++ ++#---------------------------------------------------------------------------------------------------------------------------------- ++# Getting it all together and finishing model ++ ++# Assembly everything into single model. ++# xassembly is already included into yassembly so don't need to include it. ++model = Collection([frame, yassembly, zassembly]) ++ ++# Finally, call main() with parameter to let linuxcnc know. ++# parameter list: ++# final model name must include all parts you want to use ++# tooltip (special for tool tip inclusuion) ++# work (special for work part inclusion) ++# size of screen (bigger means more zoomed out to show more of machine) ++# last 2 is where view point source is. ++main(model, tooltip, work, 600, lat=-75, lon=215) ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ ++ +diff --git a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial.hal b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial.hal +new file mode 100644 +index 0000000..aa04e3b +--- /dev/null ++++ b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial.hal +@@ -0,0 +1,71 @@ ++# core HAL config file for simulation ++ ++# first load all the RT modules that will be needed ++# kinematics ++loadrt [KINS]KINEMATICS ++#autoconverted trivkins ++# motion controller, get name and thread periods from ini file ++loadrt [EMCMOT]EMCMOT base_period_nsec=[EMCMOT]BASE_PERIOD servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS ++# load 6 differentiators (for velocity and accel signals ++loadrt ddt names=ddt_x,ddt_xv,ddt_y,ddt_yv,ddt_z,ddt_zv ++# load additional blocks ++loadrt hypot names=vel_xy,vel_xyz ++ ++# add motion controller functions to servo thread ++addf motion-command-handler servo-thread ++addf motion-controller servo-thread ++# link the differentiator functions into the code ++addf ddt_x servo-thread ++addf ddt_xv servo-thread ++addf ddt_y servo-thread ++addf ddt_yv servo-thread ++addf ddt_z servo-thread ++addf ddt_zv servo-thread ++addf vel_xy servo-thread ++addf vel_xyz servo-thread ++ ++# create HAL signals for position commands from motion module ++# loop position commands back to motion module feedback ++net Xpos joint.0.motor-pos-cmd => joint.0.motor-pos-fb ddt_x.in ++net Ypos joint.1.motor-pos-cmd => joint.1.motor-pos-fb ddt_y.in ++net Zpos joint.2.motor-pos-cmd => joint.2.motor-pos-fb ddt_z.in ++ ++# send the position commands thru differentiators to ++# generate velocity and accel signals ++net Xvel ddt_x.out => ddt_xv.in vel_xy.in0 ++net Xacc <= ddt_xv.out ++net Yvel ddt_y.out => ddt_yv.in vel_xy.in1 ++net Yacc <= ddt_yv.out ++net Zvel ddt_z.out => ddt_zv.in vel_xyz.in0 ++net Zacc <= ddt_zv.out ++ ++# Cartesian 2- and 3-axis velocities ++net XYvel vel_xy.out => vel_xyz.in1 ++net XYZvel <= vel_xyz.out ++ ++# estop loopback ++net estop-loop iocontrol.0.user-enable-out iocontrol.0.emc-enable-in ++ ++loadusr -W hal_manualtoolchange ++net tool-change iocontrol.0.tool-change => hal_manualtoolchange.change ++net tool-changed iocontrol.0.tool-changed <= hal_manualtoolchange.changed ++net tool-number iocontrol.0.tool-prep-number => hal_manualtoolchange.number ++net tool-prepare-loopback iocontrol.0.tool-prepare => iocontrol.0.tool-prepared ++ ++# start 3axis-tutorial vismach addition ++loadusr -W ./3axis-tutorial ++ ++# "wire" linuxcnc pins to joints defined in vismach file ++net j0 joint.0.pos-fb => 3axis-tutorial.jointX ++net j1 joint.1.pos-fb => 3axis-tutorial.jointY ++net j2 joint.2.pos-fb => 3axis-tutorial.jointZ ++ ++#tool sinput ++net tool_len 3axis-tutorial.toollength <= motion.tooloffset.z ++net tool_rad halui.tool.diameter 3axis-tutorial.tooldiameter # Only in 2.8 or later ++ ++ ++ ++ ++ ++ +diff --git a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial.ini b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial.ini +new file mode 100644 +index 0000000..4133b0d +--- /dev/null ++++ b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/3axis-tutorial.ini +@@ -0,0 +1,224 @@ ++# This config file was created 2018-11-21 06:26:44.941844 by the update_ini script ++# The original config files may be found in the /home/john/linuxcnc/configs/rolfmill/rolfmill.old directory ++ ++# EMC controller parameters for a simulated machine. ++ ++# General note: Comments can either be preceded with a # or ; - either is ++# acceptable, although # is in keeping with most linux config files. ++ ++# General section ------------------------------------------------------------- ++[EMC] ++ ++ ++# Version of this INI file ++VERSION = 1.0 ++ ++# Name of machine, for use with display, etc. ++MACHINE = 3axis-tutorial ++ ++# Debug level, 0 means no messages. See src/emc/nml_int/emcglb.h for others ++# DEBUG = 0x7FFFFFFF ++DEBUG = 0 ++ ++# Sections for display options ------------------------------------------------ ++[DISPLAY] ++ ++# Name of display program, e.g., xemc ++DISPLAY = axis ++ ++# Cycle time, in seconds, that display will sleep between polls ++CYCLE_TIME = 0.100 ++ ++# Path to help file ++HELP_FILE = doc/help.txt ++ ++# Initial display setting for position, RELATIVE or MACHINE ++POSITION_OFFSET = RELATIVE ++ ++# Initial display setting for position, COMMANDED or ACTUAL ++POSITION_FEEDBACK = ACTUAL ++ ++# Highest value that will be allowed for feed override, 1.0 = 100% ++MAX_FEED_OVERRIDE = 1.2 ++MAX_SPINDLE_OVERRIDE = 1.0 ++# Prefix to be used ++PROGRAM_PREFIX =/home/rolf/linuxcnc/nc_files #need to change ++OPEN_FILE = configs/nc_files/3dtest.ngc ++ ++# Introductory graphic ++INTRO_GRAPHIC = linuxcnc.gif ++INTRO_TIME = 5 ++ ++#EDITOR = geany ++ ++INCREMENTS = 1 mm, .01 in, .1mm, 1 mil, .1 mil, 1/8000 in ++ ++[FILTER] ++PROGRAM_EXTENSION = .png,.gif,.jpg Grayscale Depth Image ++PROGRAM_EXTENSION = .py Python Script ++ ++png = image-to-gcode ++gif = image-to-gcode ++jpg = image-to-gcode ++py = python3 ++ ++# Task controller section ----------------------------------------------------- ++ ++[RS274NGC] ++ ++# File containing interpreter variables ++PARAMETER_FILE = 3axis-tutorial_mm.var ++ ++# Motion control section ------------------------------------------------------ ++[EMCMOT] ++ ++ ++EMCMOT = motmod ++ ++# Timeout for comm to emcmot, in seconds ++COMM_TIMEOUT = 1.0 ++ ++ ++# BASE_PERIOD is unused in this configuration but specified in core_sim.hal ++BASE_PERIOD = 0 ++# Servo task period, in nano-seconds ++SERVO_PERIOD = 1000000 ++ ++# Hardware Abstraction Layer section -------------------------------------------------- ++[TASK] ++ ++# Name of task controller program, e.g., milltask ++TASK = milltask ++ ++# Cycle time, in seconds, that task controller will sleep between polls ++CYCLE_TIME = 0.001 ++ ++# Part program interpreter section -------------------------------------------- ++ ++[HAL] ++ ++# The run script first uses halcmd to execute any HALFILE ++# files, and then to execute any individual HALCMD commands. ++# ++ ++# list of hal config files to run through halcmd ++# files are executed in the order in which they appear ++HALFILE = 3axis-tutorial.hal ++ ++# list of halcmd commands to execute ++# commands are executed in the order in which they appear ++#HALCMD = save neta ++ ++# Single file that is executed after the GUI has started. Only supported by ++# AXIS at this time (only AXIS creates a HAL component of its own) ++#POSTGUI_HALFILE = test_postgui.hal ++ ++HALUI = halui ++ ++# Trajectory planner section -------------------------------------------------- ++ ++[HALUI] ++#No Content ++ ++[TRAJ] ++ ++ ++AXES = 3 ++COORDINATES = X Y Z ++HOME = 0 0 0 ++LINEAR_UNITS = mm ++ANGULAR_UNITS = degree ++DEFAULT_LINEAR_VELOCITY = 30.48 ++MAX_LINEAR_VELOCITY = 53.34 ++DEFAULT_ACCELERATION = 508 ++MAX_LINEAR_ACCELERATION = 508 ++POSITION_FILE = position_mm.txt ++ARC_BLEND_ENABLE = 1 ++ARC_BLEND_FALLBACK_ENABLE = 1 ++ARC_BLEND_OPTIMIZATION_DEPTH = 50 ++#Use this setting for no smoothing (for debugging and stress-testing) ++ARC_BLEND_SMOOTHING_THRESHOLD = .75 ++#Use this setting for "normal" smoothing, i.e. if we blend over more than 40% of a segment ++#ARC_BLEND_SMOOTHING_THRESHOLD = 0.40 ++ ++# Axes sections --------------------------------------------------------------- ++ ++[EMCIO] ++ ++# Name of IO controller program, e.g., io ++EMCIO = io ++ ++# cycle time, in seconds ++CYCLE_TIME = 0.100 ++ ++# tool table file ++TOOL_TABLE = tool.tbl ++TOOL_CHANGE_POSITION = 0 0 0 ++ ++ ++[KINS] ++KINEMATICS = trivkins ++#This is a best-guess at the number of joints, it should be checked ++JOINTS = 3 ++ ++[AXIS_X] ++MIN_LIMIT = -500.0 ++MAX_LIMIT = 500.0 ++MAX_VELOCITY = 25.0 ++MAX_ACCELERATION = 750.0 ++ ++[JOINT_0] ++ ++TYPE = LINEAR ++HOME = 0.0 ++MAX_VELOCITY = 25.0 ++MAX_ACCELERATION = 750.0 ++STEPGEN_MAXACCEL = 937.5 ++SCALE = 80.0 ++FERROR = 1 ++MIN_FERROR = .25 ++MIN_LIMIT = -500.0 ++MAX_LIMIT = 500.0 ++HOME_OFFSET = 0.0 ++ ++[AXIS_Y] ++MIN_LIMIT = -100.0 ++MAX_LIMIT = 100.0 ++MAX_VELOCITY = 25.0 ++MAX_ACCELERATION = 750.0 ++ ++[JOINT_1] ++ ++TYPE = LINEAR ++HOME = 0.0 ++MAX_VELOCITY = 25.0 ++MAX_ACCELERATION = 750.0 ++STEPGEN_MAXACCEL = 937.5 ++SCALE = 80.0 ++FERROR = 1 ++MIN_FERROR = .25 ++MIN_LIMIT = -100.0 ++MAX_LIMIT = 100.0 ++HOME_OFFSET = 0.0 ++ ++[AXIS_Z] ++MIN_LIMIT = -240.0 ++MAX_LIMIT = 0.001 ++MAX_VELOCITY = 25.0 ++MAX_ACCELERATION = 750.0 ++ ++[JOINT_2] ++ ++TYPE = LINEAR ++HOME = 0.0 ++MAX_VELOCITY = 25.0 ++MAX_ACCELERATION = 750.0 ++STEPGEN_MAXACCEL = 937.5 ++SCALE = 80.0 ++FERROR = 1 ++MIN_FERROR = .25 ++MIN_LIMIT = -240.0 ++MAX_LIMIT = 0.001 ++HOME_OFFSET = 0.0 ++ ++# section for main IO controller parameters ----------------------------------- +diff --git a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/README b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/README +new file mode 100644 +index 0000000..6522282 +--- /dev/null ++++ b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/README +@@ -0,0 +1,2 @@ ++A simple vismach 3 axis mill example built using primitives. ++Comments is in 3axis-tutorial vismach file, and some in 3axis-tutorial.hal explains step by step the process to build. +diff --git a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/README_es b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/README_es +new file mode 100644 +index 0000000..5193b11 +--- /dev/null ++++ b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/README_es +@@ -0,0 +1,2 @@ ++Un ejemplo simple de fresadora vismach de 3 ejes construido usando primitivas. ++Los comentarios se encuentran en el archivo vismach 3axis-tutorial, y algunos en 3axis-tutorial.hal explican paso a paso el proceso de creación. +diff --git a/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/tool.tbl b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/tool.tbl +new file mode 100644 +index 0000000..2e64501 +--- /dev/null ++++ b/configs/sim/axis/vismach/3axis-tutorial/3axis-tutorial.old/tool.tbl +@@ -0,0 +1,4 @@ ++T1 P1 Z12 D30 ;big ++T2 P2 Z50 D10 ;1/16 end mill ++T3 P3 Z50 D5 ;#7 tap drill ++T99999 P99999 Z0.1 ;big tool number +diff --git a/configs/sim/axis/vismach/scorbot/scorbot.hal b/configs/sim/axis/vismach/scorbot/scorbot.hal +new file mode 100644 +index 0000000..d5da59d +--- /dev/null ++++ b/configs/sim/axis/vismach/scorbot/scorbot.hal +@@ -0,0 +1,5 @@ ++# Workspace-derived scorbot-kins module registration candidate. ++loadrt [KINS]KINEMATICS ++loadrt [EMCMOT]EMCMOT servo_period_nsec=[EMCMOT]SERVO_PERIOD num_joints=[KINS]JOINTS ++addf motion-command-handler servo-thread ++addf motion-controller servo-thread +diff --git a/configs/sim/axis/vismach/scorbot/scorbot.ini b/configs/sim/axis/vismach/scorbot/scorbot.ini +new file mode 100644 +index 0000000..f18fde2 +--- /dev/null ++++ b/configs/sim/axis/vismach/scorbot/scorbot.ini +@@ -0,0 +1,26 @@ ++# Workspace-derived simulation candidate for scorbot-kins. ++# The locked LinuxCNC source contains scorbot-kins.c but no shipped sim INI. ++ ++[EMC] ++MACHINE = scorbot_candidate ++VERSION = 1.1 ++ ++[KINS] ++JOINTS = 5 ++KINEMATICS = scorbot-kins ++ ++[TRAJ] ++COORDINATES = XYZAB ++LINEAR_UNITS = mm ++ANGULAR_UNITS = degree ++ ++[HAL] ++HALFILE = scorbot.hal ++ ++[EMCMOT] ++EMCMOT = motmod ++SERVO_PERIOD = 1000000 ++ ++[TASK] ++TASK = milltask ++CYCLE_TIME = 0.010 diff --git a/scripts/test_axis_control_contract.mjs b/scripts/test_axis_control_contract.mjs new file mode 100644 index 0000000..0c8578e --- /dev/null +++ b/scripts/test_axis_control_contract.mjs @@ -0,0 +1,40 @@ +import assert from "node:assert/strict"; +import { readFile } from "node:fs/promises"; + +const root = new URL("../", import.meta.url); +const read = (path) => readFile(new URL(path, root), "utf8"); +const [axisPy, axisTcl, taskSource, contract, app, worker, programCore, runtime] = await Promise.all([ + read("linuxcnc/src/emc/usr_intf/axis/scripts/axis.py"), + read("linuxcnc/share/axis/tcl/axis.tcl"), + read("linuxcnc/src/emc/task/emctaskmain.cc"), + read("docs/linuxcnc-axis-web-control-panel-source-logic.md"), + read("web/react/src/App.tsx"), + read("web/worker/sim-session.mjs"), + read("wasm-core/src/sim_program.c"), + read("web/worker/wasm-program-runtime.mjs"), +]); + +for (const symbol of ["manual_ok", "ensure_mode", "open_file_guts", "task_run", "task_step", "task_pause", "task_resume", "task_stop", "send_mdi_command", "home_all_joints", "home_joint", "touch_off_system", "touch_off_tool", "spindle_forward_toggle", "spindle_backward_toggle", "toggle_override_limits", "cycle_view"]) assert.match(axisPy, new RegExp(`(?:def|class) ${symbol}`), `missing source symbol ${symbol}`); +for (const binding of ["machine_estop", "machine_power", "file_open", "reload", "program_run", "program_step", "program_pause", "program_stop", "program_blockdelete", "program_optpause", "view_zoomin", "view_zoomout", "clear_plot", "jogminus", "jogplus", "zerohome.home", "zerohome.zero", "zerohome.tooltouch", "spindlef.ccw", "spindlef.stop", "spindlef.cw"]) assert.match(axisTcl, new RegExp(`(?:toolbar\\.${binding}|manual\\.jogf|manual\\.spindlef|manual\\.jogf\\.zerohome)`), `missing source binding ${binding}`); +for (const taskTerm of ["EMC_TASK_PLAN_RUN_TYPE", "emcTaskPlanOpen", "emcTaskPlanClose", "programStartLine = run_msg->line"]) assert.match(taskSource, new RegExp(taskTerm.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")), `missing task source ${taskTerm}`); +for (const term of ["manual_ok", "ensure_mode", "open_file_guts", "EMC_TASK_PLAN_RUN", "PROGRAM_LOAD", "PROGRAM_RUN", "PROGRAM_STEP", "PROGRAM_PAUSE", "PROGRAM_RESUME", "PROGRAM_ABORT", "JOG_START", "HOME", "TOUCH_OFF", "Run after completion or Stop", "Toolpath display lifecycle", "live_path_epoch", "positionlogger", "blocked_by_abi_tool_offsets", "Button Dependency Matrix"]) assert.match(contract, new RegExp(term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")), `contract missing ${term}`); +assert.match(app, /Begin executing current file \[R\]/); +assert.match(app, /Reload current G-code \[Ctrl-R\]/); +assert.match(app, /Rapid Override/); +assert.doesNotMatch(app, /Reset machine/); +assert.doesNotMatch(app, /Run Startup Sequence/); +assert.doesNotMatch(app, /G92\s+\$\{selectedAxis/); +assert.doesNotMatch(app, /cachedProgram/); +assert.doesNotMatch(app, /program:\s*\{\s*path:\s*programPath/); +assert.match(contract, /exactly one PROGRAM_LOAD for the configured OPEN_FILE/); +assert.match(worker, /blocked_by_abi_tool_offsets/); +assert.doesNotMatch(worker, /xyzac_program_aborted_requires_restart/); +assert.match(worker, /reopened_taskfile/); +assert.match(worker, /livePathEpoch/); +assert.doesNotMatch(worker.match(/const visualClearResponse[\s\S]*?switch \(input\.kind\)/)?.[0] ?? "", /previewState\s*=\s*null/); +assert.match(programCore, /SIM_PROGRAM_COMPLETED \|\| program->status == SIM_PROGRAM_ABORTED/); +assert.match(programCore, /sim_program_set_position/); +assert.match(runtime, /synchronizePosition/); +assert.match(worker, /xyzac_motion_active/); + +console.log(JSON.stringify({ schema: "axis-control-source-contract.v1", status: "verified", source: "linuxcnc-axis-web-control-panel-source-logic.md", checked: { axis_py_symbols: 17, axis_tcl_bindings: 21, task_source_edges: 4, app_source_controls: 3, worker_abi_boundaries: 1, direct_rerun_edges: 2 } })); diff --git a/scripts/test_xyzac_live_path_lifecycle_browser.mjs b/scripts/test_xyzac_live_path_lifecycle_browser.mjs new file mode 100644 index 0000000..6725534 --- /dev/null +++ b/scripts/test_xyzac_live_path_lifecycle_browser.mjs @@ -0,0 +1,122 @@ +import { pathToFileURL } from "node:url"; + +const modulePath = process.env.PLAYWRIGHT_MODULE; +const url = process.env.XYZAC_PANEL_URL ?? "https://49.232.250.35:58010/"; +if (!modulePath) { + console.log(JSON.stringify({ schema: "xyzac-live-path-lifecycle-browser.v1", status: "blocked", code: "playwright_unavailable" })); + process.exit(0); +} +const imported = await import(pathToFileURL(modulePath).href); +const playwright = imported.default ?? imported; +const browser = await playwright.chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE_PATH ?? "/usr/bin/google-chrome", args: ["--ignore-certificate-errors", "--disable-gpu"] }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, ignoreHTTPSErrors: true }); +await context.addInitScript(() => { localStorage.clear(); sessionStorage.clear(); }); +const page = await context.newPage(); +const browserErrors = []; +page.on("pageerror", (error) => browserErrors.push(`pageerror:${error.message}`)); +page.on("console", (message) => { if (message.type() === "error") browserErrors.push(`console:${message.text()}`); }); +const main = page.locator("main.axis-app"); +const state = () => main.evaluate((element) => { + const viewer = element.querySelector('[data-xyzac-preview="toolpath"]'); + return { + loading: element.dataset.axisProgramLoading, + path: element.dataset.axisProgramPath, + program: element.dataset.axisProgramStatus, + operation: element.querySelector(".operation-state")?.textContent?.trim(), + machine: element.querySelector(".machine-state")?.textContent?.trim(), + homed: element.dataset.axisHomed, + line: element.dataset.axisCurrentLine, + queue: element.dataset.axisTpQueueDepth, + velocity: element.dataset.axisTpVelocity, + epoch: Number(viewer?.getAttribute("data-xyzac-live-path-epoch") ?? -1), + liveCount: Number(viewer?.getAttribute("data-xyzac-live-trace-count") ?? 0), + previewCount: Number(viewer?.getAttribute("data-xyzac-toolpath-count") ?? 0), + error: element.querySelector(".diagnostic-error")?.textContent?.trim() ?? null, + }; +}); +const wait = async (predicate, label, timeout = 90000) => { + const started = Date.now(); let last; + while (Date.now() - started < timeout) { last = await state(); if (predicate(last)) return last; await page.waitForTimeout(50); } + throw new Error(`${label}:${JSON.stringify(last)}`); +}; +const click = async (locator, label, timeout = 30000) => { + const started = Date.now(); + while (Date.now() - started < timeout) { if (await locator.count() && !await locator.first().isDisabled()) { await locator.first().click(); return; } await page.waitForTimeout(100); } + throw new Error(`${label}:disabled_or_missing`); +}; +const load = async (name, source) => { + const input = main.locator('input[type="file"][aria-label="Open G-code file"]'); + await input.setInputFiles({ name, mimeType: "text/plain", buffer: Buffer.from(source) }); + return wait((value) => value.loading === "false" && value.path === `browser/${name}` && value.program === "loaded" && value.error === null, `${name}_loaded`); +}; +const canvasPixels = async (targetPage) => targetPage.locator('[data-xyzac-preview="toolpath"] canvas').evaluate((canvas) => { + const gl = canvas.getContext("webgl2", { preserveDrawingBuffer: true }) ?? canvas.getContext("webgl", { preserveDrawingBuffer: true }); + if (!gl) return { width: canvas.width, height: canvas.height, changed: 0 }; + const pixels = new Uint8Array(canvas.width * canvas.height * 4); + gl.readPixels(0, 0, canvas.width, canvas.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels); + let changed = 0; + for (let index = 0; index < pixels.length; index += 4) if (Math.abs(pixels[index] - 5) + Math.abs(pixels[index + 1] - 11) + Math.abs(pixels[index + 2] - 15) > 20) changed += 1; + return { width: canvas.width, height: canvas.height, changed }; +}); + +const longMoves = Array.from({ length: 160 }, (_, index) => `G1 X${index % 2 ? 0 : 6} Y${index % 2 ? 0 : 4} Z${index % 2 ? 10 : 8} A${index % 2 ? 0 : 10} C${index % 2 ? 0 : 15} F300`); +const longSource = ["G21", "G90", ...longMoves, "M2", ""].join("\n"); +const shortMoves = Array.from({ length: 12 }, (_, index) => `G1 X${index % 2 ? -0.2 : 0.2} Y${index % 2 ? -0.1 : 0.1} F600`); +const shortSource = ["G21", "G91", ...shortMoves, "M2", ""].join("\n"); +const replacementSource = "G21\nG90\nG1 X1 Y1 Z1 F300\nM2\n"; + +await page.goto(`${url}?live-path-lifecycle=20260907`, { waitUntil: "domcontentloaded", timeout: 30000 }); +await wait((value) => value.loading === "false" && value.program === "loaded", "startup"); +await click(main.locator('button[aria-label="Power on [F2]"]'), "power_on"); +await wait((value) => value.machine === "Machine ON", "power_state"); +await click(main.locator('button[aria-label="Home all axes"]'), "home_all"); +await wait((value) => value.homed === "[true,true,true,true,true]", "home_state"); + +const loadedLong = await load("live-long.ngc", longSource); +await click(main.locator('button[aria-label="Begin executing current file [R]"]'), "run_long"); +const running = await wait((value) => value.program === "running" && value.liveCount >= 3, "long_live_trace"); +await click(main.locator('button[aria-label="Pause execution [P]"]'), "pause"); +const paused = await wait((value) => value.program === "paused", "paused"); +await page.waitForTimeout(1000); +const pausedStable = await state(); +if (paused.epoch !== running.epoch || pausedStable.epoch !== running.epoch || pausedStable.liveCount < running.liveCount || pausedStable.previewCount !== loadedLong.previewCount) throw new Error(`pause_cleared_path:${JSON.stringify({ loadedLong, running, paused, pausedStable })}`); +await click(main.locator('button[aria-label="Resume execution [S]"]'), "resume"); +const resumed = await wait((value) => value.program === "running" && value.liveCount >= pausedStable.liveCount, "resumed"); +if (resumed.epoch !== running.epoch || resumed.previewCount !== loadedLong.previewCount) throw new Error(`resume_changed_epoch:${JSON.stringify(resumed)}`); +await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "stop"); +const stopped = await wait((value) => value.operation === "Operation IDLE" && value.program === "aborted", "stopped"); +if (stopped.epoch !== running.epoch || stopped.liveCount < pausedStable.liveCount || stopped.previewCount !== loadedLong.previewCount) throw new Error(`stop_cleared_path:${JSON.stringify(stopped)}`); + +const loadedShort = await load("live-short.ngc", shortSource); +if (loadedShort.epoch <= stopped.epoch || loadedShort.liveCount !== 0) throw new Error(`load_did_not_clear_live_path:${JSON.stringify({ stopped, loadedShort })}`); +await click(main.locator('button[aria-label="Begin executing current file [R]"]'), "run_short"); +const completed = await wait((value) => value.program === "completed" && value.operation === "Operation IDLE" && value.liveCount >= 2, "short_completed"); +await page.waitForTimeout(1000); +const completedStable = await state(); +if (completedStable.epoch !== completed.epoch || completedStable.liveCount < completed.liveCount || completedStable.previewCount !== loadedShort.previewCount) throw new Error(`completion_cleared_path:${JSON.stringify({ completed, completedStable })}`); + +await click(main.locator('button[aria-label="Begin executing current file [R]"]'), "rerun_short"); +const rerun = await wait((value) => value.epoch > completedStable.epoch && value.liveCount < completedStable.liveCount, "rerun_new_epoch"); +await wait((value) => value.program === "completed" && value.operation === "Operation IDLE", "rerun_completed"); + +const replacement = await load("live-replacement.ngc", replacementSource); +if (replacement.epoch <= rerun.epoch || replacement.liveCount !== 0 || replacement.previewCount !== 1) throw new Error(`replacement_lifecycle_invalid:${JSON.stringify({ rerun, replacement })}`); +await click(main.locator('button[aria-label="Begin executing current file [R]"]'), "run_replacement"); +await wait((value) => value.liveCount >= 1 && Number(value.line) > 0, "replacement_trace"); +await wait((value) => value.operation === "Operation IDLE", "replacement_idle"); +const beforeClear = await state(); +await click(main.locator('button[aria-label="Clear live plot [Ctrl-K]"]'), "clear_live_plot"); +const cleared = await wait((value) => value.epoch > beforeClear.epoch && value.liveCount <= 1, "cleared_live_plot"); +if (cleared.previewCount !== beforeClear.previewCount) throw new Error(`clear_removed_static_preview:${JSON.stringify({ beforeClear, cleared })}`); + +const desktopPixels = await canvasPixels(page); +if (desktopPixels.changed < 100) throw new Error(`desktop_canvas_blank:${JSON.stringify(desktopPixels)}`); +await page.screenshot({ path: "/tmp/xyzac-live-path-lifecycle-desktop.png", fullPage: true }); +await page.setViewportSize({ width: 390, height: 844 }); +await page.waitForTimeout(500); +const mobilePixels = await canvasPixels(page); +if (mobilePixels.changed < 100) throw new Error(`mobile_canvas_blank:${JSON.stringify(mobilePixels)}`); +await page.screenshot({ path: "/tmp/xyzac-live-path-lifecycle-mobile.png", fullPage: true }); + +console.log(JSON.stringify({ schema: "xyzac-live-path-lifecycle-browser.v1", status: browserErrors.length ? "failed" : "verified", lifecycle: { loadedLong, running, paused: pausedStable, resumed, stopped, loadedShort, completed: completedStable, rerun, replacement, beforeClear, cleared }, canvas_pixels: { desktop: desktopPixels, mobile: mobilePixels }, browser_errors: browserErrors, screenshots: ["/tmp/xyzac-live-path-lifecycle-desktop.png", "/tmp/xyzac-live-path-lifecycle-mobile.png"] })); +await browser.close(); diff --git a/scripts/test_xyzac_multi_program_load_browser.mjs b/scripts/test_xyzac_multi_program_load_browser.mjs new file mode 100644 index 0000000..04c50b6 --- /dev/null +++ b/scripts/test_xyzac_multi_program_load_browser.mjs @@ -0,0 +1,112 @@ +import { pathToFileURL } from "node:url"; +import { fnv1a64 } from "../web/worker/replay.mjs"; + +const modulePath = process.env.PLAYWRIGHT_MODULE; +const url = process.env.XYZAC_PANEL_URL ?? "https://49.232.250.35:58010/"; +if (!modulePath) { + console.log(JSON.stringify({ schema: "xyzac-multi-program-load-browser.v1", status: "blocked", code: "playwright_unavailable" })); + process.exit(0); +} +const imported = await import(pathToFileURL(modulePath).href); +const playwright = imported.default ?? imported; +const browser = await playwright.chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE_PATH ?? "/usr/bin/google-chrome", args: ["--ignore-certificate-errors", "--disable-gpu"] }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, ignoreHTTPSErrors: true }); +await context.addInitScript(() => { localStorage.clear(); sessionStorage.clear(); }); +const page = await context.newPage(); +const failures = []; +const browserErrors = []; +const dialogs = []; +page.on("pageerror", (error) => browserErrors.push(`pageerror:${error.message}`)); +page.on("console", (message) => { if (message.type() === "error") browserErrors.push(`console:${message.text()}`); }); +page.on("dialog", async (dialog) => { dialogs.push({ type: dialog.type(), message: dialog.message() }); await dialog.dismiss(); }); +const main = page.locator("main.axis-app"); +const state = () => main.evaluate((element) => ({ + source: element.dataset.axisStateSource, + machine: element.querySelector(".machine-state")?.textContent?.trim(), + operation: element.querySelector(".operation-state")?.textContent?.trim(), + program: element.dataset.axisProgramStatus, + line: element.dataset.axisCurrentLine, + queue: element.dataset.axisTpQueueDepth, + velocity: element.dataset.axisTpVelocity, + homed: element.dataset.axisHomed, + loading: element.querySelector(".case-status")?.getAttribute("aria-busy") === "true", + command: element.querySelector(".command-status")?.textContent?.trim(), + error: element.querySelector(".diagnostic-error")?.textContent?.trim() ?? null, + editor: element.querySelector("#axis-program")?.value ?? "", + sourceHash: element.querySelector(".xyzac-program header code")?.textContent?.trim() ?? "", + previewCount: element.querySelector('[data-xyzac-preview="toolpath"]')?.getAttribute("data-xyzac-toolpath-count") ?? "0", +})); +const wait = async (predicate, label, timeout = 60000) => { + const started = Date.now(); let last; + while (Date.now() - started < timeout) { last = await state(); if (predicate(last)) return last; await page.waitForTimeout(200); } + throw new Error(`${label}:${JSON.stringify(last)}`); +}; +const click = async (locator, label, timeout = 30000) => { + const started = Date.now(); + while (Date.now() - started < timeout) { if (await locator.count() && !await locator.first().isDisabled()) { await locator.first().click(); return; } await page.waitForTimeout(200); } + throw new Error(`${label}:disabled_or_missing`); +}; +const record = async (name, action) => { try { return { name, result: "verified", ...(await action() ?? {}) }; } catch (error) { const row = { name, result: "failed", reason: error?.message ?? String(error) }; failures.push(row); return row; } }; + +const absoluteMoves = Array.from({ length: 12 }, (_, index) => { + const positive = index % 2 === 0; + return `G1 X${positive ? 20 : 0} Y${positive ? 10 : 0} Z${positive ? 5 : 10} A${positive ? 30 : 0} C${positive ? 40 : 0} F600`; +}); +const incrementalMoves = (x, y, z, a, c) => Array.from({ length: 12 }, (_, index) => { + const sign = index % 2 === 0 ? 1 : -1; + return `G1 X${sign * x} Y${sign * y} Z${sign * z} A${sign * a} C${sign * c} F600`; +}); +const programs = [ + { name: "browser-a.ngc", source: ["G21", "G90", "G0 X0 Y0 Z10 A0 C0", ...absoluteMoves, "M2", ""].join("\n") }, + { name: "browser-b.ngc", source: ["G21", "G91", ...incrementalMoves(1, 0.5, 0, 1, 2), "M2", ""].join("\n") }, + { name: "browser-c.ngc", source: ["G21", "G91", ...incrementalMoves(0.5, 1, 0.5, 2, 1), "M2", ""].join("\n") }, +]; +const results = []; +const evidence = []; +try { + await page.goto(`${url}?strict-multi-load=20260907`, { waitUntil: "domcontentloaded", timeout: 30000 }); + results.push(await record("startup", async () => { await wait((s) => s.source === "linuxcnc-wasm", "startup"); })); + results.push(await record("power_home", async () => { + await click(main.getByRole("button", { name: "Load 3D_Chips.ngc", exact: true }), "initial_load"); + await wait((s) => s.program === "loaded" && !s.loading && s.error === null, "initial_loaded"); + await click(main.locator('button[aria-label="Power on [F2]"]'), "power"); + await wait((s) => s.machine === "Machine ON", "power_state"); + await click(main.locator('button[aria-label="Home all axes"]'), "home"); + await wait((s) => s.homed === "[true,true,true,true,true]", "home_state"); + })); + for (const program of programs) { + results.push(await record(`load_${program.name}`, async () => { + const input = main.locator('input[type="file"][aria-label="Open G-code file"]'); + await input.setInputFiles({ name: program.name, mimeType: "text/plain", buffer: Buffer.from(program.source) }); + const loaded = await wait((s) => s.program === "loaded" && !s.loading && s.command?.includes("PROGRAM_LOAD acknowledged") && s.error === null, `${program.name}_loaded`); + const hash = fnv1a64(program.source); + if (!loaded.editor.includes(program.source.trim())) throw new Error(`${program.name}:editor_source_mismatch`); + if (!loaded.sourceHash.includes(hash.slice(0, 12))) throw new Error(`${program.name}:source_hash_mismatch:${loaded.sourceHash}:${hash}`); + if (Number(loaded.previewCount) <= 0) throw new Error(`${program.name}:preview_empty`); + evidence.push({ name: program.name, source_hash: hash, preview_count: Number(loaded.previewCount), line_after_load: loaded.line }); + await click(main.locator('button[aria-label="Begin executing current file [R]"]'), `${program.name}_run`); + const running = await wait((s) => ["running", "completed"].includes(s.program) && (Number(s.line) > 0 || Number(s.queue) > 0 || Number(s.velocity) > 0), `${program.name}_running`); + await page.waitForTimeout(2000); + const active = await state(); + if (Number(active.line) <= 0 && Number(active.queue) <= 0 && Number(active.velocity) <= 0) throw new Error(`${program.name}:motion_not_observed:${JSON.stringify(active)}`); + let stopped = active; + if (active.operation !== "Operation IDLE") { + await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), `${program.name}_stop`); + stopped = await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted", "completed"].includes(s.program) && s.error === null, `${program.name}_stopped`); + } + return { source_hash: hash, preview_count: Number(loaded.previewCount), running_line: running.line, stopped_program: stopped.program }; + })); + } + results.push(await record("round_trip_A", async () => { + const input = main.locator('input[type="file"][aria-label="Open G-code file"]'); + await input.setInputFiles({ name: programs[0].name, mimeType: "text/plain", buffer: Buffer.from(programs[0].source) }); + const loaded = await wait((s) => s.program === "loaded" && !s.loading && s.error === null, "roundtrip_loaded"); + if (!loaded.sourceHash.includes(evidence[0].source_hash.slice(0, 12))) throw new Error("roundtrip_hash_mismatch"); + if (Number(loaded.previewCount) <= 0) throw new Error("roundtrip_preview_empty"); + })); +} finally { + await page.screenshot({ path: "/tmp/xyzac-multi-program-load-browser.png", fullPage: true }); + if (dialogs.length) failures.push({ name: "automatic_dialog", result: "failed", reason: JSON.stringify(dialogs) }); + console.log(JSON.stringify({ schema: "xyzac-multi-program-load-browser.v1", status: failures.length === 0 && browserErrors.length === 0 ? "verified" : "failed", url, results, evidence, dialogs, failures, browser_errors: browserErrors, final_state: await state(), screenshot: "/tmp/xyzac-multi-program-load-browser.png" })); + await browser.close(); +} diff --git a/scripts/test_xyzac_panel_buttons_browser.mjs b/scripts/test_xyzac_panel_buttons_browser.mjs index 90b0c5e..0868551 100644 --- a/scripts/test_xyzac_panel_buttons_browser.mjs +++ b/scripts/test_xyzac_panel_buttons_browser.mjs @@ -75,7 +75,6 @@ try { })); results.push(await record("POWER ON", async () => { await click(main.locator('button[aria-label="Power on [F2]"]'), "power_on"); await wait((s) => s.machine === "Machine ON", "power_state"); })); results.push(await record("HOME ALL", async () => { await click(main.locator('button[aria-label="Home all axes"]'), "home_all"); await wait((s) => s.homed === "[true,true,true,true,true]", "home_state"); })); - results.push(await record("RESET", async () => { await click(main.locator('button[aria-label="Reset machine"]'), "reset"); await wait((s) => s.command?.includes("RESET acknowledged") || s.error === null, "reset_state"); })); results.push(await record("KINEMATICS IDENTITY/TCP/USERK", async () => { for (const name of ["Identity", "TCP: XYZAC", "User K", "Identity", "TCP: XYZAC", "User K"]) { await click(main.getByRole("button", { name: new RegExp(`^${name}`) }), `kinematics_${name}`); @@ -99,13 +98,13 @@ try { await axisInput.check(); await click(main.locator(`button[aria-label="Jog ${axis} positive"]`), `jog_${axis}_positive`); await wait((s) => s.error === null, `jog_${axis}_ack`); - await click(main.getByRole("button", { name: "Stop", exact: true }).first(), `jog_${axis}_stop`); + await click(main.getByRole("button", { name: "Stop jog", exact: true }), `jog_${axis}_stop`); } })); results.push(await record("SPINDLE", async () => { await click(main.locator('button[aria-label="Spindle clockwise"]'), "spindle_cw"); await click(main.locator('button[aria-label="Spindle counter-clockwise"]'), "spindle_ccw"); - await click(main.getByRole("button", { name: "Stop", exact: true }).nth(1), "spindle_stop"); + await click(main.getByRole("button", { name: "Stop spindle", exact: true }), "spindle_stop"); const brake = main.getByLabel("Brake", { exact: true }); if (await brake.count() && !await brake.isDisabled()) { await brake.click(); @@ -158,7 +157,7 @@ try { await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted"].includes(s.program), "program_aborted"); await click(main.locator(".program-actions button").first(), "program_reload_before_step"); await wait((s) => s.program === "loaded" && s.error === null, "program_reload_before_step_ack"); - await click(main.locator(".program-actions button").nth(2), "program_step"); + await click(main.locator('button[aria-label="Execute next line [T]"]'), "program_step"); await wait((s) => s.program === "paused", "program_stepped"); await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "program_step_abort"); await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted"].includes(s.program), "program_step_abort_ack"); @@ -169,28 +168,23 @@ try { await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "program_abort_again"); await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted"].includes(s.program) && s.error === null, "program_abort_again_ack"); })); - results.push(await record("RUN STARTUP SEQUENCE", async () => { - await click(main.locator(".program-actions button").first(), "startup_sequence_reload"); - await wait((s) => s.program === "loaded" && s.queue === "0" && s.runEnabled === "true" && !s.programLoading && s.error === null, "startup_sequence_reload_ack"); - await click(main.getByRole("button", { name: "Run startup sequence", exact: true }), "startup_sequence"); - await wait((s) => s.program === "running", "startup_sequence_running"); - await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "startup_sequence_abort"); - await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted"].includes(s.program) && s.error === null, "startup_sequence_abort_ack"); - })); - results.push(await record("EDITOR PROGRAM LOAD + REOPEN", async () => { + results.push(await record("EDITOR PROGRAM LOAD + RELOAD", async () => { const editor = main.locator("#axis-program"); await editor.fill("G21\nG1 X2 Y2 Z2 F100\nM2\n"); await click(main.locator(".program-actions button").first(), "editor_program_load"); await wait((s) => s.program === "loaded" && s.command?.includes("PROGRAM_LOAD acknowledged") && s.error === null, "editor_program_load_ack"); - await click(main.locator('button[aria-label="Reopen editor defaults"]'), "reopen_defaults"); - await wait((s) => s.program === "loaded" && s.case?.includes("xyzac_switchkins") && s.error === null, "reopen_defaults_ack"); + await click(main.locator('button[aria-label="Reload current G-code [Ctrl-R]"]'), "reload_current_program"); + await wait((s) => s.program === "loaded" && s.command?.includes("PROGRAM_LOAD acknowledged") && s.error === null, "reload_current_program_ack"); })); results.push(await record("DISABLED unsupported buttons", async () => { for (const name of ["Toggle skip lines with slash", "Toggle optional pause"]) if (!await main.locator(`button[aria-label="${name}"]`).isDisabled()) throw new Error(`${name}:must_be_disabled`); })); } finally { const buttons = await main.locator("button").evaluateAll((items) => items.map((button) => ({ text: button.textContent?.trim() ?? "", aria: button.getAttribute("aria-label"), disabled: button.disabled }))); + const visibleLabels = buttons.map((button) => button.aria ?? button.text).filter(Boolean); + const duplicateLabels = Object.entries(visibleLabels.reduce((counts, label) => { counts[label] = (counts[label] ?? 0) + 1; return counts; }, {})).filter(([, count]) => count > 1); + for (const [label, count] of duplicateLabels) if (["Emergency Stop [F1]", "Power on [F2]", "Home all axes", "Run program", "Clear plot", "Stop Jog", "Stop Spindle"].includes(label)) failures.push({ name: "duplicate_visible_control", result: "failed", reason: `${label}:${count}` }); await page.screenshot({ path: "/tmp/xyzac-panel-buttons-browser.png", fullPage: true }); - console.log(JSON.stringify({ schema: "xyzac-panel-buttons-browser.v1", status: failures.length === 0 && browserErrors.length === 0 ? "verified" : "failed", url, results, button_count: buttons.length, disabled_button_count: buttons.filter((button) => button.disabled).length, failures, browser_errors: browserErrors, final_state: await state(), screenshot: "/tmp/xyzac-panel-buttons-browser.png" })); + console.log(JSON.stringify({ schema: "xyzac-panel-buttons-browser.v1", status: failures.length === 0 && browserErrors.length === 0 ? "verified" : "failed", url, results, button_count: buttons.length, disabled_button_count: buttons.filter((button) => button.disabled).length, duplicate_labels: duplicateLabels, failures, browser_errors: browserErrors, final_state: await state(), screenshot: "/tmp/xyzac-panel-buttons-browser.png" })); await browser.close(); } diff --git a/scripts/test_xyzac_program_execution_browser_strict.mjs b/scripts/test_xyzac_program_execution_browser_strict.mjs new file mode 100644 index 0000000..a79b847 --- /dev/null +++ b/scripts/test_xyzac_program_execution_browser_strict.mjs @@ -0,0 +1,143 @@ +import { pathToFileURL } from "node:url"; + +const modulePath = process.env.PLAYWRIGHT_MODULE; +const url = process.env.XYZAC_PANEL_URL ?? "https://49.232.250.35:58010/"; +if (!modulePath) { + console.log(JSON.stringify({ schema: "xyzac-program-execution-browser-strict.v1", status: "blocked", code: "playwright_unavailable" })); + process.exit(0); +} + +const imported = await import(pathToFileURL(modulePath).href); +const playwright = imported.default ?? imported; +const browser = await playwright.chromium.launch({ + headless: true, + executablePath: process.env.BROWSER_EXECUTABLE_PATH ?? "/usr/bin/google-chrome", + args: ["--ignore-certificate-errors", "--disable-gpu"], +}); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, ignoreHTTPSErrors: true }); +await context.addInitScript(() => { localStorage.clear(); sessionStorage.clear(); }); +const page = await context.newPage(); +const failures = []; +const browserErrors = []; +page.on("pageerror", (error) => browserErrors.push(`pageerror:${error.message}`)); +page.on("console", (message) => { if (message.type() === "error") browserErrors.push(`console:${message.text()}`); }); +page.on("dialog", async (dialog) => { await dialog.accept(); }); +const main = page.locator("main.axis-app"); +const state = () => main.evaluate((element) => ({ + source: element.dataset.axisStateSource, + authority: element.dataset.axisAuthority, + motion: element.dataset.axisMotionAuthority, + machine: element.querySelector(".machine-state")?.textContent?.trim(), + operation: element.querySelector(".operation-state")?.textContent?.trim(), + mode: element.dataset.axisTaskMode, + program: element.dataset.axisProgramStatus, + runEnabled: element.dataset.axisRunEnabled, + loading: element.querySelector(".case-status")?.getAttribute("aria-busy") === "true", + homed: element.dataset.axisHomed, + line: element.dataset.axisCurrentLine, + queue: element.dataset.axisTpQueueDepth, + velocity: element.dataset.axisTpVelocity, + command: element.querySelector(".command-status")?.textContent?.trim(), + error: element.querySelector(".diagnostic-error")?.textContent?.trim() ?? null, +})); +const wait = async (predicate, label, timeout = 60000) => { + const started = Date.now(); let last; + while (Date.now() - started < timeout) { + last = await state(); + if (predicate(last)) return last; + await page.waitForTimeout(200); + } + throw new Error(`${label}:${JSON.stringify(last)}`); +}; +const click = async (locator, label, timeout = 30000) => { + const started = Date.now(); + while (Date.now() - started < timeout) { + if (await locator.count() && !await locator.first().isDisabled()) { await locator.first().click(); return; } + await page.waitForTimeout(200); + } + throw new Error(`${label}:disabled_or_missing`); +}; +const record = async (name, action) => { + try { const result = await action(); return { name, result: "verified", ...(result ?? {}) }; } + catch (error) { const row = { name, result: "failed", reason: error?.message ?? String(error) }; failures.push(row); return row; } +}; +const samples = []; +const runAndObserve = async (name, waitMs = 5000) => record(name, async () => { + await click(main.locator('button[aria-label="Begin executing current file [R]"]'), `${name}_run`); + const started = await wait((s) => s.program === "running" && s.operation === "Operation RUNNING", `${name}_running`); + await page.waitForTimeout(waitMs); + const observed = await state(); + samples.push({ name, started, observed }); + if (observed.error !== null) throw new Error(`${name}_error:${observed.error}`); + if (Number(observed.line) <= 0 && Number(observed.queue) <= 0 && Number(observed.velocity) <= 0) throw new Error(`${name}_no_motion:${JSON.stringify(observed)}`); + return { observed }; +}); + +const results = []; +try { + await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 }); + results.push(await record("startup", async () => { + const s = await wait((v) => v.source === "linuxcnc-wasm" && v.motion === "wasm", "wasm_startup"); + if (s.authority !== "linuxcnc-wasm-worker") throw new Error("authority_marker_missing"); + })); + results.push(await record("initial_program_load", async () => { + await click(main.getByRole("button", { name: "Load 3D_Chips.ngc", exact: true }), "load_initial"); + return { state: await wait((s) => s.program === "loaded" && !s.loading && s.error === null, "initial_program_loaded") }; + })); + results.push(await record("power_on", async () => { + await click(main.locator('button[aria-label="Power on [F2]"]'), "power_on"); + await wait((s) => s.machine === "Machine ON", "power_state"); + })); + results.push(await record("home_all", async () => { + await click(main.locator('button[aria-label="Home all axes"]'), "home_all"); + await wait((s) => s.homed === "[true,true,true,true,true]", "home_state"); + })); + results.push(await runAndObserve("first_run", 5000)); + results.push(await record("stop_first_run", async () => { + await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "stop_first_run"); + return { state: await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted"].includes(s.program), "first_stop_idle") }; + })); + results.push(await runAndObserve("rerun_after_abort_without_reload", 3000)); + results.push(await record("stop_direct_rerun", async () => { + await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "stop_direct_rerun"); + await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted"].includes(s.program), "direct_rerun_stop_idle"); + })); + results.push(await record("reload_after_stop", async () => { + await click(main.getByRole("button", { name: "Load 3D_Chips.ngc", exact: true }), "reload_after_stop"); + return { state: await wait((s) => s.program === "loaded" && s.queue === "0" && !s.loading && s.error === null, "reload_after_stop_loaded") }; + })); + results.push(await runAndObserve("rerun_after_reload", 3000)); + results.push(await record("stop_second_run", async () => { + await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "stop_second_run"); + await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted"].includes(s.program), "second_stop_idle"); + })); + results.push(await record("load_second_gcode", async () => { + const moves = Array.from({ length: 160 }, (_, index) => { + const direction = index % 2 === 0 ? 1 : 0; + return `G1 X${direction ? 20 : 0} Y${direction ? 10 : 0} Z${direction ? 5 : 10} A${direction ? 30 : 0} C${direction ? 40 : 0} F100`; + }); + const source = ["G21", "G90", "G0 X0 Y0 Z10 A0 C0", ...moves, "M2", ""].join("\n"); + const fileInput = main.locator('input[type="file"][aria-label="Open G-code file"]'); + await fileInput.setInputFiles({ name: "strict-second-load.ngc", mimeType: "text/plain", buffer: Buffer.from(source) }); + return { state: await wait((s) => s.program === "loaded" && !s.loading && s.command?.includes("PROGRAM_LOAD acknowledged") && s.error === null, "second_gcode_loaded") }; + })); + results.push(await runAndObserve("run_second_gcode", 3000)); + results.push(await record("stop_second_gcode", async () => { + await click(main.locator('button[aria-label="Stop program execution [ESC]"]'), "stop_second_gcode"); + await wait((s) => s.operation === "Operation IDLE" && ["loaded", "aborted", "completed"].includes(s.program), "second_gcode_stop_idle"); + })); +} finally { + await page.screenshot({ path: "/tmp/xyzac-program-execution-browser-strict.png", fullPage: true }); + console.log(JSON.stringify({ + schema: "xyzac-program-execution-browser-strict.v1", + status: failures.length === 0 && browserErrors.length === 0 ? "verified" : "failed", + url, + results, + samples, + failures, + browser_errors: browserErrors, + final_state: await state(), + screenshot: "/tmp/xyzac-program-execution-browser-strict.png", + })); + await browser.close(); +} diff --git a/scripts/test_xyzac_refresh_single_program_browser.mjs b/scripts/test_xyzac_refresh_single_program_browser.mjs new file mode 100644 index 0000000..4b2d917 --- /dev/null +++ b/scripts/test_xyzac_refresh_single_program_browser.mjs @@ -0,0 +1,99 @@ +import { readFile } from "node:fs/promises"; +import { pathToFileURL } from "node:url"; +import { fnv1a64 } from "../web/worker/replay.mjs"; + +const modulePath = process.env.PLAYWRIGHT_MODULE; +const url = process.env.XYZAC_PANEL_URL ?? "https://49.232.250.35:58010/"; +if (!modulePath) { + console.log(JSON.stringify({ schema: "xyzac-refresh-single-program-browser.v1", status: "blocked", code: "playwright_unavailable" })); + process.exit(0); +} + +const defaultPath = "linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting/demos/xyzac_switchkins.ngc"; +const legacyPath = "linuxcnc/nc_files/3D_Chips.ngc"; +const defaultSource = await readFile(new URL(`../${defaultPath}`, import.meta.url), "utf8"); +const legacySource = await readFile(new URL(`../${legacyPath}`, import.meta.url), "utf8"); +const defaultHash = fnv1a64(defaultSource.replace(/\r\n/g, "\n").replace(/\r/g, "\n")); +const legacyHash = fnv1a64(legacySource.replace(/\r\n/g, "\n").replace(/\r/g, "\n")); +const imported = await import(pathToFileURL(modulePath).href); +const playwright = imported.default ?? imported; +const browser = await playwright.chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE_PATH ?? "/usr/bin/google-chrome", args: ["--ignore-certificate-errors", "--disable-gpu"] }); +const context = await browser.newContext({ viewport: { width: 1440, height: 1000 }, ignoreHTTPSErrors: true }); +const page = await context.newPage(); +const browserErrors = []; +page.on("pageerror", (error) => browserErrors.push(`pageerror:${error.message}`)); +page.on("console", (message) => { if (message.type() === "error") browserErrors.push(`console:${message.text()}`); }); +page.on("dialog", async (dialog) => { await dialog.accept(); }); +const main = page.locator("main.axis-app"); +const state = () => main.evaluate((element) => ({ + loading: element.dataset.axisProgramLoading, + path: element.dataset.axisProgramPath, + sourceHash: element.dataset.axisProgramSourceHash, + program: element.dataset.axisProgramStatus, + runEnabled: element.dataset.axisRunEnabled, + machine: element.querySelector(".machine-state")?.textContent?.trim(), + operation: element.querySelector(".operation-state")?.textContent?.trim(), + homed: element.dataset.axisHomed, + line: element.dataset.axisCurrentLine, + queue: element.dataset.axisTpQueueDepth, + velocity: element.dataset.axisTpVelocity, + case: element.querySelector(".case-status")?.textContent?.trim(), + previewCount: element.querySelector('[data-xyzac-preview="toolpath"]')?.getAttribute("data-xyzac-toolpath-count") ?? "0", + powerDisabled: element.querySelector('button[aria-label="Power on [F2]"]')?.disabled, + runDisabled: element.querySelector('button[aria-label="Begin executing current file [R]"]')?.disabled, + error: element.querySelector(".diagnostic-error")?.textContent?.trim() ?? null, +})); +const wait = async (predicate, label, timeout = 60000) => { + const started = Date.now(); let last; + while (Date.now() - started < timeout) { last = await state(); if (predicate(last)) return last; await page.waitForTimeout(200); } + throw new Error(`${label}:${JSON.stringify(last)}`); +}; +const click = async (locator, label, timeout = 30000) => { + const started = Date.now(); + while (Date.now() - started < timeout) { if (await locator.count() && !await locator.first().isDisabled()) { await locator.first().click(); return; } await page.waitForTimeout(200); } + throw new Error(`${label}:disabled_or_missing`); +}; + +await page.goto(`${url}?refresh-single-program-seed=20260907`, { waitUntil: "domcontentloaded", timeout: 30000 }); +await wait((s) => s.loading === "false" && s.path === defaultPath && s.sourceHash === defaultHash, "initial_default_program"); + +const legacyState = { version: 1, selectedAxis: "x", leftTab: "manual", rightTab: "preview", view: "p", zoom: 1, rotateMode: false, coordType: "machine", displayType: "actual", metric: true, layers: { grid: true, tool: true, path: true, live: true, limits: false, velocity: false, offsets: false, extents: false }, casePath: "linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting/xyzac-trt.ini", touchOffSystem: "P1 G54", program: { path: legacyPath, source: legacySource } }; +const savedAt = Date.now(); +const legacyRecordUnsigned = { schema: "linuxcnc-ui-temp-json.v1", context_id: "linuxcnc-2.10.0-pre0-wasm-m1-py-c1", key: "xyzac-trt", generation: 1000, saved_at_ms: savedAt, state: legacyState }; +const legacyRecord = { ...legacyRecordUnsigned, state_hash: fnv1a64(legacyState), record_hash: fnv1a64(legacyRecordUnsigned) }; +await page.evaluate(async (record) => { + const root = await navigator.storage.getDirectory(); + const app = await root.getDirectoryHandle("linuxcnc-web-wasm", { create: true }); + const states = await app.getDirectoryHandle("ui-state", { create: true }); + const project = await states.getDirectoryHandle("xyzac-trt", { create: true }); + for (const name of ["state-a.json", "state-b.json", "manifest.json"]) { try { await project.removeEntry(name); } catch { /* empty cache */ } } + const handle = await project.getFileHandle("state-a.json", { create: true }); + const writable = await handle.createWritable(); + await writable.write(JSON.stringify(record)); + await writable.close(); +}, legacyRecord); + +await page.reload({ waitUntil: "domcontentloaded", timeout: 30000 }); +const transitions = []; +for (let index = 0; index < 140; index += 1) { + const sample = await state(); + transitions.push(sample); + if (sample.path === legacyPath || sample.sourceHash === legacyHash || sample.case?.includes("3D_Chips.ngc")) throw new Error(`legacy_program_auto_loaded:${JSON.stringify(sample)}`); + if (sample.loading === "true" && (sample.powerDisabled !== true || sample.runDisabled !== true || sample.previewCount !== "0")) throw new Error(`startup_loading_gate_invalid:${JSON.stringify(sample)}`); + await page.waitForTimeout(250); +} +const stable = await state(); +if (stable.loading !== "false" || stable.path !== defaultPath || stable.sourceHash !== defaultHash || stable.previewCount !== "29" || stable.error !== null) throw new Error(`configured_program_not_stable:${JSON.stringify(stable)}`); + +await click(main.locator('button[aria-label="Power on [F2]"]'), "power_on"); +await wait((s) => s.machine === "Machine ON", "power_on_state"); +await click(main.locator('button[aria-label="Home all axes"]'), "home_all"); +await wait((s) => s.homed === "[true,true,true,true,true]", "home_state"); +await click(main.locator('button[aria-label="Begin executing current file [R]"]'), "run"); +const running = await wait((s) => s.program === "running" && s.operation === "Operation RUNNING", "program_running"); +await page.waitForTimeout(3000); +const moving = await state(); +if (Number(moving.line) <= 0 && Number(moving.queue) <= 0 && Number(moving.velocity) <= 0) throw new Error(`program_not_moving:${JSON.stringify(moving)}`); +await page.screenshot({ path: "/tmp/xyzac-refresh-single-program-browser.png", fullPage: true }); +console.log(JSON.stringify({ schema: "xyzac-refresh-single-program-browser.v1", status: browserErrors.length ? "failed" : "verified", configured_program: { path: defaultPath, source_hash: defaultHash, preview_count: Number(stable.previewCount) }, ignored_legacy_program: { path: legacyPath, source_hash: legacyHash }, sampled_ms: transitions.length * 250, running, moving, browser_errors: browserErrors, screenshot: "/tmp/xyzac-refresh-single-program-browser.png" })); +await browser.close(); diff --git a/wasm-core/CMakeLists.txt b/wasm-core/CMakeLists.txt index 27dc9b4..5da0e8b 100644 --- a/wasm-core/CMakeLists.txt +++ b/wasm-core/CMakeLists.txt @@ -295,7 +295,7 @@ if(EMSCRIPTEN) ) get_target_property(_sim_module_link_flags sim_core_module LINK_FLAGS) string(REPLACE "_sim_task_recover','_sim_task_restore" "_sim_task_recover','_sim_task_command_gate','_sim_task_restore" _sim_module_link_flags "${_sim_module_link_flags}") - string(REPLACE "_sim_interpreter_size" "_sim_program_size','_sim_program_requires_subroutines','_sim_program_init','_sim_program_reset','_sim_program_destroy','_sim_program_load','_sim_program_add_subroutine','_sim_program_set_rapid_velocity','_sim_program_start','_sim_program_pause','_sim_program_resume','_sim_program_abort','_sim_program_step','_sim_program_execute_block','_sim_program_seek','_sim_program_read_motion','_sim_program_clear_motion','_sim_program_canonical','_sim_program_state_hash','_sim_interpreter_size" _sim_module_link_flags "${_sim_module_link_flags}") + string(REPLACE "_sim_interpreter_size" "_sim_program_size','_sim_program_requires_subroutines','_sim_program_init','_sim_program_reset','_sim_program_destroy','_sim_program_load','_sim_program_add_subroutine','_sim_program_set_rapid_velocity','_sim_program_set_position','_sim_program_start','_sim_program_pause','_sim_program_resume','_sim_program_abort','_sim_program_step','_sim_program_execute_block','_sim_program_seek','_sim_program_read_motion','_sim_program_clear_motion','_sim_program_canonical','_sim_program_state_hash','_sim_interpreter_size" _sim_module_link_flags "${_sim_module_link_flags}") string(REPLACE "_sim_kinematics_switch_select','_sim_kinematics_switch_forward" "_sim_kinematics_switch_select','_sim_kinematics_switch_select_physical','_sim_kinematics_switch_forward" _sim_module_link_flags "${_sim_module_link_flags}") string(REPLACE "_sim_kinematics_switch_inverse','_sim_kinematics_switch_active" "_sim_kinematics_switch_inverse','_sim_kinematics_switch_inverse_mode','_sim_kinematics_switch_active" _sim_module_link_flags "${_sim_module_link_flags}") string(REPLACE "_sim_motion_init" "_sim_motion_set_profile','_sim_motion_set_lookahead','_sim_motion_set_dynamics','_sim_motion_set_feed_override','_sim_motion_set_paused','_sim_motion_peek','_sim_motion_init" _sim_module_link_flags "${_sim_module_link_flags}") diff --git a/wasm-core/include/sim_program.h b/wasm-core/include/sim_program.h index 6be49d2..3b04d54 100644 --- a/wasm-core/include/sim_program.h +++ b/wasm-core/include/sim_program.h @@ -89,6 +89,7 @@ void sim_program_destroy(sim_program *program); int32_t sim_program_load(sim_program *program, const char *source, uint32_t length); int32_t sim_program_add_subroutine(sim_program *program, const char *source, uint32_t length); int32_t sim_program_set_rapid_velocity(sim_program *program, double velocity); +int32_t sim_program_set_position(sim_program *program, const sim_posemath_pose *position); int32_t sim_program_start(sim_program *program); int32_t sim_program_pause(sim_program *program); int32_t sim_program_resume(sim_program *program); diff --git a/wasm-core/src/sim_program.c b/wasm-core/src/sim_program.c index d2c89c5..376a0ab 100644 --- a/wasm-core/src/sim_program.c +++ b/wasm-core/src/sim_program.c @@ -367,9 +367,46 @@ int32_t sim_program_set_rapid_velocity(sim_program *program, double velocity) { return SIM_PROGRAM_OK; } +int32_t sim_program_set_position(sim_program *program, const sim_posemath_pose *position) { + const double *values; + size_t index; + if (program == NULL || position == NULL || program->status == SIM_PROGRAM_IDLE) return SIM_PROGRAM_ERR_ARGUMENT; + values = &position->tran.x; + for (index = 0; index < 9; ++index) if (!isfinite(values[index])) return SIM_PROGRAM_ERR_RANGE; + program->interpreter.state.x = position->tran.x; + program->interpreter.state.y = position->tran.y; + program->interpreter.state.z = position->tran.z; + program->interpreter.state.a = position->a; + program->interpreter.state.b = position->b; + program->interpreter.state.c = position->c; + program->interpreter.state.u = position->u; + program->interpreter.state.v = position->v; + program->interpreter.state.w = position->w; + program->interpreter.state.status = SIM_INTERP_OK; + return SIM_PROGRAM_OK; +} + int32_t sim_program_start(sim_program *program) { if (program == NULL || program->status == SIM_PROGRAM_IDLE) return SIM_PROGRAM_ERR_STATE; - if (program->status == SIM_PROGRAM_COMPLETED || program->status == SIM_PROGRAM_ABORTED) return SIM_PROGRAM_ERR_STATE; + /* LinuxCNC EMC_TASK_PLAN_RUN reopens the current task file after an M2/ + end-of-file or task abort, then starts again at the requested line + (AXIS uses line zero for the normal Run button). Preserve the current + interpreter position/offset state as the task-plan synchronization + point, but rewind file/control execution before accepting AUTO_RUN. */ + if (program->status == SIM_PROGRAM_COMPLETED || program->status == SIM_PROGRAM_ABORTED) { + program->current_line = 0; + program->last_error = 0; + program->error_line = 0; + program->has_motion = 0; + program->call_depth = 0; + program->has_control = 0; + program->control_code = 0; + program->interpreter.state.line = 0; + program->interpreter.state.program_end = 0; + program->interpreter.state.status = SIM_INTERP_OK; + memset(&program->motion, 0, sizeof(program->motion)); + memset(program->call_stack, 0, sizeof(program->call_stack)); + } program->status = SIM_PROGRAM_RUNNING; return SIM_PROGRAM_OK; } diff --git a/wasm-core/tests/sim_xyzac_trace_test.c b/wasm-core/tests/sim_xyzac_trace_test.c index fd08364..64c9f68 100644 --- a/wasm-core/tests/sim_xyzac_trace_test.c +++ b/wasm-core/tests/sim_xyzac_trace_test.c @@ -95,6 +95,14 @@ int main(void) { } } assert(have_arc && arc.turn == -3); + assert(program.status == SIM_PROGRAM_COMPLETED); + assert(sim_program_start(&program) == SIM_PROGRAM_OK); + assert(program.status == SIM_PROGRAM_RUNNING && program.current_line == 0); + assert(program.interpreter.state.program_end == 0); + assert(sim_program_step(&program) == SIM_PROGRAM_OK); + assert(sim_program_abort(&program) == SIM_PROGRAM_OK); + assert(sim_program_start(&program) == SIM_PROGRAM_OK); + assert(program.status == SIM_PROGRAM_RUNNING && program.current_line == 0); saved_switcher = switcher; saved_pose = pose; diff --git a/web/react/src/App.tsx b/web/react/src/App.tsx index 3788157..e26fc07 100644 --- a/web/react/src/App.tsx +++ b/web/react/src/App.tsx @@ -12,59 +12,58 @@ import { XYZAC_CASE, projectXyzacPanel, type XyzacOperationTrace } from "./xyzac export const SELECTED_XYZAC_CASE = XYZAC_CASE; const DEFAULT_CASE = SELECTED_XYZAC_CASE; const PROGRAM_PATH = "linuxcnc/configs/sim/axis/vismach/5axis/table-rotary-tilting/demos/xyzac_switchkins.ngc"; -const DEFAULT_PROGRAM = ""; const normalizeProgramSource = (source: string) => source.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); +// Button-to-command sequencing is defined in +// docs/linuxcnc-axis-web-control-panel-source-logic.md; React only projects +// Worker gates and emits the documented operation. type Action = (kind: string, payload?: Record) => Promise | void; -type IconButtonProps = { label: string; asset: string; onClick?: () => void; disabled?: boolean; danger?: boolean; pressed?: boolean; feature?: string }; +type IconButtonProps = { label: string; asset: string; onClick?: () => void; disabled?: boolean; disabledReason?: string; danger?: boolean; pressed?: boolean; feature?: string }; -function IconButton({ label, asset, onClick, disabled = false, danger = false, pressed = false, feature = "AXIS-UI-05" }: IconButtonProps) { - return ; +function IconButton({ label, asset, onClick, disabled = false, disabledReason, danger = false, pressed = false, feature = "AXIS-UI-05" }: IconButtonProps) { + return ; } -function TextButton({ children, onClick, onPointerDown, onPointerUp, onPointerCancel, onPointerLeave, ariaLabel, disabled = false, danger = false, feature = "AXIS-UI-07" }: { children: React.ReactNode; onClick?: () => void; onPointerDown?: React.PointerEventHandler; onPointerUp?: React.PointerEventHandler; onPointerCancel?: React.PointerEventHandler; onPointerLeave?: React.PointerEventHandler; ariaLabel?: string; disabled?: boolean; danger?: boolean; feature?: string }) { - return ; +function TextButton({ children, onClick, onPointerDown, onPointerUp, onPointerCancel, onPointerLeave, ariaLabel, disabled = false, disabledReason, danger = false, feature = "AXIS-UI-07" }: { children: React.ReactNode; onClick?: () => void; onPointerDown?: React.PointerEventHandler; onPointerUp?: React.PointerEventHandler; onPointerCancel?: React.PointerEventHandler; onPointerLeave?: React.PointerEventHandler; ariaLabel?: string; disabled?: boolean; disabledReason?: string; danger?: boolean; feature?: string }) { + return ; } function Separator() { return