# SerialFlow reference for AI assistants
- **Product:** SerialFlow, a serial terminal, UART logger and real-time graph tool for Windows, by Lizerd
- **Describes:** SerialFlow 0.9.0 beta 2 (`0.9.0-beta.2`). Where beta 1 behaves differently, the text says so
- **This file:** version 2026-11-13. Newest copy: https://lizerd.se/serialflow/ai/serialflow-ai-reference.md
- **Human manual:** https://lizerd.se/serialflow/manual/ · **Product page and download:** https://lizerd.se/serialflow/
The user has attached this file to a chat so that you, the AI assistant, can help them use SerialFlow: write the
firmware side for their microcontroller, set up the PC side, build dashboards, write test files and rule files, and
find out why something does not show up. Everything below was checked against the SerialFlow 0.9.0 beta 2 code.
## Contents
1. Instructions for the AI assistant
2. What to find out before writing code
3. Hard rules: the mistakes that fail silently
4. What SerialFlow can do: the capability map
5. Ports and connection
6. Terminal output: text, colour and characters
7. Status windows
8. Graph commands (text protocol)
9. Device commands: save captures, start and stop logging
10. CRC-8 on graph lines
11. Packed binary graph data
12. Speed and timing
13. Firmware: a portable helper and per-platform recipes
14. Test files: try it without hardware
15. PC side: everything the user does in SerialFlow
16. Files an AI can write for SerialFlow
17. Troubleshooting
18. Known limits in beta 2, and what changed since beta 1
19. A complete worked example
---
## 1. Instructions for the AI assistant
1. **Treat this file as the specification.** Use only the commands, fields, menus and file formats described here.
If the user wants something that is not in this file, say that SerialFlow 0.9.0 beta 2 does not do it (or that
this reference does not cover it), and offer the closest thing that does work. Never invent a command letter, a
field, a menu item, a setting or a file format.
2. **Respect the limits, and ask which version the user runs.** Section 18 lists the few things beta 2 does not do,
and what beta 1 does differently. If the user still runs beta 1 (**Settings → About**), tell them to update
first: the X-axis commands (`~{G:X:…}`) and the device commands (section 9) need beta 2, and beta 1 reads every
`~{G:X…}` as "delete the graph".
3. **Settle the facts first** (section 2). Ask only for what you cannot sensibly assume, and state the assumptions
you make. One short round of questions is better than code for the wrong platform.
4. **Give complete code** for the user's platform: includes, the output function, set-up and the loop. Say which
file it goes in and what the user must change (UART handle, pins, baud).
5. **Check every line your firmware will print against section 3** before you answer.
6. **Give a test file as well** (section 14): the exact lines the firmware will print, so the user can load them in
SerialFlow (**☰ → Test → Load Test File**) and see the result before flashing.
7. **Give PC-side steps as exact menu paths**, written as SerialFlow's manual does: **☰ → Tools → Signal Manager...**,
**Settings → Port → DTR Enable**.
8. **When something does not work**, use section 17. Ask the user for: what the log shows with **Raw Display** on
(Ctrl+R), the list in **☰ → Tools → RX Error Collector...** (**Copy All**), the status-bar
message, the baud rate and how the board is connected.
9. **Keep the firmware simple.** Plain text lines are easiest to debug. Suggest CRC-8 for long or noisy links and
packed binary only for high rates (section 12).
10. If the user asks about a newer SerialFlow version than 0.9.0 beta 2, point them to the newest copy of this file.
## 2. What to find out before writing code
| Ask about | Why it matters |
|---|---|
| **MCU and board** (e.g. STM32F401 Nucleo, ESP32-S3 DevKit, RP2040 Pico, ATmega328P Uno, nRF52840 DK) | RAM for line buffers; `double` size (4 bytes on 8-bit AVR); USB or UART |
| **Framework / toolchain** (Arduino, STM32 HAL + CubeIDE/Keil/IAR, ESP-IDF, Zephyr / nRF Connect SDK, Pico SDK, MicroPython, bare-metal register code, an RTOS) | Which call sends bytes, how `printf` is retargeted, how floats are printed |
| **The link to the PC** | A UART through a USB-serial adapter or a debug probe's virtual COM port (the baud must match), or native USB CDC (the baud does not matter; some stacks wait for DTR, section 5) |
| **Baud rate** | SerialFlow offers 9 600 to 3 000 000 only, from a fixed list (section 5) |
| **How text leaves the board today** | `printf` retarget, `HAL_UART_Transmit`, `Serial.print`, DMA, or a logging macro. Logging macros add prefixes, which break SerialFlow commands (rule 1) |
| **Float printing** | newlib-nano and AVR print no floats from `printf` until enabled; Arduino AVR `snprintf` has no `%f` |
| **What the user wants to see** | Colour log, live status table, live graph, recording of a long run, oscilloscope-style frames, XY plot, dashboard, unit conversion, files saved when something happens (section 9) |
| **Rates** | Samples per second × signals: decides text or binary and the baud (section 12) |
| **Link quality** | A long or noisy cable: add CRC-8 to graph lines (section 10) |
| **Commands to the board** | Quick Send buttons, macros with WaitFor, auto-reply rules (section 15) |
| **Several boards** | Each COM port is its own workspace with its own graphs `A`–`Z` |
## 3. Hard rules: the mistakes that fail silently
Check every firmware line against these. Most of them produce no error message: the line is shown as text, or
dropped.
1. **A command line starts with `~`.** Only spaces may come before it: no log prefix, no timestamp, no colour code.
Never send SerialFlow command lines through a logging macro that adds a prefix (`ESP_LOGI`, Zephyr `LOG_INF`,
`NRF_LOG_INFO` and the like). Use `printf`, `puts`, `Serial.print` or a raw UART write. Normal log text may use
any logging macro. (One exception: after 100 ms with nothing received, a command may follow text that is already
on the line, such as a prompt printed without a line end.)
2. **One command per line, ended by LF (`\n`).** `\r\n` is fine. Only the first `~{…}` on a line is executed; a second
status command on a line becomes part of the first one's text. A CR on its own does not end a line (with the
default **RX Line Ending** it returns to the start of the line, section 6.4).
3. **Graph letters `A`–`Z`, command letters and format letters are capitals.** `~{a:…}`, `~{A:s:…}` and format `r`
fail.
4. **Numbers use a point**: `23.5`, never `23,5`. No thousands separators. `1.2e-3` and `NaN` are fine in format `R`.
5. **Text fields (names, units, labels) must not contain `:`, `}` or `|`.** Spaces and UTF-8 (`°`, `µ`) are fine,
except on CRC lines (rule 14).
6. **Set up a graph before sending data:** the `I` line (at least 5 fields), then the `S` lines (at least 6 fields),
then data. Data for an unknown graph or signal is dropped. SerialFlow only sees what arrives after the user presses
**Connect**, so a board that prints its set-up once at boot, before Connect, shows nothing. Make the firmware
print the set-up again on request (for example when it receives `?`), or the user resets the board after
connecting (section 5 has a DTR trick for Arduino boards).
7. **`I` again starts the graph over**: all signals and data are gone, so send the `S` lines again after it. `S` again
for an existing id keeps its data and updates its settings.
8. **Signal ids 1 to 32.** Other numbers are dropped. (Beta 1 dropped the data of signal 32; firmware that must also
work with beta 1 uses 1–31.)
9. **One data line is one sample of all signals.** Values go to the signals in rising id order. Never send one line
per signal: each line is a new X.
10. **Format `R` for anything with decimals.** `D` and `U` read `23.5` as 0. An unreadable value becomes 0.
11. **Pick one kind of X per graph.** Auto-X (`1`) is the simplest for streamers; explicit X (`0`, e.g. a time) suits
loggers and works on streamers too. Never mix `0` and `1` on one graph. Keep X rising on streamers and loggers:
one X that goes back switches that signal to arrival-order (XY) drawing until the graph is cleared.
12. **Frame graphs need the flush line `~{G:F}`** after each frame; without it nothing changes on screen.
13. **Never send a `0x00` byte in text output.** A zero byte starts a packed binary frame. A stray one in text is
dropped and the text after it is kept (beta 1 lost that text), but don't rely on it.
14. **CRC lines must be plain ASCII.** The CRC is computed over characters, so a line with `°` or `µ` never matches.
15. **Send each command line in one go: build it in a buffer and send it with one write.** SerialFlow joins a line
that arrives in two serial reads, but when the rest of an unfinished command line has not arrived after 100 ms,
the part it has is shown as text and the command is lost. So never pause (a `delay()`, a slow sensor read) in the
middle of a command line.
16. **Binary frames must be sent byte for byte.** No LF → CR LF translation (common in `stdout`, consoles and
`printk`), no buffering that drops or reorders bytes. Send them with a raw write.
17. **Status windows: one digit for the window, 1–9.** `~ClA1:` clears window 1; `~ClA:` and `~ClA0:` clear the main
log. Keep row numbers small (every row up to the one written is created). Print each row with one write.
18. **Colour with ANSI codes** (or the short tags `…`, section 6.3). End each coloured part with `ESC[0m`.
19. **`\r` redraws and cursor moves work on the log line, not as a full screen.** A lone CR returns to the start of
the line and the next text overwrites it, so a progress bar or spinner redraws in place; end a shorter redraw with
`ESC[K` to clear what is left of the old text. Full-screen VT100 (`ESC[?…` modes, screens built with cursor
positioning) is not supported: use a status window for a table of values that change.
20. **Device commands (section 9) do nothing until the user switches them on** (**Settings → Device Captures**). While
they are off they are still consumed, so nothing shows in the log. Tell the user to tick the box.
21. **In a multi-threaded firmware (RTOS), send SerialFlow lines from one task or under a mutex**, so two tasks never
interleave inside a line.
## 4. What SerialFlow can do: the capability map
SerialFlow runs on Windows 11 64-bit (Windows 10 64-bit should work, not tested). It is free to use,
for personal and commercial use, and works fully offline. It reads any COM port and shows the text in a terminal.
Short command lines in the same text stream drive status windows and graphs; everything else (dashboards, units,
recording, automation) is set up on the PC and needs nothing extra from the firmware.
| The user wants | The firmware sends | On the PC | Section |
|---|---|---|---|
| A readable log | Plain text lines | Terminal, timestamps, line numbers, find, keyword colours, bookmarks | 6, 15 |
| Colours in the log | ANSI SGR codes (`ESC[…m`): 16, 256 or 24-bit colours | Nothing | 6 |
| A live table of values that updates in place | `~WrLi{W}:{row}:{text}` lines | Window 1–9 tabs open by themselves | 7 |
| Live graphs | `~{G:I:…}`, `~{G:S:…}`, then `~{G:1:…}` per sample | Graph panes open by themselves; zoom, cursors, statistics | 8, 15 |
| A long recording (minutes to days) | A logger graph (`L`) with time X | Data Collector to SQLite, CSV, JSON Lines | 8, 15 |
| An oscilloscope view, spectrum or XY shape | A frame graph (`F`) and `~{G:F}` per frame; `~{G:X:R:…}` and `~{G:X:E:1}` for a fixed, 1:1 XY plot | Frame shown in one step | 8 |
| Keep the data around an event (a fault, a spike) | `~{G:W:label}`, `~SvLog:label`; `~LogOn` / `~LogOff`, `~RecOn` / `~RecOff` | The user ticks **Settings → Device Captures**; files listed in **Saved Captures** | 9 |
| Limit lines, events, notes, bookmarks on a graph | `H`, `M`, `E`, `T`, `B` lines | Also listed and recorded | 8 |
| Safe data over a noisy link | `*XX` CRC-8 after graph lines | Bad lines dropped and listed in RX Error Collector | 10 |
| High sample rates, many signals, full float precision | Packed binary frames (COBS, CRC-8) | Nothing | 11 |
| Raw ADC counts shown as volts, amps, degrees | Counts (whole numbers) | Signal Manager: scale, offset, unit, computed signals | 8, 15 |
| A dashboard (HMI) | Ordinary graph lines | Canvas dashboard (67 widget types, writable as text; four of them send commands) or grid dashboard | 15, 16 |
| Commands to the board | Nothing extra | Transmit, Quick Send Bar, Quick Send buttons, macros with WaitFor, auto-reply rules | 15 |
| Data in Excel, Python, MATLAB | Graph lines | Export, Data Collector | 15 |
| Several boards at once | Each on its own COM port | One workspace per port | 5 |
| Try without hardware | Nothing | Load Test File, Delayed Playback | 14 |
The firmware needs no library: anything that can print a line can use every firmware feature.
## 5. Ports and connection
- **Ports:** anything Windows lists as a COM port: USB-serial adapters (FTDI, CH340, CP210x, …), USB-CDC boards,
debug probes with a virtual COM port (ST-Link, J-Link, CMSIS-DAP), on-board UARTs. There is no TCP, Bluetooth-LE or
other transport in this reference.
- **Baud rates:** a fixed list: 9 600, 19 200, 38 400, 57 600, 115 200 (default), 230 400, 460 800, 921 600,
1 500 000, 2 000 000, 3 000 000. **There is no custom baud rate.** Pick one of these on the firmware side too.
**Settings → Port → Max** can shorten the list (921 600, 1 500 000, 2 000 000 or 3 000 000).
- **Port settings** (**Settings → Port**; they apply the next time the port opens): Data Bits 5–8 (default 8), Parity
None/Odd/Even/Mark/Space (None), Stop Bits One/Two/OnePointFive (One), Handshake None/XOnXOff/RequestToSend/
RequestToSendXOnXOff (None), **DTR Enable** (off), **RTS Enable** (off), Read and Write timeouts (500 ms),
Non-blocking reads (on), Max Retries (5, 0 = no limit), Retry Delay (100 ms).
- **Communication** (**Settings → Communication**): TX Line Ending None/CR/LF/CRLF (CRLF); **RX Line Ending**
Auto (default) / CRLF: LF or CR LF ends a line, a lone CR returns to the start of the line; CR: every CR ends a
line (for CR-only devices); LF: LF ends a line and CR is ignored (beta 1's behaviour). Encoding UTF-8
(default)/ASCII/Latin-1. What SerialFlow sends is always UTF-8.
- **Connect:** pick the port and baud in the toolbar, press **Connect** (F5). Auto-connect: **Settings →
Behavior → Auto-connect on Startup**. Unplugged devices are reconnected automatically (**Auto-reconnect on
disconnect**, on by default); a port the user disconnects stays disconnected. After sleep, lost ports reconnect.
A port another program holds gives "Connection failed: COM4 is in use by another program" (close the IDE's serial
monitor).
- **The device, not just the COM number:** SerialFlow remembers the USB serial number (and VID:PID) of the device a
port was connected to, and follows it when Windows gives it another COM number: at start, when it is plugged back
in and after sleep; the status bar says so (`… is now on COM12 (was COM5)`). This needs a device that reports a USB
serial number, such as an FTDI cable; one without (many CH340 boards) is matched by its COM name as before.
**Settings → Diagnostics → Port Dropdown: Extensive** shows the serial number in the port list.
- **Several ports:** **Add Port (new terminal)** on the toolbar. Each port is a workspace with its own terminal,
Window 1–9, graphs `A`–`Z` and auto-log. Graph `A` on COM4 and graph `A` on COM5 are unrelated. Shared between
ports: keyword rules, CRC Calculator, Port Info, the Data Collector (one recording covers all ports), canvas
dashboards (each widget can bind to a port), the Saved Captures list, settings and profiles. Close a port with the
**✕** on its chip or its Terminal tab (right-click → **Close**); **Close All But This** on a Terminal tab closes the
other ports. The last port's Terminal can't be closed.
- **FTDI latency timer:** an FTDI adapter holds bytes up to 16 ms before sending a part-filled USB packet. **Settings →
Port → Override Latency Timer** (1–255 ms) lowers it, but only when SerialFlow runs as administrator; without admin
rights the status bar shows a warning after connecting and the timer stays as it was.
**DTR and RTS matter for some boards.** SerialFlow holds both low when it opens the port, unless **Settings → Port →
DTR Enable** / **RTS Enable** are ticked; they are set once at open. While connected, the **Signal Lines** pane
(**☰ → View → Signal Lines**) shows CTS, DSR, DCD and RI and switches DTR and RTS (not saved). DTR Enable stays off by
default; when a native USB CDC port opened with DTR off has sent nothing after 3 s, the status bar suggests ticking it.
| Board | What to do |
|---|---|
| Native USB with TinyUSB, Pico SDK `stdio_usb`, Arduino Leonardo/Micro, SAMD21, RP2040 Arduino cores, many USB-CDC samples | These often send nothing, or wait in `while (!Serial)`, until the PC raises DTR. **Tick DTR Enable.** |
| Arduino Uno, Nano, Mega (auto-reset through DTR) | With **DTR Enable** ticked, pressing **Connect** resets the board, so it prints its graph set-up again after the connection is open: a handy fix for rule 6. Untick it if the reset is unwanted. |
| ESP32 / ESP8266 dev boards with the usual auto-program circuit (RTS → EN, DTR → GPIO0) | Leave **RTS Enable** off (the default): RTS alone holds the chip in reset. |
| Native USB CDC in general | The baud rate is usually ignored by the device; any value from the list works. |
| UART through a USB-serial adapter or debug-probe VCP | The baud, data bits, parity and stop bits must match the MCU exactly, or the text is garbled. |
## 6. Terminal output: text, colour and characters
**What the terminal does with each received line:**
| What arrives | What is shown |
|---|---|
| Plain text | The text. Each LF starts a new line; a lone CR returns to the start of the line (section 6.4) |
| ANSI colour codes `ESC[…m` | Text in that colour; the codes are removed |
| Short colour tags `…` | The text in that colour; the tags are removed |
| Status-window lines `~WrLi…` | Nothing in the log: the row goes to the window |
| Graph lines `~{…}` | Nothing in the log: the data goes to the graph |
| Device commands `~SvLog`, `~LogOn`, … | Nothing in the log (section 9) |
| A malformed `~{…}` line | Shown as text, and listed in the RX Error Collector |
Scrollback: the newest 100 000 lines by default (**Settings → Terminal → Max Lines**, no upper limit). Lines do not
wrap. A line growing past about 4 000 characters continues on a new line. The font is fixed width, Consolas 13 pt by
default (**Settings → Terminal → Font Family**, **Font Size**).
### 6.1 ANSI colour and style (SGR)
`ESC` is byte 0x1B: `"\x1B"` or `"\033"` in C, `"\x1b"` in Python. Codes can be combined: `ESC[1;31m` = bold red.
| Code | Effect |
|---|---|
| `0` or empty (`ESC[m`) | Reset all |
| `1`, `3`, `4`, `9` | Bold, italic, underline, strikethrough |
| `22`, `23`, `24`, `29` | Bold off, italic off, underline off, strikethrough off |
| `30`–`37` / `90`–`97` | Text colour 0–7 / bright 8–15 |
| `38;5;n` | Text colour from the 256-colour palette |
| `38;2;r;g;b` | Text colour, 24-bit |
| `39` | Default text colour |
| `40`–`47` / `100`–`107` | Background 0–7 / bright 8–15 |
| `48;5;n`, `48;2;r;g;b`, `49` | Background 256-colour, 24-bit, default |
| `2`, `5`, `7`, `8`, `25`, `27`, `28` | Accepted, no visible effect (no dim, blink, reverse, hidden) |
The 16 colours (the same in every colour profile): 0 black `#000000`, 1 red `#CC0000`, 2 green `#4E9A06`,
3 yellow `#C4A000`, 4 blue `#3465A4`, 5 magenta `#75507B`, 6 cyan `#06989A`, 7 white `#D3D7CF`, 8 grey `#555753`,
9 bright red `#EF2929`, 10 bright green `#8AE234`, 11 bright yellow `#FCE94F`, 12 bright blue `#729FCF`,
13 bright magenta `#AD7FA8`, 14 bright cyan `#34E2E2`, 15 bright white `#EEEEEC`. 256 palette: 0–15 as above,
16–231 a 6×6×6 cube (`16 + 36r + 6g + b`, each 0–5), 232–255 greys.
- A colour stays on, across lines, until changed or reset: end each coloured part with `ESC[0m`.
- Bold does not brighten: use `91` for bright red (`1;91` bold bright red).
- The colour profile sets only the default text colour, background, selection and find colours.
```c
printf("\x1B[1;31m[FAIL]\x1B[0m sensor 3 not responding\n");
printf("\x1B[92m[ OK ]\x1B[0m ADC calibrated\n");
printf("\x1B[33m[WARN]\x1B[0m MOSFET 72.4 C\n");
printf("\x1B[38;5;208mOrange from the 256 palette\x1B[0m\n");
printf("\x1B[30;43m BLACK ON YELLOW \x1B[0m\n");
```
ESP-IDF `ESP_LOGx` and Zephyr logging already emit ANSI colours when their colour options are on
(`CONFIG_LOG_COLORS`, `CONFIG_LOG_BACKEND_SHOW_COLOR`); SerialFlow shows them in colour.
### 6.2 Other escape sequences
SerialFlow is a log viewer with a cursor, not a full VT100 screen. The cursor moves within the log: rows count from
the oldest line kept, columns from 0 at the left.
| Sequence | Effect |
|---|---|
| `ESC[2J`, `ESC[J`, `ESC[3J` (any `J`) | Clears the whole terminal, including the scrollback |
| `ESC[K`, `ESC[0K` | Clears from the cursor to the end of the line |
| `ESC[1K` | Clears from the start of the line up to the cursor |
| `ESC[2K` | Clears the whole line; the cursor stays where it is |
| `ESC[H`, `ESC[row;colH`, `ESC[row;colf` | Moves to that row and column (1-based; row 1 = oldest line kept) |
| `ESC[nA`, `ESC[nB` | Moves n rows up / down |
| `ESC[nC`, `ESC[nD` | Moves n columns right / left |
| `ESC[s`, `ESC[u` | Save / restore the cursor (row and column) |
| Other `ESC[…letter` | Ignored |
| `ESC[?…` (e.g. `ESC[?25l`) | Not understood: the characters after `ESC[?` appear as text. Don't send them |
| `ESC` + anything but `[` (`ESC 7`, `ESC ]` titles) | `ESC` and the next character dropped, the rest shown as text |
Text after a cursor move or a lone CR overwrites the line from the cursor column; past the end of the line the gap is
filled with spaces. Below the last line, text starts a new line at the end of the log. Good for progress lines and
spinners; for a screen of values that change, use a status window (section 7).
```c
for (int pct = 0; pct <= 100; pct += 10) {
printf("\rFlashing %3d %%\x1B[K", pct); /* back to column 0, rewrite, clear the rest */
fflush(stdout); /* no line end, so flush a buffered stdout */
flash_next_block();
}
printf("\rFlashing done\x1B[K\n");
```
### 6.3 Short colour tags
``, ``, ``, ``, ``, ``, `` with closing tags (``; any closing tag ends the colour). Upper
case only. Colours: red `#FF0000`, green `#00FF00`, blue `#0000FF`, yellow `#FFFF00`, cyan `#00FFFF`, magenta
`#FF00FF`, white `#FFFFFF`. They work in the log and in status-window rows. (Beta 1 removed them but drew the text
grey.) ANSI codes give more colours and work everywhere.
### 6.4 Characters, encoding, line endings
- Received bytes are decoded as **UTF-8** by default, so box drawing (`╔ ═ ╗ ─ │ █`) works. Send them as UTF-8:
`█` U+2588 = `\xE2\x96\x88`, `─` U+2500 = `\xE2\x94\x80`, `°` = `\xC2\xB0`. Invalid UTF-8 shows as `�`.
- **Encoding ASCII**: bytes 0x80+ show as `?`. **Latin-1**: one byte per character (`é` = 0xE9).
- Tab, backspace and bell are kept as characters; they do not move the cursor.
- Block characters `░ ▒ ▓ █` and box drawing line up with the text.
- **Line endings** (**Settings → Communication → RX Line Ending**, default **Auto**): LF or CR LF ends a line; a lone
CR returns to the start of the line and the next text overwrites it, so `Progress 10%\rProgress 20%\n` shows as
`Progress 20%`. A device that ends lines with CR only needs **CR**. **LF** ignores CR, as beta 1 did.
### 6.5 Terminal options the user can switch
| Option | Where |
|---|---|
| Timestamps `[19:53:47.384]` | **Settings → Terminal → Show Timestamps**; **Timestamp Fmt** is a .NET format, default `HH:mm:ss.fff` |
| Line numbers | **Settings → Behavior → Show Line Numbers** |
| Raw Display: show command lines as text instead of executing them (ANSI still applied, binary still decoded) | Ctrl+R, **☰ → View → Raw Display**. Applies to all ports, saved in the profile |
| Hex View: hex dump of the last 100 stored lines (after colour codes and commands are removed; not a raw wire capture) | **☰ → View → Hex View** |
| Clear | Ctrl+L; firmware: `ESC[2J`, `CLR_ALL` or `~ClA:` |
| Auto Scroll | Ctrl+End; scrolling up pauses following, scrolling to the bottom resumes |
| Font, size, colours | **Settings → Terminal → Font Family**, **Font Size**; **ANSI Color Enabled** off draws all text in the default colour |
## 7. Status windows
A status window is a table of text rows that the firmware rewrites one row at a time; nothing scrolls. Each port has
**Window 1 to Window 9**. A window opens as a tab the first time a line names it. Nothing has to be set up on the PC.
```text
~ClA1:
~WrLi1:0:DRIVE STATUS
~WrLi1:2:Speed 2594 rpm
~WrLi1:3:Torque 7.42 Nm
```
### 7.1 Commands
`{W}` = window digit, `{n}` = row number from 0.
| Command | Format | Effect |
|---|---|---|
| Write Line | `~WrLi{W}:{n}:{text}` | Writes `text` to row `n`, replacing the whole row. Creates the row and empty rows before it |
| Update Line | `~UpLi{W}:{n}:{text}` | The same as Write Line |
| Clear Line | `~ClL{W}:{n}` | Empties row `n`; nothing moves |
| Clear All | `~ClA{W}:` | Empties the whole window (note the colon) |
| Insert Line | `~InLi{W}:{n}:{text}` | Inserts at `n`; the rows below move down with their text. (Beta 1 left the moved rows empty.) |
| Delete Line | `~DeLi{W}:{n}` | Deletes row `n`; the rows below move up with their text. (Beta 1 left the moved rows empty.) |
Rarely needed: `~ClL{W}` (row at the window cursor), `~ClP{W}` (row above the cursor), `~Go{W}:{row}:{col}` (move the
cursor), `~Hm{W}` (row 0), `~En{W}` (last row). Avoid them in window 0, where they move the log cursor.
`~SvLog{W}` saves a window's text to a file (section 9).
### 7.2 Field rules
- `~` must be the first character of the line (spaces before it are allowed).
- Command names exactly as written: `WrLi`, `UpLi`, `ClL`, `ClA`, `InLi`, `DeLi`.
- **The window is one digit.** `1`–`9` are status windows, `0` (or no digit) is the main log. `~WrLi12:5:x` means
window 1, row 2, text `5:x`.
- `~WrLi0:5:text` overwrites row 5 of the main log (counted from the oldest line kept). Avoid.
- Text runs to the end of the line. Leading spaces are kept; trailing spaces are dropped.
- One command per line. Rows 0 to 9 999; a row outside that (a negative one, say) is ignored. A line that is not a
valid command (row not a number, unknown name) is shown in the log as text.
- Colour inside a row: ANSI colour codes (`ESC[…m`) or the short tags (section 6.3). Each row starts in default
colours. Any other escape sequence ends the row there and the rest goes to the log; a CR inside a row is dropped.
- Bars: repeat `█` (U+2588); `░ ▒ ▓` work too.
- A row that reaches the PC in two serial reads is joined, as long as its rest comes within 100 ms (rule 15). Print
each row with one write.
- **Clear Terminal** (Ctrl+L) and **Delayed Playback** also empty the windows. Firmware that
rewrites its rows now and then (for example the static rows every few seconds) recovers by itself.
- Keyword highlighting colours status windows too.
**Long forms** (old firmware; main log only, no colour inside): `WRITE_LINE:{n}:{text}`, `UPDATE_LINE:{n}:{text}`,
`INSERT_LINE:{n}:{text}`, `DELETE_LINE:{n}`, `CLR_LINE:{n}`, `CLR_LINE`, `CLR_PREV`, `CLR_ALL`, `GOTO:{row}:{col}`,
`HOME`, `END`. A log line that is exactly `END` (or `HOME`, `CLR_ALL`, …) is taken as a command and disappears. Use the
short forms for anything new.
### 7.3 Example
```c
#define RST "\x1B[0m"
#define TITLE "\x1B[1;96m" /* bold bright cyan */
#define GREEN "\x1B[92m"
#define RED "\x1B[1;91m"
void status_init(void) /* once, and again whenever the PC asks */
{
printf("~ClA1:\n");
printf("~WrLi1:0:" TITLE "PUMP STATUS" RST "\n");
printf("~WrLi1:1:\xE2\x94\x80\xE2\x94\x80\xE2\x94\x80\xE2\x94\x80\xE2\x94\x80\xE2\x94\x80\n"); /* ────── */
}
void status_update(float flow_lpm, float pressure_bar, int fault)
{
printf("~WrLi1:2:Flow %6.2f l/min\n", flow_lpm);
printf("~WrLi1:3:Pressure %6.2f bar\n", pressure_bar);
printf("~WrLi1:4:State %s\n", fault ? RED "FAULT" RST : GREEN "RUN" RST);
}
```
Pad values with `printf` widths (`%6.2f`) so columns stay aligned. A bar of `n` blocks out of 20:
```c
char bar[20 * 3 + 1]; int k = 0;
for (int i = 0; i < 20; i++) { const char *c = (i < n) ? "\xE2\x96\x88" : " "; while (*c) bar[k++] = *c++; }
bar[k] = 0;
printf("~WrLi1:5:Temp %s %5.1f C\n", bar, temp);
```
## 8. Graph commands (text protocol)
Each port has up to **26 graphs, `A` to `Z`, with up to 32 signals each**. One `I` line creates a graph, one `S` line
per signal sets it up, and each sample is one data line. Graph lines never appear in the log.
```text
~{A:I:Quick Start:500:S:T:R:Sample::0} graph A: "Quick Start", streamer, 500 points
~{A:S:1:F32:R:Sine:V:0:4FC3F7} signal 1: Sine, volts, light blue
~{A:S:2:F32:R:Cosine:V:0:FFB74D} signal 2: Cosine, volts, orange
~{A:1:0.841:0.540} one sample of both signals
```
### 8.1 Line format
```text
~{G:C:field1:field2:...}
~{G:C:field1:field2:...}*XX optional CRC-8, section 9
```
`G` graph letter `A`–`Z`; `C` command letter; fields separated by `:`; `}` ends the command; LF ends the line.
Anything after `}` (or `*XX`) is ignored. **Leave optional fields off at the end** rather than empty in the middle:
some fields read empty as 0, not as their default.
| The line | Result |
|---|---|
| Valid | Executed; not shown in the log |
| Broken frame: no `}`, letter not `A`–`Z`, unknown command letter, missing `:`, wrong CRC | Shown in the log as text; listed in RX Error Collector with the reason; status bar **Err:** counts up |
| Right shape, wrong fields (too few fields, signal 40) | Dropped silently |
| Names a graph that does not exist (except `I`) | Dropped silently |
### 8.2 `I`: create a graph
```text
~{G:I:name:buffer:mode:xtype:xdisplay:xlabel:xunit:xprefix}
```
| # | Field | Values | Default / notes |
|---|---|---|---|
| 1 | name | Tab title, text | Required (may be empty) |
| 2 | buffer | Whole number > 0. Streamer: points kept and visible X width. Frame: max points per frame per signal. Logger: not used | `1000` if empty, 0 or not a number |
| 3 | mode | `S` streamer, `L` logger, `F` frame | Required; anything else gives a streamer |
| 4 | xtype | `T` time, `V` value. Stored only; no visible effect | Required (may be empty) |
| 5 | xdisplay | `R` raw, `F` formatted. Stored only | Required (may be empty) |
| 6 | xlabel | Text under the X axis | Empty |
| 7 | xunit | Shown as `[unit]` after the label | Empty |
| 8 | xprefix | Power of ten applied to every X sent (section 8.5) | `0` |
Fewer than 5 fields: the line is dropped. Re-sending `I` resets the graph (rule 7). On the PC, **☰ → Tools → Panel
Configuration...** can keep data on a re-init (**Preserve Data on Re-Init**) and can block the firmware's `C`, `P`
and `X` (destroy; the X-axis commands of section 8.8 are not blocked).
```text
~{A:I:Speed Control:800:S:T:R:Sample (10 ms)::0} streamer, newest 800 samples
~{B:I:Thermal & Battery:100000:L:T:R:Time:min:0} logger, X in minutes
~{C:I:Phase Currents:256:F:V:R:Electrical angle:deg:0} frame, up to 256 points per frame
~{D:I:Battery Log:1000:L:T:R:Time:s:-3} logger, X sent in ms, shown in s
```
### 8.3 Graph modes
| | Streamer `S` | Logger `L` | Frame `F` |
|---|---|---|---|
| Use for | Watching live values | Recording a whole run | Oscilloscope, spectrum, XY shapes |
| Keeps | The newest *buffer* points per signal | Every point, up to 1 000 000 per signal by default (**Ingest Policies…**, 0 = no limit) | Only the last complete frame |
| X axis | Follows the newest point; the window shows the *buffer* samples | Whole run | Fitted to each frame |
| Redraw | As data arrives | As data arrives | Only on `~{G:F}` |
| Data command | `1` (auto-X) or `0` | `0` (time) or `1` | `0` or `1`, then `F` |
- A streamer's visible window is as wide as its buffer: *buffer* samples with auto-X; with explicit X, *buffer* ×
the spacing of the samples (500 samples at 10 ms = a 5 s window). It fills from the right. (Beta 1 made it
*buffer* X units wide, so a streamer with a time X in seconds looked empty: use auto-X there.)
- `~{G:X:R:min:max}` fixes the X range in every mode (section 8.8).
- **XY:** there is no XY switch. While each X is ≥ the previous one, a normal trace is drawn; once X goes back, that
signal's points are joined in arrival order. In a frame graph each flush starts the check again, which is how XY
plots are made (section 8.7).
### 8.4 `S`: add or update a signal
```text
~{G:S:id:type:format:name:unit:prefix:colour:visible}
```
| # | Field | Values | Default / notes |
|---|---|---|---|
| 1 | id | `1`–`32` | Required; other numbers: line dropped |
| 2 | type | `u8 i8 u16 i16 u32 i32 u64 i64 f32 f64`, any case | `i32` if empty/unknown. In text lines it only matters for the sign of hex values |
| 3 | format | `R` real, `D` signed int, `U` unsigned int, `F`*n* zero-padded int, `H` hex, `H`*n* padded hex. **Capitals** | `D` if empty/unknown |
| 4 | name | Text | Required (may be empty) |
| 5 | unit | Text, shown as `[unit]`; converts nothing | Required (may be empty) |
| 6 | prefix | Power of ten applied to every value (section 8.5) | Required (may be empty = 0) |
| 7 | colour | `RRGGBB`, six hex digits, no `#` | Empty: next colour of the graph style's palette |
| 8 | visible | `1` shown, `0` hidden at start (hidden signals still record) | Shown |
Fewer than 6 fields: the signal is not created and its data is dropped.
| Format | Reads | Example | Note |
|---|---|---|---|
| `R` | Real number | `23.5`, `-0.004`, `1.2e-3`, `NaN` | The only format for decimals. `NaN` leaves a gap |
| `D` | Signed integer | `1500`, `-42` | `23.5` reads as 0 |
| `U` | Unsigned integer | `1500` | A minus sign reads as 0 |
| `F`*n* | Zero-padded integer | `F6`: `001500` | Read like `D` |
| `H` | Hex, no `0x` | `5DC` | With a signed type, two's complement of that size: `FFFF` as `i16` = −1 |
| `H`*n* | Zero-padded hex | `H4`: `05DC` | Read like `H` |
Usual pairs: `F32` + `R` for real numbers, `I16`/`I32` + `D` for counts, `U16` + `H4` for raw registers.
```text
~{A:S:1:F32:R:Temperature:°C:0:FF6644}
~{A:S:2:I16:D:Humidity:%:0} palette colour
~{B:S:1:U16:D:Voltage:V:-3:00FF00} sent in mV, shown in V
~{C:S:1:U16:H4:ADC:cnt:0:FFFFFF}
~{A:S:3:F32:R:Debug:V:0::0} hidden at start
```
Data values follow **rising id order**, not the id: with signals 1 and 3, the first value goes to 1, the second to 3.
Keep ids 1, 2, 3, … without gaps. The legend shows *name [unit]*.
### 8.5 Units and SI prefixes
SerialFlow multiplies each value by 10^prefix on arrival and stores and shows the result, so firmware can send
integers in small units: prefix `-3` turns mV into V and ms into s; `-6` µ, `-9` n, `3` k, `6` M; any integer works.
| Prefix | Applies to |
|---|---|
| Signal prefix (`S` field 6) | Every value of that signal, text and binary |
| Graph X prefix (`I` field 8) | Explicit X (`0`, binary explicit X) and the X of `E`, `T`, `B` |
| Not scaled | Auto-X counter; `M` X positions; every Y you send in `H`, `T`, `Y` |
So, with X sent in ms (prefix −3) and voltage in mV (prefix −3): a limit line at 3.3 V is `~{B:H:1:3.3:FF5252:D:Low}`
(shown units); an event at 3 s is `~{B:E:1:3000:Start}` (sent units); a marker line at 3 s is
`~{B:M:1:3:FFFF00:S:3 s}` (`M` is not scaled). For factors that are not powers of ten (e.g. 3.3/4095), send counts
and use **Signal Manager** on the PC (section 15.8).
### 8.6 `1` and `0`: send data
| Command | Line | X |
|---|---|---|
| `1` auto-X | `~{G:1:v1:v2:...}` | A counter: 0, 1, 2, … per data line (and per binary row) |
| `0` explicit X | `~{G:0:x:v1:v2:...}` | The first field × 10^xprefix |
- One line = one sample of all signals, in rising id order.
- Fewer values than signals: only the first signals get a point. More values: extras ignored.
- Empty or unreadable value → 0 (send `NaN` for a gap in an `R` signal). Non-numeric X → the line is dropped.
- The auto-X counter restarts at 0 on `I`, on `~{G:C}` and on `~{G:F}`.
- Don't mix `1` and `0` on one graph. While paused (`~{G:P}`) data is dropped, not queued.
- Every value also feeds the dashboards and the Data Collector.
```c
/* Arduino: a logger with explicit X in ms, shown in s; values in mV, shown in V. */
void setup() {
Serial.begin(115200);
Serial.println("~{B:I:Battery Log:1000:L:T:R:Time:s:-3}");
Serial.println("~{B:S:1:U16:D:Battery:V:-3:81C784}");
Serial.println("~{B:H:1:3.3:FF5252:D:Low 3.3 V}");
}
void loop() {
long mv = analogRead(A0) * 5000L / 1023; /* replace with your measurement in mV */
Serial.print("~{B:0:"); Serial.print(millis()); Serial.print(":"); Serial.print(mv); Serial.println("}");
delay(1000);
}
```
(Each `Serial.print` call here may go out on its own; that is fine as long as the line is finished within 100 ms.
The `SfLine` helper in section 13.2 builds the same line and sends it in one write, rule 15.)
### 8.7 Frame mode and XY
Data lines fill a hidden staging buffer per signal; `~{G:F}` swaps the staged points onto the screen in one step
(status strip shows `Frame # n`), empties the staging buffers and restarts auto-X at 0. Points beyond *buffer* per
signal before the `F` are dropped. A signal with no points in a frame is empty after the flush. `F` does nothing on
streamers and loggers.
```c
/* Arduino: capture first, then send, so serial output does not disturb the sample timing. */
#define N 128
uint16_t samples[N];
void setup() {
Serial.begin(115200);
Serial.println("~{C:I:Scope:128:F:V:R:Sample::0}");
Serial.println("~{C:S:1:U16:D:CH1:cnt:0:00FF88}");
Serial.println("~{C:Y:R:0:1023}"); /* fixed Y range so frames compare */
}
void loop() {
for (int i = 0; i < N; i++) samples[i] = analogRead(A0);
for (int i = 0; i < N; i++) { Serial.print("~{C:1:"); Serial.print(samples[i]); Serial.println("}"); }
Serial.println("~{C:F}");
delay(50);
}
```
**XY:** send each point's X as explicit X (`0`) and its Y as the signal value, then `F`. Example, a Lissajous figure:
```c
void setup() {
Serial.begin(115200);
Serial.println("~{D:I:Lissajous:200:F:V:R:X:V:0}");
Serial.println("~{D:S:1:F32:R:Y:V:0:69F0AE}");
Serial.println("~{D:X:R:-1.2:1.2}"); /* fixed X range: no refit per frame */
Serial.println("~{D:Y:R:-1.2:1.2}");
Serial.println("~{D:X:E:1}"); /* 1:1, so a circle stays round */
}
void loop() {
static float phase = 0;
for (int i = 0; i < 200; i++) {
float a = i * 2 * PI / 199;
Serial.print("~{D:0:"); Serial.print(sin(3 * a), 3);
Serial.print(":"); Serial.print(sin(2 * a + phase), 3); Serial.println("}");
}
Serial.println("~{D:F}");
phase += 0.05;
}
```
Without `~{G:X:R:…}` a frame graph fits X to every frame, so an XY shape whose size changes always fills the width,
and in a wide pane a circle looks like an ellipse. Send the X range (and the Y range) once, plus `~{G:X:E:1}` for
equal axes, and the picture stays still and round. These need beta 2: **beta 1 reads every `~{G:X…}` as "delete the
graph"**. For beta 1, hold X steady by hand: send one frame that spans the wanted X range, press **Fit** on the graph
toolbar, then stream.
### 8.8 Axis, legend, lines, events, notes, bookmarks
**`Y` axis:** `~{G:Y:R:min:max}` fixes the range (min < max, shown units); `~{G:Y:A}` auto-scales again (default);
`~{G:Y:L:label:unit}` labels the axis *label [unit]*. A user's zoom wins over a fixed range. In stacked lanes it applies
to the top lane.
**`X` axis** (since beta 2):
| Line | Effect |
|---|---|
| `~{G:X:R:min:max}` | Fixes the X range in every mode: frame and XY graphs stop refitting, streamers and loggers stop following the newest point. min and max in the units you send X in (scaled by the `I` line's xprefix, like data X); max > min |
| `~{G:X:A}` | Automatic X again (the mode's normal behaviour) |
| `~{G:X:L:label:unit}` | Names the X axis *label [unit]*, replacing the `I` line's; also the X column name in CSV export |
| `~{G:X:E:1}` / `~{G:X:E:0}` | Equal axes on / off: one unit as long on X as on Y, so a circle stays round. Overlay layout only |
Only a bare `~{G:X}` destroys the graph; `X` with anything after it is an axis command, and an invalid one is ignored.
A user's zoom, pan or **Fit** wins over a fixed X range until Auto-Scale (double-click). The X range, equal axes and
the Y set-up are kept in a saved session.
**`L` legend:** `~{G:L:visible:position:size:alpha}`; `visible` `1` / `0` shows or hides it (the firmware's choice
wins over **New View Defaults → Show legend**; the user can still toggle it with G on the plot); position
`TL TC TR BL BC BR` (default `TR`), size default 12 (empty = smallest), alpha 0–255 (default 200, empty = 0). Example
`~{A:L:1:TL:12:200}`, or `~{A:L:0}` for no legend.
**`H` horizontal and `M` vertical lines:**
```text
~{G:H:id:y:colour:style:label} ~{G:M:id:x:colour:style:label}
~{G:H:id} remove line id ~{G:H:0} remove all H lines (M the same)
```
id ≥ 1 (the same id moves or relabels the line; never keep a line with id 0); `H` y in shown units; `M` x as sent
(not scaled); colour default `H` `CCCCCC`, `M` `FFFF00`; style `S` solid, `D` dashed (default), `T` dotted,
`A` dash-dot; label optional (`H` label at the left end, `M` label at the top). `~{G:C}` keeps them. Example
`~{B:H:1:85:FF5252:D:MOSFET limit 85 °C}`.
**`E` event markers:** `~{G:E:id:x:label:colour:style}`; `~{G:E:id}` removes one, `~{G:E:0}` all. X is scaled like
data X; colour default `00FF00`; style default `D`. `~{G:C}` removes events. Use `E` for things that happen during a
run, `M` for fixed reference positions. An event can be sent after the data it marks.
```c
if (temp > 82.0f && !derated) { derated = true; printf("~{B:E:3:%.2f:Thermal derate:FF5252:D}\n", t); }
```
**`T` notes:** `~{G:T:id:x:y:text:colour:size:rotation}`; colour default `FFFFFF`, size default 12, rotation degrees
clockwise (default 0); `~{G:T:id}` / `~{G:T:0}` remove. The text starts at X and is centred on Y. `~{G:C}` removes
notes. Example `~{B:T:1:19.33:89.6:Peak 82.6 °C:F06292:12:0}`.
**`B` bookmarks:** `~{G:B:x:label:comment:colour}` adds a flag at X (scaled), listed in **☰ → View → Graph
Bookmarks**. There is no id, so it cannot be moved. `~{G:C}` keeps bookmarks; `~{G:B}` removes them all (it did
nothing in beta 1).
### 8.9 Control commands
| Line | Effect |
|---|---|
| `~{G:C}` | Clear: empties every signal, restarts auto-X, removes events and notes. Keeps signals, `H`/`M` lines, bookmarks, Y axis, legend |
| `~{G:C:id}` | Empties only signal *id* |
| `~{G:P}` | Pause: drops data and `F` until `R` |
| `~{G:R}` | Resume; nothing sent while paused is replayed |
| `~{G:V:id:1}` / `~{G:V:id:0}` | Show / hide signal *id* (`0` = all); hidden signals keep recording |
| `~{G:X}` | Destroy the graph and its data (also leaves dashboards). A new `I` creates it again. Only this bare form: `~{G:X:…}` is the X axis (section 8.8) |
| `~{G:W[:label[:P\|C\|B]]}` | Save the graph's data to a file as it is now: `.sfplot` (`P`, default), CSV (`C`) or both (`B`). Opt-in, section 9 |
### 8.10 Cheat sheet
| Cmd | Fields | Example |
|---|---|---|
| `I` | name:buffer:mode:xtype:xdisplay[:xlabel:xunit:xprefix] | `~{A:I:Sensors:500:S:T:R:Sample::0}` |
| `S` | id:type:format:name:unit:prefix[:colour:visible] | `~{A:S:1:F32:R:Temperature:°C:0:FF6644}` |
| `1` | v1:v2:… | `~{A:1:23.5:67.2}` |
| `0` | x:v1:v2:… | `~{B:0:1.5:3.31}` |
| `F` | — | `~{C:F}` |
| `C` | [id] | `~{A:C}` · `~{A:C:2}` |
| `P` / `R` / `X` | — | `~{A:P}` · `~{A:R}` · `~{A:X}` |
| `V` | id:0/1 | `~{A:V:3:0}` |
| `Y` | `R`:min:max · `A` · `L`:label[:unit] | `~{A:Y:R:-10:100}` · `~{A:Y:A}` · `~{A:Y:L:Voltage:mV}` |
| `X` + sub-command (beta 2) | `R`:min:max · `A` · `L`:label[:unit] · `E`:1/0 | `~{D:X:R:-1.2:1.2}` · `~{D:X:A}` · `~{B:X:L:Time:min}` · `~{D:X:E:1}` |
| `L` | visible[:position:size:alpha] | `~{A:L:1:TR:12:200}` · `~{A:L:0}` |
| `H` | id:y[:colour:style:label] | `~{A:H:1:30:FF4444:D:High temp}` |
| `M` | id:x[:colour:style:label] | `~{A:M:1:250:FFFFFF:S:Calibration}` |
| `E` | id:x[:label:colour:style] | `~{A:E:1:500:Motor start:00FF00:S}` |
| `T` | id:x:y:text[:colour:size:rotation] | `~{A:T:1:100:50:Peak:FF0000:14:0}` |
| `B` | x:label[:comment:colour] · nothing = remove all | `~{A:B:100:Peak:Max voltage:FF0000}` · `~{A:B}` |
| `W` (beta 2, opt-in) | [label[:P/C/B]] | `~{A:W}` · `~{A:W:spike}` · `~{A:W:spike:B}` |
## 9. Device commands: save captures, start and stop logging
Since beta 2 the firmware can ask SerialFlow to keep data: save the log, a status window or a graph to a file, and
start or stop the Data Logger and the Data Collector. The typical use: a streamer graph shows the newest *buffer*
samples; when the firmware sees something worth a look (a fault, a spike, the end of a test step) it sends one save
line, and exactly that window of data is kept while the stream goes on.
**Off by default.** The user must tick **Settings → Device Captures → Allow device commands that save captures and
start or stop logging**, so a stray line can never write files. While it is off the commands are still recognised and
consumed (nothing shows in the log) but do nothing; the first one of a run shows a one-time hint in the status bar.
Always tell the user to tick it. Beta 1 does not know these commands: it shows them in the log as text (and lists
`~{G:W}` in the RX Error Collector as an unknown command).
| Line | What it does |
|---|---|
| `~SvLog` · `~SvLog:label` | Saves the main log, the lines it holds now, to a text file |
| `~SvLog{W}` · `~SvLog{W}:label` | Saves status window `W` (`1`–`9`) instead: `~SvLog2:pack` |
| `~{G:W}` · `~{G:W:label}` · `~{G:W:label:F}` | Saves graph `G`'s data as it is now. `F`: `P` `.sfplot` session (default), `C` CSV, `B` both. `~{A:W::C}` = no label, CSV |
| `~LogOn` · `~LogOn:label` | Starts this port's Data Logger on a new file in the capture folder, in the format set in its panel (`.txt`, `.csv` or `.bin`) |
| `~LogOff` | Stops the Data Logger (its panel gets its own file path back) |
| `~RecOn` · `~RecOn:label` | Starts a Data Collector recording (all ports); the label is the run name. Its files go to the Data Collection folder, not the capture folder |
| `~RecOff` | Stops the recording |
- Like every command: at the start of a line, ended by `\n` (or `\r\n`), case-sensitive.
- **File names:** the label becomes the file name. Blanks and characters a file name can't hold become `_`, at most
60 characters (`~SvLog:motor stall/1` → `motor_stall_1.txt`). Without a label SerialFlow numbers the captures with
one rising id: `log-0001.txt`, `window2-0002.txt`, `graphA-0003.sfplot`, `datalog-0004.txt`. An existing file is
never overwritten: `boot.txt`, `boot-2.txt`, … So send one save per event, not one per sample.
- **Folder:** **Settings → Device Captures → Capture Folder**; empty = `\captures`, normally
`Documents\SerialFlow\captures`.
- **What a log save holds:** the lines in the log or window when the command arrives (not the command line itself),
UTF-8, one per line, with `[time] ` in front when the terminal shows timestamps.
- **What a graph save holds:** every signal (names, units, colours), the `H`/`M` lines, events, notes and bookmarks,
frozen at the command; samples that arrive while the file is written are not in it. The view (zoom, axis ranges) is
not saved: the capture opens fitted to its data. CSV is the wide form (long when X goes backwards).
- **Ignored, with a status-bar notice:** `~SvLog{W}` for a window that does not exist (no window is opened), `~{G:W}`
for a graph that does not exist, `~LogOn` while the Data Logger is logging, `~RecOn` while recording.
- Files are written in the background; the port is never held up.
**Saved Captures** (**☰ → View → Saved Captures**, or its toolbar button) lists every capture of every port, newest
first: Time, Label, Kind (`Log · Terminal`, `Log · Window 2`, `Graph A · .sfplot`, `Graph A · CSV`, `Data Logger`),
Port, Size. **Open** (or a double-click) opens it: a graph capture in a new graph view, or (**Graphs open in**) added to an
open graph as a compare layer; a text capture in the default viewer. **Open Folder**, **Delete** (asks first) and
**Refresh**. The list survives a restart. Recordings started with `~RecOn` are not listed there; they are Data
Collector runs (section 15.6).
```c
/* Arduino: a streamer of the newest 500 current samples (5 s); keep them when an overcurrent trips. */
void setup() {
Serial.begin(115200);
Serial.println("~{A:I:Phase current:500:S:T:R:Sample (10 ms)::0}");
Serial.println("~{A:S:1:F32:R:Current:A:0:FF7043}");
}
void loop() {
static bool tripped = false;
float amps = read_current(); /* your measurement */
Serial.print("~{A:1:"); Serial.print(amps, 2); Serial.println("}");
if (amps > 25.0f && !tripped) { /* once per event, not once per sample */
tripped = true;
Serial.println("~{A:W:overcurrent:B}"); /* overcurrent.sfplot + overcurrent.csv */
Serial.println("~SvLog:overcurrent"); /* and the log up to now */
}
if (amps < 20.0f) tripped = false;
delay(10);
}
```
Log one test run to its own file: `~LogOn:test42` before the run, `~LogOff` after it.
## 10. CRC-8 on graph lines
Add `*XX` after the `}` and SerialFlow drops the line if it does not match. Optional, per line, on any graph command.
- Polynomial `0x07` (x⁸ + x² + x + 1), start value `0x00`, no reflection, no final XOR (CRC-8/SMBUS). Check value of
the text `123456789` is `0xF4`.
- Computed over every character from `{` to `}`, both braces included. Not the `~`, not the `*XX`.
- Sent as `*` and two hex digits right after `}` (upper case usual, lower case accepted).
- **ASCII only on CRC lines** (write `degC`, `uA`).
- A line without `*XX`, or with `*` not followed by two hex digits, is accepted unchecked.
| Line | CRC |
|---|---|
| `~{A:1:3000:3004.9}*7E` | `0x7E` |
| `~{A:1:2200:2187}*7F` | `0x7F` |
| `~{A:1:23.5}*35` | `0x35` |
| `~{A:I:Sensors:500:S:T:F:Sample::0}*C1` | `0xC1` |
A rejected line is shown as text, counted in the status bar's **Err:** and listed in **☰ → Tools → RX Error
Collector...** with a reason such as `CRC mismatch (expected 0xB4, got 0xC7)` (*expected* = the CRC that came with the
line, *got* = the CRC of what arrived). A wrong digit in a line *without* CRC reaches the graph unchecked. The CRC
code is in section 13 (`sf_crc8`, `crc8`). **☰ → View → CRC Calculator**, algorithm **CRC-8**, checks a line by hand:
paste it from `{` to `}`.
## 11. Packed binary graph data
Binary frames carry **data rows only** (like `1` and `0`). Create the graph and signals with text `I` and `S` lines
first; send `F`, `C`, `H`, `E` and everything else as text. Binary and text mix freely in one stream. Binary data for
a graph that does not exist is dropped.
Use binary for many signals, high rates, full float precision, or fast frames. For one or two slow signals, text is as
good and easier to read.
**On the wire:**
```text
0x00 LEN_LO LEN_HI [COBS-encoded packet, LEN bytes] 0x00
```
LEN = number of COBS-encoded bytes, 1–1 024, low byte first. COBS removes every zero byte from the packet, so `0x00`
marks start and end (it adds 1 byte, +1 per 254).
**The packet before COBS:**
| Byte | Field | Values |
|---|---|---|
| 0 | Magic | `0xBD` |
| 1 | Graph | `0` = A … `25` = Z |
| 2 | Command | `0x01` auto-X, `0x02` explicit X |
| 3 | Flags | bit 0 `0x01`: each row starts with an X · bit 1 `0x02`: all values have the type in byte 5 · bit 2 `0x04`: batch, a row count follows |
| 4 | Signal count | `1`–`32` values per row |
| 5 | Value type | `0`–`9` (table below); must be valid even when bit 1 is clear |
| 6–7 | Row count | Only with the batch flag; low byte first; 1–10 000 |
| … | Rows | See below |
| last | CRC-8 | Over every byte before it, same CRC as section 10 |
Row: if bit 0, an 8-byte IEEE 754 double X first (little-endian). Then, with bit 1 set, *count* values of the byte-5
type; with bit 1 clear, *count* pairs of (1-byte type code, value). All little-endian (Cortex-M, ESP32, RP2040, AVR,
x86 are little-endian, so `memcpy` of a variable is right).
| Code | Type | Bytes | Code | Type | Bytes |
|---|---|---|---|---|---|
| 0 | u8 | 1 | 5 | i32 | 4 |
| 1 | i8 | 1 | 6 | u64 | 8 |
| 2 | u16 | 2 | 7 | i64 | 8 |
| 3 | i16 | 2 | 8 | f32 | 4 |
| 4 | u32 | 4 | 9 | f64 | 8 |
- Rows are used exactly like text data: rising id order, each signal's SI prefix applied, the X prefix applied to
explicit X; auto-X rows share the graph's counter with text `1` lines; in frame mode rows are staged until a text
`~{G:F}`. The `S` line's type is not used: the packet's type code decides.
- Use command `0x02` **with** flag bit 0, or `0x01` **without** it.
- Size: the COBS-encoded packet must be ≤ 1 024 bytes; a packet (header + row count + rows + CRC) of ≤ 1 019 bytes
always fits. Rows per frame with a 1 000-byte budget = (1 000 − 9) ÷ bytes per row: 2 × f32 auto-X → 123 rows;
4 × f32 → 61; 2 × i16 → 247; 1 × f32 with explicit X (12 bytes) → 82.
- Send each frame in one go: a frame that pauses more than 100 ms in the middle is dropped.
- A frame is dropped for a wrong length, bad COBS, wrong magic, graph > 25, signal count 0 or > 32, type > 9, row
count 0 or > 10 000, too few bytes, or a CRC mismatch. A dropped frame counts in the status bar's **Err:** and is
listed in **RX Error Collector** (graph `?`, first bytes in hex, the reason, e.g. "CRC mismatch in binary packet: got
0x7E, expected 0x3C"); still check the encoder against the example below.
- Binary frames are reassembled across serial reads.
- On 8-bit AVR `double` is 4 bytes: explicit-X binary rows need a real 8-byte double; use auto-X or send time as a
signal.
- Nothing between board and PC may change bytes (rule 16).
**Reference bytes:** one row of two f32 (23.5, 67.25) on graph A with auto-X is the packet
`BD 00 01 02 02 08 00 00 BC 41 00 80 86 42` + CRC `62`, sent as the 20 bytes
`00 10 00 02 BD 05 01 02 02 08 01 03 BC 41 05 80 86 42 62 00`. The encoders in section 13 produce exactly this.
## 12. Speed and timing
The serial link is the limit, not SerialFlow (its parser and log handle hundreds of thousands of lines per second).
At 8N1 each byte costs 10 bits: *lines per second ≈ baud ÷ 10 ÷ bytes per line*.
| Line | Bytes with `\r\n` | 115 200 baud | 921 600 baud |
|---|---|---|---|
| `~{A:1:3000:3004.9}` | 20 | ≈ 576 lines/s | ≈ 4 600 lines/s |
| `~{A:1:3000:3004.9}*7E` | 23 | ≈ 500 lines/s | ≈ 4 000 lines/s |
| Binary, 100 rows of 2 × f32 per frame | ≈ 817 per frame | ≈ 1 400 rows/s | ≈ 11 000 rows/s |
- All signals of a graph in one data line; auto-X when possible; only the digits needed (`%.1f`, not `%f`);
integers in small units with an SI prefix instead of long decimals; raise the baud; CRC only where needed.
- Frame mode: capture, then send, then `F`; buffer = the frame size.
- High rates: packed binary in batch frames.
- Send set-up lines (`I`, `S`, `H`, `Y`, `L`) while the stream is quiet: a lost `I` or `S` costs more than a lost sample.
- **Lines split across serial reads:** SerialFlow reads the port in blocks, and a block often ends in the middle of
a line. Since beta 2 an unfinished command line is held back and joined with the next block, so it works at any
rate, as long as its rest arrives within 100 ms (rule 15). Beta 1 lost such lines (shown as text, sample gone),
more often at high rates; there, one write per line and binary for fast streams helped.
## 13. Firmware: a portable helper and per-platform recipes
### 13.1 The portable C helper (`sf.c`)
Plain C99, no heap, works on any MCU. The user provides one function, `sf_write()`. Every line is built in RAM and
sent with one write (rule 15), and graph lines get an optional CRC-8. Tested: the outputs match sections 10 and 11.
```c
/* sf.c: SerialFlow output helpers. Plain C99, no heap, any MCU.
You provide sf_write(): send len bytes on the UART or USB, exactly as given (no LF -> CR LF translation). */
#include
#include
#include
#include
void sf_write(const uint8_t *data, size_t len); /* yours */
#ifndef SF_LINE_MAX
#define SF_LINE_MAX 128 /* longest line, including "~", "*XX" and "\n" */
#endif
/* CRC-8: polynomial 0x07, start value 0, no reflection, no final XOR (check value of "123456789" = 0xF4). */
uint8_t sf_crc8(const uint8_t *p, size_t len)
{
uint8_t crc = 0;
while (len--) {
crc ^= *p++;
for (int i = 0; i < 8; i++)
crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x07) : (uint8_t)(crc << 1);
}
return crc;
}
/* One text line (log text or a status-window line), built in RAM and sent in one write. Adds "\n".
sf_line("~WrLi1:2:Speed %5d rpm", rpm); sf_line("\x1B[92m[ OK ]\x1B[0m ADC ready"); */
void sf_line(const char *fmt, ...)
{
char buf[SF_LINE_MAX];
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(buf, sizeof buf - 1, fmt, ap); /* keep one byte for '\n' */
va_end(ap);
if (n < 0) return;
if (n > (int)sizeof buf - 2) n = (int)sizeof buf - 2; /* too long: cut (text only) */
buf[n++] = '\n';
sf_write((const uint8_t *)buf, (size_t)n);
}
/* One graph command. fmt is the part from '{' to '}'; "~" is added in front, "*XX" (if crc) and "\n" after.
sf_cmd(0, "{A:I:Motor:800:S:T:R:Sample::0}"); sf_cmd(1, "{A:1:%d:%.1f}", set_rpm, rpm); */
void sf_cmd(int crc, const char *fmt, ...)
{
char buf[SF_LINE_MAX];
const int room = SF_LINE_MAX - 1 - 4; /* after '~'; keep 4 bytes for "*XX\n" */
va_list ap;
buf[0] = '~';
va_start(ap, fmt);
int n = vsnprintf(buf + 1, (size_t)room, fmt, ap);
va_end(ap);
if (n < 0 || n >= room) return; /* too long: drop it, never send half a command */
int len = 1 + n;
if (crc) {
static const char hex[] = "0123456789ABCDEF";
uint8_t c = sf_crc8((const uint8_t *)buf + 1, (size_t)n); /* over '{' ... '}' */
buf[len++] = '*';
buf[len++] = hex[c >> 4];
buf[len++] = hex[c & 0x0F];
}
buf[len++] = '\n';
sf_write((const uint8_t *)buf, (size_t)len);
}
/* ---- Packed binary frames (optional) ---- */
#define SF_MAX_PACKET 1000 /* packet incl. CRC; keeps the COBS frame under 1 024 bytes */
/* COBS encoder. out must hold len + len / 254 + 1 bytes. Returns the encoded length. */
static size_t sf_cobs_encode(const uint8_t *in, size_t len, uint8_t *out)
{
size_t code_pos = 0, out_pos = 1;
uint8_t code = 1;
for (size_t i = 0; i < len; i++) {
if (in[i] == 0) {
out[code_pos] = code;
code_pos = out_pos++;
code = 1;
} else {
out[out_pos++] = in[i];
if (++code == 0xFF) {
out[code_pos] = code;
code_pos = out_pos++;
code = 1;
}
}
}
out[code_pos] = code;
return out_pos;
}
/* Adds the CRC after pkt[0 .. len-1], COBS-encodes and sends one frame. pkt needs room for one more byte. */
static void sf_send_packet(uint8_t *pkt, size_t len)
{
static uint8_t frame[3 + 1024 + 1];
pkt[len] = sf_crc8(pkt, len);
size_t n = sf_cobs_encode(pkt, len + 1, &frame[3]);
frame[0] = 0x00; /* start */
frame[1] = (uint8_t)(n & 0xFF); /* length, low byte */
frame[2] = (uint8_t)(n >> 8); /* length, high byte */
frame[3 + n] = 0x00; /* end */
sf_write(frame, n + 4);
}
/* One row of floats with auto-X, like ~{G:1:v1:v2:...}. count 1..32. */
void sf_bin_f32(char graph, const float *v, uint8_t count)
{
uint8_t pkt[6 + 32 * 4 + 1];
pkt[0] = 0xBD; /* magic */
pkt[1] = (uint8_t)(graph - 'A'); /* graph 0 = A */
pkt[2] = 0x01; /* auto-X */
pkt[3] = 0x02; /* flags: one value type */
pkt[4] = count; /* values per row */
pkt[5] = 8; /* f32 */
memcpy(&pkt[6], v, (size_t)count * 4);
sf_send_packet(pkt, 6 + (size_t)count * 4);
}
/* Many rows of floats in one frame, auto-X. v holds rows * count values, row after row.
Returns -1 if they don't fit: (8 + rows * count * 4 + 1) must be <= 1000. */
int sf_bin_f32_batch(char graph, const float *v, uint8_t count, uint16_t rows)
{
static uint8_t pkt[SF_MAX_PACKET];
size_t data = (size_t)rows * count * 4;
if (8 + data + 1 > SF_MAX_PACKET) return -1;
pkt[0] = 0xBD;
pkt[1] = (uint8_t)(graph - 'A');
pkt[2] = 0x01; /* auto-X */
pkt[3] = 0x02 | 0x04; /* flags: one value type, batch */
pkt[4] = count;
pkt[5] = 8; /* f32 */
pkt[6] = (uint8_t)(rows & 0xFF); /* row count, low byte first */
pkt[7] = (uint8_t)(rows >> 8);
memcpy(&pkt[8], v, data);
sf_send_packet(pkt, 8 + data);
return 0;
}
/* One row of floats with its own X (an 8-byte double), like ~{G:0:x:v1:...}. Not on 8-bit AVR (double = 4 bytes). */
void sf_bin_f32_x(char graph, double x, const float *v, uint8_t count)
{
uint8_t pkt[6 + 8 + 32 * 4 + 1];
pkt[0] = 0xBD;
pkt[1] = (uint8_t)(graph - 'A');
pkt[2] = 0x02; /* explicit X */
pkt[3] = 0x02 | 0x01; /* flags: one value type, X in each row */
pkt[4] = count;
pkt[5] = 8; /* f32 */
memcpy(&pkt[6], &x, 8);
memcpy(&pkt[14], v, (size_t)count * 4);
sf_send_packet(pkt, 14 + (size_t)count * 4);
}
```
Use it:
```c
/* once at start-up, and again when the PC asks (e.g. on '?') */
sf_line("\x1B[1;96mPUMP BOARD v1.2\x1B[0m ready");
sf_cmd(0, "{A:I:Pump:500:S:T:R:Sample::0}");
sf_cmd(0, "{A:S:1:F32:R:Flow:l/min:0:4FC3F7}");
sf_cmd(0, "{A:S:2:F32:R:Pressure:bar:0:FFB74D}");
sf_cmd(0, "{A:H:1:2.5:FF5252:D:Max 2.5 bar}");
sf_line("~ClA1:");
sf_line("~WrLi1:0:\x1B[1;96mPUMP STATUS\x1B[0m");
/* every sample */
sf_cmd(1, "{A:1:%.2f:%.3f}", flow, pressure); /* with CRC-8 */
sf_line("~WrLi1:2:Flow %6.2f l/min", flow);
/* binary instead, for fast data */
float row[2] = { flow, pressure };
sf_bin_f32('A', row, 2);
```
- `fmt` is a `printf` format: write `%%` for a literal `%` (a unit such as `Duty:%%:0`).
- `%f` needs float support in `vsnprintf` (see the platform notes). Without it, send integers in small units with an
SI prefix: `sf_cmd(1, "{A:1:%ld}", (long)(flow * 100))` with `~{A:S:1:I32:D:Flow:l/min:-2}`.
- On small MCUs (2 KB RAM, such as the ATmega328P) leave out the binary part: its two static buffers take about 2 KB.
With `-ffunction-sections` and `--gc-sections` (Arduino's default) unused functions and their buffers are dropped.
### 13.2 Arduino (AVR, SAMD, ESP32, RP2040, STM32duino, Teensy)
- `Serial.begin(115200)`; `Serial.print()` / `Serial.println()` (ends with `\r\n`, fine). `Serial.write(buf, len)`
sends a buffer in one write. `Serial` does not translate line endings, so binary frames can go through
`Serial.write()`.
- With `sf.c`: `void sf_write(const uint8_t *d, size_t n) { Serial.write(d, n); }` (in a `.cpp`/`.ino`, declare the
helpers `extern "C"` or rename `sf.c` to `sf.cpp`).
- **AVR (Uno, Nano, Mega):** `snprintf`/`vsnprintf` print no floats (`%f` gives `?`), and `double` is 4 bytes. Use
`Serial.print(value, digits)`, `dtostrf()`, or the `SfLine` class below. Explicit-X binary rows don't work on AVR.
- Native-USB boards (Leonardo, Micro, SAMD21, RP2040, ESP32-S2/S3 with USB CDC): the baud is ignored; some wait for DTR
(section 5). `while (!Serial) {}` in `setup()` then prints the set-up after the PC connects, which also solves
rule 6, but only with **DTR Enable** ticked.
- ESP32 Arduino: `Serial.printf()` prints floats.
`SfLine`: builds a line with ordinary `print()` calls, then sends it in one write, with an optional CRC (works on AVR):
```cpp
class SfLine : public Print {
public:
using Print::write;
size_t write(uint8_t b) override {
if (len < sizeof(buf) - 4) { buf[len++] = (char)b; return 1; }
return 0; // line too long: the rest is cut
}
void send(bool withCrc) {
if (withCrc) {
uint8_t crc = 0;
for (uint8_t i = 1; i < len; i++) { // buf[0] is '~': start at '{'
crc ^= (uint8_t)buf[i];
for (uint8_t k = 0; k < 8; k++)
crc = (crc & 0x80) ? (uint8_t)((crc << 1) ^ 0x07) : (uint8_t)(crc << 1);
}
const char hex[] = "0123456789ABCDEF";
buf[len++] = '*';
buf[len++] = hex[crc >> 4];
buf[len++] = hex[crc & 0x0F];
}
buf[len++] = '\n';
Serial.write((const uint8_t *)buf, len);
len = 0;
}
private:
char buf[100];
uint8_t len = 0;
};
SfLine line;
void sendSpeed(int setpoint, float speed) {
line.print("~{A:1:"); line.print(setpoint); line.print(':'); line.print(speed, 1); line.print('}');
line.send(true); // ~{A:1:3000:3004.9}*7E for (3000, 3004.9)
}
```
(For status rows or log text, call `line.send(false)`; the CRC is only for graph lines.)
Re-send the set-up when the PC asks:
```cpp
void loop() {
if (Serial.available() && Serial.read() == '?') sendSetup(); // a Quick Send button can send "?"
...
}
```
### 13.3 STM32 (HAL, STM32CubeIDE / GCC)
Retarget `printf` to a UART. On most Nucleo boards the ST-Link virtual COM port is `huart2` (check the board's user
manual; e.g. some use `huart1` or `huart3`). Put this in `main.c` (USER CODE sections). It replaces CubeIDE's weak
`_write()` from `syscalls.c`:
```c
#include
#include
extern UART_HandleTypeDef huart2;
int _write(int file, char *ptr, int len) /* printf ends up here, one call per line */
{
(void)file;
HAL_UART_Transmit(&huart2, (uint8_t *)ptr, (uint16_t)len, HAL_MAX_DELAY);
return len;
}
void sf_write(const uint8_t *data, size_t len) /* for sf.c: raw, also for binary frames */
{
HAL_UART_Transmit(&huart2, (uint8_t *)data, (uint16_t)len, HAL_MAX_DELAY);
}
```
- **Floats in printf:** Project → Properties → C/C++ Build → Settings → MCU/MPU Settings → tick **Use float with printf
from newlib-nano (-u _printf_float)**. Without it, `%f` prints nothing.
- Keep newlib's default stdout buffering: `printf` then hands `_write()` a whole line. `setvbuf(stdout, NULL,
_IONBF, 0)` makes it byte by byte.
- `HAL_UART_Transmit` blocks. For high rates use `HAL_UART_Transmit_DMA` with a buffer that stays valid until the
transfer completes (a ring buffer or double buffer), and never start a new DMA transfer while one is running.
- Keil MDK: retarget `fputc()` (`int fputc(int ch, FILE *f) { HAL_UART_Transmit(&huart2, (uint8_t *)&ch, 1,
HAL_MAX_DELAY); return ch; }`) with MicroLIB; IAR: `__write()`. Prefer `sf_write()` + `sf.c` for whole lines.
- **USB CDC (USB_DEVICE middleware):** `CDC_Transmit_FS()` returns `USBD_BUSY` while a transfer runs, and the buffer
must stay valid until it is done. Copy into a static buffer after the previous transfer finished:
```c
#include "usbd_cdc_if.h"
extern USBD_HandleTypeDef hUsbDeviceFS;
void sf_write(const uint8_t *data, size_t len)
{
static uint8_t tx[3 + 1024 + 1]; /* fits the largest binary frame */
USBD_CDC_HandleTypeDef *cdc = (USBD_CDC_HandleTypeDef *)hUsbDeviceFS.pClassData;
uint32_t t0 = HAL_GetTick();
if (cdc == NULL || len > sizeof tx) return; /* not enumerated yet */
while (cdc->TxState != 0) /* previous transfer still running */
if (HAL_GetTick() - t0 > 50) return; /* no PC reading: drop this line */
memcpy(tx, data, len);
CDC_Transmit_FS(tx, (uint16_t)len);
}
```
### 13.4 ESP-IDF (ESP32 family)
- `printf()` goes to the console: by default UART0 at 115 200 (menuconfig: Component config → ESP System Settings →
console output; USB-Serial-JTAG or USB CDC on chips that have it). The console adds CR before LF: fine for text, not
for binary.
- `ESP_LOGx()` adds a prefix (`I (1234) tag: `) and colour codes: use it for log text only, never for `~` commands.
- Raw writes for `sf_write()` on a UART:
```c
#include "driver/uart.h"
#define SF_UART UART_NUM_0
void sf_init(void) /* once, at start-up */
{
uart_driver_install(SF_UART, 1024, 4096, 0, NULL, 0); /* RX buffer, TX buffer */
}
void sf_write(const uint8_t *data, size_t len)
{
uart_write_bytes(SF_UART, (const char *)data, len); /* one call = contiguous bytes */
}
```
- If `printf` / `ESP_LOGx` also use this UART, let the console go through the same driver after installing it:
`uart_vfs_dev_use_driver(SF_UART)` (ESP-IDF 5.3 and later, `driver/uart_vfs.h`; earlier
`esp_vfs_dev_uart_use_driver()`). Or put SerialFlow on a second UART with its own USB-serial adapter.
- If other tasks also print, send all SerialFlow lines from one task or guard `sf_write()` with a FreeRTOS mutex
(rule 21).
- `printf("%f")` works by default on ESP-IDF.
- Dev boards with the auto-program circuit: leave **RTS Enable** off (section 5).
### 13.5 Zephyr and nRF Connect SDK (nRF52/53/54/91, STM32, …)
- `printk()` / `printf()` go to the `zephyr,console` UART. The UART console adds CR before LF: fine for text, not for
binary.
- The logging subsystem (`LOG_INF`, …) adds a timestamp and module prefix: log text only, never `~` commands.
- Raw writes:
```c
#include
#include
#include
static const struct device *const sf_uart = DEVICE_DT_GET(DT_CHOSEN(zephyr_console));
K_MUTEX_DEFINE(sf_lock);
void sf_write(const uint8_t *data, size_t len)
{
k_mutex_lock(&sf_lock, K_FOREVER);
for (size_t i = 0; i < len; i++) uart_poll_out(sf_uart, data[i]); /* blocking, byte by byte */
k_mutex_unlock(&sf_lock);
}
```
- Floats: `CONFIG_CBPRINTF_FP_SUPPORT=y` for `printk`/`snprintf` through cbprintf; with picolibc also
`CONFIG_PICOLIBC_IO_FLOAT=y`, with newlib `CONFIG_NEWLIB_LIBC_FLOAT_PRINTF=y`.
- `uart_poll_out` is fine for moderate rates; for high rates use the interrupt-driven or async UART API.
- USB CDC ACM samples often wait for DTR before printing: tick **DTR Enable** (section 5).
### 13.6 Raspberry Pi Pico SDK (RP2040, RP2350)
- `stdio_init_all()` and `printf()`. USB: `pico_enable_stdio_usb( 1)`, UART: `pico_enable_stdio_uart( 1)`
in `CMakeLists.txt`.
- **USB stdio sends nothing until the PC raises DTR** (the SDK default): tick **Settings → Port → DTR Enable**.
- stdio translates LF to CR LF by default. For binary frames use `putchar_raw()` (no translation):
```c
#include "pico/stdlib.h"
void sf_write(const uint8_t *data, size_t len)
{
for (size_t i = 0; i < len; i++) putchar_raw(data[i]);
stdio_flush();
}
```
On a hardware UART you can also write directly: `uart_write_blocking(uart0, data, len)`.
### 13.7 MicroPython and CircuitPython
Send each line with one `write` (not `print`, which may write the text and the newline separately):
```python
import sys
w = sys.stdout.write
w("~{A:I:Sensors:500:S:T:R:Sample::0}\n")
w("~{A:S:1:F32:R:Temperature:C:0:FF6644}\n")
w("~{A:1:%.2f}\n" % temp)
w("~WrLi1:2:Temp %6.2f C\n" % temp)
```
For CRC lines and binary frames, use `sf.py` (section 13.9; it runs on MicroPython) and write frames raw with
`sys.stdout.buffer.write(frame)` where the port has it, or with `machine.UART(...).write(frame)` on a separate UART.
USB REPL ports may need **DTR Enable** to send (section 5).
### 13.8 Bare-metal and others
- **avr-libc:** `static FILE uart_out = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE); stdout = &uart_out;`
with `int uart_putchar(char c, FILE *s)`. Floats: link with `-Wl,-u,vfprintf -lprintf_flt -lm`.
- **Microchip XC8 (PIC):** implement `void putch(char c)` to retarget `printf`.
- **NXP MCUXpresso:** `PRINTF()` from `fsl_debug_console`, or `LPUART_WriteBlocking(base, data, len)` for `sf_write()`.
- **Any other platform:** implement `sf_write()` with the HAL's blocking UART write and use `sf.c`.
- **Rust (embedded-hal, Embassy):** format each line into a `heapless::String` with `core::fmt::Write`, append `\n`,
then write the bytes in one call; the CRC and COBS functions translate directly from `sf.c`.
### 13.9 Python helper (`sf.py`): MicroPython, PC-side simulators, test files
Runs on CPython 3 and MicroPython. Tested: same bytes as `sf.c`.
```python
# sf.py: SerialFlow lines and packed binary frames. Runs on CPython 3 and MicroPython.
import struct
def crc8(data):
"""CRC-8, polynomial 0x07, start 0. crc8(b"123456789") == 0xF4."""
crc = 0
for b in data:
crc ^= b
for _ in range(8):
crc = ((crc << 1) ^ 0x07) & 0xFF if crc & 0x80 else (crc << 1) & 0xFF
return crc
def cmd(body, with_crc=False):
"""A graph command line. body runs from '{' to '}': cmd("{A:1:23.5}", True) -> "~{A:1:23.5}*35\\n"."""
line = "~" + body
if with_crc:
line += "*%02X" % crc8(body.encode()) # CRC lines must be plain ASCII
return line + "\n"
def cobs(data):
out = bytearray([0])
code_pos = 0
code = 1
for b in data:
if b == 0:
out[code_pos] = code
code_pos = len(out)
out.append(0)
code = 1
else:
out.append(b)
code += 1
if code == 0xFF:
out[code_pos] = code
code_pos = len(out)
out.append(0)
code = 1
out[code_pos] = code
return bytes(out)
TYPES = {"u8": (0, "B"), "i8": (1, "b"), "u16": (2, "H"), "i16": (3, "h"), "u32": (4, "I"),
"i32": (5, "i"), "u64": (6, "Q"), "i64": (7, "q"), "f32": (8, "f"), "f64": (9, "d")}
def frame(graph, rows, vtype="f32", xs=None):
"""One packed binary frame for graph 'A'..'Z'. rows = [[v1, v2, ...], ...], every row the same length (1..32).
xs = None for auto-X, or one X per row (explicit X, sent as a 64-bit double)."""
code, fmt = TYPES[vtype]
count = len(rows[0])
batch = len(rows) > 1
flags = 0x02 | (0x04 if batch else 0) | (0x01 if xs is not None else 0)
pkt = bytearray(struct.pack(" 1024:
raise ValueError("frame too big: send fewer rows per frame")
return bytes([0, len(enc) & 0xFF, len(enc) >> 8]) + enc + b"\x00"
```
`frame("A", [[23.5, 67.25]])` returns the 20 reference bytes of section 11.
## 14. Test files: try it without hardware
SerialFlow can feed a file in as if it came from the port. No port needs to be connected; the data goes to the
active port's workspace.
| | **☰ → Test → Load Test File** | **☰ → Test → Delayed Playback** |
|---|---|---|
| Files | `.txt`, `.bin`, `.ans` (or any) | `.txt` (or any) |
| Feeds | The whole file at once, byte for byte; everything appears instantly | One line at a time |
| Clears first | Nothing | The log and Window 1–9 (graphs stay, so playback can continue a loaded run) |
| Stop | — | Choose **Delayed Playback** again, or the red stop button |
- **Playback speed:** a first line `DELAY:20` (milliseconds per line, alone on line 1, not played). Without it: 100 ms
per line. Short delays are kept on average: `DELAY:1` plays about 1 000 lines/s (in small bursts), `DELAY:16` about
60. (Beta 1 played at most about 64 lines/s, whatever the delay; the demo files now use `DELAY:16`.)
- Write exactly the lines the firmware prints: log text, ANSI codes, `~WrLi…` and `~{…}` lines. One graph command per
line. Use UTF-8 and LF line ends.
- **ANSI codes in a test file must be the real ESC byte (0x1B)**, not the four characters `\x1B`. A chat answer
cannot carry that byte reliably, so for coloured test files give a small Python script that writes the file.
Command lines without colour can be given as plain text.
- Binary frames: write a `.bin` file and use **Load Test File** (Delayed Playback works line by line).
- File data is not counted in the `RX:` counters, which count bytes from the port (`RX: 0 B`); the **Statistics**
pane's **Parsed** rate and **Graph cmds/sec** include it. A command line without a line end at the very end of the
file still runs.
- The installer ships demo files in `Documents\SerialFlow\Demo` (simulated "MDX-400" motor-drive bench run):
`showcase_preload.txt` (Load Test File: four graphs, log, two status windows), then `showcase_live.txt` (Delayed
Playback), and more listed in `Demo\README.txt`.
A test-file generator (CPython):
```python
# make_test.py: writes pump_test.txt for ☰ → Test → Delayed Playback
import math
ESC = "\x1b"
lines = ["DELAY:20"] # 20 ms per line
lines.append(ESC + "[1;96mPUMP BOARD v1.2" + ESC + "[0m ready")
lines.append("~{A:I:Pump:500:S:T:R:Sample::0}")
lines.append("~{A:S:1:F32:R:Flow:l/min:0:4FC3F7}")
lines.append("~{A:S:2:F32:R:Pressure:bar:0:FFB74D}")
lines.append("~{A:H:1:2.5:FF5252:D:Max 2.5 bar}")
lines.append("~ClA1:")
lines.append("~WrLi1:0:" + ESC + "[1;96mPUMP STATUS" + ESC + "[0m")
for i in range(300):
flow = 12 + 3 * math.sin(i / 20)
bar = 1.8 + 0.6 * math.sin(i / 35)
lines.append("~{A:1:%.2f:%.3f}" % (flow, bar))
if i % 10 == 0:
lines.append("~WrLi1:2:Flow %6.2f l/min" % flow)
lines.append("~WrLi1:3:Pressure %6.3f bar" % bar)
if i == 150:
lines.append(ESC + "[33m[WARN]" + ESC + "[0m pressure rising")
lines.append("~{A:E:1:150:Valve closed:FFAB40:D}")
with open("pump_test.txt", "w", encoding="utf-8", newline="\n") as f:
f.write("\n".join(lines) + "\n")
```
## 15. PC side: everything the user does in SerialFlow
Menu paths: **☰** is the main menu (first toolbar button) with the sections Profile, Connection, View, Tools, Test and
Settings. **Settings** opens with Ctrl+,. Most panes are also toolbar buttons. Panes dock, float
(right-click the tab → **Float**) and come back via **☰ → View** or **Hidden Views** (right-click any tab, or **☰ →
View → Hidden Views**: every hidden pane, graph, dashboard and canvas of every port; **Close All Hidden Views** at
its top empties the list); **☰ → Tools → Reset Layout**
restores the standard arrangement. **Pop Out** puts a pane in its own window in one click (for a second monitor), **Pop Out Full Screen**
maximises it there: both are in every tab's right-click menu, and graphs, the Signal Dashboard and canvases also have
**Pop Out** and **Full Screen** buttons on their toolbar.
### 15.1 Window, status bar, shortcuts
- Status bar: connection dot (green/amber/red), `COM4: 115200`, last error, messages, `RX:`/`TX:` bytes, `Lines:`,
`Err:` (rejected graph lines, red above 0), bytes per second, version; a dashboard alarm shows there with an
**Acknowledge** button (section 15.9).
- A blank (white) SerialFlow window on some PCs is a graphics-driver problem: **Settings → About → Use software
rendering** (per PC, from the next start), or start SerialFlow with `--software`.
- App shortcuts (changeable in **Settings → Shortcuts**): Ctrl+F find, F3 /
Shift+F3 next/previous, Esc close find, Ctrl+C copy,
Ctrl+A select all, Ctrl+B bookmark, Ctrl+L clear,
Ctrl+End auto scroll, Ctrl+Shift+End jump to end,
Ctrl+, settings, F5 connect/disconnect, Ctrl+R raw display,
F1 shortcut list, Ctrl+T always on top, Ctrl+S save profile.
- A compact logger beside an IDE: **Settings → Toolbar → Preset → Simple Terminal** (or **Minimal**), hide panes,
**☰ → View → Quick Send Bar**, Ctrl+T; the window shrinks to 400 × 500.
### 15.2 Find, keywords, bookmarks
- **Find** (Ctrl+F): plain text, options match case (**Aa**) and whole word (**Ab|**), and
**.\*** for a .NET regular expression (`ERR\d+|FAULT`; an invalid one says "Invalid pattern"). Enter /
Shift+Enter or F3 / Shift+F3 step through the matches. Also
**☰ → View → Search Panel** (match case and **.\***; Prev / Next scroll to the match).
- **Keyword Highlighter** (**☰ → View → Keyword Highlighter**): rules colour a word wherever it appears, on all ports.
Per rule: **Aa** match case, **W** whole word (otherwise it also matches inside longer words), **.\*** .NET regular
expression (an invalid one marks nothing; slow patterns are cut off); a later rule draws on top. Rules load from a
text or JSON file (section 16.2).
- **Bookmarks:** Ctrl+B on a line; **☰ → View → Bookmarks** lists them with notes, exports
`bookmarks.json`.
### 15.3 Logging to a file
- **☰ → View → Data Logger:** format `txt`, `csv` or `binary` (which is text + LF), a full **Path** (the folder must
exist), **Start** / **Stop**. Writes only lines that arrive after Start, overwrites the file, logs the main terminal
of that port (no status windows; no command lines unless Raw Display is on). ANSI codes removed. A line is written
once, when its line end arrives, with its final text (a line split across reads is whole; a `\r` progress line is
logged as it ended); a line without a line end is written when the next one starts or logging stops. `csv`: a
header `time,n,text`, then `yyyy-MM-dd HH:mm:ss.fff,n,"text"` with the time the line arrived and `n` counting
the file's lines from 1. `txt`: tick **Time** in the panel for `[HH:mm:ss.fff] ` before each line.
- The firmware can start and stop the Data Logger itself: `~LogOn:label` / `~LogOff` (section 9).
- **Auto-log:** **Settings → Data Logger → Enable Long-Term Logging Mode** + **Auto-log all data to disk**: rotating
files per port in `Documents\SerialFlow\logs` (`serial-log-COM4-20261104-195621.txt`), Max File Size 1–500 MB
(50), Max Log Files 1–100 (10). Long-term retention modes: `LineCount`, `TimeBased` (minutes), `MemoryBased` (MB).
Auto-log writes whole lines the same way.
### 15.4 Sending to the board
| Tool | Where | Notes |
|---|---|---|
| **Transmit** panel | **☰ → View → Transmit Panel** | Enter sends; **CR+LF** adds the TX line ending (**Settings → Communication → TX Line Ending**, default CRLF); **Hex** sends hex bytes `48 65 6C 6C 6F`; ↑/↓ history (not saved) |
| **Quick Send Bar** | **☰ → View → Quick Send Bar** | One-line send box; Enter = send + line ending + clear, Ctrl+Enter = send raw (configurable in **Settings → Behavior → Quick Send Bar**) |
| **Quick Send buttons** | **☰ → View → Quick Send Buttons**, **+**, right-click → **Edit...** | Label, tooltip, multi-line data (each line sent separately; a line `delay:200` waits 200 ms), Hex, line ending (default CRLF), local echo, auto delay between lines (100 ms), colours, font |
| **Macros** | **☰ → View → Macros**, **Add**, **Edit** (or double-click) | Steps `Send` (text + the macro's line ending, or hex), `Delay` (ms), `WaitFor` (waits until a received line contains the text, case-sensitive, timeout ms, 0 = 5 s; stops the macro on timeout). **Repeat** count. Run with **Run**, or with the macro's **Shortcut**, which runs it on the active port (also while typing in the Transmit box). Allowed shortcuts: F1–F24 with any modifiers, or Ctrl or Alt with a letter or digit (Shift optional); not Ctrl+Alt together, not one of the app's shortcuts, not Ctrl+A/C/V/X/Y/Z, Alt+F4 or Ctrl+F4 (the editor says why). **Import** / **Export**: a JSON file (section 16.4) |
| **Auto-reply** | **☰ → View → Auto-Reply**, tick **Enable Auto-Reply** | **Add** / **Edit** (or double-click) open the rule editor: name, pattern `PlainText` (contains), `Hex` (bytes of the line's text) or `Regex` (.NET), response (text or hex), the reply's line ending (default: the TX line ending), delay, one-shot, match case. Rules are tried top to bottom (**Up** / **Dn**) and every matching rule replies. **Matches** counts live; a reply that could not be sent shows as `5 (2 failed)`. **Import** / **Export** JSON (section 16.3) |
| **Send File** | **☰ → Tools → Send File...** | `Binary` (chunks, default 1 024 bytes) or `TextLineByLine` with a line ending; inter-chunk delay |
**Local Echo** (**Settings → Behavior**, on by default) shows what the Transmit panel and Quick Send Bar send; turn it
off if the device echoes. Echoed lines can trigger auto-reply and WaitFor. Macros and auto-replies are never echoed.
Everything is sent to the active port, which must be connected. Auto-reply answers a whole line when its line end
arrives, and a prompt without a line end (`Password: `) once nothing has arrived for 200 ms. **Since beta 2 a text
reply ends with the TX line ending** (CRLF by default); beta 1 sent none: set the rule's line ending to **None** for
that.
### 15.5 Working with graphs (PC side, changes nothing in the firmware)
- Graph pane toolbar: **Pause/Resume**, **Clear**, **AutoScale**, **Fit**, **Points**, **Overlay/Stacked**,
**Bookmark**, **Signals**, **Stats**, **Import…** / **Compare…**, **Export…**, **Image** (PNG), **Save Session**
(`.sfplot`), **Pop Out**, **Full Screen**, **Display:** averaging, style list.
- Signals sidebar: tick to hide/show, right-click **Solo**, **Show All**, **Clear Data**, **Delete Signal**, **Copy
Statistics**; expand a row for **Lane** (0–7, for stacked lanes), **Width**, **Scale**/**Offset** (drawing only),
**Style**, **Marker**, **Smooth**, **Shape**.
- Mouse: left-drag pan, right-drag zoom box, wheel zoom X (Shift Y, Ctrl both), double-click follow again,
Alt+drag or middle-drag mark a region, hold Ctrl for a vertical cursor (all values at X), Ctrl+Shift horizontal
cursor (Δ to a level, crossings).
- Keys (click the plot first; changeable in **Graph View Settings…**, Ctrl+G): F fit, Home
follow, Y reset Y, arrows pan, +/− zoom, Z zoom to region, Esc clear region, Ctrl+N new view from region, C cursor
mode, X add X marker, Ctrl+Y add Y marker, Ctrl+B bookmark, Space pause, P points, L overlay/stacked, G legend,
B sidebar, Ctrl+P save PNG.
- Region menu (right-click): **Zoom to Selection**, **New View from Selection**, **Crop Data to Selection**,
**Delete Selected Range** (both irreversible), **Clear Selection**.
- **X/Y markers** (**☰ → View → Graph Markers**): pair two X markers for ΔX, f = 1/ΔX, mean, RMS, peak-to-peak between
them; markers are not saved.
- **Statistics tab:** per signal Cur, Min, Max, P-P, Avg, RMS, Std, N by default (also Mean, Median, Var, Sum,
Integral, Slope, Δ, First/Last, X@Min/X@Max, ΔX, Rate, |Max|, Crest), over the last 100 points, the visible range
or all points, plus a column for a marked region.
- **Display averaging** (toolbar **Display:**): Raw, Average, Minimum, Maximum, Rms, Sum, Count, First, Last per X
interval; drawing only.
- **Ingest Policies…** (right-click the plot): change what is *stored* (decimation, aggregation, keep limit, logger
retention, default 1 000 000 points per signal).
- **Graph styles:** 26 built-in (one per colour profile); **☰ → Tools → Graph Styles...** to make your own.
- **Compare runs:** **Compare…** lays a `.sfplot`, Data Collector `.sqlite`, CSV, TSV, JSON Lines or JSON file over the
live graph, with X offset and opacity per layer.
### 15.6 Recording: the Data Collector
**☰ → View → Data Collector** → optional **Run name** → **● Record** → **■ Stop**. Records every graph sample of every
connected port (after override rules and unit conversion), plus events, with no firmware change (the firmware can
start and stop it too: `~RecOn:name` / `~RecOff`, section 9). Formats (**Settings →
Data Collection**): SQLite (default on; one database `serialflow-recordings.sqlite` for all runs, or one per run),
CSV (`samples.csv` + `events.csv`, delimiter comma/semicolon/tab), JSON Lines (`data.ndjson`). Folder:
`Documents\SerialFlow\recordings`. Options: include computed signals, record events, start when a port connects, stop
when the last port disconnects. Samples arriving while a graph is paused are not recorded. If the disk falls behind,
samples are dropped and counted (**Dropped**).
SQLite tables and views:
| Table / view | Columns |
|---|---|
| `runs` | `run_id`, `run_key`, `name`, `started_utc_ticks`, `ended_utc_ticks`, `app_version`, `profile`, `ports`, `notes`, `sample_count`, `dropped_count` |
| `signals` | `run_id`, `signal_key`, `port_slot`, `port`, `session_id`, `graph_id`, `signal_id`, `name`, `unit`, `color`, `value_type`, `is_computed` |
| `samples` | `run_id`, `signal_key`, `t_utc_ticks`, `x`, `y` |
| `events` | `run_id`, `t_utc_ticks`, `port`, `graph_id`, `kind`, `label`, `x`, `detail` |
| `v_samples` | `run_id`, `run_name`, `port`, `graph_id`, `signal_id`, `signal_name`, `unit`, `is_computed`, `t_utc`, `t_utc_ticks`, `x`, `y` |
| `v_events` | `run_id`, `run_name`, `port`, `graph_id`, `kind`, `label`, `x`, `detail`, `t_utc`, `t_utc_ticks` |
Event kinds: `RunStarted`, `RunStopped`, `GraphInitialized`, `GraphCleared`, `FrameFlushed`, `Bookmark`,
`EventMarker`, `MarkerLine`, `PortConnected`, `PortDisconnected`. `t_utc_ticks` is the PC arrival time; `x` is the
firmware's X. For data fed from a test file, use `x` (many samples arrive within one second).
CSV columns: `samples.csv` = `timestamp_utc, port, graph, signal_id, signal_name, unit, is_computed, x, y`;
`events.csv` = `timestamp_utc, port, graph, kind, label, x, detail`.
```python
# Read the newest run into pandas, one column per signal
import sqlite3
import pandas as pd
db = r"C:\Users\\Documents\SerialFlow\recordings\serialflow-recordings.sqlite"
con = sqlite3.connect(db)
run_id = con.execute("SELECT max(run_id) FROM runs").fetchone()[0]
df = pd.read_sql_query(
"SELECT graph_id, signal_id, signal_name, unit, x, y FROM v_samples WHERE run_id = ? ORDER BY t_utc_ticks",
con, params=(run_id,))
wide = df.pivot_table(index="x", columns="signal_name", values="y")
print(wide.describe())
```
### 15.7 Export, sessions, import
- **Export…** (graph toolbar): CSV wide (the X column named after the X axis, e.g. `Time [min]`, or `X` when it has
no name, then one column per signal *name [unit]*), CSV long (`series,x,y`), TSV, JSON Lines
(`{"type":"series",…}` then `{"s":…,"x":…,"y":…}`), JSON (graph name, `xLabel`, `xUnit`, per signal name, unit,
colour, `x` and `y` arrays), `.sfplot`. Point decimal, full precision, UTF-8. Mark a region first to export only
that range (CSV and TSV only; the other formats hold everything). Default folder `Documents\SerialFlow\sessions`.
- **Save Session** (`.sfplot`): one graph view with data, `H`/`M`/`E`/`T` lines, bookmarks, compare layers, the view,
and the firmware's Y axis, X axis and legend set-up. Reopen: right-click a graph → **Open Session in New View…**.
(Beta 1 reopened sessions auto-scaled, without the Y range and label.)
- **Import…**: `.sfplot`, `.sqlite` (pick a run), `.csv`/`.tsv`/`.txt` (comma, semicolon or tab, header line,
decimal comma detected, `#` lines skipped; first column X, every other column a signal named from the header),
`.ndjson`/`.jsonl`, `.json` (SerialFlow's export, or a plain array of `{"x":…,"y":…}`).
### 15.8 Signal Manager: units, computed signals, overrides
**☰ → Tools → Signal Manager...** (stays on top; changes apply at once, saved in the profile).
- **Incoming Signals:** per firmware signal, a linear conversion `shown = received × Scale + Offset`, plus **Name**,
**Unit**, **Color**, **Note**. Tick the row to enable it. **Quick:** buttons (milli→base, micro→base, centi→base,
kilo→base, base→kilo, Invert, Reset). It also lets the PC override the signal's **Format** and **SI Prefix**. New
samples only; the converted value is what graphs, statistics, dashboards, export and recording see. Linear only:
curved sensors (NTC) still need the curve in firmware. **Color** here is applied again when the graph is
re-created (after a restart, or a new `I` line) and reaches dashboard widgets (beta 1: only the graph open at the
time; there, put colours in the firmware's `S` line).
- **Computed Signals:** from one or two signals (any graphs): Add, Subtract, Multiply, Divide, Maximum, Minimum,
Average, Percentage, Absolute Value, Negate, Scale + Offset, Square, Square Root, Delta. Templates: Power (V×I),
Efficiency (%), Difference, Sum, Average, Ratio, Scale+Offset, Rate of Change (a plain difference of successive
values, not divided by time). IDs from 100 up; shown on a target graph; recorded too.
- **Overrides** (**Enable Override System**, on by default): Graph Gating (AcceptAll, Whitelist, ManualOnly, Locked),
Manual Graph Definitions, Init Overrides (Suppress the firmware's init, name, buffer, mode), Signal Filters, Value
Range Rules (Discard, Clamp, Hold), Decimation. **+ Add** adds a rule; every field is edited in its row (graph,
signal, Min/Max, action, factor, mode); a red cell says why its input is not accepted. Value-range limits are in
the units the firmware sends, before Incoming Signals conversion (ADC counts, not volts). Signal `0` (or `all`)
means every signal of the graph in Signal Filters and Decimation. Decimation works on windows of *factor* samples:
**NthSample** keeps the last sample of each window, **Average** stores the window's mean at the X of its last
sample, **MinMax** stores its lowest and highest value at their own X (two points, so short peaks stay visible).
When two enabled rules in one list cover the same graph (and signal), an amber line under the list names them and
the winner: the lower row in the list (Signal Filters: Reject / InitOnly win over Accept). **⚙ Setup Wizard**
walks through the same settings and applies them on **Apply**.
- **Details…** on an Init Overrides or Manual Graph Definitions row (Overrides tab and wizard) sets what the row has
no cells for. **X axis:** Type (`T` time, `V` value), Display (`R` raw, `F` formatted), Label, Unit, SI prefix −9…6.
**Signals:** a grid with **+ Add** / **Remove**: Signal 1–32 (each once), Type (`U8` … `F64`), Format (`D`, `U`,
`R`, `F`/`Fn`, `H`/`Hn`, n = width 1–20), Name, Unit, SI prefix, Color `RRGGBB`, Visible. In an init override,
`(MCU)` or an empty field keeps the firmware's value, and the override applies from the next init line the firmware
sends; in a manual definition an empty Color gives an automatic colour and **Import** replaces every field with the
live graph's. A field takes effect when it is left (Signal Manager: at once and saved; wizard: on Apply); invalid
input shows a red box and the rule keeps its last valid value.
### 15.9 Dashboards
Widgets and tiles read graph signals (graph letter + signal id), not the port, so the firmware just sends graph lines.
The four Control widgets are the exception: they send a text line to the port on a click (see 16.1).
**Canvas dashboard (HMI):** **☰ → Tools → New Canvas Dashboard**. A 1920 × 1080 canvas; **Edit** switches edit/run
mode; **+ Widget ▾** or the toolbox adds widgets; drag to move, drag the eight handles of a selected widget to resize.
Double-click → **Widget Settings**: General (Label, Unit Display, Decimal Places, Font Size; for the Image widget the
**Picture** and **Picture Stretch**, for Data Alive the **Timeout**, for State Text and State Timeline the **States**,
for Bullet Gauge the **Target**, for Peak Hold and Duty Cycle the **Window**), Appearance (Primary / Background colour as 6 hex digits, Border style and
colour, Opacity, Rotation), Chart (chart widgets only, below), Send (Control widgets only: text, hex, line ending, port, ask first; 16.1), Signals (**Add Binding** with Graph, Signal, Port,
empty = the main port; **×** removes one), Thresholds (below). On OK the widget redraws at once. **Canvas
Properties**: name, size, background colour or a gradient fill, a background picture (PNG, JPG, BMP, GIF, TIFF) with
**Image Stretch** and opacity, grid. Pictures are copied into `canvas\images`, so moving the original does not break
the canvas. - **Saving and reopening:** a canvas is saved on **Save** (toolbar, Ctrl+S); the
canvases that were open come back at the next start, and **☰ → Tools → Open Canvas Dashboard...** opens any saved
one (**Delete** there removes a saved canvas that is not on screen). Closing SerialFlow with unsaved canvas changes asks first. **Import/Export ▾ → Export Canvas (.sfcanvas)...**
writes one file with the pictures inside, for another PC; **Import Canvas (.sfcanvas)...** opens it as a new canvas.
- **Keys:** after a click into the canvas, F5 (edit/run), Ctrl+S,
Ctrl+Z / Ctrl+Y (100 undo steps), Delete,
Ctrl+C / Ctrl+V / Ctrl+D, arrows (1 px, with Shift
10 px) act on the canvas; with the focus elsewhere they are the app's shortcuts. - **Several bindings:** Multi-Signal
Trend draws one trace per binding, Data Table one row and Live Bar Chart one bar per binding (one scale: Range Min /
Max, or the values of every bound signal); Radar Chart one spoke and Heat Grid one cell (same shared scale), Donut
Share one slice, Trend Grid one small trend (own scale each) and Annunciator Panel one lamp per binding; XY Plot plots its `x` binding against its `y` binding (without those
roles: the first against the second; with one binding, that signal against the reading number); Attitude Indicator
reads `pitch` and `roll` (without those roles: the first is pitch, the second roll), Polar Plot `angle` (degrees, 0
at the top, clockwise) and `radius` (else the first is the angle); Log Ticker and Mini
Terminal show the last 12 readings of their first binding. The other widgets use their first binding (a Control
widget has at most one: feedback, never what it sends). - **Chart
axes** (Widget Settings → **Chart**, for Sparkline, Step Chart, Area Chart, Multi-Signal Trend, Live Bar Chart,
Histogram, XY Plot; all off by default): **Grid lines**, **Values on the X / Y axis**, **X / Y axis title**; **X
axis** *Readings* (newest = 0) or *Time* (seconds before the newest reading; Sparkline, Step Chart, Area Chart and
Trend); **Y scale** *Auto* (rounded to whole steps),
*Fixed* (= **Range Min / Max**, values outside cut off) or, on a Trend, *Each trace its own scale* (its default; no
Y values then: ticking Y values switches the Trend to one shared scale); XY Plot **X scale** Auto or Fixed with **X
Min / Max**; **Readings kept** 2–10 000 (default 100). A Histogram's value scale is its X axis (bands over Range Min
/ Max when Fixed). Charts take one reading per screen refresh that brings a new value (about 30/s at most), not
every sample: use a graph for every sample. Changing a binding starts a chart over. - The fastest way to build a
canvas is text (section 16.1): **Import/Export ▾ → Paste AI Text...**.
**Thresholds and alarms** (Widget Settings → Thresholds → **Add Threshold**; **×** removes one). Each rule has a
threshold and a colour, and optionally: **When** *Value* (default), or the *Minimum*, *Maximum* or *Average* **over
last** N s, *Above* (default: active at or above the threshold) or *Below*; **True for** N s **before it triggers**
(hold-off); **Hysteresis** (an active Above rule clears only below threshold − hysteresis); **Sound**: a WAV or MP3
file played when the rule triggers, **repeat** every N s while it stays active (0 = once; **▶** tests it). Rules are
checked top to bottom and the **last active rule gives the colour**, so list them lowest first (72 orange, then 78
red). Every widget takes the active rule's colour: value displays, gauges and bars change their colour; Status LED,
On/Off Toggle, Alarm Banner, Valve / Switch and Multi-State Indicator light up in it and are grey when no rule is
active. A Traffic Light is green with no rule active, red while the last rule is, amber while another is; an Event
Log lists each rule switching on and off, an Alarm Counter counts the switches to on, a State Timeline colours each
reading by the rule active then, a Zone Gauge draws the rules as bands on its arc. The canvas toolbar (and the grid dashboard's) has **Mute** (all alert sounds, not saved) and **Acknowledge
(n)** (stops a sound and its repeats until the rule clears and triggers again); each new alarm also shows in the
status bar with an **Acknowledge** button. A rule with only a threshold and a colour is active while the value is at
or above the threshold.
**Grid Signal Dashboard:** **☰ → Tools → Panel Configuration...** → **+ Dashboard** → **Columns** (1–6) → **+ Add
Widget** per tile (Graph, Sig, Type, Label, Unit, Color, Size, Min, Max, Dec, Value = Last/Min/Max/Average, Min/Max
row, **Span** columns × rows) → **Create Now** → **OK**. Tick **Auto-Create on Load** to have it at every start. Up to
9 (D1–D9), each showing its own port's signals. Tile types: `NumericDisplay`, `ProgressBar`, `RadialGauge`,
`TextLabel`, `ColorIndicator`, `Sparkline`, `LedIndicator`, `StatisticsPanel`. **+ Threshold** on a tile row adds a
rule with the same fields as a canvas rule (colour, condition, sound). No text format: give the user a table of rows
to enter.
### 15.10 Tools for the wire
- **RX Error Collector** (**☰ → Tools → RX Error Collector...**): every rejected graph line since start, with
category and reason: `CRC mismatch (expected 0x.., got 0x..)` (CRC), `Missing closing brace`, `Content too short (n
chars, need >= 3)`, `Missing colon separator at position 1` (Structure), `Invalid graph ID 'b' (not A-Z)`,
`Unknown command code 'p'` (Command), `Format error: no colon after command code` (Format). Mostly CRC = bit errors;
mostly Structure = cut lines. **Copy All** copies a tab-separated list. Binary frames and status lines are not
checked here.
- **CRC Calculator** (**☰ → View → CRC Calculator**), text or hex input, results in hex/dec/bin. Algorithms and check
values for `123456789`: CRC-8 (poly 0x07, init 0, = SerialFlow's) `0xF4`; CRC-16-CCITT (0x1021, init 0xFFFF,
CCITT-FALSE) `0x29B1`; CRC-16-Modbus (0x8005 reflected, init 0xFFFF) `0x4B37` (sent low byte first: `37 4B`);
CRC-16-XMODEM (0x1021, init 0) `0x31C3`; CRC-32 (zlib) `0xCBF43926`; LRC `0x23`; XOR `0x31`; Sum8 `0xDD`; Sum16
`0x01DD`; MD5; SHA-1; SHA-256.
- **Doc & Code Gen** (**☰ → Tools → Doc & Code Gen**): a built-in command reference with C examples and an ANSI
colour picker.
- **Port Info** / **Port Details** (**☰ → Tools → Port Details...**): VID:PID, chip, serial number, driver, FTDI
latency; **Copy All** for bug reports. **FTDI Devices → Connect by Serial #** connects the selected FTDI adapter and
remembers it by its serial number (section 5).
- **Statistics** pane: RX / TX bytes and rates, Lines/sec, **Graph cmds/sec**, **Parsed** (bytes parsed per second
from every source, also test files); RX HEALTH (shown when something was lost): parse errors, dropped chunks and
bytes if the PC could not keep up, **CRC Rejects**.
### 15.11 Profiles, colours, files
- **Profiles:** every setting, the toolbar, ☰ menu, colours, graph styles, shortcuts, presets, Signal Manager rules,
macros, auto-reply rules, Quick Send buttons, keyword rules, window layout. Switch in the toolbar list; **☰ → Profile
→ Save As New Profile...**, **Export Profile...** (`.sfprofile`), **Import Profile...**. Canvas files are not inside
a profile (they live in `canvas\`; the profile's layout only remembers which canvases are open). Don't run two
copies of SerialFlow at once.
- **Colour profiles:** 26 built-in (default **VS Dark**), **Settings → Color Profile**; graphs on **(Global Default)**
follow it.
- **Toolbar** and **☰ menu** layouts: presets **Full**, **Simple Terminal**, **Minimal**, **Graphing & Dashboards**,
**Logging & Analysis**, **Developer / Test**; both can be exported and imported as text. Their text formats and
item IDs are described in the app: **Settings → Toolbar** (or **Hamburger Menu**) → **Copy Format Reference**. Ask
the user to paste that reference before you write such a layout.
- **Folders:** `Documents\SerialFlow` (main folder: `app-config.json`, `profiles\\`, `canvas\` with
`canvas\images\`, `captures\`, `logs\`, `recordings\`, `sessions\`, `Demo\`); `%APPDATA%\SerialFlow\backup` (last
10 versions of each file);
`%LocalAppData%\SerialFlow` (program and its event log `logs\`).
- **Privacy:** SerialFlow sends no serial data anywhere. It checks `lizerd.se/serialflow/latest.json` for updates at
start (can be turned off) and, only if the user agreed, one anonymous daily count with no ID.
## 16. Files an AI can write for SerialFlow
| What | Format | How the user loads it |
|---|---|---|
| Canvas dashboard | Text, 16.1 | Canvas → **Edit** → **Import/Export ▾ → Paste AI Text...** → **Import** |
| Keyword rules | Text or JSON, 16.2 | **Keyword Highlighter → Load** (replaces the list) |
| Auto-reply rules | JSON, 16.3 | **Auto-Reply → Import** (replaces the list), then tick **Enable Auto-Reply** |
| Quick Send button | Lines + `delay:N`, 16.4 | Paste into the button's Data box (**Edit...**) |
| Macros | JSON or a step table, 16.4 | **Macros → Import** (adds to the list), or typed into **Edit Macro** |
| Test file | Text lines, section 14 | **☰ → Test → Load Test File** / **Delayed Playback** |
| Data to compare | CSV with a header, first column X | Graph → **Compare…** |
| Toolbar / ☰ menu layout | The app's own format | Ask the user for **Copy Format Reference** first |
### 16.1 Canvas dashboard as text
```text
=== SERIALFLOW CANVAS WIDGETS ===
Description: Pump test rig, graph A
--- CANVAS HINTS ---
Width: 1280
Height: 720
BackgroundColorHex: 1A1D21
--- WIDGET: ArcGauge ---
Label: Temperature
X: 20
Y: 20
Width: 220
Height: 240
RangeMin: 0
RangeMax: 120
UnitDisplay: °C
DecimalPlaces: 1
PrimaryColorHex: FF8A65
Binding: primary=A:1
--- WIDGET: AlarmBanner ---
Label: Temperature
X: 260
Y: 20
Width: 300
Height: 50
UnitDisplay: °C
DecimalPlaces: 1
Binding: primary=A:1
Threshold: 80=FFA726
Threshold: 100=FF5252
--- WIDGET: StatusLed ---
Label: Pump
X: 260
Y: 90
Width: 60
Height: 60
Binding: primary=A:2
Threshold: 1=69F0AE
--- WIDGET: Sparkline ---
Label: Temperature trend
X: 20
Y: 280
Width: 540
Height: 100
PrimaryColorHex: FF8A65
UnitDisplay: °C
SparklineBufferSize: 200
Binding: primary=A:1
=== END WIDGETS ===
```
Rules:
- Starts with `=== SERIALFLOW CANVAS WIDGETS ===`, ends with `=== END WIDGETS ===`; an optional `Description:` line.
- `--- CANVAS HINTS ---` is optional: `Width`, `Height`, `BackgroundColorHex`, `GridSize`, `SnapToGrid`. They are
applied when the text goes into an empty canvas; a canvas that already has widgets keeps its own settings. (Beta 1
ignored them.)
- Each widget starts with `--- WIDGET: TypeKey ---` (exact spelling; a wrong key gives a plain value box), then one
`Key: value` per line. Only `Label` is required. Unknown keys are skipped silently. Write `UnitDisplay:`, not `Unit:`.
- Numbers with a dot; colours six hex digits without `#`.
- `Binding: role=Graph:SignalID`, e.g. `primary=A:1`; capital graph letter. Most widgets use the first binding only;
`MultiSignalTrend`, `LiveBarChart`, `RadarChart`, `DonutShare`, `TrendGrid` (up to 8), `DataTable`, `Annunciator`
and `HeatGrid` (up to 16) use every `Binding:` line, in order (any role names, e.g. `primary`, `secondary`); `XYPlot`
uses `Binding: x=A:1` and `Binding: y=A:2`; `AttitudeIndicator` uses `Binding: pitch=A:1` and `Binding: roll=A:2`
(degrees); `PolarPlot` uses `Binding: angle=A:1` (degrees, 0 at the top, clockwise) and `Binding: radius=A:2`. The text has no port field: text bindings read the main port (set **Port** in Widget Settings
afterwards for another one).
- `Threshold: value=colour`, one per line, **lowest value first** (the last active rule gives the colour); works on
every widget type. A 0/1 flag needs one threshold: `1=69F0AE`. Options after the colour, separated by `;`:
`statistic=Value|Minimum|Maximum|Average` (also `min`, `max`, `avg`), `window=` seconds, `direction=Above|Below`,
`hold=` seconds, `hysteresis=` (signal units), `sound=` a WAV or MP3 path, `repeat=` seconds. Example:
`Threshold: 72=FF5252; statistic=Average; window=10; hold=10; sound=C:\Sounds\alarm.wav; repeat=30`.
- `ImagePath:` (a picture file, absolute or relative to the canvas folder) and `ImageStretch:` (`None`, `Uniform`,
`UniformToFill`, `Fill`) for an `ImageWidget`.
- Chart widgets (`Sparkline`, `StepChart`, `AreaChart`, `MultiSignalTrend`, `LiveBarChart`, `Histogram`, `XYPlot`):
`ChartGrid:`, `ChartXValues:`, `ChartYValues:` (`True` / `False`), `ChartXTitle:`, `ChartYTitle:`, `ChartXAxis:`
(`Samples`, `Time`), `ChartScale:` (`Auto`, `Fixed`, `PerTrace` = the Trend's default), and on an `XYPlot`
`ChartXScale:` (`Auto`, `Fixed`), `ChartXMin:`, `ChartXMax:`. Unknown values are ignored.
- `AliveTimeout:` seconds for a `DataAlive` (default 2); `StateTexts:` for a `StateText` or `StateTimeline`,
`0=Idle; 1=Running; 2=Fault` (a value with no text shows as the number); `BulletTarget:` for a `BulletGauge` (left
out: the running average); `WindowSeconds:` for a `PeakHold` (default 10) or `DutyCycle` (default 60).
- Give `Width` and `Height` for every widget (the text format does not use the toolbox sizes).
- Imports add to the canvas; they never replace it. The status bar says `Imported 4 widget(s).` or `Could not parse
AI text. Check the format.`
| Key | Default | Meaning |
|---|---|---|
| `Label` | empty | Title; empty shows the signal's name |
| `X`, `Y` | `0` | Top-left corner, pixels |
| `Width`, `Height` | `200`, `100` | Size, pixels |
| `PrimaryColorHex` | `00B4D8` | Value, line, fill or needle colour |
| `BackgroundColorHex` | `2D2D2D` | Widget background |
| `BorderColorHex` | `555555` | Border of a `Shape`, and the `BorderStyle` frame |
| `BorderStyle` | `None` | Frame around the widget: `None`, `Thin`, `Medium`, `Thick`, `Rounded` |
| `Rotation` | `0` | Degrees, clockwise about the widget's centre |
| `RangeMin`, `RangeMax` | `0`, `100` | Range of gauges, bars, rings, DialKnob, SignalColorMap (if Max ≤ Min: the min and max seen) |
| `UnitDisplay` | empty | Unit text; empty uses the signal's unit |
| `DecimalPlaces` | `2` | Decimals |
| `FontSize` | `24` | Main value size (LargeValueDisplay, TextLabel, MultiStateIndicator, RollingCounter, ClockUptime) |
| `Opacity` | `1.0` | 0–1 |
| `ZIndex` | `0` | Higher is on top |
| `IsLocked` | `False` | `True` locks position |
| `SparklineBufferSize` | `100` | Readings kept by chart widgets (2–10 000 in Widget Settings) |
| `ChartGrid`, `ChartXValues`, `ChartYValues` | `False` | Chart grid lines, X / Y axis values |
| `ChartXTitle`, `ChartYTitle` | empty | Axis titles |
| `ChartXAxis` | `Samples` | Sparkline, StepChart, AreaChart, MultiSignalTrend: `Samples` or `Time` (seconds) |
| `ChartScale` | `Auto` | `Auto`, `Fixed` (RangeMin–RangeMax), `PerTrace` (MultiSignalTrend; its default) |
| `ChartXScale`, `ChartXMin`, `ChartXMax` | `Auto`, `0`, `100` | XYPlot X scale |
| `AliveTimeout` | `2` | DataAlive: seconds without a new value before **No data** |
| `StateTexts` | empty | StateText, StateTimeline: `value=text` pairs, `;` between them |
| `BulletTarget` | empty | BulletGauge: the target mark; empty = the running average |
| `WindowSeconds` | `10` / `60` | PeakHold (10), DutyCycle (60): seconds looked back |
| `SendText` | empty | Control widgets: the text sent, `{value}` = the value (ToggleSwitch: when switched on) |
| `SendTextOff` | empty | ToggleSwitch: the text sent when switched off |
| `SendHex` | `False` | `True`: the text is hex bytes (`01 A0 FF`); then no `{value}` |
| `LineEnding` | `CRLF` | Control widgets: `None`, `CR`, `LF`, `CRLF` |
| `SendPort` | empty | Control widgets: port slot (`port1`); empty = the port of the binding, else the main port |
| `ConfirmSend` | `True` | Control widgets: ask Yes / No before each send |
| `Step` | `1` | SendSlider: the step from `RangeMin` |
| `Binding` | none | `role=Graph:SignalID` |
| `Threshold` | none | `value=colour` |
`LabelPosition`: `Top` (default), `Bottom`, `Left`, `Right`, `Inside` (over the top-left corner) or `Hidden`, for
widgets that show their label as a caption (not TextLabel, AlarmBanner, OnOffToggle, MultiStateIndicator, GroupFrame,
StatusLed, SendButton, ToggleSwitch, ImageWidget, Shape, PipeConnector, Arrow).
The 67 widget type keys (beta 1 had the first 35; the 32 marked *new* came in beta 2). The four of the Control group
send to the port (below); every other widget only shows values.
| Group | Type keys |
|---|---|
| Numeric | `LargeValueDisplay` (big value, unit, min/max seen), `DigitalLedDisplay` (seven-segment), `PercentageBar` (horizontal bar over the range), `RollingCounter` (counter box); *new:* `StatisticsPanel` (last, min, max, avg, number of readings), `RateMeter` (readings per second over the last 2 s), `Totalizer` (sum of every reading since Reset Stats, and their number), `ValueTrend` (value with a filled trend under it), `PeakHold` (highest and lowest of the last `WindowSeconds`, the peak's age), `DutyCycle` (share of the last `WindowSeconds` the value was not 0, and the starts) |
| Gauge | `ArcGauge` (arc with value), `LinearGauge` (vertical thermometer), `RadialGauge` (dial with needle), `TankLevel` (tank filling up); *new:* `SemiGauge` (180° arc with needle), `SegmentedBar` (LED segments, VU-meter style: top 30 % amber and red), `BatteryLevel` (battery fill with percentage, red below 20 %), `ZoneGauge` (270° arc with the threshold rules as coloured bands; without rules primary / amber / red at 70 and 90 %), `BulletGauge` (bar over three grey bands, target mark at `BulletTarget` or the running average) |
| Status | `StatusLed` (lamp in threshold colour), `OnOffToggle` (small lamp + label), `MultiStateIndicator` (tile in threshold colour), `AlarmBanner` (⚠ banner in threshold colour); *new:* `TrafficLight` (green = no rule active, red = the last rule active, amber = another rule), `Annunciator` (one lamp tile per binding, up to 16, lit while the value is not 0), `DataAlive` (Receiving / No data after `AliveTimeout` seconds, and the age of the last value), `AlarmCounter` (rule switches to on, the last one's time, the total active time) |
| Chart | `Sparkline` (trend + value), `MultiSignalTrend` (one trace per binding, overlaid, latest values below), `LiveBarChart` (one bar per binding, values below), `Histogram` (distribution of recent values); *new:* `StepChart` (trend in steps, for on/off and state signals), `AreaChart` (trend with the area filled), `RadarChart` (one spoke per binding, up to 8, one shared scale), `DonutShare` (each binding's share of the sum, up to 8, with a legend), `StateTimeline` (a slice per reading in the active rule's colour, else primary while not 0, else grey; `StateTexts` names the state), `HeatGrid` (a cell per binding, up to 16, blue to red on one shared scale), `TrendGrid` (a small trend per binding, up to 8, each on its own scale). `Sparkline`, `StepChart`, `AreaChart`, `MultiSignalTrend`, `LiveBarChart` and `Histogram` can have axes (`Chart…` keys) |
| Text | `TextLabel` (fixed text, no signal needed), `ValueTimestamp` (label, value, unit and the time it arrived), `SignalInfoCard` (value with min, max, avg), `DataTable` (one row per binding: name, value, unit), `LogTicker` (the last 12 readings of the first binding, newest first, with the time); *new:* `EventLog` (a line per threshold rule switching on or off, the last 50), `StateText` (a text per value from `StateTexts`) |
| Shape | `PipeConnector` (grey pipe), `Shape` (filled rectangle), `ImageWidget` (a picture: `ImagePath`, `ImageStretch`), `GroupFrame` (titled frame); *new:* `Arrow` (filled arrow pointing right, turn it with `Rotation`; threshold colour when bound) |
| Specialized | `Compass` (needle in degrees), `XYPlot` (the `x` binding against the `y` binding), `DialKnob` (display only), `BitfieldDisplay` (lowest 8 bits as cells), `SignalColorMap` (gradient with marker), `DeltaIndicator` (arrow + difference from average), `ClockUptime` (time since created, no signal needed), `MiniTerminal` (the last 12 readings, terminal style), `ProgressRing` (ring over the range), `ValveSwitch` (opens at a threshold); *new:* `FanPump` (rotor turning while not 0, faster higher in the range), `AttitudeIndicator` (artificial horizon from `pitch` and `roll` in degrees), `PolarPlot` (points by `angle` and `radius`, rings and 30° spokes) |
| Control | *new:* `SendButton` (a click sends `SendText` as it is), `ToggleSwitch` (on sends `SendText`, off `SendTextOff`, `{value}` = 1 / 0; with a binding it shows the signal), `SendSlider` (sends `{value}` when let go, or after the arrow keys; never while dragging; `RangeMin`..`RangeMax` in steps of `Step`), `NumberEntry` (a number box: Enter or Send; outside `RangeMin`..`RangeMax` nothing is sent) |
**Control widgets** send only in run mode, only on the user's click or key, and only while their port is open (greyed
out otherwise). Nothing is sent when the canvas opens or is pasted as text, on undo, or on a new value. `{value}` is
written with `DecimalPlaces` and a dot (`12.5`); `LineEnding` follows (default CRLF). "Ask before sending"
(`ConfirmSend`) is on by default and shows the exact text. Their one optional binding is feedback: write the firmware
to parse the text like a typed command (`SET 42`, `PUMP 1`) and to answer with a graph line of its new state, and bind
that signal so the widget shows what the board did. Example:
```text
--- WIDGET: ToggleSwitch ---
Label: Pump
X: 20
Y: 20
Width: 170
Height: 50
SendText: PUMP {value}
SendTextOff: PUMP {value}
Binding: primary=A:8
```
Layout tips: a 1280 × 720 or 1920 × 1080 grid with 20 px gaps; gauges about 220 × 240, value cards 220 × 100, banners
300 × 50, sparklines 500 × 100, LEDs 60 × 60; `GroupFrame` behind a panel of widgets (lower `ZIndex`).
### 16.2 Keyword rules
Text file, one rule per line, `#` comments; the last four fields are optional (beta 1 read five):
```text
# Format: keyword | foreground | background | enabled | case_sensitive | whole_word | regex
TRIP | #FFFFFF | #C62828 | true | true
WARN | #1A1A1A | #FFB300 | true | true
derate | #1A1A1A | #FF8A3D | true | false
ERR\d+ | #FFFFFF | #C62828 | true | true | true | true
```
JSON alternative (`wholeWord` and `isRegex` are optional, false by default):
```json
[
{ "keyword": "TRIP", "foregroundHex": "#FFFFFF", "backgroundHex": "#C62828", "isEnabled": true, "caseSensitive": true }
]
```
### 16.3 Auto-reply rules (JSON)
| Field | Meaning | Default |
|---|---|---|
| `name` | Label | `New Rule` |
| `pattern` | What to look for in a received line | |
| `patternType` | `PlainText`, `Hex` or `Regex` (.NET) | `PlainText` |
| `response` | The reply text; the line ending below is added. In JSON `\r\n` is a real CR LF | |
| `responseLineEnding` | Added to a text reply: `UseTxSetting` (the TX line ending, CRLF unless changed), `None`, `CR`, `LF`, `CRLF` | `UseTxSetting` |
| `responseIsHex` | `true`: response is hex bytes like `"06"`, sent exactly as given (no line ending) | `false` |
| `delayMs` | Wait before replying | `0` |
| `isEnabled` | Rule on | `true` |
| `isOneShot` | Switches itself off after one reply | `false` |
| `caseSensitive` | Match case | `false` |
| `id` | Leave out (SerialFlow makes one); never duplicate | new |
```json
[
{ "name": "Watchdog", "pattern": "WDT ping", "patternType": "PlainText", "response": "WDT ack", "isEnabled": true },
{ "name": "BMS query", "pattern": "42 4D 53 3F", "patternType": "Hex", "response": "06", "responseIsHex": true, "isEnabled": true },
{ "name": "Trip log", "pattern": "Overcurrent phase [ABC]", "patternType": "Regex", "response": "log dump 200", "delayMs": 50, "isEnabled": true },
{ "name": "Stop autoboot", "pattern": "Hit any key to stop autoboot", "patternType": "PlainText", "response": "x", "responseLineEnding": "None", "isOneShot": true, "isEnabled": true }
]
```
Rules are checked top to bottom on each whole line of the port's main terminal, and every matching rule replies, in
that order (there is no priority field). A line without a line end, such as a prompt, is tried once nothing has
arrived for 200 ms. A hex pattern can only match bytes that end up in the line's text (not CR, LF, ESC or 0x00). An
invalid regex never matches, and an empty pattern never matches. **Rules written for beta 1** whose `response` ends
in `\r\n` now send the line ending twice: remove it from the text, or add `"responseLineEnding": "None"`.
### 16.4 Quick Send buttons and macros
A Quick Send button's Data box, one line per send, with pauses:
```text
fault clear
delay:200
status
```
`delay:N` must be alone on its line (any case) and sends nothing. An empty line sends just the line ending. **Hex**
makes each line hex bytes (`FF 0A 1B`; `-` and `0x` allowed).
A macro is typed into **Edit Macro** as steps; give it as a table:
| Type | Data | Delay / Timeout (ms) |
|---|---|---|
| `Send` | `run 1500` | |
| `WaitFor` | `speed 1500 rpm` | 5000 |
| `Delay` | | 5000 |
| `Send` | `stop` | |
Or as a JSON file for **Macros → Import**: an array of macros. Imported macros are added; one with the `id` of a macro
already in the list replaces it (leave `id` out for new ones). The step `type` is a number: `0` Send, `1` Delay,
`2` WaitFor. `delayMs` is the Delay time or the WaitFor timeout (0 = 5 s); `lineEnding` (`UseTxSetting`, `None`,
`CR`, `LF`, `CRLF`) is added to every text Send step. `keyboardShortcut` is optional, written like `Ctrl+Shift+1` or
`F6` (section 15.4 lists what is allowed; the import message names a shortcut that cannot be used).
```json
[
{
"name": "Bench cycle",
"description": "Run at 1500 rpm for 5 s, then stop",
"keyboardShortcut": "F6",
"repeatCount": 1,
"isEnabled": true,
"lineEnding": "UseTxSetting",
"steps": [
{ "type": 0, "data": "run 1500" },
{ "type": 2, "data": "speed 1500 rpm", "delayMs": 5000 },
{ "type": 1, "delayMs": 5000 },
{ "type": 0, "data": "stop" }
]
}
]
```
## 17. Troubleshooting
| Symptom | Likely cause and fix |
|---|---|
| Nothing at all arrives | Wrong port or baud; another program holds the port ("… is in use by another program": close the IDE's serial monitor); native-USB board waiting for DTR (tick **DTR Enable**; the status bar hints at it after 3 s); ESP32 held in reset by RTS (untick **RTS Enable**); `printf` not retargeted |
| The SerialFlow window is blank (white) | A graphics-driver problem on that PC: **Settings → About → Use software rendering**, or start with `--software` |
| Garbled text | Baud, data bits, parity or stop bits differ from the MCU; `°` instead of `°` = encoding (**Settings → Communication → Encoding**) |
| All lines run together, or each line overwrites the last | The device ends lines with CR only: set **Settings → Communication → RX Line Ending** to **CR**, or send `\n` |
| A progress line leaves old characters behind | The redraw is shorter than the old text: end it with `ESC[K` (section 6.2) |
| No graph tab appears | `I` line has fewer than 5 fields; lower-case letter; line does not start with `~` (log prefix?); the board printed `I` before **Connect** (rule 6) |
| A graph disappears when the firmware sends `~{G:X:…}` | The PC runs beta 1, which reads every `~{G:X…}` as "delete the graph": update SerialFlow |
| A tab but no trace | No `S` line or fewer than 6 fields; id outside 1–32; data sent before `S` |
| Every value is 0 | Decimals in a `D`/`U` signal; lower-case format `r`; decimal comma; `%f` not supported by the libc (prints nothing or `?`) |
| Values on the wrong signal | Values follow rising id order; a missing `S` line or a gap in ids |
| Graph lines show as text in the log | **Raw Display** is on (Ctrl+R); more than one command on a line; a prefix before `~`; a rejected line (**Err:** > 0: see RX Error Collector); a pause of 100 ms or more inside the line (rule 15); on beta 1, a line split across two serial reads |
| Status rows partly in the log | A pause inside the row (rule 15), or an escape sequence other than a colour code in it; on beta 1, a row split across two reads |
| `~ClA:` cleared the log instead of the window | Use `~ClA1:` |
| A device command (`~SvLog`, `~{G:W}`, `~LogOn`, …) does nothing | **Settings → Device Captures → Allow…** is off (the status bar says so once); the window or graph it names does not exist; on beta 1 the command shows as text |
| A streamer looks almost empty | On beta 1: explicit time X on a streamer; use auto-X `1` |
| A trace zigzags back | X went backwards; clear (`~{G:C}`) and keep X rising |
| Frame graph never changes | No `~{G:F}`; graph not in mode `F`; graph paused |
| Frame cut off | More points than the buffer size |
| CRC lines all rejected | Non-ASCII character in the line; CRC not over exactly `{` … `}`; wrong polynomial or init |
| Binary data never appears | Graph/signals not set up in text first; wrong CRC, length or COBS; frame > 1 024 bytes; command and flag bit 0 disagree; LF→CR LF translation in the output path; compare with the reference bytes in section 11 |
| All graphs stopped | Raw Display on, or `~{G:P}` sent |
| Data stops after a while at high rates | The serial link is full (section 12); status bar "RX data dropped by driver backpressure" means the PC fell behind: report it |
| `~{G:L:0}` does not hide the legend, `~{G:B}` does not remove bookmarks | The PC runs beta 1; use G on the plot / remove them on the PC, or update |
| The device sees an extra empty line after each auto-reply | A rule from beta 1 whose response ends in `\r\n`: since beta 2 the TX line ending is added as well (section 16.3) |
| The device never sees the end of an auto-reply | The rule's line ending is **None**, or the TX line ending is None; pick the one the firmware reads |
| Settings look gone | Another profile active; **Settings → General → Restore from Backup** |
## 18. Known limits in beta 2, and what changed since beta 1
**What beta 2 does not do** (design around these):
| Area | Limit |
|---|---|
| Graph commands | One per line: only the first `~{…}` of a line is executed (by design) |
| Terminal | No full-screen VT100: `ESC[?…` modes are not understood; the cursor moves within the log |
| `I` line | X type and X display are stored only; they change nothing on screen |
| Canvas | Most widgets use only their first binding (Multi-Signal Trend, Data Table, Live Bar Chart, Radar Chart, Donut Share, Annunciator Panel, Heat Grid, Trend Grid, XY Plot, Attitude Indicator and Polar Plot use more). Only the four Control widgets send to the port: a text or hex line on a click or key in run mode, while the port is open |
**What changed since beta 1** (for firmware that must also work on beta 1, and for users who update):
| Area | Beta 2 | Beta 1 |
|---|---|---|
| `~{G:X:…}` X-axis commands | Fix the X range, auto X, X label, equal axes | Every `~{G:X…}` deletes the graph |
| Device commands (section 9) | Save captures, start / stop logging (opt-in) | Unknown: shown as text |
| Lines split across serial reads | Joined (rest within 100 ms) | Lost: shown as text, sample gone |
| Signal 32 | Works | Dropped (use 1–31) |
| Lone CR, cursor moves | CR returns to the line start; cursor columns, `ESC[K` / `ESC[1K` from the cursor | CR ignored (RX Line Ending **LF** gives that back); columns ignored |
| `~InLi` / `~DeLi` | Moved rows keep their text | Moved rows come out empty |
| Colour tags `…` | In colour | Grey |
| `░ ▒ ▓` | Line up | `░` drawn a line too high |
| `~{G:L:0}`, `~{G:B}` | Hide the legend, remove bookmarks | No effect |
| Streamer with explicit time X | Shows its buffer | Window *buffer* X units wide, looks empty (use auto-X) |
| Auto-reply text replies | End with the TX line ending (CRLF by default) | No line ending |
| Delayed Playback `DELAY:1` | About 1 000 lines/s | About 64 lines/s at most |
| Data Logger csv | Header `time,n,text`, arrival time, `n` from 1 | No header, 0-based index, the logger's write time |
| Canvas and dashboard thresholds | Colour every widget; time conditions, sounds | Only status widgets (grid: LED and colour tiles, no editor); no time conditions or sounds |
| Canvas text `--- CANVAS HINTS ---` | Applied to an empty canvas | Ignored |
| Canvas charts | Axis values, grid, titles, time axis, fixed or shared scale (`Chart…` keys); XY Plot plots X against Y; Live Bar Chart one bar per binding | No axis values or titles; XY Plot plots its first binding against sample number; one bar; `Chart…` keys skipped |
| Canvas widgets | 67 types; `Rotation`, `BorderStyle` and `LabelPosition` are drawn; the grid shows in edit mode; `ValueTimestamp` shows the time; Align menu and size presets; Control widgets send to the port (`Send…` keys) | 35 types; stored only, no effect; no grid drawn; no time; no alignment tools or presets; no widget sends (`Send…` keys skipped) |
| Graph colours, markers, export | Sidebar colour picker per view; a Signal Manager colour also reaches graphs created anew; the Markers panel has a Graph choice; JSON Lines, JSON and `.sfplot` export keep to a selected range | No picker; the colour reached only the open graph; Add X / At Max used the first marker's graph; only CSV / TSV kept to the range |
| Keyword Highlighter | Per rule: whole word (**W**) and regular expression | Plain text only |
| Dropped binary frames | Counted in **Err:** and listed in RX Error Collector with the reason | Not counted or listed |
Anything not described in this file should be treated as not available in 0.9.0 beta 2. Bugs and wishes go to
https://github.com/Lizerd/SerialFlow-Releases/issues (include the SerialFlow version, Windows version, adapter
details from **Port Details → Copy All**, and a few lines of the serial output).
## 19. A complete worked example
A user writes: *"STM32F401 Nucleo, CubeIDE with HAL, UART2 at 115 200 through the ST-Link. A fan controller: I want a
colour boot log, a status table with RPM, duty and temperature, a live graph of RPM vs set point with a limit line,
and a dashboard."* A good answer contains these parts.
**1. Assumptions stated:** `huart2` on the ST-Link VCP, 115 200 8N1; float printf enabled (or integers with SI
prefixes); `sf.c` from section 13.1 added to the project.
**2. Output function** (in `main.c`):
```c
extern UART_HandleTypeDef huart2;
void sf_write(const uint8_t *data, size_t len)
{
HAL_UART_Transmit(&huart2, (uint8_t *)data, (uint16_t)len, HAL_MAX_DELAY);
}
```
**3. The firmware's SerialFlow part:**
```c
#include
void sf_line(const char *fmt, ...);
void sf_cmd(int crc, const char *fmt, ...);
static uint32_t sf_samples; /* = the graphs' auto-X counter */
void sf_setup(void) /* at boot, and when the PC sends '?' */
{
sf_line("\x1B[1;96m=== FAN CONTROLLER v1.0 ===\x1B[0m");
sf_cmd(0, "{A:I:Fan speed:600:S:T:R:Sample (100 ms)::0}");
sf_cmd(0, "{A:S:1:F32:R:Set point:rpm:0:9E9E9E}");
sf_cmd(0, "{A:S:2:F32:R:Speed:rpm:0:4FC3F7}");
sf_cmd(0, "{A:H:1:3000:FF5252:D:Max 3000 rpm}");
sf_cmd(0, "{A:Y:R:0:3500}");
sf_cmd(0, "{B:I:Fan drive:600:S:T:R:Sample (100 ms)::0}");
sf_cmd(0, "{B:S:1:F32:R:Temperature:C:0:FF8A65}");
sf_cmd(0, "{B:S:2:F32:R:Duty:%%:0:AED581}"); /* %% = a literal % */
sf_cmd(0, "{B:H:1:70:FF5252:D:Hot 70 C}");
sf_line("~ClA1:");
sf_line("~WrLi1:0:\x1B[1;96mFAN STATUS\x1B[0m");
sf_samples = 0; /* I restarts auto-X at 0 */
}
void sf_sample(float set_rpm, float rpm, float duty, float temp_c) /* every 100 ms */
{
sf_cmd(1, "{A:1:%.0f:%.0f}", set_rpm, rpm); /* with CRC-8 */
sf_cmd(1, "{B:1:%.1f:%.1f}", temp_c, duty);
sf_samples++;
sf_line("~WrLi1:2:Speed %5.0f rpm", rpm);
sf_line("~WrLi1:3:Duty %5.1f %%", duty);
sf_line("~WrLi1:4:Temp %5.1f C %s", temp_c,
temp_c > 70.0f ? "\x1B[1;91mHOT\x1B[0m" : "\x1B[92mOK\x1B[0m");
}
void sf_event_stall(void) /* in the log as text, and on graph A */
{
sf_line("\x1B[1;31m[FAIL]\x1B[0m fan stalled");
sf_cmd(0, "{A:E:1:%lu:Stall:FF5252:D}", (unsigned long)sf_samples);
}
```
At 115 200 baud each 100 ms costs about 130 bytes (two data lines, three status rows), well under the link's
~11 500 bytes/s.
**4. PC side:** pick the ST-Link COM port and 115 200, press **Connect**, then reset the board (or send `?` from a
Quick Send button) so the set-up lines arrive after Connect. Drag the **Window 1** tab under the terminal.
**5. A test file** (from the generator pattern in section 14) with the same lines, so the user sees the result first.
**6. A canvas** (paste via **Import/Export ▾ → Paste AI Text...**):
```text
=== SERIALFLOW CANVAS WIDGETS ===
Description: Fan controller, graphs A and B
--- WIDGET: RadialGauge ---
Label: Speed
X: 20
Y: 20
Width: 240
Height: 240
RangeMin: 0
RangeMax: 3500
UnitDisplay: rpm
DecimalPlaces: 0
PrimaryColorHex: 4FC3F7
Binding: primary=A:2
--- WIDGET: LargeValueDisplay ---
Label: Temperature
X: 280
Y: 20
Width: 240
Height: 110
UnitDisplay: °C
DecimalPlaces: 1
PrimaryColorHex: FF8A65
Binding: primary=B:1
--- WIDGET: AlarmBanner ---
Label: Temperature
X: 280
Y: 150
Width: 240
Height: 50
UnitDisplay: °C
DecimalPlaces: 1
Binding: primary=B:1
Threshold: 60=FFA726
Threshold: 70=FF5252
--- WIDGET: Sparkline ---
Label: Speed trend
X: 20
Y: 280
Width: 500
Height: 100
PrimaryColorHex: 4FC3F7
UnitDisplay: rpm
SparklineBufferSize: 300
Binding: primary=A:2
=== END WIDGETS ===
```