// ============================================================================ // SCPI text commands on the USB port (fw ≥1.18) // // The board's USB CDC port speaks two languages, chosen per line: // * GCSP bridge lines " <0|1> [hex payload]" (Python library) // * SCPI text lines "MOVE:ABS 1,90", "POS? 1", "ON" (LabVIEW / VISA) // so LabVIEW can drive this board, and every node on its CAN bus, through // plain NI-VISA serial with no host software. // // Port modes (serialMode): // SER_AUTO after boot: nothing is printed (no boot banner, no CAN frames), // so the first VISA read is the reply to the first command // SER_GCSP entered by any GCSP line or the word "GCSP": classic bridge, // every CAN frame and '#' debug line is printed (fw ≤1.17 behavior) // SER_SCPI entered by any SCPI line: only SCPI replies are printed // // Command set and replies match the host gateway canstepper/scpi.py, see // "NEMA 17 LabVIEW/LabVIEW_Integration_Guide.md". Differences: ACK is on by // default (every command answers OK / ERROR), node defaults to this board for // ON / OFF / ON?, and one serial client means one error queue. // // This file is included by GrafitoCANStepper_C3.ino; it uses its statics. // ============================================================================ #pragma once #include #include static void coreService(); // GrafitoCANStepper_C3.ino: one loop() pass minus serial // ---- small helpers --------------------------------------------------------- static void fmtNum(char *out, size_t n, double v) { if (!isfinite(v)) { snprintf(out, n, "NAN"); return; } snprintf(out, n, "%.6f", v); char *e = out + strlen(out) - 1; while (e > out && *e == '0') *e-- = 0; if (e > out && *e == '.') *e = 0; if (strcmp(out, "-0") == 0) strcpy(out, "0"); } static bool hexToken(const char *s) { if (!s || !*s) return false; for (; *s; s++) if (!isxdigit((unsigned char)*s)) return false; return true; } // True when the line looks like a GCSP bridge line (" <0|1> [hex]"). static bool looksLikeGcsp(const char *line) { char tmp[24]; const char *p = line; while (*p == ' ' || *p == '\t') p++; size_t i = 0; while (*p && *p != ' ' && *p != '\t' && i < sizeof(tmp) - 1) tmp[i++] = *p++; tmp[i] = 0; if (!hexToken(tmp) || i > 3) return false; while (*p == ' ' || *p == '\t') p++; if ((p[0] != '0' && p[0] != '1') || (p[1] != 0 && p[1] != ' ' && p[1] != '\t')) return false; p++; while (*p == ' ' || *p == '\t') p++; i = 0; while (*p && *p != ' ' && *p != '\t' && i < sizeof(tmp) - 1) tmp[i++] = *p++; tmp[i] = 0; return i == 0 || hexToken(tmp); } // ---- error queue ------------------------------------------------------------- #define SCPI_ERRQ 16 static int16_t scpiErrCode[SCPI_ERRQ]; static char scpiErrMsg[SCPI_ERRQ][72]; static uint8_t scpiErrN = 0; static void scpiPush(int code, const char *msg) { if (scpiErrN >= SCPI_ERRQ) { scpiErrCode[SCPI_ERRQ - 1] = -350; strcpy(scpiErrMsg[SCPI_ERRQ - 1], "Queue overflow"); return; } scpiErrCode[scpiErrN] = (int16_t)code; strncpy(scpiErrMsg[scpiErrN], msg, sizeof(scpiErrMsg[0]) - 1); scpiErrMsg[scpiErrN][sizeof(scpiErrMsg[0]) - 1] = 0; scpiErrN++; } static void scpiPop(char *out, size_t n) { if (!scpiErrN) { snprintf(out, n, "0,\"No error\""); return; } snprintf(out, n, "%d,\"%s\"", scpiErrCode[0], scpiErrMsg[0]); for (uint8_t i = 1; i < scpiErrN; i++) { scpiErrCode[i - 1] = scpiErrCode[i]; memcpy(scpiErrMsg[i - 1], scpiErrMsg[i], sizeof(scpiErrMsg[0])); } scpiErrN--; } // ---- per-call context ----------------------------------------------------------- struct ScpiCtx { char out[384]; // reply being built (several ';' parts) size_t n; bool failed; // current part failed (error already queued) int errCode; char errMsg[72]; }; static void ctxAppend(ScpiCtx &c, const char *s) { size_t l = strlen(s); if (c.n + l >= sizeof(c.out) - 2) l = sizeof(c.out) - 2 - c.n; memcpy(c.out + c.n, s, l); c.n += l; c.out[c.n] = 0; } static void fail(ScpiCtx &c, int code, const char *fmt, ...) { if (c.failed) return; c.failed = true; c.errCode = code; va_list ap; va_start(ap, fmt); vsnprintf(c.errMsg, sizeof(c.errMsg), fmt, ap); va_end(ap); scpiPush(code, c.errMsg); } // SCPI error codes (negative = standard, positive = device-specific; same as the gateway) enum : int { E_SYNTAX = -102, E_DATA_TYPE = -104, E_TOO_MANY = -108, E_MISSING = -109, E_UNDEFINED = -113, E_RANGE = -222, E_ILLEGAL = -224, E_HARDWARE = -240, E_NO_RESPONSE = 201, E_DISABLED = 202, E_ESTOP = 203, E_REJECTED = 204, E_ALARM_ACTIVE = 207, E_ENDSTOP_ACTIVE = 208, E_NODE_TAKEN = 209, E_NODE_DUPLICATE = 210, E_NODE_BUSY = 211, }; // ---- arguments ---------------------------------------------------------------------- #define SCPI_MAXARG 6 struct Args { char *v[SCPI_MAXARG]; int n; }; static bool aNargs(ScpiCtx &c, const Args &a, int maxn) { if (a.n > maxn) { fail(c, E_TOO_MANY, "Too many parameters (expected %d)", maxn); return false; } return true; } static bool aNum(ScpiCtx &c, const Args &a, int i, const char *name, double *out) { if (i >= a.n || !a.v[i][0]) { fail(c, E_MISSING, "Missing parameter: %s", name); return false; } char *end = nullptr; double v = strtod(a.v[i], &end); if (end == a.v[i] || *end) { fail(c, E_DATA_TYPE, "%s must be numeric", name); return false; } if (!isfinite(v)) { fail(c, E_ILLEGAL, "%s must be finite", name); return false; } *out = v; return true; } static bool aInt(ScpiCtx &c, const Args &a, int i, const char *name, long lo, long hi, long *out) { double v; if (!aNum(c, a, i, name, &v)) return false; if (v != floor(v)) { fail(c, E_DATA_TYPE, "%s must be an integer", name); return false; } if (v < lo || v > hi) { fail(c, E_RANGE, "%s must be %ld..%ld", name, lo, hi); return false; } *out = (long)v; return true; } static bool aBool(ScpiCtx &c, const Args &a, int i, const char *name, bool *out) { if (i >= a.n || !a.v[i][0]) { fail(c, E_MISSING, "Missing parameter: %s", name); return false; } const char *s = a.v[i]; if (!strcasecmp(s, "1") || !strcasecmp(s, "ON") || !strcasecmp(s, "TRUE")) { *out = true; return true; } if (!strcasecmp(s, "0") || !strcasecmp(s, "OFF") || !strcasecmp(s, "FALSE")) { *out = false; return true; } fail(c, E_ILLEGAL, "%s must be 0/1/ON/OFF", name); return false; } static bool aNode(ScpiCtx &c, const Args &a, uint8_t *out) { long v; if (!aInt(c, a, 0, "node", 1, 31, &v)) return false; *out = (uint8_t)v; return true; } // ---- mnemonic matching (SCPI short / long form) ------------------------------------------ static bool mnemMatch(const char *tok, size_t tl, const char *pat, size_t pl) { char shortForm[16]; size_t sn = 0; for (size_t i = 0; i < pl && sn < sizeof(shortForm) - 1; i++) if (!islower((unsigned char)pat[i])) shortForm[sn++] = pat[i]; if (tl == sn && !strncasecmp(tok, shortForm, sn)) return true; return tl == pl && !strncasecmp(tok, pat, pl); } static bool headerMatch(const char *hdr, const char *pat) { for (;;) { const char *he = strchr(hdr, ':'); size_t hl = he ? (size_t)(he - hdr) : strlen(hdr); const char *pe = strchr(pat, ':'); size_t pl = pe ? (size_t)(pe - pat) : strlen(pat); if (!mnemMatch(hdr, hl, pat, pl)) return false; if (!he && !pe) return true; if (!he || !pe) return false; hdr = he + 1; pat = pe + 1; } } // ---- node access: local board or a remote node on CAN ------------------------------------------ static float scpiTimeoutS = 0.5f; static void canTx(uint8_t node, uint8_t msg, bool rtr, const void *d, uint8_t len) { twai_message_t m; memset(&m, 0, sizeof(m)); m.identifier = ((uint32_t)node << 6) | msg; m.rtr = rtr ? 1 : 0; m.data_length_code = rtr ? 8 : (len > 8 ? 8 : len); if (!rtr && d && len) memcpy(m.data, d, m.data_length_code); twai_transmit(&m, pdMS_TO_TICKS(2)); } // Send a GCSP command to node (0 = broadcast, includes this board). static void nodeCmd(uint8_t node, uint8_t cmd, const void *d = nullptr, uint8_t len = 0) { if (node == 0 || node == nodeId) handleCommand(cmd, (const uint8_t *)d, len); if (node != nodeId) canTx(node, cmd, false, d, len); } // Awaited reply from a remote node (filled by scpiOnFrame from the CAN RX path). static bool awActive = false, awGot = false; static uint8_t awNode = 0, awMsg = 0; static int16_t awParam = -1; static uint8_t awData[8], awLen = 0; static uint32_t nodesSeen = 0; // SYST:NODE duplicate check: distinct STATUS payloads (bytes 1..7) heard from one node ID. static uint8_t dupNode = 0, dupN = 0, dupPay[3][7]; static uint32_t ownIdHeardMs = 0; // last CAN frame from another board using our own ID // Waits while keeping the control loop, CAN and the serial e-stop path alive. static void scpiPollSerial(); static void scpiIdle() { coreService(); scpiPollSerial(); delay(1); } static bool awaitFrame(uint32_t ms) { uint32_t t0 = millis(); while (!awGot && (uint32_t)(millis() - t0) < ms) scpiIdle(); awActive = false; return awGot; } static bool nodeFetch(ScpiCtx &c, uint8_t node, uint8_t tel, uint8_t *out) { if (node == nodeId) { switch (tel) { case TEL_STATUS: buildStatus(out); return true; case TEL_POSITION: { encoderUpdate(); double d = encoderDeg(); memcpy(out, &d, 8); return true; } case TEL_MOTION: buildMotion(out); return true; case TEL_TARGET: memcpy(out, &targetDeg, 8); return true; case TEL_DRIVER: buildDriver(out); return true; case TEL_ENV: buildEnv(out); return true; case TEL_CAN_HEALTH: buildCanHealth(out); return true; case TEL_ENC_COUNTS: { encoderUpdate(); int64_t v = encCounts; memcpy(out, &v, 8); return true; } default: return false; } } awNode = node; awMsg = tel; awParam = -1; awGot = false; awActive = true; canTx(node, tel, true, nullptr, 0); if (!awaitFrame((uint32_t)(scpiTimeoutS * 1000))) { fail(c, E_NO_RESPONSE, "Node %u not responding", node); return false; } memcpy(out, awData, 8); return true; } // Returns the PARAM status (0 ok, 1 unknown, 2 rejected) or -1 on timeout. static int nodeParam(ScpiCtx &c, uint8_t node, bool set, uint8_t id, ParamValue in, ParamValue *out) { if (node == nodeId) { if (!paramDef(id)) return PS_UNKNOWN; uint8_t st = set ? paramApply(id, in) : PS_OK; if (out) *out = params[id]; return st; } uint8_t p[5] = { id, 0, 0, 0, 0 }; memcpy(p + 1, &in, 4); awNode = node; awMsg = TEL_PARAM; awParam = id; awGot = false; awActive = true; canTx(node, set ? CMD_SET_PARAM : CMD_GET_PARAM, false, p, set ? 5 : 1); if (!awaitFrame((uint32_t)(scpiTimeoutS * 1000))) { fail(c, E_NO_RESPONSE, "Node %u not responding", node); return -1; } if (out) memcpy(out, awData + 2, 4); return awData[1]; } static const char *const PARAM_NAMES[PARAM_MAX + 1] = { "", "node_id", "steps_per_rev", "microsteps", "run_current", "hold_current", "stall_threshold", "invert_dir", "closed_loop", "max_speed", "acceleration", "cl_max_speed", "cl_max_accel", "pid_kp", "pid_ki", "pid_kd", "pid_tolerance", "fast_rate_hz", "slow_rate_hz", "enable_on_boot", "zero_on_boot", "standstill_mode", "endstop_enable", "endstop_active_high", "endstop_action", "homing_current", "homing_backoff", "homing_timeout_ms", "stealthchop", "lut_enable", "cl_max_jerk", "pid_ka", }; static bool setParamF(ScpiCtx &c, uint8_t node, uint8_t id, double value) { const ParamDef *d = paramDef(id); ParamValue v; if (d && d->isFloat) v.f = (float)value; else v.u = (uint32_t)llround(value); int st = nodeParam(c, node, true, id, v, nullptr); if (st < 0) return false; if (st == PS_UNKNOWN) { fail(c, E_ILLEGAL, "Unknown parameter %s", PARAM_NAMES[id]); return false; } if (st == PS_REJECTED) { fail(c, E_REJECTED, "Node %u rejected %s", node, PARAM_NAMES[id]); return false; } return true; } static bool getParamF(ScpiCtx &c, uint8_t node, uint8_t id, double *out) { ParamValue v; v.u = 0; int st = nodeParam(c, node, false, id, v, &v); if (st < 0) return false; if (st != PS_OK) { fail(c, E_ILLEGAL, "Unknown parameter %u", id); return false; } const ParamDef *d = paramDef(id); *out = (d && d->isFloat) ? (double)v.f : (double)v.u; return true; } // ---- status decode -------------------------------------------------------------------------- struct NodeSt { bool enabled, moving, homed, estop, endstop, stall, encOk; uint8_t mode, fault, fwMaj, fwMin; }; static bool nodeStatus(ScpiCtx &c, uint8_t node, NodeSt *s) { uint8_t p[8] = {0}; if (!nodeFetch(c, node, TEL_STATUS, p)) return false; s->enabled = p[0] & 0x01; s->moving = p[0] & 0x02; s->homed = p[0] & 0x04; s->estop = p[0] & 0x08; s->endstop = p[0] & 0x10; s->stall = p[0] & 0x20; s->encOk = p[0] & 0x40; s->mode = p[1]; s->fault = p[2]; s->fwMaj = p[3]; s->fwMin = p[4]; return true; } static bool requireReady(ScpiCtx &c, uint8_t node) { NodeSt s; if (!nodeStatus(c, node, &s)) return false; if (s.estop) { fail(c, E_ESTOP, "Node %u e-stop latched; send ALAR:CLE %u or ENAB %u,1", node, node, node); return false; } if (!s.enabled) { fail(c, E_DISABLED, "Node %u driver disabled; send ENAB %u,1", node, node); return false; } return true; } // ---- units (RAM only, per node) ----------------------------------------------------------------- struct Unit { uint8_t kind; float mmPerRev; }; // 0 DEG, 1 REV, 2 MM static Unit scpiUnits[32]; static double degPerUnit(uint8_t node) { const Unit &u = scpiUnits[node & 31]; if (u.kind == 1) return 360.0; if (u.kind == 2 && u.mmPerRev > 0) return 360.0 / u.mmPerRev; return 1.0; } // ---- motion-completion tracker (armed before the command is sent) ---------------------------------- enum : uint8_t { OC_IDLE, OC_BUSY, OC_JOG, OC_STOPPING, OC_DONE, OC_STOPPED, OC_FAULT, OC_ESTOP, OC_HOMEFAIL, OC_ENDSTOP }; static uint8_t ocState[32], ocKind[32], ocDetail[32]; // kind: 1 move, 2 home static bool ocEndstop[32]; // an endstop hit interrupted the motion static void ocArm(uint8_t node, uint8_t state, uint8_t kind = 0) { node &= 31; ocState[node] = state; ocKind[node] = kind; ocDetail[node] = 0; ocEndstop[node] = false; } static void scpiNoteEvent(uint8_t node, uint8_t evt, uint8_t detail) { node &= 31; bool active = ocState[node] == OC_BUSY || ocState[node] == OC_JOG || ocState[node] == OC_STOPPING; if (evt == EVT_ESTOP) { ocState[node] = OC_ESTOP; return; } if (evt == EVT_FAULT) { ocState[node] = OC_FAULT; ocDetail[node] = detail; return; } if (!active) return; // A move or jog hit the endstop. With endstop_action >= 1 the firmware stops // without MOVE_DONE, so fall back to polling; report-only keeps moving and // still ends with MOVE_DONE. (Endstop homing consumes its own trigger.) if (evt == EVT_ENDSTOP_HIT && ocKind[node] != 2) { ocEndstop[node] = true; if (ocState[node] == OC_BUSY || ocState[node] == OC_JOG) ocState[node] = OC_STOPPING; return; } if (evt == EVT_MOVE_DONE && ocKind[node] == 1) ocState[node] = OC_DONE; else if (evt == EVT_HOMING_DONE && ocKind[node] == 2) ocState[node] = OC_DONE; else if (evt == EVT_HOMING_FAILED && ocKind[node] == 2) { ocState[node] = OC_HOMEFAIL; ocDetail[node] = detail; } } // Called for every CAN frame received (before dispatch). static void scpiOnFrame(uint32_t id, bool rtr, const uint8_t *d, uint8_t len) { if (rtr) return; uint8_t src = (id >> 6) & 0x1F, msg = id & 0x3F; if (msg < 32) return; if (msg == TEL_STATUS) nodesSeen |= (1u << src); if (src == nodeId) ownIdHeardMs = millis() | 1; // our own frames are never received back if (msg == TEL_STATUS && dupNode && src == dupNode && len >= 8) { bool known = false; for (uint8_t i = 0; i < dupN; i++) if (!memcmp(dupPay[i], d + 1, 7)) known = true; if (!known && dupN < 3) memcpy(dupPay[dupN++], d + 1, 7); } if (msg == TEL_EVENT && len >= 2) scpiNoteEvent(src, d[0], d[1]); if (awActive && !awGot && src == awNode && msg == awMsg && (awParam < 0 || (len >= 1 && d[0] == (uint8_t)awParam))) { memset(awData, 0, 8); memcpy(awData, d, len > 8 ? 8 : len); awLen = len; awGot = true; } } static uint32_t ocPollMs[32]; static bool isFinished(ScpiCtx &c, uint8_t node) { uint8_t s = ocState[node]; if (s == OC_IDLE || s == OC_DONE || s == OC_STOPPED || s == OC_FAULT || s == OC_ESTOP || s == OC_HOMEFAIL || s == OC_ENDSTOP) return true; if (s == OC_STOPPING || s == OC_JOG) { // No completion event for stops / velocity: ask the node (rate-limited). if ((uint32_t)(millis() - ocPollMs[node]) < 20) return false; ocPollMs[node] = millis(); NodeSt st; if (!nodeStatus(c, node, &st)) return false; if (st.estop) { ocState[node] = OC_ESTOP; return true; } if (!st.moving && (st.mode == MODE_IDLE || st.mode == MODE_POSITION)) { ocState[node] = ocEndstop[node] ? OC_ENDSTOP : OC_STOPPED; return true; } } return false; } static const char *faultName(uint8_t f) { switch (f) { case FAULT_NONE: return "NONE"; case FAULT_ENCODER: return "ENCODER"; case FAULT_NO_PROGRESS: return "NO_PROGRESS"; case FAULT_HOMING_TIMEOUT: return "HOMING_TIMEOUT"; case FAULT_DRIVER_OT: return "DRIVER_OT"; case FAULT_DRIVER_SHORT: return "DRIVER_SHORT"; case FAULT_HOMING_SWITCH_ACTIVE: return "HOMING_SWITCH_ACTIVE"; default: return "UNKNOWN"; } } static void outcomeText(uint8_t node, char *out, size_t n) { switch (ocState[node]) { case OC_IDLE: snprintf(out, n, "IDLE"); break; case OC_BUSY: snprintf(out, n, "BUSY"); break; case OC_JOG: snprintf(out, n, "JOG"); break; case OC_STOPPING: snprintf(out, n, "STOPPING"); break; case OC_DONE: snprintf(out, n, "DONE"); break; case OC_STOPPED: snprintf(out, n, "STOPPED"); break; case OC_ESTOP: snprintf(out, n, "ESTOP"); break; case OC_FAULT: snprintf(out, n, "FAULT,%u,%s", ocDetail[node], faultName(ocDetail[node])); break; case OC_HOMEFAIL: snprintf(out, n, "HOMING_FAILED,%u", ocDetail[node]); break; case OC_ENDSTOP: snprintf(out, n, "ENDSTOP"); break; } } // ---- alarms ---------------------------------------------------------------------------------------- static const char *alarmName(int a) { switch (a) { case 0: return "NONE"; case 1: return "ENCODER"; case 2: return "NO_PROGRESS"; case 3: return "HOMING_TIMEOUT"; case 4: return "DRIVER_OVERTEMP"; case 5: return "DRIVER_SHORT"; case 6: return "HOMING_SWITCH_ACTIVE"; case 10: return "ESTOP_LATCHED"; case 11: return "STALL"; case 12: return "ENCODER_SIGNAL"; default: return "UNKNOWN"; } } // Fills up to 8 alarm codes, most severe first; returns count or -1 on comms failure. static int nodeAlarms(ScpiCtx &c, uint8_t node, int *codes) { NodeSt s; if (!nodeStatus(c, node, &s)) return -1; int n = 0; if (s.estop) codes[n++] = 10; if (s.fault == 4 || s.fault == 5) codes[n++] = s.fault; if ((s.fault >= 1 && s.fault <= 3) || s.fault == 6) codes[n++] = s.fault; if (s.stall) codes[n++] = 11; if (!s.encOk && s.fault != 1) codes[n++] = 12; if (!s.estop && s.fault != 4 && s.fault != 5) { uint8_t p[8] = {0}; ScpiCtx tmp; memset(&tmp, 0, sizeof(tmp)); if (nodeFetch(tmp, node, TEL_DRIVER, p)) { if (p[2] & 0x04) { memmove(codes + 1, codes, n * sizeof(int)); codes[0] = 4; n++; } else if (p[2] & 0x78) { memmove(codes + 1, codes, n * sizeof(int)); codes[0] = 5; n++; } } else if (tmp.failed) { scpiErrN--; // optional driver read: drop its queued error } } return n; } // ---- command table ------------------------------------------------------------------------------------ typedef void (*ScpiFn)(ScpiCtx &c, Args &a); struct ScpiCmd { const char *pat; bool query; ScpiFn fn; }; static bool scpiAck = true; static void replyNum(ScpiCtx &c, double v) { char b[32]; fmtNum(b, sizeof(b), v); ctxAppend(c, b); } static void replyStr(ScpiCtx &c, const char *s) { ctxAppend(c, s); } // -- common ---- static void cIdn(ScpiCtx &c, Args &a) { if (!aNargs(c, a, 0)) return; char b[96]; snprintf(b, sizeof(b), "Grafito,CANStepper NEMA17,NODE%u,%u.%u", nodeId, FW_MAJOR, FW_MINOR); replyStr(c, b); } static void cRst(ScpiCtx &c, Args &a) { if (!aNargs(c, a, 0)) return; nodeCmd(0, CMD_STOP); memset(scpiUnits, 0, sizeof(scpiUnits)); for (int i = 0; i < 32; i++) if (ocState[i] != OC_IDLE) ocArm(i, OC_STOPPING); } static void cCls(ScpiCtx &c, Args &a) { if (aNargs(c, a, 0)) scpiErrN = 0; } static void cOpc(ScpiCtx &c, Args &a) { replyStr(c, "1"); } static void cWai(ScpiCtx &c, Args &a) {} static void cTst(ScpiCtx &c, Args &a) { replyStr(c, encFrameOk ? "0" : "1"); } // -- system ---- static void cErr(ScpiCtx &c, Args &a) { char b[96]; scpiPop(b, sizeof(b)); replyStr(c, b); } static void cErrCount(ScpiCtx &c, Args &a) { replyNum(c, scpiErrN); } static void cErrAll(ScpiCtx &c, Args &a) { if (!scpiErrN) { replyStr(c, "0,\"No error\""); return; } bool first = true; while (scpiErrN) { char b[96]; scpiPop(b, sizeof(b)); if (!first) replyStr(c, ","); replyStr(c, b); first = false; } } static void cVers(ScpiCtx &c, Args &a) { replyStr(c, "1999.0"); } static void cAck(ScpiCtx &c, Args &a) { bool v; if (aNargs(c, a, 1) && aBool(c, a, 0, "ack", &v)) scpiAck = v; } static void cAckQ(ScpiCtx &c, Args &a) { replyStr(c, scpiAck ? "1" : "0"); } static void cTim(ScpiCtx &c, Args &a) { double v; if (!aNargs(c, a, 1) || !aNum(c, a, 0, "timeout", &v)) return; if (v < 0.05 || v > 10) { fail(c, E_RANGE, "timeout must be 0.05..10 s"); return; } scpiTimeoutS = (float)v; } static void cTimQ(ScpiCtx &c, Args &a) { replyNum(c, scpiTimeoutS); } static void cNodes(ScpiCtx &c, Args &a) { nodesSeen = 0; canTx(0, CMD_PING, false, nullptr, 0); uint32_t t0 = millis(); while ((uint32_t)(millis() - t0) < 300) scpiIdle(); nodesSeen |= (1u << nodeId); bool first = true; for (int i = 1; i < 32; i++) { if (!(nodesSeen & (1u << i))) continue; char b[8]; snprintf(b, sizeof(b), first ? "%d" : ",%d", i); replyStr(c, b); first = false; } } // -- node ID (fw 1.20) ---- // Pings the bus and listens; returns the set of answering nodes. With watch != 0 also // collects the distinct STATUS payloads of that node (two = two boards share the ID). static uint32_t busScan(uint8_t watch, uint32_t ms) { nodesSeen = 0; dupNode = watch; dupN = 0; canTx(0, CMD_PING, false, nullptr, 0); uint32_t t0 = millis(); bool asked = false; while ((uint32_t)(millis() - t0) < ms) { scpiIdle(); if (watch && !asked && (uint32_t)(millis() - t0) >= ms / 2) { canTx(watch, TEL_STATUS, true, nullptr, 0); asked = true; } } dupNode = 0; return nodesSeen; } static void moveNodeState(uint8_t from, uint8_t to) { scpiUnits[to] = scpiUnits[from]; scpiUnits[from] = {0, 0}; ocState[to] = OC_IDLE; ocState[from] = OC_IDLE; } static void renumberLocal(ScpiCtx &c, uint8_t nw) { uint8_t old = nodeId; ParamValue v; v.u = nw; if (paramApply(P_NODE_ID, v) != PS_OK) { fail(c, E_REJECTED, "Node %u rejected node_id %u", old, nw); return; } paramsSaveNvs(); // local only: nothing goes out on the CAN bus moveNodeState(old, nw); } static void renumberRemote(ScpiCtx &c, uint8_t old, uint8_t nw) { uint8_t p[5] = { P_NODE_ID, nw, 0, 0, 0 }; // The node applies the new ID before it acknowledges, so the reply comes from the new ID. awNode = nw; awMsg = TEL_PARAM; awParam = P_NODE_ID; awGot = false; awActive = true; canTx(old, CMD_SET_PARAM, false, p, 5); if (!awaitFrame((uint32_t)(scpiTimeoutS * 1000) + 200)) { fail(c, E_NO_RESPONSE, "Node %u did not confirm the new ID %u", old, nw); return; } if (awData[1] != PS_OK) { fail(c, E_REJECTED, "Node %u rejected node_id %u", old, nw); return; } canTx(nw, CMD_SAVE_CONFIG, false, nullptr, 0); uint32_t t0 = millis(); while ((uint32_t)(millis() - t0) < 150) scpiIdle(); // NVS write on the node uint8_t st[8]; if (!nodeFetch(c, nw, TEL_STATUS, st)) return; if (st[6] != nw) { fail(c, E_REJECTED, "Node reports ID %u after renumbering", st[6]); return; } moveNodeState(old, nw); } // SYST:NODE this board (on USB) only, nothing is sent on the bus // SYST:NODE , any node; the old ID must be unique on the bus static void cNode(ScpiCtx &c, Args &a) { long o, nw; if (!aNargs(c, a, 2)) return; bool two = a.n >= 2 && a.v[1][0]; if (two) { if (!aInt(c, a, 0, "old node", 1, 31, &o) || !aInt(c, a, 1, "new node", 1, 31, &nw)) return; } else { o = nodeId; if (!aInt(c, a, 0, "new node", 1, 31, &nw)) return; } if (o == nw) return; // nothing to do bool local = (o == nodeId); // also the fix when another board shares this board's ID uint32_t seen = busScan(local ? 0 : (uint8_t)o, 400); if (nw == nodeId || (seen & (1u << nw))) { fail(c, E_NODE_TAKEN, "Node %ld already on the bus", nw); return; } if (!local && !(seen & (1u << o))) { fail(c, E_NO_RESPONSE, "Node %ld not responding", o); return; } if (!local && dupN > 1) { fail(c, E_NODE_DUPLICATE, "Two boards answer as node %ld: use SYST:NODE on each", o); return; } NodeSt s; if (!nodeStatus(c, (uint8_t)o, &s)) return; if (s.moving) { fail(c, E_NODE_BUSY, "Node %ld is moving; stop it first", o); return; } if (local) renumberLocal(c, (uint8_t)nw); else renumberRemote(c, (uint8_t)o, (uint8_t)nw); } static void cNodeQ(ScpiCtx &c, Args &a) { if (aNargs(c, a, 0)) replyNum(c, nodeId); } // SYST:NODE:DUPlicate? 1 when another board on the bus uses this board's ID static void cNodeDupQ(ScpiCtx &c, Args &a) { if (!aNargs(c, a, 0)) return; ownIdHeardMs = 0; busScan(0, 300); replyStr(c, ownIdHeardMs ? "1" : "0"); } // -- configuration ---- static void cUnit(ScpiCtx &c, Args &a) { uint8_t n; if (!aNode(c, a, &n)) return; if (a.n < 2 || !a.v[1][0]) { fail(c, E_MISSING, "Missing parameter: unit"); return; } const char *k = a.v[1]; if (mnemMatch(k, strlen(k), "DEGrees", 7)) { if (aNargs(c, a, 2)) scpiUnits[n] = {0, 0}; } else if (mnemMatch(k, strlen(k), "REVolutions", 11)) { if (aNargs(c, a, 2)) scpiUnits[n] = {1, 0}; } else if (!strcasecmp(k, "MM")) { double rd; if (!aNargs(c, a, 3) || !aNum(c, a, 2, "rotation_distance (mm/rev)", &rd)) return; if (rd <= 0) { fail(c, E_RANGE, "rotation_distance must be > 0"); return; } scpiUnits[n] = {2, (float)rd}; } else fail(c, E_ILLEGAL, "unit must be one of DEG|REV|MM"); } static void cUnitQ(ScpiCtx &c, Args &a) { uint8_t n; if (!aNode(c, a, &n)) return; const Unit &u = scpiUnits[n]; if (u.kind == 1) replyStr(c, "REV"); else if (u.kind == 2) { replyStr(c, "MM,"); replyNum(c, u.mmPerRev); } else replyStr(c, "DEG"); } // Value in node units -> one or two firmware params (deg-based). static void unitSet(ScpiCtx &c, Args &a, uint8_t p1, uint8_t p2, bool positive) { uint8_t n; double v; if (!aNode(c, a, &n) || !aNargs(c, a, 2) || !aNum(c, a, 1, "value", &v)) return; if (positive && v <= 0) { fail(c, E_RANGE, "value must be > 0"); return; } if (!positive && v < 0) { fail(c, E_RANGE, "value must be >= 0"); return; } double deg = v * degPerUnit(n); if (!setParamF(c, n, p1, deg)) return; if (p2) setParamF(c, n, p2, deg); } static void unitGet(ScpiCtx &c, Args &a, uint8_t p) { uint8_t n; double v; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !getParamF(c, n, p, &v)) return; replyNum(c, v / degPerUnit(n)); } static void cSpe(ScpiCtx &c, Args &a) { unitSet(c, a, P_MAX_SPEED, P_CL_MAX_SPEED, true); } static void cSpeQ(ScpiCtx &c, Args &a) { unitGet(c, a, P_CL_MAX_SPEED); } static void cAcc(ScpiCtx &c, Args &a) { unitSet(c, a, P_ACCELERATION, P_CL_MAX_ACCEL, true); } static void cAccQ(ScpiCtx &c, Args &a) { unitGet(c, a, P_CL_MAX_ACCEL); } static void cJerk(ScpiCtx &c, Args &a) { unitSet(c, a, P_CL_MAX_JERK, 0, false); } static void cJerkQ(ScpiCtx &c, Args &a){ unitGet(c, a, P_CL_MAX_JERK); } static void cTol(ScpiCtx &c, Args &a) { unitSet(c, a, P_PID_TOLERANCE, 0, true); } static void cTolQ(ScpiCtx &c, Args &a) { unitGet(c, a, P_PID_TOLERANCE); } static void intSet(ScpiCtx &c, Args &a, uint8_t p, long lo, long hi) { uint8_t n; long v; if (!aNode(c, a, &n) || !aNargs(c, a, 2) || !aInt(c, a, 1, "value", lo, hi, &v)) return; if (p == P_MICROSTEPS && (v & (v - 1))) { fail(c, E_ILLEGAL, "microsteps must be a power of 2 (1..256)"); return; } setParamF(c, n, p, (double)v); } static void intGet(ScpiCtx &c, Args &a, uint8_t p) { uint8_t n; double v; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !getParamF(c, n, p, &v)) return; replyNum(c, v); } static void cMicr(ScpiCtx &c, Args &a) { intSet(c, a, P_MICROSTEPS, 1, 256); } static void cMicrQ(ScpiCtx &c, Args &a) { intGet(c, a, P_MICROSTEPS); } static void cStep(ScpiCtx &c, Args &a) { intSet(c, a, P_STEPS_PER_REV, 1, 100000); } static void cStepQ(ScpiCtx &c, Args &a) { intGet(c, a, P_STEPS_PER_REV); } static void cRun(ScpiCtx &c, Args &a) { intSet(c, a, P_RUN_CURRENT, 1, 100); } static void cRunQ(ScpiCtx &c, Args &a) { intGet(c, a, P_RUN_CURRENT); } static void cHold(ScpiCtx &c, Args &a) { intSet(c, a, P_HOLD_CURRENT, 0, 100); } static void cHoldQ(ScpiCtx &c, Args &a) { intGet(c, a, P_HOLD_CURRENT); } static void cClos(ScpiCtx &c, Args &a) { intSet(c, a, P_CLOSED_LOOP, 0, 1); } static void cClosQ(ScpiCtx &c, Args &a) { intGet(c, a, P_CLOSED_LOOP); } static void cDir(ScpiCtx &c, Args &a) { intSet(c, a, P_INVERT_DIR, 0, 1); } static void cDirQ(ScpiCtx &c, Args &a) { intGet(c, a, P_INVERT_DIR); } static void cSte(ScpiCtx &c, Args &a) { intSet(c, a, P_STEALTHCHOP, 0, 1); } static void cSteQ(ScpiCtx &c, Args &a) { intGet(c, a, P_STEALTHCHOP); } static void cStal(ScpiCtx &c, Args &a) { intSet(c, a, P_STALL_THRESHOLD, 0, 255); } static void cStalQ(ScpiCtx &c, Args &a) { intGet(c, a, P_STALL_THRESHOLD); } static void cPid(ScpiCtx &c, Args &a) { uint8_t n; double kp, ki, kd; if (!aNode(c, a, &n) || !aNargs(c, a, 4) || !aNum(c, a, 1, "kp", &kp) || !aNum(c, a, 2, "ki", &ki) || !aNum(c, a, 3, "kd", &kd)) return; if (kp < 0 || ki < 0 || kd < 0) { fail(c, E_RANGE, "PID gains must be >= 0"); return; } if (setParamF(c, n, P_PID_KP, kp) && setParamF(c, n, P_PID_KI, ki)) setParamF(c, n, P_PID_KD, kd); } static void cPidQ(ScpiCtx &c, Args &a) { uint8_t n; double kp, ki, kd; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !getParamF(c, n, P_PID_KP, &kp) || !getParamF(c, n, P_PID_KI, &ki) || !getParamF(c, n, P_PID_KD, &kd)) return; replyNum(c, kp); replyStr(c, ","); replyNum(c, ki); replyStr(c, ","); replyNum(c, kd); } static void cHom(ScpiCtx &c, Args &a) { uint8_t n; long cur; double back, tmo; if (!aNode(c, a, &n) || !aNargs(c, a, 4) || !aInt(c, a, 1, "homing current %", 0, 100, &cur) || !aNum(c, a, 2, "backoff", &back) || !aNum(c, a, 3, "timeout_s", &tmo)) return; if (back < 0) { fail(c, E_RANGE, "backoff must be >= 0"); return; } if (tmo < 0.1 || tmo > 600) { fail(c, E_RANGE, "timeout must be 0.1..600 s"); return; } if (setParamF(c, n, P_HOMING_CURRENT, cur) && setParamF(c, n, P_HOMING_BACKOFF, back * degPerUnit(n))) setParamF(c, n, P_HOMING_TIMEOUT_MS, llround(tmo * 1000)); } static void cHomQ(ScpiCtx &c, Args &a) { uint8_t n; double cur, back, tmo; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !getParamF(c, n, P_HOMING_CURRENT, &cur) || !getParamF(c, n, P_HOMING_BACKOFF, &back) || !getParamF(c, n, P_HOMING_TIMEOUT_MS, &tmo)) return; replyNum(c, cur); replyStr(c, ","); replyNum(c, back / degPerUnit(n)); replyStr(c, ","); replyNum(c, tmo / 1000.0); } static void cEnds(ScpiCtx &c, Args &a) { uint8_t n; bool en, hi; long act; if (!aNode(c, a, &n) || !aNargs(c, a, 4) || !aBool(c, a, 1, "enable", &en) || !aBool(c, a, 2, "active_high", &hi) || !aInt(c, a, 3, "action", 0, 2, &act)) return; if (setParamF(c, n, P_ENDSTOP_ENABLE, en) && setParamF(c, n, P_ENDSTOP_ACTIVE_HIGH, hi)) setParamF(c, n, P_ENDSTOP_ACTION, act); } static void cEndsQ(ScpiCtx &c, Args &a) { uint8_t n; double e, h, x; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !getParamF(c, n, P_ENDSTOP_ENABLE, &e) || !getParamF(c, n, P_ENDSTOP_ACTIVE_HIGH, &h) || !getParamF(c, n, P_ENDSTOP_ACTION, &x)) return; replyNum(c, e); replyStr(c, ","); replyNum(c, h); replyStr(c, ","); replyNum(c, x); } static int paramByName(const char *s) { if (!s || !*s) return -1; bool digits = true; for (const char *p = s; *p; p++) if (!isdigit((unsigned char)*p)) digits = false; if (digits) { int v = atoi(s); return (v >= 1 && v <= PARAM_MAX) ? v : -1; } for (int i = 1; i <= PARAM_MAX; i++) if (!strcasecmp(s, PARAM_NAMES[i])) return i; return -1; } static void cPar(ScpiCtx &c, Args &a) { uint8_t n; double v; if (!aNode(c, a, &n) || !aNargs(c, a, 3)) return; if (a.n < 2 || !a.v[1][0]) { fail(c, E_MISSING, "Missing parameter: name"); return; } int id = paramByName(a.v[1]); if (id < 0) { fail(c, E_ILLEGAL, "unknown parameter name: %s", a.v[1]); return; } if (id == P_NODE_ID) { fail(c, E_ILLEGAL, "node_id cannot be changed over SCPI"); return; } if (!aNum(c, a, 2, "value", &v)) return; const ParamDef *d = paramDef(id); if (d && !d->isFloat && v != floor(v)) { fail(c, E_DATA_TYPE, "%s takes an integer", PARAM_NAMES[id]); return; } setParamF(c, n, id, v); } static void cParQ(ScpiCtx &c, Args &a) { uint8_t n; double v; if (!aNode(c, a, &n) || !aNargs(c, a, 2)) return; if (a.n < 2 || !a.v[1][0]) { fail(c, E_MISSING, "Missing parameter: name"); return; } int id = paramByName(a.v[1]); if (id < 0) { fail(c, E_ILLEGAL, "unknown parameter name: %s", a.v[1]); return; } if (getParamF(c, n, id, &v)) replyNum(c, v); } static void cSave(ScpiCtx &c, Args &a) { uint8_t n; if (aNode(c, a, &n) && aNargs(c, a, 1)) nodeCmd(n, CMD_SAVE_CONFIG); } static void cDef(ScpiCtx &c, Args &a) { uint8_t n; if (aNode(c, a, &n) && aNargs(c, a, 1)) nodeCmd(n, CMD_LOAD_DEFAULTS); } // -- power / safety ---- static void cEnab(ScpiCtx &c, Args &a) { uint8_t n; bool en; if (!aNode(c, a, &n) || !aNargs(c, a, 2) || !aBool(c, a, 1, "state", &en)) return; uint8_t b = en ? 1 : 0; if (!en) ocArm(n, OC_STOPPING); nodeCmd(n, CMD_ENABLE, &b, 1); } static void cEnabQ(ScpiCtx &c, Args &a) { uint8_t n; NodeSt s; if (aNode(c, a, &n) && aNargs(c, a, 1) && nodeStatus(c, n, &s)) replyStr(c, s.enabled ? "1" : "0"); } static void cEnabAll(ScpiCtx &c, Args &a) { bool en; if (!aNargs(c, a, 1) || !aBool(c, a, 0, "state", &en)) return; uint8_t b = en ? 1 : 0; nodeCmd(0, CMD_ENABLE, &b, 1); } static void cStop(ScpiCtx &c, Args &a) { uint8_t n; if (!aNode(c, a, &n) || !aNargs(c, a, 1)) return; ocArm(n, OC_STOPPING); nodeCmd(n, CMD_STOP); } static void cStopAll(ScpiCtx &c, Args &a) { if (!aNargs(c, a, 0)) return; for (int i = 0; i < 32; i++) if (ocState[i] != OC_IDLE) ocArm(i, OC_STOPPING); nodeCmd(0, CMD_STOP); } static void cEstop(ScpiCtx &c, Args &a) { uint8_t n; if (aNode(c, a, &n) && aNargs(c, a, 1)) nodeCmd(n, CMD_ESTOP); } static void cEstopAll(ScpiCtx &c, Args &a) { if (aNargs(c, a, 0)) nodeCmd(0, CMD_ESTOP); } // -- motion ---- static void startMove(ScpiCtx &c, uint8_t n, uint8_t cmd, double deg) { if (!requireReady(c, n)) return; ocArm(n, OC_BUSY, 1); nodeCmd(n, cmd, °, 8); } static void cMoveAbs(ScpiCtx &c, Args &a) { uint8_t n; double v; if (aNode(c, a, &n) && aNargs(c, a, 2) && aNum(c, a, 1, "position", &v)) startMove(c, n, CMD_MOVE_ABS, v * degPerUnit(n)); } static void cMoveRel(ScpiCtx &c, Args &a) { uint8_t n; double v; if (aNode(c, a, &n) && aNargs(c, a, 2) && aNum(c, a, 1, "distance", &v)) startMove(c, n, CMD_MOVE_REL, v * degPerUnit(n)); } static void jogAt(ScpiCtx &c, uint8_t n, double degS) { float f = (float)degS; if (f == 0.0f) { ocArm(n, OC_STOPPING); nodeCmd(n, CMD_MOVE_VEL, &f, 4); return; } if (!requireReady(c, n)) return; ocArm(n, OC_JOG); nodeCmd(n, CMD_MOVE_VEL, &f, 4); } static void cJog(ScpiCtx &c, Args &a) { uint8_t n; double v; if (aNode(c, a, &n) && aNargs(c, a, 2) && aNum(c, a, 1, "velocity", &v)) jogAt(c, n, v * degPerUnit(n)); } static bool optNode(ScpiCtx &c, Args &a, uint8_t *n) { if (a.n == 0 || !a.v[0][0]) { *n = nodeId; return true; } return aNode(c, a, n); } static void cOn(ScpiCtx &c, Args &a) { // ON [node[,speed]]: enable if needed + continuous rotation. Refuses a latched e-stop. uint8_t n; if (!optNode(c, a, &n) || !aNargs(c, a, 2)) return; double speed = 90.0 / degPerUnit(n); if (a.n > 1 && a.v[1][0]) { if (!aNum(c, a, 1, "speed", &speed)) return; if (speed == 0) { fail(c, E_RANGE, "speed must be non-zero"); return; } } NodeSt s; if (!nodeStatus(c, n, &s)) return; if (s.estop) { fail(c, E_ESTOP, "Node %u e-stop latched; send ALAR:CLE %u first", n, n); return; } if (!s.enabled) { uint8_t b = 1; nodeCmd(n, CMD_ENABLE, &b, 1); } float f = (float)(speed * degPerUnit(n)); ocArm(n, OC_JOG); nodeCmd(n, CMD_MOVE_VEL, &f, 4); } static void cOff(ScpiCtx &c, Args &a) { uint8_t n; if (!optNode(c, a, &n) || !aNargs(c, a, 1)) return; ocArm(n, OC_STOPPING); nodeCmd(n, CMD_STOP); } static void cOnQ(ScpiCtx &c, Args &a) { uint8_t n; NodeSt s; if (optNode(c, a, &n) && aNargs(c, a, 1) && nodeStatus(c, n, &s)) replyStr(c, s.moving ? "1" : "0"); } static void cHome(ScpiCtx &c, Args &a) { // HOME n,ENDStop|STALlguard|SENSorless|ZERO[,dir[,speed]] uint8_t n; if (!aNode(c, a, &n) || !aNargs(c, a, 4)) return; if (a.n < 2 || !a.v[1][0]) { fail(c, E_MISSING, "Missing parameter: method"); return; } const char *m = a.v[1]; size_t ml = strlen(m); uint8_t method; if (mnemMatch(m, ml, "ENDStop", 7)) method = 1; else if (mnemMatch(m, ml, "STALlguard", 10) || mnemMatch(m, ml, "SENSorless", 10)) method = 2; else if (!strcasecmp(m, "ZERO")) method = 0; else { fail(c, E_ILLEGAL, "method must be one of ENDSTOP|STALLGUARD|SENSORLESS|ZERO"); return; } int8_t dir = -1; if (a.n > 2 && a.v[2][0]) { double d; if (!aNum(c, a, 2, "direction", &d)) return; if (d != 1 && d != -1) { fail(c, E_ILLEGAL, "direction must be -1 or 1"); return; } dir = (int8_t)d; } // StallGuard reads "stalled" on a free shaft below ~45 deg/s (see // STALL_HOME_MIN_DEG_S in the .ino), so sensorless homing defaults faster. double speed = (method == 2 ? 90.0 : 30.0) / degPerUnit(n); if (a.n > 3 && a.v[3][0]) { if (!aNum(c, a, 3, "speed", &speed)) return; if (speed <= 0) { fail(c, E_RANGE, "speed must be > 0"); return; } } if (method == 2 && speed * degPerUnit(n) < 59.999) { char mn[24]; fmtNum(mn, sizeof(mn), 60.0 / degPerUnit(n)); fail(c, E_RANGE, "StallGuard homing needs speed >= %s units/s (60 deg/s)", mn); return; } if (!requireReady(c, n)) return; if (method == 1) { NodeSt s; if (!nodeStatus(c, n, &s)) return; if (s.endstop) { fail(c, E_ENDSTOP_ACTIVE, "Node %u endstop active: pressed, unwired or wrong polarity (CONF:ENDS)", n); return; } } uint8_t p[6]; p[0] = method; p[1] = (uint8_t)dir; float f = (float)(speed * degPerUnit(n)); memcpy(p + 2, &f, 4); ocArm(n, OC_BUSY, 2); nodeCmd(n, CMD_HOME, p, 6); } static void cHomeQ(ScpiCtx &c, Args &a) { uint8_t n; NodeSt s; if (aNode(c, a, &n) && aNargs(c, a, 1) && nodeStatus(c, n, &s)) replyStr(c, s.homed ? "1" : "0"); } // HOMING_FAILED, -> HOMING_FAILED,, (reason = the node's fault name, // e.g. HOMING_TIMEOUT or HOMING_SWITCH_ACTIVE). Best effort: unchanged if the status read fails. static void homeFailReason(ScpiCtx &c, uint8_t n, char *b, size_t sz) { if (ocState[n] != OC_HOMEFAIL) return; NodeSt s; ScpiCtx tmp; memset(&tmp, 0, sizeof(tmp)); if (nodeStatus(tmp, n, &s) && s.fault) { size_t l = strlen(b); snprintf(b + l, sz - l, ",%s", faultName(s.fault)); } else if (tmp.failed) { scpiErrN--; // optional read: drop its queued error } } static void cDone(ScpiCtx &c, Args &a) { uint8_t n; if (!aNode(c, a, &n) || !aNargs(c, a, 1)) return; ocPollMs[n] = millis() - 1000; bool f = isFinished(c, n); if (!c.failed) replyStr(c, f ? "1" : "0"); } static void cWait(ScpiCtx &c, Args &a) { uint8_t n; double tmo = 30; if (!aNode(c, a, &n) || !aNargs(c, a, 2)) return; if (a.n > 1 && a.v[1][0] && !aNum(c, a, 1, "timeout_s", &tmo)) return; if (tmo < 0 || tmo > 3600) { fail(c, E_RANGE, "timeout must be 0..3600 s"); return; } uint32_t t0 = millis(), ms = (uint32_t)(tmo * 1000); ocPollMs[n] = t0 - 1000; for (;;) { bool f = isFinished(c, n); if (c.failed) return; if (f) { char b[64]; outcomeText(n, b, sizeof(b)); homeFailReason(c, n, b, sizeof(b)); replyStr(c, b); return; } if ((uint32_t)(millis() - t0) >= ms) { replyStr(c, "TIMEOUT"); return; } scpiIdle(); } } static void cMoveStat(ScpiCtx &c, Args &a) { uint8_t n; if (!aNode(c, a, &n) || !aNargs(c, a, 1)) return; ocPollMs[n] = millis() - 1000; isFinished(c, n); if (c.failed) return; char b[64]; outcomeText(n, b, sizeof(b)); homeFailReason(c, n, b, sizeof(b)); replyStr(c, b); } static void cZero(ScpiCtx &c, Args &a) { uint8_t n; if (aNode(c, a, &n) && aNargs(c, a, 1)) nodeCmd(n, CMD_SET_ZERO); } static void cPosSet(ScpiCtx &c, Args &a) { uint8_t n; double v; if (!aNode(c, a, &n) || !aNargs(c, a, 2) || !aNum(c, a, 1, "position", &v)) return; double deg = v * degPerUnit(n); nodeCmd(n, CMD_SET_POSITION, °, 8); } // -- read-back ---- static void readF64(ScpiCtx &c, Args &a, uint8_t tel) { uint8_t n, p[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeFetch(c, n, tel, p)) return; double d; memcpy(&d, p, 8); replyNum(c, d / degPerUnit(n)); } static void cPos(ScpiCtx &c, Args &a) { readF64(c, a, TEL_POSITION); } static void cTarg(ScpiCtx &c, Args &a) { readF64(c, a, TEL_TARGET); } static void motionPart(ScpiCtx &c, Args &a, int which) { uint8_t n, p[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeFetch(c, n, TEL_MOTION, p)) return; float v; memcpy(&v, p + 4 * which, 4); replyNum(c, v / degPerUnit(n)); } static void cVel(ScpiCtx &c, Args &a) { motionPart(c, a, 0); } static void cPosErr(ScpiCtx &c, Args &a) { motionPart(c, a, 1); } static void cCounts(ScpiCtx &c, Args &a) { uint8_t n, p[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeFetch(c, n, TEL_ENC_COUNTS, p)) return; int64_t v; memcpy(&v, p, 8); char b[24]; snprintf(b, sizeof(b), "%lld", (long long)v); replyStr(c, b); } static void cStat(ScpiCtx &c, Args &a) { uint8_t n; NodeSt s; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeStatus(c, n, &s)) return; char b[48]; snprintf(b, sizeof(b), "%d,%d,%d,%d,%d,%d,%d,%u,%u", s.enabled, s.moving, s.homed, s.estop, s.endstop, s.stall, s.encOk, s.mode, s.fault); replyStr(c, b); } static void cMode(ScpiCtx &c, Args &a) { static const char *const names[] = { "IDLE", "POSITION", "VELOCITY", "HOMING", "FOLLOW", "LUT", "OTA" }; uint8_t n; NodeSt s; if (aNode(c, a, &n) && aNargs(c, a, 1) && nodeStatus(c, n, &s)) replyStr(c, s.mode <= 6 ? names[s.mode] : "UNKNOWN"); } static void cFault(ScpiCtx &c, Args &a) { uint8_t n; NodeSt s; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeStatus(c, n, &s)) return; char b[32]; snprintf(b, sizeof(b), "%u,%s", s.fault, faultName(s.fault)); replyStr(c, b); } static void cFirm(ScpiCtx &c, Args &a) { uint8_t n; NodeSt s; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeStatus(c, n, &s)) return; char b[16]; snprintf(b, sizeof(b), "%u.%u", s.fwMaj, s.fwMin); replyStr(c, b); } static void cDriv(ScpiCtx &c, Args &a) { // uart_ok,otpw,ot,short,open_load,cs_actual,stallguard uint8_t n, p[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeFetch(c, n, TEL_DRIVER, p)) return; uint16_t sg; memcpy(&sg, p, 2); char b[48]; snprintf(b, sizeof(b), "%d,%d,%d,%d,%d,%u,%u", (p[2] & 0x01) != 0, (p[2] & 0x02) != 0, (p[2] & 0x04) != 0, (p[2] & 0x78) != 0, ((p[2] & 0x80) | (p[3] & 0x01)) != 0, p[5], sg); replyStr(c, b); } static void cTemp(ScpiCtx &c, Args &a) { uint8_t n, p[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeFetch(c, n, TEL_ENV, p)) return; float t; memcpy(&t, p, 4); replyNum(c, t); } static void cCan(ScpiCtx &c, Args &a) { uint8_t n, p[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1) || !nodeFetch(c, n, TEL_CAN_HEALTH, p)) return; uint16_t txf, bus; memcpy(&txf, p + 4, 2); memcpy(&bus, p + 6, 2); char b[48]; snprintf(b, sizeof(b), "%u,%u,%u,%u,%u,%u", p[0], p[1], p[2], p[3], txf, bus); replyStr(c, b); } // -- alarms ---- static void cAlar(ScpiCtx &c, Args &a) { uint8_t n; int codes[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1)) return; int k = nodeAlarms(c, n, codes); if (k < 0) return; int code = k ? codes[0] : 0; char b[32]; snprintf(b, sizeof(b), "%d,%s", code, alarmName(code)); replyStr(c, b); } static void cAlarList(ScpiCtx &c, Args &a) { uint8_t n; int codes[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1)) return; int k = nodeAlarms(c, n, codes); if (k < 0) return; if (!k) { replyStr(c, "NONE"); return; } for (int i = 0; i < k; i++) { if (i) replyStr(c, ","); replyStr(c, alarmName(codes[i])); } } static void cAlarCle(ScpiCtx &c, Args &a) { // Ramped stop, re-enable (clears the e-stop latch and TMC OT/short latches); // encoder / no-progress faults clear on the next move. uint8_t n; int codes[8]; if (!aNode(c, a, &n) || !aNargs(c, a, 1)) return; uint8_t one = 1; nodeCmd(n, CMD_STOP); nodeCmd(n, CMD_ENABLE, &one, 1); ocArm(n, OC_IDLE); uint32_t t0 = millis(); while ((uint32_t)(millis() - t0) < 50) scpiIdle(); int k = nodeAlarms(c, n, codes); if (k < 0) return; char names[64] = ""; int left = 0; for (int i = 0; i < k; i++) { if (codes[i] == 2 || codes[i] == 3 || codes[i] == 6 || codes[i] == 11) continue; if (left++) strncat(names, ",", sizeof(names) - strlen(names) - 1); strncat(names, alarmName(codes[i]), sizeof(names) - strlen(names) - 1); } if (left) fail(c, E_ALARM_ACTIVE, "Node %u alarm still active: %s", n, names); } static const ScpiCmd SCPI_CMDS[] = { {"*IDN", true, cIdn}, {"*RST", false, cRst}, {"*CLS", false, cCls}, {"*OPC", true, cOpc}, {"*WAI", false, cWai}, {"*TST", true, cTst}, {"SYSTem:ERRor", true, cErr}, {"SYSTem:ERRor:NEXT", true, cErr}, {"SYSTem:ERRor:COUNt", true, cErrCount}, {"SYSTem:ERRor:ALL", true, cErrAll}, {"SYSTem:VERSion", true, cVers}, {"SYSTem:ACK", false, cAck}, {"SYSTem:ACK", true, cAckQ}, {"SYSTem:TIMeout", false, cTim}, {"SYSTem:TIMeout", true, cTimQ}, {"SYSTem:NODes", true, cNodes}, {"SYSTem:NODE", false, cNode}, {"SYSTem:NODE", true, cNodeQ}, {"SYSTem:NODE:DUPlicate", true, cNodeDupQ}, {"CONFigure:UNIT", false, cUnit}, {"CONFigure:UNIT", true, cUnitQ}, {"CONFigure:SPEed", false, cSpe}, {"CONFigure:SPEed", true, cSpeQ}, {"CONFigure:ACCeleration", false, cAcc}, {"CONFigure:ACCeleration", true, cAccQ}, {"CONFigure:DECeleration", false, cAcc}, {"CONFigure:DECeleration", true, cAccQ}, {"CONFigure:JERK", false, cJerk}, {"CONFigure:JERK", true, cJerkQ}, {"CONFigure:TOLerance", false, cTol}, {"CONFigure:TOLerance", true, cTolQ}, {"CONFigure:MICRosteps", false, cMicr}, {"CONFigure:MICRosteps", true, cMicrQ}, {"CONFigure:STEPs", false, cStep}, {"CONFigure:STEPs", true, cStepQ}, {"CONFigure:CURRent:RUN", false, cRun}, {"CONFigure:CURRent:RUN", true, cRunQ}, {"CONFigure:CURRent:HOLD", false, cHold}, {"CONFigure:CURRent:HOLD", true, cHoldQ}, {"CONFigure:CLOSedloop", false, cClos}, {"CONFigure:CLOSedloop", true, cClosQ}, {"CONFigure:DIRection", false, cDir}, {"CONFigure:DIRection", true, cDirQ}, {"CONFigure:STEalthchop", false, cSte}, {"CONFigure:STEalthchop", true, cSteQ}, {"CONFigure:STALl", false, cStal}, {"CONFigure:STALl", true, cStalQ}, {"CONFigure:PID", false, cPid}, {"CONFigure:PID", true, cPidQ}, {"CONFigure:HOMing", false, cHom}, {"CONFigure:HOMing", true, cHomQ}, {"CONFigure:ENDStop", false, cEnds}, {"CONFigure:ENDStop", true, cEndsQ}, {"CONFigure:PARameter", false, cPar}, {"CONFigure:PARameter", true, cParQ}, {"CONFigure:SAVE", false, cSave}, {"CONFigure:DEFaults", false, cDef}, {"ENABle", false, cEnab}, {"ENABle", true, cEnabQ}, {"ENABle:ALL", false, cEnabAll}, {"STOP", false, cStop}, {"STOP:ALL", false, cStopAll}, {"ESTop", false, cEstop}, {"ESTop:ALL", false, cEstopAll}, {"ABORt", false, cEstopAll}, {"MOVE:ABSolute", false, cMoveAbs}, {"MOVE:RELative", false, cMoveRel}, {"JOG:STEP", false, cMoveRel}, {"JOG", false, cJog}, {"ON", false, cOn}, {"OFF", false, cOff}, {"ON", true, cOnQ}, {"HOME", false, cHome}, {"HOME", true, cHomeQ}, {"MOVE:DONE", true, cDone}, {"MOVE:WAIT", true, cWait}, {"MOVE:STATe", true, cMoveStat}, {"POSition:ZERO", false, cZero}, {"POSition:SET", false, cPosSet}, {"POSition", true, cPos}, {"POSition:TARGet", true, cTarg}, {"POSition:ERRor", true, cPosErr}, {"POSition:COUNts", true, cCounts}, {"VELocity", true, cVel}, {"STATus", true, cStat}, {"STATus:MODE", true, cMode}, {"STATus:FAULt", true, cFault}, {"STATus:FIRMware", true, cFirm}, {"STATus:DRIVer", true, cDriv}, {"STATus:TEMPerature", true, cTemp}, {"STATus:CAN", true, cCan}, {"ALARm", true, cAlar}, {"ALARm:LIST", true, cAlarList}, {"ALARm:CLEar", false, cAlarCle}, }; static const size_t SCPI_NCMDS = sizeof(SCPI_CMDS) / sizeof(SCPI_CMDS[0]); // ---- execution ------------------------------------------------------------------------------------------ static void scpiExecPart(ScpiCtx &c, char *text) { while (*text == ' ' || *text == '\t') text++; if (!*text) return; char *hdr = text; char *rest = hdr; while (*rest && *rest != ' ' && *rest != '\t') rest++; if (*rest) *rest++ = 0; if (*hdr == ':') hdr++; size_t hl = strlen(hdr); bool query = hl && hdr[hl - 1] == '?'; if (query) hdr[--hl] = 0; Args a; a.n = 0; while (*rest == ' ' || *rest == '\t') rest++; if (*rest) { char *save = nullptr; // keep empty fields: split manually on ',' char *p = rest; for (;;) { char *comma = strchr(p, ','); if (comma) *comma = 0; while (*p == ' ' || *p == '\t') p++; char *e = p + strlen(p); while (e > p && (e[-1] == ' ' || e[-1] == '\t')) *--e = 0; if (a.n < SCPI_MAXARG) a.v[a.n++] = p; else a.n = SCPI_MAXARG + 1; if (!comma) break; p = comma + 1; } (void)save; } c.failed = false; const ScpiCmd *hit = nullptr; bool other = false; if (!hl) fail(c, E_SYNTAX, "Empty command"); else { for (size_t i = 0; i < SCPI_NCMDS; i++) { if (!headerMatch(hdr, SCPI_CMDS[i].pat)) continue; if (SCPI_CMDS[i].query == query) { hit = &SCPI_CMDS[i]; break; } other = true; } if (!hit) { if (other) fail(c, E_UNDEFINED, "%s is only a %s", hdr, query ? "command" : "query"); else fail(c, E_UNDEFINED, "Undefined header %s", hdr); } } if (c.n) ctxAppend(c, ";"); size_t mark = c.n; if (hit) { if (a.n > SCPI_MAXARG) fail(c, E_TOO_MANY, "Too many parameters"); else hit->fn(c, a); } if (c.failed) { c.n = mark; c.out[c.n] = 0; // drop any partial reply of this part if (query || scpiAck) { char b[96]; snprintf(b, sizeof(b), "ERROR %d,\"%s\"", c.errCode, c.errMsg); ctxAppend(c, b); } } else if (!query && scpiAck) { ctxAppend(c, "OK"); } if (c.n == mark && mark > 0) { c.n--; c.out[c.n] = 0; } // nothing written: drop the ';' } static void scpiExecuteLine(char *line, bool silent) { ScpiCtx c; c.n = 0; c.out[0] = 0; c.failed = false; c.errCode = 0; c.errMsg[0] = 0; char *p = line; for (;;) { char *semi = strchr(p, ';'); if (semi) *semi = 0; scpiExecPart(c, p); if (!semi) break; p = semi + 1; } if (!silent && c.n) { Serial.write((const uint8_t *)c.out, c.n); Serial.write('\n'); } } // ---- serial input while a SCPI command is busy (MOVE:WAIT?, remote reads) ------------------------------- // Bytes are collected into pendBuf. An ESTOP / ABORt / STOP / OFF line runs at // once (silently) so a test sequence can always stop the motor; any other // line is queued and runs after the current one. static char pendBuf[160]; static size_t pendLen = 0; static char queuedLine[160]; static bool queuedValid = false; static uint8_t scpiDepth = 0; static bool isEmergencyLine(const char *s) { while (*s == ' ' || *s == ':') s++; return !strncasecmp(s, "EST", 3) || !strncasecmp(s, "ABOR", 4) || !strncasecmp(s, "STOP", 4) || !strncasecmp(s, "OFF", 3); } static void scpiPollSerial() { if (scpiDepth == 0) return; while (Serial.available()) { char ch = (char)Serial.read(); if (ch == '\n' || ch == '\r') { if (!pendLen) continue; pendBuf[pendLen] = 0; pendLen = 0; if (isEmergencyLine(pendBuf)) { char tmp[160]; strcpy(tmp, pendBuf); scpiDepth++; scpiExecuteLine(tmp, true); scpiDepth--; } else if (!queuedValid) { strcpy(queuedLine, pendBuf); queuedValid = true; } else { scpiPush(-350, "Queue overflow: line dropped while busy"); } } else if (pendLen < sizeof(pendBuf) - 1) { pendBuf[pendLen++] = ch; } else { pendLen = 0; } } } // Entry point from serialLineExecute() for every non-GCSP line. static void scpiHandleLine(char *line) { serialMode = SER_SCPI; scpiDepth++; scpiExecuteLine(line, false); while (queuedValid) { char tmp[160]; strcpy(tmp, queuedLine); queuedValid = false; if (looksLikeGcsp(tmp)) break; // drop a stray bridge line while in SCPI scpiExecuteLine(tmp, false); } scpiDepth--; }