Skip to content

About

Portable C parser for the Ferrum/KMBox ASCII command protocol (shared by the Hurra firmware family)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

ferrum-parser

A portable C11 parser for the Ferrum command protocol, written against the spec at https://docs.xferrum.dev/print.html. It's shared by the Hurra firmware family and its host tools.

It handles syntax, argument validation and output formatting only. It does no I/O, allocates nothing, keeps no global state, and doesn't use printf or atoi. Each consumer keeps its own action layer and transport.

Coverage

All three command families in the spec are covered:

API Commands
Keyboard and Mouse (km.*) version, move (and the m alias), left, right, middle, side1, side2, click, wheel, lock_ml/mr/mm/ms1/ms2, lock_mx/my/mw with +/- directional forms, scale_mx/my/mw with +/- forms, catch_xy, down, up, press, multidown, multiup, multipress, isdown, mask, init, buttons, axes (and the axis alias), keys, echo, has_mouse, has_keyboard, has_controller, controller, controller_axes, controller_buttons, device.VID, device.PID. Also the Legacy baud and the Hurra-only human.
Ferrum (ferrum.*) version, output, move_multiplier, mouse_rendering, no_baseline_frame, no_button_release, settings_locked, serial_mouse/keyboard/controller and their _reset forms
Mouse Proxy (mouse_proxy.*) start, fetch, modify, stop

Parsing rules from the spec

  • Ignored characters. Everything except letters, digits and +-_.,()[];= is removed before parsing. km . move ( 1 , 2 ) and km.down('a') are therefore valid.
  • Line terminators. Any combination of \r and \n ends a line.
  • Multiple commands. ; separates several commands on one line. They run in order, the line is echoed once, and only the last result is sent. Use ferrum_cmd_has_result() to find which command that is before running the line.
  • Invalid lines. If a line has missing or unbalanced parentheses or brackets, or text after the closing ), the whole line is discarded (status JUNK) and nothing is sent back. This also applies when only one of its ;-separated commands is invalid.
  • Unsupported commands. An unknown km.* or device.* command gets status UNKNOWN: it is echoed but has no effect.
  • Ignored arguments. A known command with arguments it doesn't accept gets status BAD_ARGS: it is echoed but has no effect. Examples are km.left(2), km.scale_mx(17), km.controller(zz=1) and device.VID(1).
  • Keys. Keys can be given by number (0–255) or by key string (case-insensitive, such as space or shift-l). Bare numbers are read as key numbers, so the digit key strings 0–9 are only usable through their numbers 30–39.
  • Special cases:
    • km.isdown() with no key, or with an unknown key, replies 0.
    • km.catch_xy() with no duration defaults to 1000 ms.
    • The multi-key commands accept up to FERRUM_MAX_MULTI keys (32 by default).
  • Quoted serials. A quoted serial in ferrum.serial_<dev>("...") is taken from the raw line: everything between the first and last ", 1–126 characters. It must be on a line by itself.

Command names are case-sensitive. Key strings, true/false, None and controller names are not.

Output the consumer is responsible for

The library formats each piece of text. The consumer decides when to send it:

  • Software API. The consumer echoes each accepted line (OK, UNKNOWN or BAD_ARGS), terminated with \r\n. Then it sends the line's result, if any. Then it sends the FERRUM_PROMPT (">>> ").
  • Turning echo off. km.echo(0) stops both the echo and the prompt, and the line containing it is already not echoed.
  • Legacy API. There is no echo and no prompt.
  • Callbacks. The callback formatters (Axes(...), Keys(...), km.<byte>, ControllerAxes(...), ControllerButtons(...), MouseOutput(...)) already end with \r\n>>> , because the spec requires the prompt even when echo is off.

API

static ferrum_line_t   lb;      // ferrum_line_reset(&lb) at init
static ferrum_parser_t ps;      // normalized copy of the current line
const char *line; uint16_t len;
if (ferrum_line_feed(&lb, byte, millis(), &line, &len) &&
    ferrum_parse_begin(&ps, line, len) == FERRUM_PARSE_OK) {
    ferrum_cmd_t c; ferrum_parse_status_t st;
    while (ferrum_parse_next(&ps, &c, &st))
        if (st == FERRUM_PARSE_OK) dispatch(&c);   // switch (c.kind) { ... }
}

ferrum_parse_line() is a shortcut for a line holding a single command. It returns FERRUM_PARSE_MULTI for lines with several commands.

Function Purpose
ferrum_line_feed(), ferrum_line_tick() Turn bytes into lines. A partial line is dropped after 25 ms of silence, and so is any line longer than FERRUM_LINE_MAX - 1.
ferrum_parse_begin(), ferrum_parse_next(), ferrum_parse_rewind() Validate a line, then step through its commands.
ferrum_frames_begin(), ferrum_frames_next() Read the frames of a mouse_proxy.modify command, clamped as the spec requires.
ferrum_fmt_*() Format replies and callbacks. The fetch and MouseOutput lists are written in pieces (begin, then each frame, then end) so they don't need one large buffer.
ferrum_parse_int(), ferrum_parse_decimal(), ferrum_parse_key(), ferrum_normalize() Helpers for consumers that add their own commands.

Scales and the move multiplier are fixed-point values in millionths (FERRUM_DEC_ONE). ferrum_fmt_decimal() prints them the way Python prints floats: 0.25, 1.0.

Configuration

Macro Default Purpose
FERRUM_LINE_MAX 256 Longest line accepted. A full 240-slot mouse_proxy.modify needs about 8 KB, so raise this to 8192 if you implement the Mouse Proxy API. Set it the same for the library and every file that includes the header.
FERRUM_MAX_MULTI 32 Most keys accepted by one multi-key command.
FERRUM_API_VERSION "2.0.5" What ferrum.version() replies with.

The library compiles to about 8.5 KB of code on Cortex-M7 at -Os, before the linker drops any formatters that aren't used.

Using it

Makefile firmware: compile ferrum_parse.c and add this directory to the include path. CMake: add_subdirectory(...) and link ferrum_parser.

Tests

make test        # host tests under ASan/UBSan with a mutation fuzz, at both line sizes
make check-arm   # cross-compile and size check with arm-none-eabi-gcc

Changes in 0.3.0

  • Brought in line with the spec:
    • Characters the spec ignores are now removed before parsing.
    • ; can put several commands on one line.
    • Text after ) now makes the line invalid. It used to be accepted.
    • Unknown km.* commands are now accepted and ignored.
    • Key strings are accepted.
    • Multi-key commands are no longer limited to 6 keys.
    • isdown replies 0 when given no key or an unknown key.
    • catch_xy() defaults to 1000 ms.
    • Mask state must be 0 or 1.
  • New commands: the rest of the km.* commands listed under Coverage, plus all ferrum.* and mouse_proxy.* commands.
  • API changes:
    • Line length is now uint16_t.
    • catch_xy.flag was renamed to include_sw.
    • mask.mode was renamed to state.
    • Callback formatters now append the >>> prompt.
    • ferrum_cmd_name() returns the full name, such as "km.move".

About

Portable C parser for the Ferrum/KMBox ASCII command protocol (shared by the Hurra firmware family)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages