ProtoCore v1.0.16
Deterministic, zero-heap network stack for embedded targets
Loading...
Searching...
No Matches
scpi.h
Go to the documentation of this file.
1// ProtoCore v1.0.16 - Copyright (C) 2026 Douglas Quigg (dstroy0) <dquigg123@gmail.com>
2// SPDX-License-Identifier: AGPL-3.0-or-later
3
4/**
5 * @file scpi.h
6 * @brief SCPI / IEEE 488.2 instrument-control codec (PROTOCORE_ENABLE_SCPI) - a zero-heap codec for the
7 * text command language nearly every modern bench instrument speaks (DMMs, oscilloscopes,
8 * power supplies, function/arbitrary generators, SMUs, spectrum/network analyzers, loads)
9 * over a raw TCP socket on port 5025 (also USBTMC / VXI-11 / HiSLIP / serial).
10 *
11 * The codec is symmetric - it serves both roles:
12 * - **Controller** (device drives an instrument): build command lines with a `:`-hierarchy header
13 * and comma-separated parameters (@ref protocore_scpi_build), and parse the instrument's replies -
14 * numeric NR1/NR2/NR3 (@ref protocore_scpi_parse_number), boolean (@ref protocore_scpi_parse_bool), quoted
15 * string (@ref protocore_scpi_parse_string), and the IEEE 488.2 arbitrary block `#<n><len><data>` used
16 * for waveform captures (@ref protocore_scpi_parse_block).
17 * - **Instrument** (device answers a controller): the IEEE 488.2 status model - the Status Byte,
18 * Standard Event Status Register + its enable mask, the Service Request Enable mask, and the SCPI
19 * error/event queue (@ref ScpiStatus) - plus a SCPI short/long-form header matcher
20 * (@ref protocore_scpi_match) to dispatch an incoming command against a pattern like `"SYSTem:ERRor?"`.
21 *
22 * Common commands (@ref protocore_scpi_common) return the IEEE 488.2 mnemonics (`*IDN?`, `*RST`, `*CLS`,
23 * `*ESR?`, `*STB?`, ...). Pure codec, host-tested; the TCP/USB/serial transport is the app's.
24 *
25 * References:
26 * - IEEE Std 488.2-1992 (Codes, Formats, Protocols and Common Commands).
27 * - SCPI Consortium, "Standard Commands for Programmable Instruments", Vol. 1 Syntax & Style (1999).
28 *
29 * @author Douglas Quigg (dstroy0)
30 * @date 2026
31 */
32
33#ifndef PROTOCORE_SCPI_H
34#define PROTOCORE_SCPI_H
35
36#include "protocore_config.h" // the entry point: protocore_types.h for the widths
37
38#if PROTOCORE_ENABLE_SCPI
39
40EMBED_BEGIN_DECLS
41
42/** @brief The default raw-socket ("SCPI-RAW") TCP port instruments listen on. */
43#define PROTOCORE_SCPI_PORT 5025
44
45// ── Standard Event Status Register (ESR) bits - read/cleared by *ESR? ──────────────────────────
46#define SCPI_ESR_OPC 0x01 ///< bit 0: Operation Complete
47#define SCPI_ESR_RQC 0x02 ///< bit 1: Request Control
48#define SCPI_ESR_QYE 0x04 ///< bit 2: Query Error
49#define SCPI_ESR_DDE 0x08 ///< bit 3: Device-Dependent Error
50#define SCPI_ESR_EXE 0x10 ///< bit 4: Execution Error
51#define SCPI_ESR_CME 0x20 ///< bit 5: Command Error
52#define SCPI_ESR_URQ 0x40 ///< bit 6: User Request
53#define SCPI_ESR_PON 0x80 ///< bit 7: Power On
54
55// ── Status Byte Register (STB) bits - read by *STB? / serial poll (SCPI model) ─────────────────
56#define SCPI_STB_EAV 0x04 ///< bit 2: Error/event queue not empty
57#define SCPI_STB_QSB 0x08 ///< bit 3: QUEStionable status summary
58#define SCPI_STB_MAV 0x10 ///< bit 4: Message Available (output queue not empty)
59#define SCPI_STB_ESB 0x20 ///< bit 5: Standard Event status Summary (ESR & ESE)
60#define SCPI_STB_MSS 0x40 ///< bit 6: Master Summary Status (RQS in a serial poll)
61#define SCPI_STB_OSB 0x80 ///< bit 7: OPERation status summary
62
63/** @brief The mandatory IEEE 488.2 common commands (`protocore_scpi_common` renders each). */
64EMBED_ENUM_BYTE(ScpiCommon,
65 SCPI_CLS, ///< "*CLS" clear status
66 SCPI_ESE, ///< "*ESE" set event status enable
67 SCPI_ESE_Q, ///< "*ESE?" query event status enable
68 SCPI_ESR_Q, ///< "*ESR?" query + clear event status register
69 SCPI_IDN_Q, ///< "*IDN?" identification query
70 SCPI_OPC, ///< "*OPC" set operation-complete bit when done
71 SCPI_OPC_Q, ///< "*OPC?" query operation complete (returns 1)
72 SCPI_RST, ///< "*RST" reset
73 SCPI_SRE, ///< "*SRE" set service request enable
74 SCPI_SRE_Q, ///< "*SRE?" query service request enable
75 SCPI_STB_Q, ///< "*STB?" query status byte
76 SCPI_TST_Q, ///< "*TST?" self-test query
77 SCPI_WAI, ///< "*WAI" wait to continue
78);
79
80/** @brief Render an IEEE 488.2 common command mnemonic (a static string, never null). */
81const char *protocore_scpi_common(ScpiCommon c);
82
83/**
84 * @brief Build a SCPI command line: `header` + ' ' + comma-joined `args` + '\n'.
85 *
86 * With @p argc 0 the line is just `header` + '\n' (e.g. `"*RST\n"`, `"MEAS:VOLT:DC?\n"`).
87 * @param header a full `:`-hierarchy header or a common command, e.g. `"SOURce:VOLTage"`, `"*IDN?"`.
88 * @param args already-formatted parameter strings (see @ref protocore_scpi_fmt_real to format a number).
89 * @return characters written (excluding the NUL terminator), or 0 on overflow / bad input.
90 * @note The line is NUL-terminated so callers may treat @p buf as a C-string.
91 */
92size_t protocore_scpi_build(char *buf, size_t cap, const char *header, const char *const *args, size_t argc);
93
94/**
95 * @brief Format a real number as a SCPI parameter (NR2 fixed, or NR3 scientific for large/small
96 * magnitudes), trailing zeros trimmed. Handy for @ref protocore_scpi_build args.
97 * @return characters written (excluding NUL), or 0 on overflow.
98 */
99size_t protocore_scpi_fmt_real(char *buf, size_t cap, double v);
100
101/**
102 * @brief Parse a SCPI numeric response (NR1 integer / NR2 fixed / NR3 scientific), hand-rolled
103 * (no stdlib). Recognizes the special values `9.9E37` (INFinity), `-9.9E37`, `9.91E37` (NaN).
104 * @return true on a fully-consumed numeric field; false on malformed input.
105 */
106embed_bool protocore_scpi_parse_number(const char *s, size_t len, double *out);
107
108/**
109 * @brief Parse a SCPI boolean response: `1`/`0` or `ON`/`OFF` (case-insensitive).
110 * @return true on a recognized boolean; false otherwise.
111 */
112embed_bool protocore_scpi_parse_bool(const char *s, size_t len, embed_bool *out);
113
114/**
115 * @brief Parse a SCPI string response: strip the surrounding single or double quotes and collapse a
116 * doubled quote (`""` or `''`) to one. Copies into @p out (NUL-terminated).
117 * @return the unquoted length (excluding NUL), or 0 on a missing/mismatched quote or overflow.
118 */
119size_t protocore_scpi_parse_string(const char *s, size_t len, char *out, size_t cap);
120
121/**
122 * @brief Parse an IEEE 488.2 arbitrary block: definite `#<n><n-length-digits><data>` or indefinite
123 * `#0<data>` (runs to the trailing newline). On success @p data points INTO @p buf.
124 * @param data receives a pointer to the first data byte.
125 * @param data_len receives the data byte count.
126 * @param consumed receives the total bytes the block occupied (header + data [+ the indefinite NL]).
127 * @return true on a complete block; false if truncated or malformed.
128 */
129embed_bool protocore_scpi_parse_block(const uint8_t *buf, size_t len, const uint8_t **data, size_t *data_len,
130 size_t *consumed);
131
132// ── IEEE 488.2 / SCPI status model (instrument side) ───────────────────────────────────────────
133
134/** @brief One error/event queue entry. @ref msg points at a static or app-owned string. */
135typedef struct
136{
137 int16_t number; ///< SCPI error number (negative = standard, positive = device-specific, 0 = no error)
138 const char *msg; ///< the description text (without the surrounding quotes)
139} ScpiError;
140
141/** @brief The IEEE 488.2 status registers + the SCPI error/event queue (one owned block). */
142typedef struct
143{
144 uint8_t esr; ///< Standard Event Status Register (latched events)
145 uint8_t ese; ///< Standard Event Status Enable mask (ESR -> ESB)
146 uint8_t sre; ///< Service Request Enable mask (STB -> MSS)
147 uint8_t summary; ///< app-set STB summary bits (QSB/MAV/OSB); merged into *STB?
148 ScpiError queue[PROTOCORE_SCPI_ERR_QUEUE]; ///< the error/event queue (FIFO ring)
149 uint8_t head; ///< ring read index
150 uint8_t count; ///< entries currently queued
151} ScpiStatus;
152
153/** @brief Clear every register + the queue (power-on state). */
154void protocore_scpi_status_init(ScpiStatus *s);
155
156/** @brief Latch one or more ESR event bits (e.g. @ref SCPI_ESR_OPC). */
157void protocore_scpi_event(ScpiStatus *s, uint8_t esr_bits);
158
159/**
160 * @brief Enqueue an error/event and latch its ESR class bit (CME/EXE/DDE/QYE from the -1xx/-2xx/
161 * -3xx/-4xx number range). On overflow the tail entry becomes -350 "Queue overflow".
162 * @param msg the description; pass nullptr to use the standard text for a standard number.
163 */
164void protocore_scpi_push_error(ScpiStatus *s, int16_t number, const char *msg);
165
166/**
167 * @brief Pop the head error (the `SYSTem:ERRor?` action). When the queue is empty @p out becomes
168 * `0,"No error"`.
169 * @return true if an error was dequeued; false if the queue was empty (out = the no-error entry).
170 */
171embed_bool protocore_scpi_pop_error(ScpiStatus *s, ScpiError *out);
172
173/** @brief Compute the Status Byte: EAV (queue), ESB (esr & ese), the app summary bits, and MSS. */
174uint8_t protocore_scpi_stb(const ScpiStatus *s);
175
176/** @brief The `*CLS` action: clear the ESR and empty the error/event queue (enables untouched). */
177void protocore_scpi_cls(ScpiStatus *s);
178
179/** @brief The standard SCPI message for a standard (negative) error number, or "" if unknown. */
180const char *protocore_scpi_std_error(int16_t number);
181
182/**
183 * @brief Match an incoming command header against a SCPI short/long-form pattern.
184 *
185 * Case-insensitive. Each `:`-separated node in @p pattern has an uppercase run (the required short
186 * form) followed by an optional lowercase tail (the long form); the input node must equal EITHER the
187 * short form OR the whole long form (no other truncation). An optional numeric suffix is compared
188 * with an omitted suffix defaulting to 1 (`OUTP` == `OUTPut1`). A trailing `?` in the pattern must
189 * be matched by a `?` in the input. A `*`-prefixed pattern (common command) is matched whole,
190 * case-insensitively. A leading `:` on the input (absolute path) is ignored.
191 *
192 * @return true if @p input (its header, up to the first space) matches @p pattern.
193 */
194embed_bool protocore_scpi_match(const char *input, size_t input_len, const char *pattern);
195
196EMBED_END_DECLS
197
198#endif // PROTOCORE_ENABLE_SCPI
199
200#endif // PROTOCORE_SCPI_H
#define PROTOCORE_SCPI_ERR_QUEUE
SCPI error/event queue depth (entries). The SCPI status model requires a queue; when it overflows the...
EMBED_ENUM_BYTE(ProtoConn, PROTO_NONE=0, PROTO_HTTP=1, PROTO_TELNET=2, PROTO_SSH=3, PROTO_MODBUS=4, PROTO_OPCUA=5, PROTO_SSH_RFWD=6, PROTO_RELAY=7, PROTO_BRIDGE=8, PROTO_NTRIP_CASTER=9, PROTO_MESH=10, PROTO_UDP=11,)
Application protocol spoken on a listener port or connection slot.