diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..433fd5c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,34 @@ +name: build and test + +on: + push: + pull_request: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Unit tests (model layer, no hardware) + run: test/run_host_tests.sh + - name: Desktop simulator builds (UI and model layers stay portable) + run: | + sudo apt-get update -q + sudo apt-get install -y -q libsdl2-dev + make -C sim deps + make -C sim -j"$(nproc)" + + firmware: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # FW_TAG is the short hash of HEAD + - uses: actions/cache@v4 + with: + path: ~/.platformio + key: pio-${{ hashFiles('platformio.ini') }} + - name: Install PlatformIO + run: pip install platformio + - name: Panel firmware builds + run: pio run -e crowadv diff --git a/.gitignore b/.gitignore index 8d7feae..eedbc7c 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,7 @@ sim/cncsim # Vendor STEP (40 MB), mockup only - see cad/lean_to.py cad/ref/ + +# Host test deps and binaries (test/run_host_tests.sh) +test/.deps/ +test/.build/ diff --git a/platformio.ini b/platformio.ini index f3fcccb..8c04c6e 100644 --- a/platformio.ini +++ b/platformio.ini @@ -88,7 +88,7 @@ lib_deps = platform = native ; PlatformIO does not build src/ into test binaries unless told to. test_build_src = yes -build_src_filter = + + + + + + + + + + + + + + + +build_src_filter = + + + + + + + + + + + + + + + + build_flags = -std=gnu++17 -DUNIT_TEST diff --git a/sim/src/sim_main.cpp b/sim/src/sim_main.cpp index 191d292..6c1f498 100644 --- a/sim/src/sim_main.cpp +++ b/sim/src/sim_main.cpp @@ -51,19 +51,6 @@ static const char* PAGE_NAMES[PAGE_COUNT] = { static void ui_tick_cb(lv_timer_t*) { shell_tick(); } static void touch_tick_cb(lv_timer_t*) { touch_poll(); } -static bool s_primed = false; - -static void prime_link_if_up() { - if (s_primed) return; - if (state == Disconnected) return; - s_primed = true; - caps_request_config(); - send_line("$#"); - filelist_request(); - fncset_request_all(); - Serial.println("link up: primed config, offsets, file list and settings"); -} - static void link_watchdog() { static uint32_t next_log = 0; uint32_t now = millis(); @@ -162,7 +149,7 @@ int main(int argc, char** argv) { } send_pump(); imu_poll(); - prime_link_if_up(); + link_service(); link_watchdog(); service_action(); lv_timer_handler(); diff --git a/sim/src/sim_sd.cpp b/sim/src/sim_sd.cpp index 462db5e..658544b 100644 --- a/sim/src/sim_sd.cpp +++ b/sim/src/sim_sd.cpp @@ -24,6 +24,9 @@ void sd_set_root(const char* root) { if (root && *root) { strncpy(s_root, root, sizeof(s_root) - 1); s_root[sizeof(s_root) - 1] = 0; } } +// Built like the firmware: without HAS_SD_CARD, hw/sdcard.h supplies inline +// no-card stubs and these would redefine them. +#ifdef HAS_SD_CARD bool sd_begin() { struct stat st; return stat(s_root, &st) == 0 && S_ISDIR(st.st_mode); @@ -47,3 +50,4 @@ size_t sd_read(uint8_t* dst, size_t max) { void sd_close() { if (s_fp) { fclose(s_fp); s_fp = nullptr; } } +#endif diff --git a/src/main.cpp b/src/main.cpp index 4019f2a..a20d89a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -148,11 +148,6 @@ void setup() { lv_timer_handler(); } -// The work offsets and file list are primed once, the first time the link is -// actually alive. Doing it at boot would either block (see above) or be sent -// into the void and never retried. -static bool s_primed = false; - // Act on the vibration analyser according to the Setup mode. Deliberately // conservative: // monitor - never touches the machine @@ -187,7 +182,7 @@ static void vib_guard() { rearm_ms = now + 3000; if (lvl == VIB_ESTOP && mode == 2) { - fnc_realtime(Reset); + send_reset(); clog_add("[MSG:VIBRATION: impact - soft reset sent]"); } else { fnc_realtime(FeedHold); @@ -267,36 +262,6 @@ static void link_watchdog() { touch_int_level(), touch_last_status()); } -static void prime_link_if_up() { - // A controller reset wipes everything primed below, plus the $RI auto-report - // and the parser modes, and the link may never drop to Disconnected if the - // reboot is quick. Left alone the jog page falls back to its 500 mm/min - // creep rate because the axis max rates are gone. - bool reset = model_take_board_reset(); - if (reset) { homed_forget(); motors_resync(); } - if (state == Disconnected) { s_primed = false; return; } - if (reset && s_primed) { - s_primed = false; - send_line("$G"); - send_line("$RI=200"); - Serial.println("controller reset seen: re-priming"); - } - if (s_primed) return; - s_primed = true; - motors_resync(); // a drop may have been the controller rebooting - motors_on_link(); - // Config dump first: it decides which controls are even offered, and every - // second it is late is a second the panel shows homing and probing to a - // machine that has neither. - caps_request_config(); - send_line("$#"); - filelist_request(); - // The full settings dump also feeds the Diag limit lamps: which lamps - // exist is read from the controller's configured limit/probe pins. - fncset_request_all(); - Serial.println("link up: primed config, offsets, file list and settings"); -} - // [MSG:PANEL:UPDATE] from the controller runs the same network update as the // Setup button. Never mid-job: the update blanks the screen and reboots. The // update's own tap-to-cancel countdown still gives whoever is at the panel the @@ -351,7 +316,7 @@ void loop() { imulog_poll(); console_cmd(); vib_guard(); - prime_link_if_up(); + link_service(); // liveness, controller restarts, priming caps_poll(); link_watchdog(); service_action(); diff --git a/src/model/FluidNCModel.cpp b/src/model/FluidNCModel.cpp index 0d6b5db..13fa685 100644 --- a/src/model/FluidNCModel.cpp +++ b/src/model/FluidNCModel.cpp @@ -15,6 +15,12 @@ #include "model/sendq.h" #include "model/homed.h" #include "model/motors.h" +#include "model/linkwatch.h" +#include "model/path_loader.h" +#include "model/offsets.h" +#include "model/fnc_settings.h" +#include +#include #ifdef USE_WIFI # include "WiFiConnection.h" // wifi_use_uart_mode() @@ -171,11 +177,21 @@ void drv_reset_axis(char ax) { case 'A': outs[0] = 4; break; default: return; } + // One sequence: a relay switched on must never be left on because the + // line that switches it off was dropped. + char off[32] = ""; + seq_begin("Driver reset"); for (int i = 0; i < 2; i++) - if (outs[i] >= 0) send_linef("M64 P%d", outs[i]); - send_line("G4 P0.75"); // relay drop + driver discharge; tune on bench + if (outs[i] >= 0) seq_linef("M64 P%d", outs[i]); + seq_line("G4 P0.75"); // relay drop + driver discharge; tune on bench for (int i = 0; i < 2; i++) - if (outs[i] >= 0) send_linef("M65 P%d", outs[i]); + if (outs[i] >= 0) { + seq_linef("M65 P%d", outs[i]); + const size_t n = strlen(off); + snprintf(off + n, sizeof(off) - n, "%sM65 P%d", n ? "\n" : "", outs[i]); + } + seq_cleanup(off); + seq_send(); } #ifdef E4_POS_T @@ -212,63 +228,202 @@ extern "C" void show_dro(const pos_t* axes, const pos_t* wco, bool isMpos, bool* #endif // ---- non-blocking send ----------------------------------------------------- -// fnc_send_line() opens with `while (_ackwait)`, spinning until the previous -// line is acked or its timeout expires. Every UI caller reaches it from inside -// an LVGL event callback, i.e. from inside lv_timer_handler(), which is also -// what drives touch_poll() and the input read. So a controller that is slow or -// silent does not slow the machine down, it freezes the panel. -// -// That was measured, not guessed: at link-up the panel stalled 2175ms and then -// 6175ms -- the second is three consecutive 2000ms timeouts -- from the priming -// lines alone. 8.4s of dead screen, every power-on, with no way to press HOLD. -// -// The fix belongs here rather than at the ~20 call sites: every page sends -// something, and a guard per caller is both a bigger diff and one someone will -// forget. Queue, and drain from loop(). -static const int32_t ACK_TIMEOUT_MS = 2000; - -static sendq_t s_sendq; -static uint32_t s_ack_deadline = 0; // 0 = nothing outstanding - -// Mirrors GrblParserC's private _ackwait. Deliberately self-healing: it expires -// slightly AFTER the parser's own limit, so a missed ok/error/timeout callback -// costs one late send instead of wedging the queue for ever. State another -// layer can also move must never be the only thing holding a gate open -- see -// the backlight bug in docs/HANDOFF.md. +// Every line to the controller goes through here, never straight from a UI +// callback: GrblParserC's fnc_send_line() spins in `while (_ackwait)` until the +// previous line is acked, and a UI callback runs inside lv_timer_handler(), so +// a slow controller froze the panel (8.4 s at every power-on, measured). Lines +// are queued and drained from loop() one at a time, each waiting for its ok or +// error. This layer writes the bytes and keeps the ack gate itself, so the +// parser's own gate is never armed and nothing here can spin. + +static const uint32_t ACK_TIMEOUT_MS = 2000; +// A sequence line's ok can be a long time coming: FluidNC answers G38.2 only +// when the probe move ends, which at F75 over 5 mm is 4 s. Timing out early +// would send the next line while the probe is still moving and misattribute +// every ok after it, so an error could no longer be traced to its sequence. +static const uint32_t SEQ_ACK_TIMEOUT_MS = 30000; + +static sendq_t s_sendq; +static uint32_t s_ack_deadline = 0; // 0 = nothing outstanding +static sendq_seq_t s_inflight_seq = 0; // sequence of the line awaiting its ack +static sendq_seq_t s_next_seq = 0; + +// Each sequence's name and what to send if it is cut short, by seq id. Only the +// sequences that can be in the queue at once need a slot. +#define SEQ_META 8 +static struct { + sendq_seq_t seq; + char name[24]; + char cleanup[48]; +} s_meta[SEQ_META]; + bool send_busy() { if (s_ack_deadline == 0) return false; if ((int32_t)(milliseconds() - s_ack_deadline) >= 0) { + // No ok, no error. Carry on rather than wedge the queue for ever. s_ack_deadline = 0; + s_inflight_seq = 0; + clog_add("[MSG:WARN: no reply from the controller - sending the next line]"); return false; } return true; } -static void send_now(const char* line) { - fnc_send_line(line, ACK_TIMEOUT_MS); - s_ack_deadline = milliseconds() + ACK_TIMEOUT_MS + 100; +static void send_now(const char* line, sendq_seq_t seq) { + for (const char* p = line; *p; ++p) fnc_putchar((uint8_t)*p); + fnc_putchar('\n'); + uint32_t deadline = milliseconds() + (seq ? SEQ_ACK_TIMEOUT_MS : ACK_TIMEOUT_MS); + s_ack_deadline = deadline ? deadline : 1; // 0 means idle + s_inflight_seq = seq; +} + +static void line_acked() { + s_ack_deadline = 0; + s_inflight_seq = 0; +} + +// The last line of a sequence was answered ok: it finished, and an alarm +// after this point is not its business. +static void seq_ok(sendq_seq_t seq) { + if (!seq || sendq_count_seq(&s_sendq, seq)) return; + auto& m = s_meta[seq % SEQ_META]; + if (m.seq == seq) m.seq = 0; } void send_pump() { if (send_busy()) return; - char line[SENDQ_LINE]; - if (!sendq_pop(&s_sendq, line, sizeof(line))) return; - send_now(line); + char line[SENDQ_LINE]; + sendq_seq_t seq = 0; + if (!sendq_pop_seq(&s_sendq, line, sizeof(line), &seq)) return; + send_now(line, seq); } void send_line(const char* s, int timeout) { (void)timeout; // the queue owns the timing now motors_guard(s); // re-arm hard limits ahead of anything that moves if (!sendq_push(&s_sendq, s)) { - // A machine command has been thrown away. Say so; a silently dropped - // G10 or $H is exactly the kind of thing that gets blamed on the - // controller. - dbg_println("[send] QUEUE FULL - line dropped"); + // A machine command has been thrown away. Say so on the screen; a + // silently dropped G10 or $H gets blamed on the controller. + char b[CLOG_LINE_MAX]; + snprintf(b, sizeof(b), "send queue full - dropped: %s", s); + model_flag_error(b); } dbg_println(s); send_pump(); // straight out when the link is idle, which is the normal case } +// ---- sequences -------------------------------------------------------------- + +static char s_stage[SENDQ_SLOTS][SENDQ_LINE]; +static int s_stage_n = 0; +static bool s_stage_over = false; +static char s_stage_name[24]; +static char s_stage_cleanup[48]; + +void seq_begin(const char* name) { + s_stage_n = 0; + s_stage_over = false; + snprintf(s_stage_name, sizeof(s_stage_name), "%s", name ? name : "sequence"); + s_stage_cleanup[0] = 0; +} + +void seq_cleanup(const char* line) { + snprintf(s_stage_cleanup, sizeof(s_stage_cleanup), "%s", line ? line : ""); +} + +void seq_line(const char* s) { + if (!s) return; + if (s_stage_n >= SENDQ_SLOTS) { s_stage_over = true; return; } + snprintf(s_stage[s_stage_n++], SENDQ_LINE, "%s", s); +} + +void seq_linef(const char* fmt, ...) { + char b[SENDQ_LINE]; + va_list va; + va_start(va, fmt); + vsnprintf(b, sizeof(b), fmt, va); + va_end(va); + seq_line(b); +} + +static void refuse(const char* why) { + char b[CLOG_LINE_MAX]; + snprintf(b, sizeof(b), "%s not started: %s", s_stage_name, why); + model_flag_error(b); +} + +bool seq_send() { + if (s_stage_n == 0) return false; + if (s_stage_over) { refuse("too long for the send queue"); return false; } + if (state == Disconnected) { refuse("no link"); return false; } + + // Re-arm released steppers first, as send_line() would for each line. + for (int i = 0; i < s_stage_n; i++) + if (motors_line_can_move(s_stage[i])) { motors_guard(s_stage[i]); break; } + + if (++s_next_seq == 0) s_next_seq = 1; + const char* lines[SENDQ_SLOTS]; + for (int i = 0; i < s_stage_n; i++) lines[i] = s_stage[i]; + if (!sendq_push_all(&s_sendq, lines, s_stage_n, s_next_seq)) { + refuse("the controller is still busy with earlier commands"); + return false; + } + auto& m = s_meta[s_next_seq % SEQ_META]; + m.seq = s_next_seq; + snprintf(m.name, sizeof(m.name), "%s", s_stage_name); + snprintf(m.cleanup, sizeof(m.cleanup), "%s", s_stage_cleanup); + s_stage_n = 0; + send_pump(); + return true; +} + +// The controller refused a line, or alarmed. Whatever sequence was running +// must not carry on: its later lines assume the earlier ones happened. +static void abort_seq(sendq_seq_t seq, const char* why) { + if (!seq) return; + const int dropped = sendq_drop_seq(&s_sendq, seq); + auto& m = s_meta[seq % SEQ_META]; + const bool known = m.seq == seq; + if (!known && dropped == 0) return; // already stopped (an alarm, then its error) + char b[CLOG_LINE_MAX]; + snprintf(b, sizeof(b), "%s stopped (%s), %d line%s not sent", known ? m.name : "sequence", why, + dropped, dropped == 1 ? "" : "s"); + model_flag_error(b); + if (known && m.cleanup[0]) { + char c[sizeof(m.cleanup)]; + char* save = nullptr; + snprintf(c, sizeof(c), "%s", m.cleanup); + for (char* l = strtok_r(c, "\n", &save); l; l = strtok_r(nullptr, "\n", &save)) + sendq_push(&s_sendq, l); + } + if (known) m.seq = 0; +} + +void send_flush(const char* why) { + const size_t n = sendq_count(&s_sendq); + sendq_reset(&s_sendq); + line_acked(); // nothing written before this point will be answered + for (auto& m : s_meta) m.seq = 0; + if (n && why) { + char b[CLOG_LINE_MAX]; + snprintf(b, sizeof(b), "[MSG:WARN: %s - %u queued line%s discarded]", why, (unsigned)n, + n == 1 ? "" : "s"); + clog_add(b); + } +} + +static uint32_t s_reset_sent_ms = 0; + +void send_reset() { + fnc_realtime(Reset); + s_reset_sent_ms = milliseconds() | 1; + send_flush("reset"); +} + +bool send_reset_was_recent() { + return s_reset_sent_ms && (int32_t)(milliseconds() - s_reset_sent_ms) < 3000; +} + // Count of jog lines streamed over Telnet but not yet acked by "ok""" to prevent outrunning FluidNC planner. static int s_jog_window = 0; int jog_window_outstanding() { return s_jog_window; } @@ -301,7 +456,7 @@ void send_jog_line(const char* s) { if (motors_released()) { send_line(s); return; } if (s_sendq.count) return; if (send_busy()) return; - send_now(s); + send_now(s, 0); dbg_println(s); } @@ -364,34 +519,70 @@ const char* mode_string() { state_t previous_state; bool awaiting_alarm = false; -// Called once when status report received after being disconnected. -// Use schedule_action() to defer execution to dispatch_events() in the main loop where the parser is idle and _report is clean. -static void connect_init() { - bootlog_printf("connected: state=%s", my_state_string); - resetFlowControl(); // clear any stale XOFF on the link -#ifndef USE_WIFI - fnc_realtime((realtime_cmd_t)0x0c); // Ctrl-L - echo off (UART only) -#endif - send_line("$G"); // Refresh GCode modes - send_line("$RI=200"); // Enable auto-reporting every 200 ms +// ---- link lifecycle --------------------------------------------------------- +// One place decides when the link is up, down, or talking to a controller that +// has just restarted, and what the panel does about each. + +static bool s_primed = false; + +// Everything the panel asks the controller once per connection. A controller +// restart wipes all of it (auto-report, parser modes, the panel's view of the +// config), so it runs again after one. +static void prime() { + s_primed = true; + bootlog_printf("link up (%s): priming", my_state_string); + resetFlowControl(); // clear any stale XOFF on the link + fnc_realtime((realtime_cmd_t)0x0c); // Ctrl-L: echo off + send_line("$G"); // G-code modes + send_line("$RI=200"); // auto-report every 200 ms + motors_resync(); // a drop may have been the controller rebooting + motors_on_link(); + // Config dump first: it decides which controls are even offered. + caps_request_config(); + send_line("$#"); + filelist_request(); + // The full settings dump also feeds the Diag limit lamps. + fncset_request_all(); +} + +static void link_lost() { + clog_add("[MSG:WARN: link lost - no reply from the controller for 4 s]"); + send_flush("link lost"); + set_disconnected_state(); + s_primed = false; + act_on_state_change(); +} + +void link_service() { + // While XModem owns the wire a '?' would land in the middle of the + // transfer, so the watch stands down (and starts a fresh window after). + const bool watch = state != Disconnected && !pathload_busy(); + switch (linkwatch_tick(milliseconds(), fnc_rx_count(), watch)) { + case LINKWATCH_PING: fnc_realtime(StatusReport); break; + case LINKWATCH_LOST: link_lost(); break; + default: break; + } - // Pre-populate the SD file list on the FIRST connect only. Re-fetching it - // on every reconnect is both wasteful and harmful over ESP-NOW - static bool s_file_list_primed = false; - if (!s_file_list_primed) { - s_file_list_primed = true; - filelist_request(); // Request SD file list (once) + if (model_take_board_reset()) { + // The banner follows a soft reset too. One the panel sent itself keeps + // position (FluidNC alarms if it did not); anything else may have been + // a power cycle, so homing is no longer trusted. + const bool ours = send_reset_was_recent(); + send_flush(ours ? nullptr : "controller restarted"); + if (!ours) { + clog_add("[MSG:WARN: controller restarted - home before moving]"); + homed_forget(); + } + s_primed = false; } - detect_homing_info(); // Probe axis homing state + if (state == Disconnected) { s_primed = false; return; } + if (!s_primed) prime(); } extern "C" void show_state(const char* state_string) { previous_state = state; state_t new_state; if (decode_state_string(state_string, new_state) && state != new_state) { - if (state == Disconnected) { - schedule_action(connect_init); - } // Leaving Alarm retires its number: the next alarm must be fetched // or reported afresh, never shown with the last one's. if (state == Alarm) lastAlarm = 0; @@ -454,6 +645,13 @@ extern "C" void show_error(int error) { #ifdef FNC_RX_TRACE dbg_printf("[rx-err] error:%d\n", error); #endif + { + const sendq_seq_t seq = s_inflight_seq; + line_acked(); + char why[16]; + snprintf(why, sizeof(why), "error:%d", error); + abort_seq(seq, why); + } errorExpire = milliseconds() + 1000; lastError = error; if (s_jog_window > 0) { @@ -470,10 +668,9 @@ extern "C" void show_error(int error) { request_redisplay(); } -extern "C" void show_timeout() { - s_ack_deadline = 0; // parser just cleared _ackwait; keep the queue moving - dbg_println("Timeout"); -} +// Only fnc_send_line() raises this, and nothing calls it: send_now() keeps +// the ack gate here. Kept so the parser's weak default is never what runs. +extern "C" void show_timeout() {} // The parser consumes ok / error:N / ALARM:N itself, so they never reached the // console log as plain lines -- the console showed no replies at all, and the // FluidNC names console_log gives error and alarm codes never appeared. @@ -487,7 +684,8 @@ extern "C" void handle_msg(char* command, char* arguments) { extern "C" void show_ok() { clog_add("ok"); caps_reply_end(); - s_ack_deadline = 0; // parser just cleared _ackwait; keep the queue moving + seq_ok(s_inflight_seq); + line_acked(); #ifdef FNC_RX_TRACE dbg_printf("[rx-ok]\n"); #endif @@ -512,6 +710,16 @@ extern "C" void show_alarm(int alarm) { } lastAlarm = alarm; homed_note_alarm(alarm); + // An alarm stops the machine whatever line it came from. Every queued + // sequence is now running on wrong assumptions; plain lines ($A, $X, $G) + // stay, since they are how the alarm gets read and cleared. + { + char why[16]; + snprintf(why, sizeof(why), "ALARM:%d", alarm); + // Every sequence not yet finished: in flight, or with lines queued. + for (int i = 0; i < SEQ_META; i++) + if (s_meta[i].seq) abort_seq(s_meta[i].seq, why); + } request_redisplay(); } diff --git a/src/model/FluidNCModel.h b/src/model/FluidNCModel.h index c0085d1..71a5b5e 100644 --- a/src/model/FluidNCModel.h +++ b/src/model/FluidNCModel.h @@ -71,6 +71,29 @@ void send_pump(); bool send_busy(); // an ack is still outstanding void send_linef(const char* fmt, ...); +// Multi-line actions that only make sense whole (AutoZero, a relative move and +// its G90, a driver reset). Stage with seq_line(), then seq_send(): the lines +// are queued all together or not at all, and false means refused, with the +// reason already on screen. If the controller answers any line with an error, +// or alarms, the rest are not sent and the cleanup lines (optional, e.g. "G90"; +// several are separated by '\n') go instead. +void seq_begin(const char* name); +void seq_cleanup(const char* line); +void seq_line(const char* s); +void seq_linef(const char* fmt, ...); +bool seq_send(); + +// Drop everything queued. Lines already written are not recalled. +void send_flush(const char* why); +// Soft-reset the controller (Ctrl-X) and drop everything queued, so nothing +// waiting behind the reset runs after it. +void send_reset(); +bool send_reset_was_recent(); + +// Link lifecycle, once per loop(): liveness (NO LINK after 4 s of silence), +// controller restarts, and priming a fresh connection. +void link_service(); + JogFlowControl jog_flow_control(); void send_jog_cancel(); diff --git a/src/model/linkwatch.cpp b/src/model/linkwatch.cpp new file mode 100644 index 0000000..34af39a --- /dev/null +++ b/src/model/linkwatch.cpp @@ -0,0 +1,28 @@ +#include "model/linkwatch.h" + +static bool s_init = false; +static unsigned long s_rx; +static uint32_t s_last_rx_ms; +static uint32_t s_last_ping_ms; + +void linkwatch_reset() { s_init = false; } + +linkwatch_t linkwatch_tick(uint32_t now, unsigned long rx, bool connected) { + if (!s_init || rx != s_rx || !connected) { + s_init = true; + s_rx = rx; + s_last_rx_ms = now; + s_last_ping_ms = now; + return LINKWATCH_OK; + } + const uint32_t silent = now - s_last_rx_ms; + if (silent >= LINKWATCH_LOST_AFTER_MS) { + s_init = false; // report it once; the next tick starts over + return LINKWATCH_LOST; + } + if (silent >= LINKWATCH_PING_AFTER_MS && now - s_last_ping_ms >= LINKWATCH_PING_EVERY_MS) { + s_last_ping_ms = now; + return LINKWATCH_PING; + } + return LINKWATCH_OK; +} diff --git a/src/model/linkwatch.h b/src/model/linkwatch.h new file mode 100644 index 0000000..7a628e5 --- /dev/null +++ b/src/model/linkwatch.h @@ -0,0 +1,22 @@ +#pragma once +#include + +// Is the controller still there? FluidNC only auto-reports when something +// changes, so an idle machine on a healthy cable can be silent for minutes. +// After PING_AFTER_MS of silence ask for a status report (one realtime '?', +// repeated every PING_EVERY_MS); if nothing at all has arrived for LOST_AFTER_MS +// the link is gone: cable out, controller off, or controller wedged. +// +// Pure: fed the clock and the UART's received-byte counter, it says what to do. +// The caller sends the '?' and handles the loss. + +#define LINKWATCH_PING_AFTER_MS 1000 +#define LINKWATCH_PING_EVERY_MS 1000 +#define LINKWATCH_LOST_AFTER_MS 4000 + +typedef enum { LINKWATCH_OK, LINKWATCH_PING, LINKWATCH_LOST } linkwatch_t; + +// connected: the panel currently believes the link is up. While it is not, +// the watch only tracks the counter, so coming up starts a fresh window. +linkwatch_t linkwatch_tick(uint32_t now_ms, unsigned long rx_count, bool connected); +void linkwatch_reset(); diff --git a/src/model/model_events.cpp b/src/model/model_events.cpp index bd86f30..378f3ce 100644 --- a/src/model/model_events.cpp +++ b/src/model/model_events.cpp @@ -66,17 +66,18 @@ static void sniff_board(const char* line) { static bool s_update_req = false; bool model_take_update_request() { bool r = s_update_req; s_update_req = false; return r; } // FluidNC prints "Grbl 4.1 [FluidNC v4.1.0 ...]" once per boot, as the LAST line -// of startup, when it can finally answer commands ("[MSG:RST]" comes ~10 s -// earlier and would prime into the void). Seeing it mid-session means the -// controller restarted while this panel stayed up, and everything primed at -// first link (settings, config, offsets, auto-report) died with the old run. +// of startup, when it can finally answer commands, and again after every soft +// reset. GrblParserC routes it to handle_signon(), never to handle_other(), so +// this is the only place it can be seen. link_service() takes the flag. static bool s_board_reset = false; bool model_take_board_reset() { bool r = s_board_reset; s_board_reset = false; return r; } -static void sniff_reset(const char* line) { - if (!line) return; - if (strncmp(line, "Grbl ", 5) == 0 && strstr(line, "FluidNC")) s_board_reset = true; +extern "C" void handle_signon(char* version, char* extra) { + char buf[CLOG_LINE_MAX]; + snprintf(buf, sizeof(buf), "Grbl %s %s", version ? version : "", extra ? extra : ""); + clog_add(buf); + s_board_reset = true; } void model_flag_message(const char* cmd, const char* args) { @@ -107,7 +108,6 @@ bool page_diag_limits_feed(const char* line); // ignores what is not addressed to it. extern "C" void handle_other_line(char* line) { if (!line) return; - sniff_reset(line); sniff_board(line); // the banner arrives as a plain line, not only as [MSG:] // The limit monitor gets first refusal: its stream is addressed to Diag, // and caps must never consume it (doing so blanked the limit lamps AND diff --git a/src/model/model_events.h b/src/model/model_events.h index a0e22bd..9633f03 100644 --- a/src/model/model_events.h +++ b/src/model/model_events.h @@ -26,8 +26,8 @@ bool model_take_update_request(); // [MSG:PANEL:UPDATE] arrived // drops the banner long before anyone opens the HW page. const char* model_expander_board(); -// True once after the controller prints its boot banner. The panel uses it to -// re-prime a link that survived a controller reset. +// True once after the controller prints its sign-on banner (boot or soft +// reset). link_service() uses it to flush and re-prime a link that survived it. bool model_take_board_reset(); // GrblParserC hands unrecognised lines to handle_other(); this fans them out to diff --git a/src/model/sendq.cpp b/src/model/sendq.cpp index a9e1ab3..f4f2e33 100644 --- a/src/model/sendq.cpp +++ b/src/model/sendq.cpp @@ -8,6 +8,14 @@ void sendq_reset(sendq_t* q) { q->dropped = 0; } +static void put(sendq_t* q, const char* s, sendq_seq_t seq) { + const uint8_t slot = (uint8_t)((q->head + q->count) % SENDQ_SLOTS); + strncpy(q->line[slot], s, SENDQ_LINE - 1); + q->line[slot][SENDQ_LINE - 1] = '\0'; + q->seq[slot] = seq; + ++q->count; +} + bool sendq_push(sendq_t* q, const char* s) { if (!s) return false; if (q->count >= SENDQ_SLOTS) { @@ -17,21 +25,62 @@ bool sendq_push(sendq_t* q, const char* s) { ++q->dropped; return false; } - const uint8_t slot = (uint8_t)((q->head + q->count) % SENDQ_SLOTS); - strncpy(q->line[slot], s, SENDQ_LINE - 1); - q->line[slot][SENDQ_LINE - 1] = '\0'; - ++q->count; + put(q, s, 0); return true; } -bool sendq_pop(sendq_t* q, char* out, size_t out_len) { +bool sendq_push_all(sendq_t* q, const char* const* lines, int n, sendq_seq_t seq) { + if (!lines || n <= 0 || seq == 0) return false; + if ((size_t)n > sendq_free(q)) return false; + for (int i = 0; i < n; i++) + if (!lines[i]) return false; + for (int i = 0; i < n; i++) put(q, lines[i], seq); + return true; +} + +bool sendq_pop_seq(sendq_t* q, char* out, size_t out_len, sendq_seq_t* seq) { if (q->count == 0 || !out || out_len == 0) return false; strncpy(out, q->line[q->head], out_len - 1); out[out_len - 1] = '\0'; + if (seq) *seq = q->seq[q->head]; q->head = (uint8_t)((q->head + 1) % SENDQ_SLOTS); --q->count; return true; } +bool sendq_pop(sendq_t* q, char* out, size_t out_len) { + return sendq_pop_seq(q, out, out_len, nullptr); +} + +// Compacts in place: walk every slot, keep the ones that stay, in order. +static int drop_where(sendq_t* q, bool all, sendq_seq_t seq) { + int kept = 0, removed = 0; + for (int i = 0; i < q->count; i++) { + const uint8_t from = (uint8_t)((q->head + i) % SENDQ_SLOTS); + const sendq_seq_t s = q->seq[from]; + if (s != 0 && (all || s == seq)) { ++removed; continue; } + const uint8_t to = (uint8_t)((q->head + kept) % SENDQ_SLOTS); + if (to != from) { + memcpy(q->line[to], q->line[from], SENDQ_LINE); + q->seq[to] = s; + } + ++kept; + } + q->count = (uint8_t)kept; + return removed; +} + +int sendq_drop_seq(sendq_t* q, sendq_seq_t seq) { return seq ? drop_where(q, false, seq) : 0; } +int sendq_drop_all_seqs(sendq_t* q) { return drop_where(q, true, 0); } + +size_t sendq_free(const sendq_t* q) { return SENDQ_SLOTS - q->count; } + size_t sendq_count(const sendq_t* q) { return q->count; } uint32_t sendq_dropped(const sendq_t* q) { return q->dropped; } + +int sendq_count_seq(const sendq_t* q, sendq_seq_t seq) { + int n = 0; + for (int i = 0; i < q->count; i++) + if (q->seq[(q->head + i) % SENDQ_SLOTS] == seq) ++n; + return n; +} diff --git a/src/model/sendq.h b/src/model/sendq.h index 74f77e7..38e809d 100644 --- a/src/model/sendq.h +++ b/src/model/sendq.h @@ -18,14 +18,23 @@ // Free of LVGL and the link so the wraparound and the overflow policy can be // tested on the host. -#define SENDQ_SLOTS 16 +// Sized for the longest sequence (AutoZero, 28 lines) with room to spare for +// whatever is already waiting. 48 x 128 bytes is 6 KB of internal RAM. +#define SENDQ_SLOTS 48 #define SENDQ_LINE 128 // matches vsend_linef()'s buffer +// A sequence is a run of lines that only makes sense whole: a probing routine, +// a relative move and its G90. It is admitted whole or not at all, and the +// lines of a sequence that hits an error are dropped rather than sent. Plain +// lines carry seq 0. +typedef uint16_t sendq_seq_t; + typedef struct { - char line[SENDQ_SLOTS][SENDQ_LINE]; - uint8_t head; // next slot to pop - uint8_t count; // slots in use - uint32_t dropped; // lines lost to a full queue, ever + char line[SENDQ_SLOTS][SENDQ_LINE]; + sendq_seq_t seq[SENDQ_SLOTS]; + uint8_t head; // next slot to pop + uint8_t count; // slots in use + uint32_t dropped; // lines lost to a full queue, ever } sendq_t; void sendq_reset(sendq_t* q); @@ -39,6 +48,21 @@ bool sendq_push(sendq_t* q, const char* s); // a pointer into the ring, so a push cannot move the caller's line underneath // it. bool sendq_pop(sendq_t* q, char* out, size_t out_len); +// Same, also handing back the line's sequence (0 for a plain line). +bool sendq_pop_seq(sendq_t* q, char* out, size_t out_len, sendq_seq_t* seq); + +// All n lines, tagged seq (non-zero), or none of them. False means there was +// not room for the whole run; nothing was queued and `dropped` is untouched, +// because the caller refuses the action as a whole instead. +bool sendq_push_all(sendq_t* q, const char* const* lines, int n, sendq_seq_t seq); + +// Remove every queued line of one sequence, or of every sequence (seq 0 lines +// stay). Order of what remains is kept. Returns the number removed. +int sendq_drop_seq(sendq_t* q, sendq_seq_t seq); +int sendq_drop_all_seqs(sendq_t* q); + +size_t sendq_free(const sendq_t* q); +int sendq_count_seq(const sendq_t* q, sendq_seq_t seq); // queued lines of one sequence size_t sendq_count(const sendq_t* q); uint32_t sendq_dropped(const sendq_t* q); diff --git a/src/model/toolchange.cpp b/src/model/toolchange.cpp index 25f4672..c119149 100644 --- a/src/model/toolchange.cpp +++ b/src/model/toolchange.cpp @@ -9,6 +9,8 @@ static bool s_remove = false; static char s_name[96]; static bool s_measured = false; static int s_current = -1; +static bool s_known = false; +static int s_tap = TC_TAP_NONE; bool tc_pending() { return s_pending; } int tc_tool() { return s_tool; } @@ -16,6 +18,10 @@ bool tc_remove() { return s_remove; } const char* tc_name() { return s_name; } bool tc_measured() { return s_measured; } int tc_current() { return s_current; } +bool tc_current_known() { return s_known; } +void tc_assume(int t) { s_current = t; s_known = true; } +int tc_tap() { return s_tap; } +void tc_tap_clear() { s_tap = TC_TAP_NONE; } void tc_clear() { s_pending = false; s_tool = 0; s_remove = false; s_name[0] = 0; s_measured = false; } static void request(int t, bool remove, bool measured) { @@ -29,7 +35,8 @@ static void request(int t, bool remove, bool measured) { void tc_note_message(const char* a) { if (!a) return; const char* p; - if ((p = strstr(a, "TOOLNOW "))) { s_current = atoi(p + 8); return; } + if ((p = strstr(a, "TOOLNOW "))) { tc_assume(atoi(p + 8)); return; } + if ((p = strstr(a, "TOOLTAP "))) { s_tap = atoi(p + 8); return; } // The operator steps. "#" from atc_manual; "T" from openatc_m6.nc, which // cannot print a literal '#' (FluidNC's PRINT reads it as a parameter). if ((p = strstr(a, "Install tool #")) || (p = strstr(a, "Install tool T"))) { diff --git a/src/model/toolchange.h b/src/model/toolchange.h index d752d5c..3ffde5f 100644 --- a/src/model/toolchange.h +++ b/src/model/toolchange.h @@ -22,3 +22,14 @@ void tc_clear(); // reply lands here. -1 = FluidNC does not know, as after every boot and reset. #define TC_ASK_CURRENT "(PRINT,TOOLNOW %d#<_current_tool>)" int tc_current(); +bool tc_current_known(); // the controller has answered at least once +void tc_assume(int t); // the panel just set it with M61: no need to wait + +// Nothing in the spindle. T0 is the custom tool on this machine, so empty needs a +// number of its own; 98 is what RapidChange's macros use for the same thing. +#define TC_EMPTY 98 + +// openatc_tap.nc's answer: TC_TAP_NONE until one arrives. +enum { TC_TAP_NONE = -1, TC_TAP_EMPTY = 0, TC_TAP_TOOL = 1 }; +int tc_tap(); +void tc_tap_clear(); diff --git a/src/sim/sim_main.cpp b/src/sim/sim_main.cpp index 3a3c195..8123f03 100644 --- a/src/sim/sim_main.cpp +++ b/src/sim/sim_main.cpp @@ -51,6 +51,8 @@ void sim_set_state(const char* st); void sim_raise_alarm(int n); void sim_tool_change(int t); extern bool s_atc_manual; +extern int s_cur_tool; +extern bool s_tap_hit; void sim_toggle_motion(); bool sim_link_open(const char* path); @@ -240,20 +242,6 @@ static void boot() { // Mirrors loop() in main.cpp. The XModem branches are gone with the SD card // they read from; everything else is the same sequence. -// Mirrors prime_link_if_up() in main.cpp: the panel asks the controller to -// describe itself exactly once, the first time the link is actually alive. -// Without this the simulator never requests the config dump and every -// capability reads UNKNOWN, which is a different UI from the panel's. -static void prime_link_if_up() { - static bool primed = false; - if (primed || state == Disconnected) return; - primed = true; - send_line("$#"); - filelist_request(); - fncset_request_all(); - caps_request_config(); -} - static void step() { sim_transport_tick(); // Same routing as loop() in main.cpp: while an XModem transfer owns the @@ -272,7 +260,7 @@ static void step() { } } send_pump(); - prime_link_if_up(); + link_service(); caps_poll(); imu_poll(); service_action(); @@ -342,6 +330,8 @@ int main(int argc, char** argv) { else if (!strcmp(argv[i], "--alarm") && i + 1 < argc) s_alarm = atoi(argv[++i]); else if (!strcmp(argv[i], "--toolchange") && i + 1 < argc) s_tool = atoi(argv[++i]); else if (!strcmp(argv[i], "--atc-manual")) s_atc_manual = true; + else if (!strcmp(argv[i], "--tool-unknown")) s_cur_tool = -1; + else if (!strcmp(argv[i], "--tap-empty")) s_tap_hit = false; } if (link) sim_link_open(link); diff --git a/src/sim/sim_transport.cpp b/src/sim/sim_transport.cpp index a60c2d0..64b768c 100644 --- a/src/sim/sim_transport.cpp +++ b/src/sim/sim_transport.cpp @@ -155,7 +155,8 @@ void sim_toggle_motion() { s_moving = !s_moving; } static uint32_t s_tc_at = 0; // when the current phase ends; 0 = idle static int s_tc_phase = 0; // 1 travelling, 2 waiting, 3 measuring static int s_tc_tool = 0; -static int s_cur_tool = -1; // what $G reports; FluidNC boots not knowing +int s_cur_tool = 0; // --tool-unknown: -1, as FluidNC boots +bool s_tap_hit = true; // --tap-empty: the tap finds nothing static int s_sel_tool = 0; // $G's T word: selected, not in the spindle static char s_tc_msg_later[112]; bool s_atc_manual = false; // --atc-manual: today's controller config @@ -317,6 +318,11 @@ static void canned_putchar(uint8_t c) { if (s_atc_manual) sim_manual_change(n); else sim_atc_change(n); } + if (strcmp(s_line, "$LocalFS/Run=openatc_tap.nc") == 0) { + char g[48]; + snprintf(g, sizeof(g), "[MSG:INFO: PRINT,TOOLTAP %d]\nok\n", s_tap_hit ? 1 : 0); + q_push(g); + } if (strcmp(s_line, "$G") == 0) { char g[96]; snprintf(g, sizeof(g), "[GC:G0 G54 G17 G21 G90 G94 M5 M9 T%d F0 S0]\nok\n", s_sel_tool); diff --git a/src/ui/home_wizard.cpp b/src/ui/home_wizard.cpp index df9fec5..03ac36a 100644 --- a/src/ui/home_wizard.cpp +++ b/src/ui/home_wizard.cpp @@ -127,6 +127,8 @@ static void open_wizard() { show(S_CHECK); } +bool home_wizard_open() { return s_root != nullptr; } + void home_wizard_tick() { if (!s_root) { // Waits for the config dump: no prompt before we know this machine diff --git a/src/ui/home_wizard.h b/src/ui/home_wizard.h index 1327be8..ab18750 100644 --- a/src/ui/home_wizard.h +++ b/src/ui/home_wizard.h @@ -4,3 +4,4 @@ // trusted (fresh link, controller restart, position-losing alarm): check the // table, HOME ALL, then an optional TLO run. Called from shell_tick(). void home_wizard_tick(); +bool home_wizard_open(); diff --git a/src/ui/page_cal.cpp b/src/ui/page_cal.cpp index 6eb105d..685e55b 100644 --- a/src/ui/page_cal.cpp +++ b/src/ui/page_cal.cpp @@ -81,8 +81,11 @@ static void dist_cb(lv_event_t* e) { // G91 for the move, then straight back to G90: leaving the parser in relative // mode is how the next absolute move from any other page goes somewhere absurd. static void move_cb(lv_event_t*) { - send_linef("G91 G0 %s%.3f", AXIS_LBL[s_axis], (double)commanded()); - send_line("G90"); + seq_begin("Calibration move"); + seq_cleanup("G90"); + seq_linef("G91 G0 %s%.3f", AXIS_LBL[s_axis], (double)commanded()); + seq_line("G90"); + seq_send(); } static void meas_cb(lv_event_t* e) { diff --git a/src/ui/page_probe.cpp b/src/ui/page_probe.cpp index 603aa68..9360c0e 100644 --- a/src/ui/page_probe.cpp +++ b/src/ui/page_probe.cpp @@ -96,16 +96,23 @@ static void az_probe() { "G38.2 Y5 F75", "G90 G53 G0 Y[[#+#5062]/2]", }; + // One sequence, 28 lines: queued whole or refused, and stopped at the + // first error or alarm (a missed wall is ALARM:5) instead of probing on + // from the wrong place. Stopped early it still leaves G91 behind, hence + // the cleanup line. + seq_begin("AutoZero"); + seq_cleanup("G90"); for (const char* l : WALLS) { - if (l) send_line(l); - else send_linef("G10 L20 P0 Z%.3f", (double)s_params[P_AZ_FLOOR].value); + if (l) seq_line(l); + else seq_linef("G10 L20 P0 Z%.3f", (double)s_params[P_AZ_FLOOR].value); } - send_linef("G10 L20 P0 X%.3f Y%.3f", - (double)(CORNER_SX[c] * s_params[P_AZ_CENTRE].value), - (double)(CORNER_SY[c] * s_params[P_AZ_CENTRE].value)); + seq_linef("G10 L20 P0 X%.3f Y%.3f", + (double)(CORNER_SX[c] * s_params[P_AZ_CENTRE].value), + (double)(CORNER_SY[c] * s_params[P_AZ_CENTRE].value)); // Out of the pocket before anything moves sideways; X/Y stay put so the // plate can be lifted off. gSender's final X0Y0 move is left to GOTO. - send_linef("G90 G0 Z%.3f", (double)(s_params[P_AZ_FLOOR].value + s_params[P_AZ_LIFT].value)); + seq_linef("G90 G0 Z%.3f", (double)(s_params[P_AZ_FLOOR].value + s_params[P_AZ_LIFT].value)); + seq_send(); } static void show_value(lv_obj_t* lbl, float v) { @@ -255,9 +262,15 @@ static void edit_cb(lv_event_t*) { // than re-derived: probe down, then retract by the configured distance. static void probe_cb(lv_event_t*) { if (settings_probe_type() == 1) { az_probe(); return; } - send_linef("G38.2G91F%dZ-%dP%.2f", - (int)s_params[P_FEED].value, (int)s_params[P_TRAVEL].value, (double)s_params[P_OFFSET].value); - send_linef("$J=G91F1000Z%.2f", (double)s_params[P_RETRACT].value); + // G91 on the probe line is modal: without the trailing G90 the parser was + // left relative, and the next absolute move from any page went wrong. + seq_begin("Probe"); + seq_cleanup("G90"); + seq_linef("G38.2G91F%dZ-%dP%.2f", + (int)s_params[P_FEED].value, (int)s_params[P_TRAVEL].value, (double)s_params[P_OFFSET].value); + seq_line("G90"); + seq_linef("$J=G91F1000Z%.2f", (double)s_params[P_RETRACT].value); + seq_send(); } static void tlo_cb(lv_event_t*) { diff --git a/src/ui/page_tools.cpp b/src/ui/page_tools.cpp index bca9824..ce7e0ff 100644 --- a/src/ui/page_tools.cpp +++ b/src/ui/page_tools.cpp @@ -5,6 +5,7 @@ #include "model/homed.h" #include "model/caps.h" #include "model/toolchange.h" +#include "ui/spindle_card.h" #include "GrblParserC.h" #include @@ -49,12 +50,15 @@ enum { A_LOAD, A_CURRENT, A_UNLOAD }; static bool by_macro() { return caps_atc() == CAPS_ATC_MACRO; } -// What is in the spindle: a cartridge, or 0 for the custom tool. With the macro -// FluidNC knows; atc_manual never updates FluidNC's current tool, so there the -// selected tool from $G is the best there is. +// What is in the spindle: a cartridge, TC_EMPTY, 0 for the custom tool, or -1 +// for not known. With the macro FluidNC knows, or says it does not (after every +// boot and reset); atc_manual never updates FluidNC's current tool, so there +// the selected tool from $G is the best there is. +static const int UNKNOWN = -1; static int in_spindle() { + if (by_macro() && tc_current() < 0) return UNKNOWN; const int t = by_macro() ? tc_current() : (int)mySelectedTool; - return in_rack(t) ? t : 0; + return in_rack(t) || (by_macro() && t == TC_EMPTY) ? t : 0; } static void refresh_tool() { @@ -75,6 +79,7 @@ static void act_cb(lv_event_t* e) { // The same decisions openatc_m6.nc makes, in words, so LOAD is never a surprise. static void plan_macro(char* out, size_t n, int from, int to) { char a[48]; + if (from == TC_EMPTY) { snprintf(out, n, "Pick up T%d from pocket %d > measure it", to, to); return; } if (in_rack(from)) snprintf(a, sizeof(a), "T%d back to pocket %d", from, from); else snprintf(a, sizeof(a), "remove the custom tool by hand"); snprintf(out, n, "%s > pick up T%d from pocket %d > measure it", a, to, to); @@ -99,7 +104,10 @@ static void gate_actions() { const char* busy = w_locked() ? LOCK_REASON : "machine busy"; const char* move = !idle ? busy : !homed() ? "home first" : nullptr; - w_gate(s_act[A_LOAD], !move && in != s_tool, move ? move : "already in the spindle"); + // An unknown spindle is not "the custom tool": the macro would skip the + // put-back for a cartridge that may still be in the collet. + const char* load_why = move ? move : in == UNKNOWN ? "spindle unknown: tap IN SPINDLE" : "already in the spindle"; + w_gate(s_act[A_LOAD], !move && in != UNKNOWN && in != s_tool, load_why); if (by_macro()) return; snprintf(why_cur, sizeof(why_cur), "T%d is loaded: load or unload", in); @@ -202,6 +210,10 @@ void page_tools_build(lv_obj_t* p) { lv_obj_set_flex_grow(now, 1); s_now = w_label(now, "--", &lv_font_montserrat_40, C_ACCENT); lv_obj_center(s_now); + // Tapping it reopens the spindle card if it was skipped. + lv_obj_add_flag(now, LV_OBJ_FLAG_CLICKABLE); + lv_obj_add_event_cb(now, [](lv_event_t*) { if (in_spindle() == UNKNOWN) spindle_card_ask(); }, + LV_EVENT_CLICKED, nullptr); lv_obj_t* rack = column(p); lv_obj_set_flex_grow(rack, 1); @@ -236,7 +248,7 @@ void page_tools_tick() { // Back at rest: a change (ours, or a job's) may have moved the tool. static state_t was = Disconnected; if (state != was) { - if (state == Idle && was != Disconnected) refresh_tool(); + if (state == Idle && was != Disconnected && was != Jog) refresh_tool(); was = state; gate_actions(); } @@ -247,8 +259,10 @@ void page_tools_tick() { shown = now; gate_actions(); char b[8]; - if (now == 0) snprintf(b, sizeof(b), "CUSTOM"); - else snprintf(b, sizeof(b), "T%d", now); + if (now == UNKNOWN) snprintf(b, sizeof(b), "?"); + else if (now == TC_EMPTY) snprintf(b, sizeof(b), "EMPTY"); + else if (now == 0) snprintf(b, sizeof(b), "CUSTOM"); + else snprintf(b, sizeof(b), "T%d", now); lv_label_set_text(s_now, b); for (int t = 1; t <= RACK_POCKETS; t++) { const bool on = t == now; diff --git a/src/ui/shell.cpp b/src/ui/shell.cpp index 51a948b..7eb622a 100644 --- a/src/ui/shell.cpp +++ b/src/ui/shell.cpp @@ -6,6 +6,7 @@ #include "ui/goto_popup.h" #include "ui/home_wizard.h" #include "ui/tool_popup.h" +#include "ui/spindle_card.h" #include "model/FluidNCModel.h" #include "model/model_events.h" #include "model/caps.h" @@ -323,7 +324,7 @@ static bool paused(state_t s) { static void hold_resume_cb(lv_event_t*) { fnc_realtime(paused(state) ? CycleStart : FeedHold); } -static void reset_cb(lv_event_t*) { fnc_realtime(Reset); } +static void reset_cb(lv_event_t*) { send_reset(); } static void close_cb(lv_event_t*) { expanded_close(); } // Three looks: RESUME green while paused, HOLD amber while there is motion to @@ -847,7 +848,45 @@ static void fmt_pos(char* out, size_t n, pos_t v) { snprintf(out, n, "%s", e4_to_cstr(v, 3)); } +// Panel-side refusals and stopped sequences ("AutoZero stopped (ALARM:5)..."). +// They used to reach only the console, where nobody at the machine sees them. +// A strip above the safety bar, until tapped or for 8 s; a newer one replaces it. +static lv_obj_t* s_notice; +static uint32_t s_notice_at; + +static void notice_close() { + if (!s_notice) return; + lv_obj_del(s_notice); + s_notice = nullptr; +} + +static void notice_tick() { + if (const char* e = model_take_error()) { + notice_close(); + s_notice = lv_obj_create(lv_layer_top()); + lv_obj_remove_style_all(s_notice); + lv_obj_set_size(s_notice, CONTENT_W - U * 4, LV_SIZE_CONTENT); + lv_obj_align(s_notice, LV_ALIGN_BOTTOM_RIGHT, -U * 2, -(SAFETY_H + U)); + lv_obj_set_style_bg_color(s_notice, C_CRIT, 0); + lv_obj_set_style_bg_opa(s_notice, LV_OPA_COVER, 0); + lv_obj_set_style_radius(s_notice, U, 0); + lv_obj_set_style_pad_all(s_notice, U * 2, 0); + lv_obj_add_flag(s_notice, LV_OBJ_FLAG_CLICKABLE); + lv_obj_add_event_cb(s_notice, [](lv_event_t*) { notice_close(); }, LV_EVENT_CLICKED, nullptr); + lv_obj_t* l = lv_label_create(s_notice); + lv_obj_set_width(l, LV_PCT(100)); + lv_label_set_long_mode(l, LV_LABEL_LONG_WRAP); + lv_obj_set_style_text_font(l, &lv_font_montserrat_20, 0); + lv_obj_set_style_text_color(l, C_TEXT, 0); + lv_label_set_text(l, e); + s_notice_at = lv_tick_get(); + } else if (s_notice && lv_tick_elaps(s_notice_at) > 8000) { + notice_close(); + } +} + void shell_tick() { + notice_tick(); // Recompute what the machine can do before anything paints, so a settings // or config dump that just landed is reflected on this frame. caps_poll(); @@ -943,6 +982,7 @@ void shell_tick() { expanded_tick(); home_wizard_tick(); tool_popup_tick(); + spindle_card_tick(); // Alarm, or motion the panel did not start, while released: the steppers // may be back on under someone's hands. Re-arm and re-enable to match. diff --git a/src/ui/spindle_card.cpp b/src/ui/spindle_card.cpp new file mode 100644 index 0000000..09a6842 --- /dev/null +++ b/src/ui/spindle_card.cpp @@ -0,0 +1,185 @@ +#include "ui/spindle_card.h" +#include "ui/home_wizard.h" +#include "ui/splash.h" +#include "ui/theme.h" +#include "ui/widgets.h" +#include "model/FluidNCModel.h" +#include "model/caps.h" +#include "model/homed.h" +#include "model/settings.h" +#include "model/toolchange.h" +#include "GrblParserC.h" +#include +#include + +static const int POCKETS = 5; // as page_tools.cpp: the rack's +static const uint32_t TAP_START_MS = 3000; // a tap that never leaves Idle was refused +static const char* const KEY = "tool_last"; // survives the controller forgetting + +static lv_obj_t* s_root; +static lv_obj_t* s_tool[POCKETS + 1]; // [0] is CUSTOM: T0 is the custom tool +static lv_obj_t* s_empty; +static lv_obj_t* s_skip; +static lv_obj_t* s_tap_btn; +static lv_obj_t* s_msg; +static bool s_tapping; +// SKIP holds the card back until something new could have changed the answer: +// a link drop, a controller restart, lost position (all bump homed_epoch()). +static uint32_t s_skipped_epoch = UINT32_MAX; +static bool s_ask_now; +static bool s_tap_left_idle; +static uint32_t s_tap_at; + +static void close_card() { + if (!s_root) return; + lv_obj_del(s_root); + s_root = nullptr; + s_tapping = false; +} + +static void answer_cb(lv_event_t* e) { + const int t = (int)(intptr_t)lv_event_get_user_data(e); + send_linef("M61 Q%d", t); + send_line(TC_ASK_CURRENT); + tc_assume(t); + close_card(); +} + +static void skip_cb(lv_event_t*) { + s_skipped_epoch = homed_epoch(); + close_card(); +} + +static void tap_cb(lv_event_t*) { + tc_tap_clear(); + s_tapping = true; + s_tap_left_idle = false; + s_tap_at = lv_tick_get(); + send_line("$LocalFS/Run=openatc_tap.nc"); +} + +static void paint() { + const int tap = tc_tap(); + const bool idle = state == Idle && !s_tapping; + const char* busy = s_tapping ? "checking" : "machine busy"; + + for (int t = 0; t <= POCKETS; t++) + w_gate(s_tool[t], idle && tap != TC_TAP_EMPTY, idle ? "toolsetter found nothing" : busy); + // EMPTY is the one answer that can crash the rack: the next LOAD skips the + // put-back and drives the tool still in the collet into a full pocket. So + // it is never taken on the operator's word, only on the toolsetter's. + w_gate(s_empty, idle && tap == TC_TAP_EMPTY, !idle ? busy : "check with the toolsetter first"); + w_gate(s_tap_btn, idle && homed(), !idle ? busy : "home first"); + + char b[96]; + const int last = (int)settings_get_float(KEY, -1.0f); + if (s_tapping) snprintf(b, sizeof(b), "Checking toolsetter..."); + else if (tap == TC_TAP_TOOL) snprintf(b, sizeof(b), "Toolsetter touched something: which tool is it?"); + else if (tap == TC_TAP_EMPTY) snprintf(b, sizeof(b), "Toolsetter found nothing: the spindle is empty."); + else if (last == TC_EMPTY) snprintf(b, sizeof(b), "Last known: empty."); + else if (last == 0) snprintf(b, sizeof(b), "Last known: custom tool."); + else if (last > 0) snprintf(b, sizeof(b), "Last known: T%d.", last); + else snprintf(b, sizeof(b), "Nothing on record."); + lv_label_set_text(s_msg, b); +} + +static lv_obj_t* row(lv_obj_t* card) { + lv_obj_t* r = lv_obj_create(card); + w_flatten(r); + lv_obj_set_size(r, LV_PCT(100), TOUCH_HOLD); + lv_obj_set_flex_flow(r, LV_FLEX_FLOW_ROW); + lv_obj_set_style_pad_column(r, U, 0); + return r; +} + +static lv_obj_t* grow(lv_obj_t* b) { + lv_obj_set_flex_grow(b, 1); + lv_obj_set_height(b, LV_PCT(100)); + return b; +} + +static void open_card() { + tc_tap_clear(); + + // Same shape as the homing card: stops short of the safety bar. + s_root = lv_obj_create(lv_layer_top()); + lv_obj_remove_style_all(s_root); + lv_obj_set_size(s_root, SCREEN_W, SCREEN_H - SAFETY_H); + lv_obj_set_style_bg_color(s_root, C_BG, 0); + lv_obj_set_style_bg_opa(s_root, LV_OPA_80, 0); + lv_obj_add_flag(s_root, LV_OBJ_FLAG_CLICKABLE); + + lv_obj_t* card = w_panel(s_root, C_SURFACE); + lv_obj_set_size(card, CONTENT_W - U * 4, LV_SIZE_CONTENT); + lv_obj_center(card); + lv_obj_set_style_pad_all(card, U * 2, 0); + lv_obj_set_style_pad_row(card, U, 0); + lv_obj_set_flex_flow(card, LV_FLEX_FLOW_COLUMN); + + w_label(card, "WHAT'S IN THE SPINDLE?", &lv_font_montserrat_20, C_WARN); + lv_obj_t* why = w_label(card, "The controller does not know. The rack needs the truth: " + "a wrong answer sends a cartridge to a full pocket.", + &lv_font_montserrat_14, C_TEXT); + lv_obj_set_width(why, LV_PCT(100)); + lv_label_set_long_mode(why, LV_LABEL_LONG_WRAP); + s_msg = w_label(card, "", &lv_font_montserrat_14, C_DIM); + + lv_obj_t* tools = row(card); + for (int t = 1; t <= POCKETS; t++) { + char b[8]; + snprintf(b, sizeof(b), "T%d", t); + s_tool[t] = grow(w_button(tools, b, " ", C_RAISE, C_TEXT, answer_cb, (void*)(intptr_t)t)); + } + lv_obj_t* others = row(card); + s_tap_btn = grow(w_button(others, "TOOLSETTER", "tool or no tool", C_ACCENT, C_BG, tap_cb, nullptr)); + s_empty = grow(w_button(others, "EMPTY", "toolsetter confirmed", C_RAISE, C_TEXT, answer_cb, (void*)(intptr_t)TC_EMPTY)); + s_tool[0] = grow(w_button(others, "CUSTOM", "by hand, rack full", C_RAISE, C_TEXT, answer_cb, (void*)(intptr_t)0)); + s_skip = grow(w_button(others, "SKIP", "LOAD stays locked", C_RAISE, C_TEXT, skip_cb, nullptr)); + paint(); +} + +void spindle_card_tick() { + if (caps_atc() != CAPS_ATC_MACRO) { close_card(); return; } + + // Ask when the answer can have changed: a new link or controller restart + // (homed_epoch), or coming to rest from anything but a jog, since a job or + // a macro may have run M6. Never after a plain jog: the query queues ahead + // of the next jog chunk, and a queued line makes that chunk get skipped. + static state_t was = Disconnected; + static uint32_t epoch = UINT32_MAX; + static bool macro = false; + const bool came_to_rest = state == Idle && was != Idle && was != Jog; + if (state == Idle && (came_to_rest || epoch != homed_epoch() || !macro)) send_line(TC_ASK_CURRENT); + const bool changed = state != was || epoch != homed_epoch(); + was = state; + epoch = homed_epoch(); + macro = true; + + static int saved = (int)settings_get_float(KEY, -1.0f); + if (tc_current() >= 0 && tc_current() != saved) { + saved = tc_current(); + settings_set_float(KEY, (float)saved); + } + + if (!s_root) { + const bool skipped = s_skipped_epoch == homed_epoch() && !s_ask_now; + if (tc_current_known() && tc_current() < 0 && state == Idle && !skipped && + !home_wizard_open() && !splash_active()) open_card(); + s_ask_now = false; + return; + } + if (tc_current() >= 0 || state == Disconnected || (state != Idle && !s_tapping)) { + close_card(); + return; + } + if (s_tapping) { + if (state != Idle) s_tap_left_idle = true; + const bool done = tc_tap() != TC_TAP_NONE || state == Alarm || (state == Idle && s_tap_left_idle) || + (!s_tap_left_idle && lv_tick_elaps(s_tap_at) > TAP_START_MS); + if (done) { s_tapping = false; paint(); } + } else if (changed) { + paint(); + } +} + +void spindle_card_ask() { s_ask_now = true; } diff --git a/src/ui/spindle_card.h b/src/ui/spindle_card.h new file mode 100644 index 0000000..aaa0c0b --- /dev/null +++ b/src/ui/spindle_card.h @@ -0,0 +1,9 @@ +#pragma once + +// With the rack, FluidNC forgets the tool on every boot and reset, and a wrong +// answer sends a cartridge to an occupied pocket. So when it does not know, this +// card asks: empty, custom, or T1..T5. A touch on the toolsetter can settle tool or no +// tool first. Called from shell_tick(). +void spindle_card_tick(); +// Bring the card back after SKIP (the TOOLS page's IN SPINDLE panel). +void spindle_card_ask(); diff --git a/test/run_host_tests.sh b/test/run_host_tests.sh new file mode 100755 index 0000000..a02747c --- /dev/null +++ b/test/run_host_tests.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Host unit tests without PlatformIO: plain g++, Unity and the GrblParser header +# cloned once into test/.deps. Same sources and flags as [env:native] in +# platformio.ini, so `pio test -e native` and this script test the same code. +# +# test/run_host_tests.sh every test_* folder +# test/run_host_tests.sh sendq caps only those +set -euo pipefail +cd "$(dirname "$0")/.." + +DEPS=test/.deps +UNITY_REF=v2.6.0 +GRBL_REF=9108f54a3e30526b66194898676af34e96a87da9 # keep in step with platformio.ini + +mkdir -p "$DEPS" +if [ ! -d "$DEPS/Unity" ]; then + git clone -q --depth 1 --branch "$UNITY_REF" https://github.com/ThrowTheSwitch/Unity "$DEPS/Unity" +fi +if [ ! -d "$DEPS/GrblParser" ]; then + git -c advice.detachedHead=false clone -q https://github.com/MitchBradley/GrblParser "$DEPS/GrblParser" + git -c advice.detachedHead=false -C "$DEPS/GrblParser" checkout -q "$GRBL_REF" +fi + +# The model sources [env:native] builds into every test binary. +SRCS=$(sed -n '/^\[env:native\]/,/^\[/{s/^build_src_filter *= *//p}' platformio.ini | + grep -o '+<[^>]*>' | sed 's/+<\(.*\)>/src\/\1/') + +CXXFLAGS="-std=gnu++17 -DUNIT_TEST -DE4_POS_T -Wall -Wno-unused-function -I src -I test + -I $DEPS/Unity/src -I $DEPS/GrblParser/src" + +OUT=test/.build +mkdir -p "$OUT" +fail=0 +tests=("$@") +[ ${#tests[@]} -eq 0 ] && tests=($(ls -d test/test_* | xargs -n1 basename | sed 's/^test_//')) + +for t in "${tests[@]}"; do + dir=test/test_$t + bin=$OUT/test_$t + # A test with its own `sources` file links exactly those (paths from the + # repo root, plus the parser) and brings its own stand-ins, instead of the + # shared model set and host_stubs.cpp, which stub out the very code it tests. + if [ -f "$dir/sources" ]; then + srcs="$(grep -v '^#' "$dir/sources" | xargs)" + extra="-I $dir -I sim/shim -x c $DEPS/GrblParser/src/GrblParserC.c $DEPS/GrblParser/src/e4math.c -x none" + else + srcs="test/host_stubs.cpp $SRCS" + extra="" + fi + # shellcheck disable=SC2086 + if ! g++ $CXXFLAGS -o "$bin" "$dir"/*.cpp $srcs $extra \ + -x c "$DEPS/Unity/src/unity.c" 2> "$bin.log"; then + echo "BUILD FAIL $t"; sed -n 1,40p "$bin.log"; fail=1; continue + fi + if "$bin" > "$bin.out" 2>&1; then + echo "PASS $t ($(tail -n 3 "$bin.out" | grep -o '^[0-9]* Tests' || true))" + else + echo "FAIL $t"; grep -E 'FAIL|Tests' "$bin.out"; fail=1 + fi +done +exit $fail diff --git a/test/test_link/main.cpp b/test/test_link/main.cpp new file mode 100644 index 0000000..55f4063 --- /dev/null +++ b/test/test_link/main.cpp @@ -0,0 +1,291 @@ +// The panel's side of the controller link, end to end through GrblParserC: +// sequences, errors, alarms, RESET, link loss and controller restarts. The +// "controller" is a script: lines the panel writes are captured, replies are +// fed back through the real parser. +#include +#include +#include +#include +#include + +#include "model/FluidNCModel.h" +#include "model/homed.h" +#include "model/model_events.h" +#include "model/console_log.h" +#include "model/model_compat.h" +#include "GrblParserC.h" + +// ---- stand-ins for the hardware and the UI ------------------------------------ +SimSerial Serial; +static int s_now = 1000; +static std::string s_tx_line; +static std::vector s_sent; // complete lines, realtime bytes excluded +static std::vector s_realtime; +static std::string s_rx; +static unsigned long s_rx_count = 0; + +extern "C" int milliseconds() { return s_now; } +extern "C" void fnc_putchar(uint8_t c) { + if (c == '\n') { s_sent.push_back(s_tx_line); s_tx_line.clear(); return; } + if (c < 0x20 || c == '?' || c >= 0x80) { s_realtime.push_back(c); return; } + s_tx_line += (char)c; +} +extern "C" int fnc_getchar() { + if (s_rx.empty()) return -1; + int c = (uint8_t)s_rx[0]; + s_rx.erase(0, 1); + ++s_rx_count; + return c; +} +extern "C" bool fnc_rx_waiting() { return !s_rx.empty(); } +unsigned long fnc_rx_count() { return s_rx_count; } +void resetFlowControl() {} +void reinit_fnc_uart() {} +bool page_diag_limits_feed(const char*) { return false; } +float settings_get_float(const char*, float def) { return def; } +void settings_set_float(const char*, float) {} + +// ---- driving it ------------------------------------------------------------- +static void reply(const char* text) { + s_rx += text; + while (!s_rx.empty()) fnc_poll(); +} +static void loop_once() { send_pump(); link_service(); service_action(); } +static void advance(int ms) { + for (int t = 0; t < ms; t += 10) { s_now += 10; loop_once(); } +} +// Answer "ok" to everything written so far, one at a time, the way FluidNC does. +static void ok_all() { + for (int guard = 0; guard < 200; guard++) { + size_t before = s_sent.size(); + loop_once(); + if (!send_busy()) { if (s_sent.size() == before) return; continue; } + reply("ok\n"); + } +} +static int count_sent(const char* prefix) { + int n = 0; + for (auto& l : s_sent) if (l.rfind(prefix, 0) == 0) n++; + return n; +} +static bool sent(const char* line) { + for (auto& l : s_sent) if (l == line) return true; + return false; +} +static bool console_has(const char* needle) { + for (size_t i = 0; i < clog_count(); i++) if (strstr(clog_line(i)->text, needle)) return true; + return false; +} + +// Bring the link up: a status report, then ack the priming lines. +static void connect() { + reply("\n"); + loop_once(); + ok_all(); +} + +void setUp() { + s_sent.clear(); s_realtime.clear(); s_rx.clear(); s_tx_line.clear(); + send_flush(nullptr); + clog_reset(); + if (state != Disconnected) { // previous test left it up: drop it cleanly + set_disconnected_state(); + loop_once(); + } + advance(50); + s_sent.clear(); +} +void tearDown() {} + +static void stage_seq(const char* name, int n) { + seq_begin(name); + seq_cleanup("G90"); + char b[32]; + for (int i = 0; i < n; i++) { snprintf(b, sizeof(b), "G0 X%d", i); seq_line(b); } +} + +// ---- tests ------------------------------------------------------------------ + +void test_connect_primes_once() { + connect(); + TEST_ASSERT_EQUAL(1, count_sent("$G")); + TEST_ASSERT_EQUAL(1, count_sent("$RI=200")); + TEST_ASSERT_EQUAL(1, count_sent("$#")); + advance(500); + ok_all(); + TEST_ASSERT_EQUAL(1, count_sent("$RI=200")); // one priming path, not two +} + +// The AutoZero bug: 28 lines through a 16-slot queue lost the last 11. +void test_long_sequence_arrives_whole_and_in_order() { + connect(); + s_sent.clear(); + stage_seq("AutoZero", 28); + TEST_ASSERT_TRUE(seq_send()); + ok_all(); + TEST_ASSERT_EQUAL(28, (int)s_sent.size()); + TEST_ASSERT_EQUAL_STRING("G0 X0", s_sent.front().c_str()); + TEST_ASSERT_EQUAL_STRING("G0 X27", s_sent.back().c_str()); + TEST_ASSERT_NULL(model_take_error()); +} + +void test_sequence_refused_without_link() { + stage_seq("AutoZero", 3); + TEST_ASSERT_FALSE(seq_send()); + TEST_ASSERT_NOT_NULL(strstr(model_take_error(), "no link")); + TEST_ASSERT_EQUAL(0, (int)s_sent.size()); +} + +void test_error_stops_the_sequence_and_sends_cleanup() { + connect(); + s_sent.clear(); + stage_seq("AutoZero", 10); + seq_send(); + loop_once(); + reply("ok\n"); // G0 X0 + loop_once(); + reply("error:20\n"); // G0 X1 refused + ok_all(); + TEST_ASSERT_TRUE(sent("G0 X1")); + TEST_ASSERT_FALSE(sent("G0 X2")); + TEST_ASSERT_TRUE(sent("G90")); + const char* e = model_take_error(); + TEST_ASSERT_NOT_NULL(e); + TEST_ASSERT_NOT_NULL(strstr(e, "AutoZero stopped (error:20), 8 lines not sent")); +} + +// A probe that misses is ALARM:4/5 while the G38.2 is still the line in flight. +void test_alarm_stops_the_sequence_but_keeps_plain_lines() { + connect(); + s_sent.clear(); + stage_seq("AutoZero", 10); + seq_send(); + loop_once(); + send_line("$A"); // a plain line queued behind it + reply("ALARM:5\n"); + reply("error:9\n"); + ok_all(); + TEST_ASSERT_FALSE(sent("G0 X1")); + TEST_ASSERT_TRUE(sent("$A")); + TEST_ASSERT_TRUE(sent("G90")); + TEST_ASSERT_EQUAL(1, count_sent("G90")); // stopped once, not again on the error +} + +// An error after a sequence has finished is not that sequence's business. +void test_finished_sequence_is_not_stopped_later() { + connect(); + stage_seq("Probe", 2); + seq_send(); + ok_all(); + model_take_error(); + s_sent.clear(); + reply("ALARM:1\n"); + ok_all(); + TEST_ASSERT_FALSE(sent("G90")); + TEST_ASSERT_NULL(model_take_error()); +} + +void test_reset_discards_everything_queued() { + connect(); + s_sent.clear(); + stage_seq("AutoZero", 10); + seq_send(); + loop_once(); // G0 X0 written, 9 queued + send_reset(); + TEST_ASSERT_EQUAL_UINT8(0x18, s_realtime.back()); + reply("Grbl 3.9 [FluidNC v3.9.1 (noradio) '$' for help]\n"); + ok_all(); + TEST_ASSERT_FALSE(sent("G0 X1")); + TEST_ASSERT_TRUE(console_has("reset - 9 queued lines discarded")); + // And the queue is usable straight away, no 2 s wait for a lost ack. + s_sent.clear(); + send_line("$X"); + TEST_ASSERT_TRUE(sent("$X")); +} + +void test_own_reset_keeps_homing_and_reprimes() { + connect(); + reply("\n"); + reply("\n"); + TEST_ASSERT_TRUE(homed()); + s_sent.clear(); + send_reset(); + reply("Grbl 3.9 [FluidNC v3.9.1 (noradio) '$' for help]\n"); + ok_all(); + TEST_ASSERT_TRUE(homed()); + TEST_ASSERT_EQUAL(1, count_sent("$RI=200")); +} + +// The reboot bug: the banner went to handle_signon(), which nothing defined, so +// a restarted controller was never noticed. Position is no longer trusted. +void test_controller_restart_forgets_homing_and_reprimes() { + connect(); + reply("\n"); + reply("\n"); + TEST_ASSERT_TRUE(homed()); + stage_seq("AutoZero", 5); + seq_send(); + loop_once(); + s_sent.clear(); + for (int i = 0; i < 5; i++) { // well past the RESET window, link alive + advance(1000); + reply("\n"); + } + reply("Grbl 3.9 [FluidNC v3.9.1 (noradio) '$' for help]\n"); + ok_all(); + TEST_ASSERT_FALSE(homed()); + TEST_ASSERT_FALSE(sent("G0 X1")); + TEST_ASSERT_EQUAL(1, count_sent("$RI=200")); + TEST_ASSERT_TRUE(console_has("controller restarted")); +} + +// The link-loss bug: nothing ever called the liveness check, so a pulled cable +// left the last state and position on screen as if live. +void test_silence_means_no_link() { + connect(); + reply("\n"); + reply("\n"); + stage_seq("AutoZero", 5); + seq_send(); + loop_once(); + s_realtime.clear(); + advance(3900); + TEST_ASSERT_NOT_EQUAL(Disconnected, state); + int pings = 0; + for (uint8_t c : s_realtime) if (c == '?') pings++; + TEST_ASSERT_TRUE(pings >= 2); + advance(200); + TEST_ASSERT_EQUAL(Disconnected, state); + TEST_ASSERT_FALSE(homed()); + TEST_ASSERT_TRUE(console_has("link lost")); + // Back again: a fresh priming, and nothing from before the drop is sent. + s_sent.clear(); + connect(); + TEST_ASSERT_FALSE(sent("G0 X1")); + TEST_ASSERT_EQUAL(1, count_sent("$RI=200")); +} + +void test_quiet_but_answering_controller_stays_connected() { + connect(); + for (int i = 0; i < 20; i++) { + advance(1000); + reply("\n"); // answers each ping + } + TEST_ASSERT_EQUAL(Idle, state); +} + +int main(int, char**) { + UNITY_BEGIN(); + RUN_TEST(test_connect_primes_once); + RUN_TEST(test_long_sequence_arrives_whole_and_in_order); + RUN_TEST(test_sequence_refused_without_link); + RUN_TEST(test_error_stops_the_sequence_and_sends_cleanup); + RUN_TEST(test_alarm_stops_the_sequence_but_keeps_plain_lines); + RUN_TEST(test_finished_sequence_is_not_stopped_later); + RUN_TEST(test_reset_discards_everything_queued); + RUN_TEST(test_own_reset_keeps_homing_and_reprimes); + RUN_TEST(test_controller_restart_forgets_homing_and_reprimes); + RUN_TEST(test_silence_means_no_link); + RUN_TEST(test_quiet_but_answering_controller_stays_connected); + return UNITY_END(); +} diff --git a/test/test_link/sources b/test/test_link/sources new file mode 100644 index 0000000..44fd726 --- /dev/null +++ b/test/test_link/sources @@ -0,0 +1,19 @@ +# The real send queue, parser glue and link lifecycle, against a scripted +# controller. Everything here runs on the panel unmodified. +src/model/FluidNCModel.cpp +src/model/model_events.cpp +src/model/model_compat.cpp +src/model/console_log.cpp +src/model/caps.cpp +src/model/filelist.cpp +src/model/fnc_settings.cpp +src/model/fnc_codes.cpp +src/model/offsets.cpp +src/model/homed.cpp +src/model/motors.cpp +src/model/toolchange.cpp +src/model/sendq.cpp +src/model/linkwatch.cpp +src/model/path_loader.cpp +src/model/gcode_stats.cpp +src/transport/xmodem_rx.cpp diff --git a/test/test_linkwatch/main.cpp b/test/test_linkwatch/main.cpp new file mode 100644 index 0000000..d8f2014 --- /dev/null +++ b/test/test_linkwatch/main.cpp @@ -0,0 +1,73 @@ +#include +#include "model/linkwatch.h" + +void setUp() { linkwatch_reset(); } +void tearDown() {} + +// Run the watch from t0 to t1 in 10 ms steps with a fixed counter, counting +// what it asked for. +static int pings, losts; +static void run(uint32_t t0, uint32_t t1, unsigned long rx, bool connected = true) { + pings = losts = 0; + for (uint32_t t = t0; t <= t1; t += 10) { + linkwatch_t a = linkwatch_tick(t, rx, connected); + if (a == LINKWATCH_PING) pings++; + if (a == LINKWATCH_LOST) losts++; + } +} + +void test_traffic_keeps_it_quiet() { + for (uint32_t t = 0; t < 20000; t += 10) { + TEST_ASSERT_EQUAL(LINKWATCH_OK, linkwatch_tick(t, t / 500, true)); // a byte every 0.5 s + } +} + +void test_silence_pings_then_declares_loss() { + run(0, 3990, 100); + TEST_ASSERT_EQUAL(3, pings); // at 1, 2 and 3 s + TEST_ASSERT_EQUAL(0, losts); + TEST_ASSERT_EQUAL(LINKWATCH_LOST, linkwatch_tick(4000, 100, true)); +} + +// The caller marks the link down on LOST; from then on nothing more is said +// until it comes back. +void test_loss_is_reported_once() { + run(0, 4000, 100); + TEST_ASSERT_EQUAL(1, losts); + run(4010, 20000, 100, false); + TEST_ASSERT_EQUAL(0, losts); +} + +void test_a_reply_to_the_ping_resets_the_window() { + run(0, 1500, 100); + TEST_ASSERT_EQUAL(1, pings); + run(1510, 5000, 101); // the controller answered at 1.51 s + TEST_ASSERT_EQUAL(0, losts); +} + +// While the panel already shows NO LINK there is nothing to lose, and coming +// back up must not inherit the old silence. +void test_disconnected_never_reports_loss() { + run(0, 20000, 100, false); + TEST_ASSERT_EQUAL(0, losts); + TEST_ASSERT_EQUAL(0, pings); + run(20010, 23990, 100, true); // up again: a full window before any verdict + TEST_ASSERT_EQUAL(0, losts); +} + +void test_clock_wraparound() { + const uint32_t t0 = 0xFFFFF000u; + TEST_ASSERT_EQUAL(LINKWATCH_OK, linkwatch_tick(t0, 5, true)); + TEST_ASSERT_EQUAL(LINKWATCH_LOST, linkwatch_tick(t0 + 4000, 5, true)); // wraps past zero +} + +int main(int, char**) { + UNITY_BEGIN(); + RUN_TEST(test_traffic_keeps_it_quiet); + RUN_TEST(test_silence_pings_then_declares_loss); + RUN_TEST(test_loss_is_reported_once); + RUN_TEST(test_a_reply_to_the_ping_resets_the_window); + RUN_TEST(test_disconnected_never_reports_loss); + RUN_TEST(test_clock_wraparound); + return UNITY_END(); +} diff --git a/test/test_sendq/main.cpp b/test/test_sendq/main.cpp index 2274cc9..d125c7e 100644 --- a/test/test_sendq/main.cpp +++ b/test/test_sendq/main.cpp @@ -95,6 +95,97 @@ void test_null_push_is_rejected() { TEST_ASSERT_EQUAL_UINT(0, sendq_count(&q)); } +static void expect_pop_seq(const char* want, sendq_seq_t want_seq) { + char out[SENDQ_LINE]; + sendq_seq_t seq = 99; + TEST_ASSERT_TRUE(sendq_pop_seq(&q, out, sizeof(out), &seq)); + TEST_ASSERT_EQUAL_STRING(want, out); + TEST_ASSERT_EQUAL_UINT16(want_seq, seq); +} + +// AutoZero is 28 lines. It used to go out one send_line() at a time into 16 +// slots, so the last 11 -- the Y walls, the G10 and the lift out of the pocket +// -- were dropped and the bit stayed in the plate. +void test_autozero_sized_sequence_fits_an_empty_queue() { + const char* lines[28]; + for (int i = 0; i < 28; i++) lines[i] = "G38.2 Z-5 F75"; + TEST_ASSERT_TRUE(sendq_push_all(&q, lines, 28, 1)); + TEST_ASSERT_EQUAL_UINT(28, sendq_count(&q)); +} + +void test_sequence_is_all_or_nothing() { + push_n(SENDQ_SLOTS - 2); + const char* lines[] = { "G91", "G0 X1", "G90" }; + TEST_ASSERT_FALSE(sendq_push_all(&q, lines, 3, 7)); + TEST_ASSERT_EQUAL_UINT(SENDQ_SLOTS - 2, sendq_count(&q)); // nothing half-queued + TEST_ASSERT_EQUAL_UINT32(0, sendq_dropped(&q)); // refused, not dropped + char out[SENDQ_LINE]; + TEST_ASSERT_TRUE(sendq_pop(&q, out, sizeof(out))); + TEST_ASSERT_TRUE(sendq_push_all(&q, lines, 3, 7)); +} + +void test_sequence_rejects_seq_zero_and_null_lines() { + const char* lines[] = { "G91", nullptr }; + TEST_ASSERT_FALSE(sendq_push_all(&q, lines, 1, 0)); + TEST_ASSERT_FALSE(sendq_push_all(&q, lines, 2, 3)); + TEST_ASSERT_EQUAL_UINT(0, sendq_count(&q)); +} + +void test_pop_reports_sequence() { + sendq_push(&q, "$#"); + const char* lines[] = { "G91", "G90" }; + sendq_push_all(&q, lines, 2, 5); + expect_pop_seq("$#", 0); + expect_pop_seq("G91", 5); + expect_pop_seq("G90", 5); +} + +// An error inside a sequence drops the rest of THAT sequence; plain lines and +// other sequences around it keep their order. +void test_drop_one_sequence_keeps_the_rest_in_order() { + const char* a[] = { "A1", "A2" }; + const char* b[] = { "B1", "B2" }; + sendq_push(&q, "P1"); + sendq_push_all(&q, a, 2, 1); + sendq_push(&q, "P2"); + sendq_push_all(&q, b, 2, 2); + TEST_ASSERT_EQUAL_INT(2, sendq_drop_seq(&q, 1)); + expect_pop_seq("P1", 0); + expect_pop_seq("P2", 0); + expect_pop_seq("B1", 2); + expect_pop_seq("B2", 2); + TEST_ASSERT_EQUAL_UINT(0, sendq_count(&q)); +} + +void test_drop_all_sequences_keeps_plain_lines() { + const char* a[] = { "A1", "A2" }; + sendq_push_all(&q, a, 2, 1); + sendq_push(&q, "$A"); + TEST_ASSERT_EQUAL_INT(2, sendq_drop_all_seqs(&q)); + expect_pop_seq("$A", 0); +} + +// Compaction across the end of the ring. +void test_drop_across_wraparound() { + char out[SENDQ_LINE]; + push_n(SENDQ_SLOTS - 3); + for (int i = 0; i < SENDQ_SLOTS - 3; i++) sendq_pop(&q, out, sizeof(out)); + const char* a[] = { "A1", "A2", "A3", "A4", "A5" }; + sendq_push(&q, "P1"); + sendq_push_all(&q, a, 5, 9); + sendq_push(&q, "P2"); + TEST_ASSERT_EQUAL_INT(5, sendq_drop_seq(&q, 9)); + expect_pop_seq("P1", 0); + expect_pop_seq("P2", 0); + TEST_ASSERT_EQUAL_UINT(0, sendq_count(&q)); +} + +void test_drop_seq_zero_is_a_no_op() { + sendq_push(&q, "P1"); + TEST_ASSERT_EQUAL_INT(0, sendq_drop_seq(&q, 0)); + TEST_ASSERT_EQUAL_UINT(1, sendq_count(&q)); +} + int main(int, char**) { UNITY_BEGIN(); RUN_TEST(test_empty_pop_fails); @@ -105,5 +196,13 @@ int main(int, char**) { RUN_TEST(test_recovers_after_pop); RUN_TEST(test_long_line_truncates_and_terminates); RUN_TEST(test_null_push_is_rejected); + RUN_TEST(test_autozero_sized_sequence_fits_an_empty_queue); + RUN_TEST(test_sequence_is_all_or_nothing); + RUN_TEST(test_sequence_rejects_seq_zero_and_null_lines); + RUN_TEST(test_pop_reports_sequence); + RUN_TEST(test_drop_one_sequence_keeps_the_rest_in_order); + RUN_TEST(test_drop_all_sequences_keeps_plain_lines); + RUN_TEST(test_drop_across_wraparound); + RUN_TEST(test_drop_seq_zero_is_a_no_op); return UNITY_END(); } diff --git a/test/test_toolchange/main.cpp b/test/test_toolchange/main.cpp index 19a9506..f2cc287 100644 --- a/test/test_toolchange/main.cpp +++ b/test/test_toolchange/main.cpp @@ -59,6 +59,18 @@ void test_current_tool_reply() { TEST_ASSERT_EQUAL(-1, tc_current()); } +void test_tap_reply_survives_the_job_ending() { + tc_tap_clear(); + TEST_ASSERT_EQUAL(TC_TAP_NONE, tc_tap()); + tc_note_message(" PRINT,TOOLTAP 1"); + TEST_ASSERT_EQUAL(TC_TAP_TOOL, tc_tap()); + tc_clear(); // the Idle edge after the tap + TEST_ASSERT_EQUAL(TC_TAP_TOOL, tc_tap()); + tc_note_message(" PRINT,TOOLTAP 0"); + TEST_ASSERT_EQUAL(TC_TAP_EMPTY, tc_tap()); + TEST_ASSERT_FALSE(tc_pending()); +} + void test_other_messages_ignored() { tc_note_message("uart_channel2 auto report interval set to 200 ms"); tc_note_message(" MSG, TLO Z reset to 0"); @@ -75,6 +87,7 @@ int main() { RUN_TEST(test_hand_tool_t0_is_a_real_request); RUN_TEST(test_removal_before_a_rack_pickup); RUN_TEST(test_current_tool_reply); + RUN_TEST(test_tap_reply_survives_the_job_ending); RUN_TEST(test_other_messages_ignored); return UNITY_END(); }