From d59083aa6d585f58dd191d82631b4876c5d30283 Mon Sep 17 00:00:00 2001 From: neu-rah Date: Thu, 8 Oct 2026 16:46:14 +0000 Subject: [PATCH 1/2] examples/sila: a Nano served as a SiLA 2 device, one field of each kind Eight roles (switch, bounded level, discrete set, action, labelled select, analog in volts, text, command in presented units) from a Nano or from a host build with simulated endpoints, served as SiLA 2 features by gateway.py, which knows only the kinds in its table and refuses the rest by name. The six kinds that are not in role/kinds.h are in src/kinds.h. The feature definitions are generated at start; the server UUID is derived from the originator and the machine hash. Moved from R&D/OneMachine/silaCompose @ f158e21 (minimal/). The firmware image built here is byte-identical to the one built there (avr-gcc 7.3.0: 8910 B flash, 345 B RAM, sha256 97f1f9ea31a4c1a35f3a0ad1c904d5ecfdeaac60e0aa160fa16eb2de0885614e). Needs describe-values (value/scale/unit lines, '%' in a unit symbol). Co-Authored-By: Claude Sonnet 5.5 --- examples/sila/.gitignore | 2 + examples/sila/README.md | 158 ++++++++++++++++ examples/sila/gateway.py | 328 +++++++++++++++++++++++++++++++++ examples/sila/host/main.cpp | 35 ++++ examples/sila/platformio.ini | 9 + examples/sila/requirements.txt | 2 + examples/sila/src/kinds.h | 126 +++++++++++++ examples/sila/src/machine.h | 33 ++++ examples/sila/src/main.cpp | 47 +++++ 9 files changed, 740 insertions(+) create mode 100644 examples/sila/.gitignore create mode 100644 examples/sila/README.md create mode 100755 examples/sila/gateway.py create mode 100644 examples/sila/host/main.cpp create mode 100644 examples/sila/platformio.ini create mode 100644 examples/sila/requirements.txt create mode 100644 examples/sila/src/kinds.h create mode 100644 examples/sila/src/machine.h create mode 100644 examples/sila/src/main.cpp diff --git a/examples/sila/.gitignore b/examples/sila/.gitignore new file mode 100644 index 0000000..d8c8ddd --- /dev/null +++ b/examples/sila/.gitignore @@ -0,0 +1,2 @@ +fdl/ +host/machine diff --git a/examples/sila/README.md b/examples/sila/README.md new file mode 100644 index 0000000..748728d --- /dev/null +++ b/examples/sila/README.md @@ -0,0 +1,158 @@ +# sila + +A Nano (or this computer, with simulated endpoints) served as a laboratory device over SiLA 2. The machine declares eight roles, +one of each kind a SiLA client can use, and a Python gateway turns them into SiLA features: any SiLA client can read and command +them without knowing OneMachine, the pins or the board. + +[SiLA 2](https://sila-standard.com) is a standard for lab instruments: a device is a server that publishes *features* (a feature has +properties you read or subscribe to, and commands you call, each with typed, constrained parameters) over gRPC, and every +feature carries an XML definition (FDL) a client can fetch. The gateway (`gateway.py`) reads the machine's description over the +serial link, writes one feature per role and serves them. It knows only the kinds in its table: a role of any other kind is +refused, naming the kind. + +## Wiring + +Arduino Nano (ATmega328P). + +| role | where | needs | +|---|---|---| +| `led` | the onboard LED, pin 13 | nothing | +| `lamp` | pin 9 (PWM) | an LED and a 330 ohm resistor to GND | +| `vin` | A0 | optional. Floating, it reads noise anywhere between 0 and 5 V; jumper it to GND, 3V3 or 5V to read about 0, 3.5 and 5 V | +| `step`, `mode`, `note`, `duty`, `ping` | RAM | nothing | + +## Build, flash, serve + +``` +pio run -e nano -t upload +pip install -r requirements.txt # sila2 and pyserial, Python 3.10 or newer +python3 gateway.py --port /dev/ttyUSB0 # the Nano's port +``` + +The gateway generates the feature definitions at start (into a temporary directory, or `--fdl-dir DIR`; `--generate` writes +them and stops). It serves on `127.0.0.1:50052` without encryption (`--address`, `--sila-port`). Opening the serial port resets the +Nano, so all outputs start off at each start. + +Without the board, the same machine on this computer (from this directory): + +``` +g++ -std=c++17 -I../../../HAPI/include -I../../include host/main.cpp -o host/machine +python3 gateway.py --sim host/machine +``` + +`SIM_ADC=511` in the environment sets what the simulated `vin` reads (0 to 1023). + +## Use it + +Any SiLA 2 client works. With the `sila2` package that the gateway already needs: + +```python +import time +from sila2.client import SilaClient + +c = SilaClient('127.0.0.1', 50052, insecure=True) +c.Led.SetOn(True) # the onboard LED +c.Note.SetText('hello') +c.Duty.SetValue(12.35) +c.Mode.SetValue('high') +time.sleep(0.4) # the gateway polls the machine every 0.1 s +print(c.Note.Text.get(), c.Duty.Value.get(), c.Mode.Value.get(), c.Vin.Voltage.get()) +c.Duty.SetValue(100.01) # ValidationError: the server refuses it, nothing reaches the machine +``` + +## How a OneMachine field becomes a SiLA type + +| role (kind) | OneMachine field | SiLA feature: property, command | SiLA type and constraint | +|---|---|---|---| +| `led` (`switch`) | `on` | `Led`: `On`, `SetOn(On)` | Boolean | +| `lamp` (`light`) | `level`, bounded by `param lamp max` | `Lamp`: `Level`, `SetLevel(Level)` | Integer, minimum 0, maximum `max` (200) | +| `step` (`discrete`) | `value`, one of the `value` lines | `Step`: `Value`, `SetValue(Value)` | Integer, Set {0, 10, 50, 100} | +| `ping` (`action`) | `fire` (command), `fired` (report) | `Ping`: `Fired`, `Fire()` | `Fire` has no parameter; `Fired` is an Integer count | +| `mode` (`select`) | `index`, each `value` line has a label | `Mode`: `Value`, `SetValue(Value)` | String, Set {off, low, high} | +| `vin` (`analog`) | `raw`, with a `scale` and a `unit` line | `Vin`: `Voltage` (no command) | Real, Unit V (kg m^2 s^-3 A^-1), Voltage = raw * 5 / 1023 | +| `note` (`text`) | `text`, a `u8[16]` array | `Note`: `Text`, `SetText(Text)` | String, MaximalLength 16, Pattern `[ -~]*` (printable ASCII) | +| `duty` (`scaled`) | `raw`, with `max`, a `scale` and a `unit` line | `Duty`: `Value`, `SetValue(Value)` | Real, Unit % (dimensionless, factor 0.01), minimum 0, maximum 100 = `max` * 1 / 10 | + +The kinds `light` and `switch` are OneMachine's (`role/kinds.h`); the other six are in `src/kinds.h`. The lines a kind prints +in the machine description (`value`, `scale`, `unit`) are described in [docs/role.md](../../docs/role.md). One generated +definition (`Mode`, trimmed): + +```xml + + Mode + + SetValue + No + + Value + Stringofflowhigh + + + + Value + Yes + String... + + +``` + +The server's UUID is derived from the originator and the machine hash, so the same firmware is always the same server; a different +description (a role, a label, a unit) is a different server. + +## The rules you meet + +- **Unknown things are refused by name, at start.** A role of a kind the gateway's table (`KINDS` in `gateway.py`) does not have, + a tuned role, a description line the kind's row does not use, a unit symbol the unit table (`UNITS`: `V` and `%`) does not + have, a label used twice, or a scale whose bound is not a finite decimal: the gateway exits with a message that names the + role and the thing. It never guesses. +- **Out of range is refused at the SiLA edge; the device ignores it anyway.** `SetLevel(250)`, `SetValue(7)` on `step`, + `SetValue('max')` on `mode`, a 17-character or non-ASCII text, `Duty.SetValue(100.01)` or `-0.1` are validation errors + from the server's constraint check: no frame goes to the board. A client that bypasses SiLA and sends such a value to the board + is ignored by the device, which keeps the previous value and reports it. +- **A numeric command in presented units is rounded, and the report is the truth.** `Duty.SetValue(12.35)` becomes the raw value + 124 (the client's decimal, times 10 / 1, to the nearest integer, halves away from zero) and `Duty.Value` then reads 12.4: the value + the device holds. Enumerated fields (`step`, `mode`) are not rounded: anything not in the set is refused. +- **One frame per command, nothing resent.** A command is sent once; a `Fire()` sends its flag in exactly one frame. The gateway + holds the serial port under one lock, so concurrent calls do not interleave. + +## Expected output + +The gateway on the Nano (trimmed): + +``` +$ python3 gateway.py --port /dev/ttyUSB0 +... sila2.server.sila_server Starting SiLA server without encryption +... sila2.server.sila_server Server started +wrote /tmp/sila-fdl-qj4ng57l/Led.sila.xml +wrote /tmp/sila-fdl-qj4ng57l/Lamp.sila.xml +wrote /tmp/sila-fdl-qj4ng57l/Step.sila.xml +wrote /tmp/sila-fdl-qj4ng57l/Mode.sila.xml +wrote /tmp/sila-fdl-qj4ng57l/Vin.sila.xml +wrote /tmp/sila-fdl-qj4ng57l/Note.sila.xml +wrote /tmp/sila-fdl-qj4ng57l/Duty.sila.xml +wrote /tmp/sila-fdl-qj4ng57l/Ping.sila.xml +serving Led, Lamp, Step, Mode, Vin, Note, Duty, Ping on 127.0.0.1:50052, server 5e39722b-8dda-5d1f-9324-689f8ec8b1da, machine hash ba36fc2d +``` + +A client session on the same run (`Vin` floating, so its value is noise): + +``` +c.Led.On.get() False +c.Led.SetOn(True) ... True +c.Note.SetText('hello') ... 'hello' +c.Duty.SetValue(12.35) ... 12.4 +c.Mode.SetValue('high') ... high +c.Vin.Voltage.get() 3.758553274682307 +c.Duty.SetValue(100.01) ValidationError Parameter value rejected: Constraint violated: MaximalInclusive(100.0) (100.01) +Duty.SetValue(12.34) -> 12.3 +Duty.SetValue(12.35) -> 12.4 +Duty.SetValue(99.95) -> 100.0 +Ping.Fire() twice: Fired 2 +``` + +## What this example does not cover + +No timeout or safe fall (a value that was set stays set), no tuning (a tuned role is refused), no observable commands or command +completion (a command returns when the frame is sent, and its effect shows in the property), and no TLS or discovery beyond the +`sila2` library's defaults (the server runs without encryption and without mDNS). `vin` is read with whatever noise the pin has: +every change of the reading is published. diff --git a/examples/sila/gateway.py b/examples/sila/gateway.py new file mode 100755 index 0000000..6605634 --- /dev/null +++ b/examples/sila/gateway.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""A SiLA 2 server for a OneMachine machine whose roles are switches, plain lights, discrete integers, selects, analog inputs, text, scaled values and actions. + + python3 gateway.py --port /dev/ttyUSB0 a Nano (or any board running the role::Link sketch) on its USB serial port, 115200 + python3 gateway.py --sim host/machine a host build of the machine, over a pipe (no board needed) + python3 gateway.py ... --generate write the feature definitions to --fdl-dir (default ./fdl) and stop + +What it knows about role kinds is one table, KINDS: a kind -> the SiLA words for it. A role of any other kind is refused, naming the kind; so is a +tuned role (tuning is not in the table). The feature definitions (FDL) are generated at start, from the description (role names, field types, params) and the table: + + switch Feature Property On Boolean, observable <- the report's `on` + Command SetOn(On: Boolean) -> the command's `on` + light Feature Property Level Integer, observable <- the report's `level` + Command SetLevel(Level: Integer in [0, max]) -> the command's `level` + discrete Feature Property Value Integer, observable <- the report's `value` + Command SetValue(Value: Integer in Set{...}) -> the command's `value`; the set is the role's `value` lines + select Feature Property Value String, observable, Set{labels} <- the report's `index`, shown as the label of its `value` line + Command SetValue(Value: String in Set{labels}) -> the command's `index`: the raw of the label's `value` line + analog Feature Property Real, observable, Unit <- the report's `raw`, presented = raw * num / den (the role's `scale` line); + no command. The unit is the role's `unit` line, looked up in UNITS (symbol -> SI components and the property's name ). + text Feature Property Text String, observable, MaximalLength N, Pattern [ -~]* <- the report's u8[N] up to the first NUL + Command SetText(Text: String, the same constraints) -> the command's u8[N]: the ASCII bytes, NUL-padded to N + scaled Feature Property Value Real, observable, Unit <- the report's `raw`, presented = raw * num / den (the role's `scale` line) + Command SetValue(Value: Real in [0, max*num/den], Unit) -> the command's `raw`: the nearest integer to value*den/num, + halves away from zero, computed from the shortest decimal of the client's double with integer arithmetic (to_raw); + the report is what the device holds, so the actual value shows. max is the role's `param max`. + action Feature Property Fired Integer, observable <- the report's `fired` (how many times the action ran since boot) + Command Fire() -> the command's `fire` is 1 for that one frame, 0 in every other + A role's description may have the line types its row lists in `lines` and no others (a switch with a `unit` line is refused, naming the line). + all: no responses, no defined errors, plus SiLAService from the library. The kind's `safe` parameter and the report's `live` are not mapped. + +The light's row says "`max` bounds `level`"; the value is the machine's own `param max` line, and the field's type and width come from the +command and report descriptions. A set above the bound is a validation error from the server's own constraint check, before anything reaches the +machine. A command is forwarded once (m.push()); nothing is held or resent. Opening a Nano's serial port resets it (DTR): the outputs start off at every connect. +Needs sila2 and pyserial (requirements.txt), and python/onemachine from this checkout (../../python, or ONEMACHINE_PY=).""" +import argparse, atexit, logging, os, re, shutil, signal, sys, tempfile, threading, time, uuid +from decimal import Decimal +from fractions import Fraction +from queue import Queue +from xml.sax.saxutils import escape, quoteattr + +HERE = os.path.dirname(os.path.abspath(__file__)) +ONEMACHINE_PY = os.environ.get('ONEMACHINE_PY') or os.path.join(HERE, '..', '..', 'python') +if not os.path.isdir(os.path.join(ONEMACHINE_PY, 'onemachine')): sys.exit('gateway: python/onemachine not found at %s: run from a OneMachine checkout or set ONEMACHINE_PY' % ONEMACHINE_PY) +sys.path.insert(0, ONEMACHINE_PY) +from onemachine import Machine, StreamLink, SchemaError, LinkError + +ORIGINATOR = 'io.github.internetofpins' # in every fully qualified feature identifier +SERVER_TYPE, SERVER_NAME = 'OneMachineGateway', 'OneMachine SiLA example' +VENDOR_URL = 'https://github.com/InternetOfPins/OneMachine' +NS = 'http://www.sila-standard.org' + +class Refused(ValueError): + """The machine has something this gateway has no SiLA words for; it does not guess.""" + +# the whole of what this gateway knows about role kinds. kind -> the SiLA words, the description's field names, and (a light) which param bounds the field +KINDS = { + 'switch': dict(type='bool', report='on', command='on', prop='On', cmd='SetOn', param='On'), + 'light': dict(type='int', report='level', command='level', prop='Level', cmd='SetLevel', param='Level', upper='max', lower=0), + 'discrete': dict(type='discrete', report='value', command='value', prop='Value', cmd='SetValue', param='Value', lines=('value',)), # the allowed values: the `value` lines + 'select': dict(type='select', report='index', command='index', prop='Value', cmd='SetValue', param='Value', lines=('value',)), # the `value` lines, each with a label + 'analog': dict(type='analog', report='raw', command=None, prop=None, cmd=None, lines=('scale', 'unit')), # report only; the property's name is the unit's + 'text': dict(type='text', report='text', command='text', prop='Text', cmd='SetText', param='Text', lines=()), # a u8[N] field: printable ASCII, NUL-padded + 'scaled': dict(type='scaled', report='raw', command='raw', prop='Value', cmd='SetValue', param='Value', upper='max', lines=('scale', 'unit')), # a raw u16 0..max presented as raw*num/den + 'action': dict(type='action', report='fired', command='fire', prop='Fired', cmd='Fire'), +} +# unit symbol -> the SiLA Unit constraint (SI base components; factor and offset to the SI unit) and the name of the property that carries it. Only V. +UNITS = {'%': dict(prop='Percent', label='%', factor='0.01', offset=0, components=(('Dimensionless', 1),)), + 'V': dict(prop='Voltage', label='V', factor=1, offset=0, components=(('Kilogram', 1), ('Meter', 2), ('Second', -3), ('Ampere', -1)))} +TEXT_PATTERN = '[ -~]*' # printable ASCII, 0x20..0x7e: what the device keeps (a byte buffer) and a person can read + +def to_raw(value, num, den): + """presented -> raw, presented = raw * num / den: the exact rational of the shortest decimal that round-trips the client's double (12.35, not its binary + neighbour 12.3499999...), times den/num, to the nearest integer, halves away from zero. Integer arithmetic only: no round(), no float multiply.""" + x = Fraction(Decimal(repr(float(value)))) * den / num + p, q = abs(x.numerator), x.denominator + r = (2 * p + q) // (2 * q) + return -r if x < 0 else r + +def decimal_str(x): + """a Fraction as an exact finite decimal string, or None (the SiLA constraint is text: it must say exactly what the bound is)""" + d = Decimal(x.numerator) / Decimal(x.denominator) + return format(d.normalize(), 'f') if Fraction(d) == x else None +INT_RANGE = {'u8': (0, 255), 'u16': (0, 65535), 'u32': (0, 2**32 - 1), 'i8': (-128, 127), 'i16': (-32768, 32767), 'i32': (-2**31, 2**31 - 1)} + +def camel(name): + if not re.fullmatch(r'[A-Za-z0-9_]+', name) or '' in name.split('_'): raise Refused('role name %r has no SiLA identifier' % name) + ident = ''.join(t[0].upper() + t[1:] for t in name.split('_')) + if not re.fullmatch(r'[A-Z][A-Za-z0-9]*', ident): raise Refused('role name %r gives %r, not a SiLA identifier' % (name, ident)) + return ident + +def model(m): + """[(role name, feature identifier, kind, row, bounds)] for every role of the machine, or Refused. bounds = (low, high) of the command field, or None.""" + out, seen = [], {'SiLAService': 'the library'} + LINES = ('value', 'scale', 'unit') + for name, info in m.roles.items(): + if info.kind not in KINDS: raise Refused('role %s is of kind %r; this gateway knows %s' % (name, info.kind, ', '.join(sorted(KINDS)))) + if info.tuned: raise Refused('role %s (%s) is tuned: tuning is not in this gateway\'s table' % (name, info.kind)) + k = dict(KINDS[info.kind]) + have = {'value': info.values, 'scale': info.scales, 'unit': info.units} + for line in LINES: + if have[line] and line not in k.get('lines', ()): raise Refused('role %s (%s): its description has %s lines, which the %s row does not use' % (name, info.kind, line, info.kind)) + fields = {} + for what, schema, field in (('command', m.command_schema, k['command']), ('report', m.report_schema, k['report'])): + if field is None: continue + layer = schema.layer(name) + f = next((f for f in layer.fields if f.name == field), None) if layer else None + if k['type'] == 'text': + if f is None or not f.n or f.base != 'u8': raise Refused('role %s (%s): its %s has no u8 array %r' % (name, info.kind, what, field)) + fields[what] = f; continue + if f is None or f.n: raise Refused('role %s (%s): its %s has no scalar %r' % (name, info.kind, what, field)) + if k['type'] == 'bool' and f.base != 'bool': raise Refused('role %s (%s): its %s %r is %s, not bool' % (name, info.kind, what, field, f.base)) + if k['type'] != 'bool' and f.base not in INT_RANGE: raise Refused('role %s (%s): its %s %r is %s, which is no SiLA Integer' % (name, info.kind, what, field, f.base)) + fields[what] = f + bounds = None + if k['type'] == 'int': + if k['upper'] not in info.params: raise Refused('role %s (%s): no param %r in its description, and the table says it bounds %r' % (name, info.kind, k['upper'], k['command'])) + lo, hi = k['lower'], info.params[k['upper']] + tlo, thi = INT_RANGE[fields['command'].base] + if not (tlo <= lo <= hi <= thi): raise Refused('role %s (%s): bound [%d, %d] does not fit the %s field %r' % (name, info.kind, lo, hi, fields['command'].base, k['command'])) + bounds = (lo, hi) + elif k['type'] == 'discrete': + if not info.values: raise Refused('role %s (%s): no allowed values in its description (`value` lines)' % (name, info.kind)) + if any(label is not None for _, label in info.values): raise Refused('role %s (%s): a value has a label, which the discrete row does not use' % (name, info.kind)) + vals = [v for v, _ in info.values] + tlo, thi = INT_RANGE[fields['command'].base] + if len(set(vals)) != len(vals) or not all(tlo <= v <= thi for v in vals): raise Refused('role %s (%s): values %s are not distinct values of the %s field %r' % (name, info.kind, vals, fields['command'].base, k['command'])) + bounds = tuple(vals) + elif k['type'] == 'select': + if not info.values: raise Refused('role %s (%s): no values in its description (`value` lines)' % (name, info.kind)) + unlabelled = [v for v, label in info.values if label is None] + if unlabelled: raise Refused('role %s (%s): value %s has no label' % (name, info.kind, unlabelled[0])) + vals, labels = [v for v, _ in info.values], [label for _, label in info.values] + tlo, thi = INT_RANGE[fields['command'].base] + if len(set(vals)) != len(vals) or not all(tlo <= v <= thi for v in vals): raise Refused('role %s (%s): values %s are not distinct values of the %s field %r' % (name, info.kind, vals, fields['command'].base, k['command'])) + if len(set(labels)) != len(labels): raise Refused('role %s (%s): two values have the same label (%s)' % (name, info.kind, ', '.join(labels))) + bounds = tuple(info.values) + elif k['type'] == 'analog': + if set(info.scales) != {k['report']}: raise Refused('role %s (%s): the description needs one `scale` line, for the field %r (it has %s)' % (name, info.kind, k['report'], sorted(info.scales) or 'none')) + if set(info.units) != {k['report']}: raise Refused('role %s (%s): the description needs one `unit` line, for the field %r (it has %s)' % (name, info.kind, k['report'], sorted(info.units) or 'none')) + symbol = info.units[k['report']] + if symbol not in UNITS: raise Refused('role %s (%s): unit symbol %r is not in this gateway\'s unit table (%s)' % (name, info.kind, symbol, ', '.join(sorted(UNITS)))) + num, den = info.scales[k['report']] + k['prop'] = UNITS[symbol]['prop'] + bounds = (num, den, symbol) + elif k['type'] == 'text': + if fields['command'].n != fields['report'].n: raise Refused('role %s (%s): its command buffer is %d bytes and its report %d' % (name, info.kind, fields['command'].n, fields['report'].n)) + bounds = (fields['command'].n,) + elif k['type'] == 'scaled': + if set(info.scales) != {k['report']}: raise Refused('role %s (%s): the description needs one `scale` line, for the field %r (it has %s)' % (name, info.kind, k['report'], sorted(info.scales) or 'none')) + if set(info.units) != {k['report']}: raise Refused('role %s (%s): the description needs one `unit` line, for the field %r (it has %s)' % (name, info.kind, k['report'], sorted(info.units) or 'none')) + symbol = info.units[k['report']] + if symbol not in UNITS: raise Refused('role %s (%s): unit symbol %r is not in this gateway\'s unit table (%s)' % (name, info.kind, symbol, ', '.join(sorted(UNITS)))) + if k['upper'] not in info.params: raise Refused('role %s (%s): no param %r in its description, and the table says it bounds %r' % (name, info.kind, k['upper'], k['command'])) + num, den = info.scales[k['report']] + if num <= 0 or den <= 0: raise Refused('role %s (%s): scale %d/%d is not positive' % (name, info.kind, num, den)) + hi_raw = info.params[k['upper']]; tlo, thi = INT_RANGE[fields['command'].base] + if not (0 <= hi_raw <= thi): raise Refused('role %s (%s): bound [0, %d] does not fit the %s field %r' % (name, info.kind, hi_raw, fields['command'].base, k['command'])) + lo_s, hi_s = decimal_str(Fraction(0)), decimal_str(Fraction(hi_raw * num, den)) + if hi_s is None: raise Refused('role %s (%s): the presented bound %d*%d/%d is not a finite decimal' % (name, info.kind, hi_raw, num, den)) + bounds = (num, den, symbol, hi_raw, lo_s, hi_s) + elif k['type'] == 'action': + if INT_RANGE[fields['command'].base][0] != 0: raise Refused('role %s (%s): its command %r (%s) is signed; the flag is 0 or 1 of an unsigned field' % (name, info.kind, k['command'], fields['command'].base)) + ident = camel(name) + if ident in seen: raise Refused('roles %r and %r are both the feature %s' % (seen[ident], name, ident)) + seen[ident] = name + out.append((name, ident, info.kind, k, bounds)) + if not out: raise Refused('the machine has no roles') + return out + +def fdl(name, ident, kind, k, bounds): + d = lambda tag, s: '<%s>%s' % (tag, escape(s), tag) + head = lambda i, disp, desc, ind: ''.join('%s%s\n' % (ind, d(t, v)) for t, v in (('Identifier', i), ('DisplayName', disp), ('Description', desc))) + integer = 'Integer' + if k['type'] == 'bool': word = ptype = 'Boolean'; tdesc = 'bool' + elif k['type'] == 'select': + word = ptype = ('String%s' + % ''.join('%s' % escape(label) for _, label in bounds)); tdesc = 'label' + elif k['type'] == 'text': + word = ptype = ('String%d%s' + % (bounds[0], escape(TEXT_PATTERN))); tdesc = 'text' + elif k['type'] == 'scaled': + u = UNITS[bounds[2]]; tdesc = 'real' + unit = ('%s%d%s' + % (escape(u['label']), u['factor'], u['offset'], ''.join('%s%d' % c for c in u['components']))) + real = 'Real' + word = '%s%s' % (real, unit) + ptype = ('%s%s%s%s' + % (real, bounds[4], bounds[5], unit)) + elif k['type'] == 'analog': + u = UNITS[bounds[2]]; ptype = None; tdesc = 'real' + word = ('Real%d%d%s' + % (escape(u['label']), u['factor'], u['offset'], ''.join('%s%d' % c for c in u['components']))) + else: + word, tdesc = integer, 'integer' + if k['type'] == 'int': + ptype = ('Integer%d' + '%d' % bounds) + elif k['type'] == 'discrete': + ptype = ('Integer%s' + % ''.join('%d' % v for v in bounds)) + else: ptype = None + if k['type'] == 'analog': command = '' # report only: no command + else: + command = ' \n' + head(k['cmd'], k['cmd'], '%s/%s %s' % (name, k['command'], tdesc if ptype else 'flag'), ' ') + ' No\n' + if ptype: command += ' \n' + head(k['param'], k['command'], '%s/%s %s' % (name, k['command'], tdesc), ' ') + ' ' + ptype + '\n \n' + command += ' \n' + return ('\n' + '\n' % (NS, quoteattr(kind), quoteattr(ORIGINATOR), NS) + + head(ident, name, 'role %s %s' % (name, kind), ' ') + + command + + ' \n' + head(k['prop'], k['report'], '%s/%s %s' % (name, k['report'], tdesc), ' ') + ' Yes\n ' + word + '\n \n' + + '\n') + +def write_fdl(models, directory): + os.makedirs(directory, exist_ok=True) + paths = {} + for name, ident, kind, k, bounds in models: + path = os.path.join(directory, '%s.sila.xml' % ident) + with open(path, 'w', encoding='utf-8') as f: f.write(fdl(name, ident, kind, k, bounds)) + paths[ident] = path + return paths + +class Traced: + """Wraps a link and writes every request and response: op, payload hex, status, payload hex (checked from outside by frame_decode.py), + then the host time (seconds since the gateway started) at which the request is written to the port, and how long the exchange took.""" + def __init__(self, link, path): self.link, self.f, self.t0 = link, open(path, 'w', buffering=1), time.monotonic() + def call(self, op, payload=b''): + t = time.monotonic() - self.t0 + st, data = self.link.call(op, payload) + self.f.write('%s %s %d %s %.4f %.4f\n' % (op if isinstance(op, str) else chr(op), bytes(payload).hex() or '-', st, data.hex() or '-', t, time.monotonic() - self.t0 - t)) + return st, data + def close(self): self.f.close(); self.link.close() + +def open_link(a): + if a.sim: link = StreamLink.popen([a.sim]) + else: + import serial + port = serial.Serial(a.port, 115200, timeout=2) + time.sleep(2); port.reset_input_buffer() # opening the port reset the board: wait for its bootloader to pass + link = StreamLink(port.read, port.write, port.flush) + return Traced(link, a.trace) if a.trace else link + +def serve(a, m, models, paths): + import sila2.server, sila2.framework + from sila2.framework import Feature + lock = threading.RLock() + server_uuid = str(uuid.uuid5(uuid.NAMESPACE_URL, 'urn:%s:%s:%08x' % (ORIGINATOR, SERVER_TYPE, m.description.hash))) # the same firmware is always the same server + server = sila2.server.SilaServer(SERVER_NAME, SERVER_TYPE, 'machine hash %08x' % m.description.hash, '1.0', VENDOR_URL, server_uuid) + impls = {} + for name, ident, kind, k, bounds in models: + class Impl(sila2.server.FeatureImplementationBase): pass + impl = Impl(server) + setattr(impl, '_%s_producer_queue' % k['prop'], Queue()) + setattr(impl, 'update_' + k['prop'], (lambda v, impl=impl, p=k['prop']: (setattr(impl, '_%s_current_value' % p, v), getattr(impl, '_%s_producer_queue' % p).put(v)))) + setattr(impl, k['prop'] + '_on_subscription', lambda *, metadata: None) + raw_of = {label: raw for raw, label in bounds} if k['type'] == 'select' else None + def setter(value, *, metadata, name=name, k=k, raw_of=raw_of, bounds=bounds): + with lock: # one frame at a time: a frame carries every role's command + if k['type'] == 'text': + b = value.encode('ascii') # the SiLA edge (Pattern, MaximalLength) has already refused anything else; this is not trusted + if len(b) > bounds[0] or not all(0x20 <= c <= 0x7e for c in b): raise ValueError('text outside the buffer or printable ASCII') + v = list(b) + [0] * (bounds[0] - len(b)) # NUL-padded: nothing of an older, longer text stays + elif k['type'] == 'scaled': v = to_raw(value, bounds[0], bounds[1]) + else: v = bool(value) if k['type'] == 'bool' else raw_of[value] if raw_of else int(value) + setattr(getattr(m.cmd, name), k['command'], v) + m.push() # once + def fire(*, metadata, name=name, k=k): + with lock: # the flag is 1 only here, during one push, and 0 in every other frame + layer = getattr(m.cmd, name) + setattr(layer, k['command'], 1) + try: m.push() # once + finally: setattr(layer, k['command'], 0) + if k['cmd']: setattr(impl, k['cmd'], fire if k['type'] == 'action' else setter) + impl.last = None + impls[name] = impl + server.set_feature_implementation(Feature(paths[ident]), impl) + def publish(): + with lock: r = m.poll() + for name, ident, kind, k, bounds in models: + v = getattr(getattr(r, name), k['report']) + if k['type'] == 'bool': v = bool(v) + elif k['type'] == 'select': + label = dict(bounds).get(int(v)) + if label is None: raise LinkError('role %s: the report says %d, which no `value` line names' % (name, v)) + v = label + elif k['type'] == 'analog': v = float(v) * bounds[0] / bounds[1] + elif k['type'] == 'scaled': v = float(Fraction(int(v) * bounds[0], bounds[1])) + elif k['type'] == 'text': v = bytes(v).split(b'\0', 1)[0].decode('ascii', 'replace') + else: v = int(v) + if impls[name].last != v: impls[name].last = v; getattr(impls[name], 'update_' + k['prop'])(v) + publish() + server.start_insecure(a.address, a.sila_port, enable_discovery=False) + print('serving %s on %s:%d, server %s, machine hash %08x' % (', '.join(i for _, i, _, _, _ in models), a.address, a.sila_port, server.server_uuid, m.description.hash), flush=True) + try: + while True: + time.sleep(a.poll) + try: publish() + except (LinkError, OSError) as e: logging.getLogger('gateway').error('the machine does not answer: %s', e); time.sleep(1) + except KeyboardInterrupt: pass + finally: server.stop(0.5) + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + src = ap.add_mutually_exclusive_group(required=True) + src.add_argument('--port', metavar='SERIAL'); src.add_argument('--sim', metavar='HOST_BINARY') + ap.add_argument('--fdl-dir', help='where the feature definitions are written (default: ./fdl with --generate, else a temporary directory)'); ap.add_argument('--generate', action='store_true') + ap.add_argument('--address', default='127.0.0.1'); ap.add_argument('--sila-port', type=int, default=50052) + ap.add_argument('--poll', type=float, default=0.1, help='seconds between report polls'); ap.add_argument('--trace', metavar='FILE') + a = ap.parse_args() + logging.basicConfig(level=logging.INFO, format='%(asctime)s %(name)s %(message)s') + try: m = Machine(open_link(a)) + except SchemaError as e: sys.exit('gateway: the binding refuses this machine: %s' % e) + except (LinkError, OSError) as e: sys.exit('gateway: cannot reach the machine: %s' % e) + try: models = model(m) + except Refused as e: sys.exit('gateway: refused: %s' % e) + if not a.fdl_dir: + if a.generate: a.fdl_dir = 'fdl' + else: a.fdl_dir = tempfile.mkdtemp(prefix='sila-fdl-'); atexit.register(shutil.rmtree, a.fdl_dir, True) + paths = write_fdl(models, a.fdl_dir) + for p in paths.values(): print('wrote', p) + if a.generate: return + signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) # a kill stops the server and removes the temporary directory + serve(a, m, models, paths) + +if __name__ == '__main__': + main() diff --git a/examples/sila/host/main.cpp b/examples/sila/host/main.cpp new file mode 100644 index 0000000..68805b5 --- /dev/null +++ b/examples/sila/host/main.cpp @@ -0,0 +1,35 @@ +// The machine of machine.h on a host, with simulated endpoints: role::Link on stdin/stdout. A stand-in for the Nano when none is attached. +#include "../src/machine.h" +#include +#include +#include +#include +#include + +struct SimAdc { // the reading is the environment variable SIM_ADC (0..1023, default 0), read once + static bool live() { return true; } + static uint16_t get() { static const uint16_t v = getenv("SIM_ADC") ? uint16_t(atoi(getenv("SIM_ADC"))) : 0; return v; } + template static void where(Put& put) { put('A'); put('0'); } +}; + +using M = MachineOf, role::SimPwm<9, 255>, SimAdc>; +struct Out { static void put(uint8_t b) { putchar(b); } }; +static M::Command cmd{}; +static M::Report rep{}; +static role::Link chan(rep, 0); +static uint32_t millis() { + using namespace std::chrono; + static const auto t0 = steady_clock::now(); + return uint32_t(duration_cast(steady_clock::now() - t0).count()); +} + +int main() { + M::apply(cmd, rep); + int c; + while ((c = getchar()) != EOF) { + chan.feed(uint8_t(c), millis()); fflush(stdout); + if (chan.take(cmd)) { M::apply(cmd, rep); state::get(cmd).fire = 0; } + M::sense(rep); + } + return 0; +} diff --git a/examples/sila/platformio.ini b/examples/sila/platformio.ini new file mode 100644 index 0000000..31ff2fb --- /dev/null +++ b/examples/sila/platformio.ini @@ -0,0 +1,9 @@ +; sila -- the machine of src/machine.h on a Nano, served over SiLA 2 by gateway.py. See README.md. +[env:nano] +platform = atmelavr +board = nanoatmega328 +framework = arduino +build_unflags = -std=c++11 -std=c++14 -std=gnu++11 -std=gnu++14 +build_flags = -std=gnu++17 -Wall -Wextra +; Local source tree, not GitHub -- matches every other example in this family. +lib_extra_dirs = ../../.. diff --git a/examples/sila/requirements.txt b/examples/sila/requirements.txt new file mode 100644 index 0000000..3d59125 --- /dev/null +++ b/examples/sila/requirements.txt @@ -0,0 +1,2 @@ +sila2==0.14.0 +pyserial==3.5 diff --git a/examples/sila/src/kinds.h b/examples/sila/src/kinds.h new file mode 100644 index 0000000..f6317a3 --- /dev/null +++ b/examples/sila/src/kinds.h @@ -0,0 +1,126 @@ +// The example's kinds, written in the shape of role::Switch and role::Light: what the library calls on a kind is name(), params(v), Command and +// Report with each(), apply, sense and safe (role/role.h, role/face.h). Tune and valid are for tuned roles only. params(v) may call +// v(name, int) for a parameter and v.value(raw[, label]), v.scale(field, num, den), v.unit(field, symbol) for what the values mean. +#pragma once +#include + +namespace extra { + // a field that takes one of a compile-time list of values; a value outside the list is ignored by the device (the previous one stays, the report shows it) + template struct Discrete { + static_assert(sizeof...(Vs) > 0 && sizeof...(Vs) <= 100, "extra: a Discrete has 1 to 100 values"); + static_assert(((Vs >= 0 && Vs <= 65535) && ...), "extra: a Discrete value is a u16"); + ONEMACHINE_STATE_NAME(name, "discrete"); + struct Command { uint16_t value; ONEMACHINE_STATE_NAME(n_value, "value"); + template static constexpr void each(Self& s, F& f) { f(n_value(), s.value); } }; + struct Report { uint16_t value; ONEMACHINE_STATE_NAME(n_value, "value"); + template static constexpr void each(Self& s, F& f) { f(n_value(), s.value); } }; + template static void params(V& v) { (v.value(Vs), ...); } + static constexpr bool allowed(uint16_t x) { return ((int(x) == Vs) || ...); } + template static void apply(const Command& c, Report& r) { if (allowed(c.value)) E::set(c.value); r.value = E::get(); } + template static void sense(Report& r) { r.value = E::get(); } + static void safe(Command& c, const Report& r) { c.value = r.value; } // hold where it is + }; + + // a field that takes one of a list of labelled values 0, 1, ...; an index outside the list is ignored by the device (the previous one stays, the report shows it) + template struct Select { + static_assert(sizeof...(Ls) > 0 && sizeof...(Ls) <= 100, "extra: a Select has 1 to 100 labels"); + // a label is 1 to 32 of A-Z a-z 0-9 _ - : one word on its description line (python/onemachine refuses any other) + static constexpr bool label_ok(::state::Name n) { + unsigned i = 0; + for (; n.at(i); i++) { char c = n.at(i); if (!((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c == '-')) return false; } + return i >= 1 && i <= 32; + } + static_assert((label_ok(Ls::name()) && ...), "extra: a Select label is 1 to 32 of A-Z a-z 0-9 _ -"); + ONEMACHINE_STATE_NAME(name, "select"); + struct Command { uint8_t index; ONEMACHINE_STATE_NAME(n_index, "index"); + template static constexpr void each(Self& s, F& f) { f(n_index(), s.index); } }; + struct Report { uint8_t index; ONEMACHINE_STATE_NAME(n_index, "index"); + template static constexpr void each(Self& s, F& f) { f(n_index(), s.index); } }; + template struct Put { template static void go(V&) {} }; + template struct Put { + template static void go(V& v) { v.value(int32_t(I), First::name()); Put::go(v); } }; + template static void params(V& v) { Put<0, Ls...>::go(v); } + template static void apply(const Command& c, Report& r) { if (c.index < sizeof...(Ls)) E::set(c.index); r.index = E::get(); } + template static void sense(Report& r) { r.index = E::get(); } + static void safe(Command& c, const Report& r) { c.index = r.index; } // hold where it is + }; + + // a value read from the device, never written: the report is the raw reading; the description gives its scale (presented = raw * Num / Den) and unit symbol + template struct Analog { + static_assert(Den != 0, "extra: an Analog's denominator is 0"); + ONEMACHINE_STATE_NAME(name, "analog"); + struct Command { template static constexpr void each(Self&, F&) {} }; + struct Report { uint16_t raw; ONEMACHINE_STATE_NAME(n_raw, "raw"); + template static constexpr void each(Self& s, F& f) { f(n_raw(), s.raw); } }; + ONEMACHINE_STATE_NAME(n_raw, "raw"); + template static void params(V& v) { v.scale(n_raw(), Num, Den); v.unit(n_raw(), Unit::name()); } + template static void apply(const Command&, Report& r) { r.raw = E::get(); } + template static void sense(Report& r) { r.raw = E::get(); } + static void safe(Command&, const Report&) {} + }; + + // printable ASCII text in a fixed buffer of N bytes, NUL-padded (a text of N characters has no NUL). A command whose buffer is not printable bytes + // followed only by NULs is ignored by the device (the previous text stays, the report shows it). + template struct Text { + static_assert(N >= 1 && N <= 60, "extra: a Text buffer is 1 to 60 bytes"); + ONEMACHINE_STATE_NAME(name, "text"); + struct Command { uint8_t text[N]; ONEMACHINE_STATE_NAME(n_text, "text"); + template static constexpr void each(Self& s, F& f) { f(n_text(), s.text); } }; + struct Report { uint8_t text[N]; ONEMACHINE_STATE_NAME(n_text, "text"); + template static constexpr void each(Self& s, F& f) { f(n_text(), s.text); } }; + template static void params(V&) {} + static bool valid(const uint8_t* t) { unsigned i = 0; while (i < N && t[i] >= 0x20 && t[i] <= 0x7e) i++; for (; i < N; i++) if (t[i]) return false; return true; } + template static void apply(const Command& c, Report& r) { if (valid(c.text)) E::set(c.text); E::get(r.text); } + template static void sense(Report& r) { E::get(r.text); } + static void safe(Command& c, const Report& r) { for (unsigned i = 0; i < N; i++) c.text[i] = r.text[i]; } // hold where it is + }; + + // a raw u16 0..Max whose meaning is presented = raw * Num / Den in Unit (the description's scale and unit lines); above Max the device ignores the command + template struct Scaled { + static_assert(Den != 0 && Max <= 65535, "extra: a Scaled needs a nonzero denominator and a u16 maximum"); + ONEMACHINE_STATE_NAME(name, "scaled"); + struct Command { uint16_t raw; ONEMACHINE_STATE_NAME(n_raw, "raw"); + template static constexpr void each(Self& s, F& f) { f(n_raw(), s.raw); } }; + struct Report { uint16_t raw; ONEMACHINE_STATE_NAME(n_raw, "raw"); + template static constexpr void each(Self& s, F& f) { f(n_raw(), s.raw); } }; + ONEMACHINE_STATE_NAME(n_raw, "raw"); ONEMACHINE_STATE_NAME(p_max, "max"); + template static void params(V& v) { v(p_max(), int32_t(Max)); v.scale(n_raw(), Num, Den); v.unit(n_raw(), Unit::name()); } + template static void apply(const Command& c, Report& r) { if (c.raw <= Max) E::set(c.raw); r.raw = E::get(); } + template static void sense(Report& r) { r.raw = E::get(); } + static void safe(Command& c, const Report& r) { c.raw = r.raw; } // hold where it is + }; + + // an action: the device fires on every command with `fire` set; nothing is stored or compared. The report is how many times it ran since boot + // (a u16: it wraps to 0 after 65535). + struct Action { + ONEMACHINE_STATE_NAME(name, "action"); + struct Command { uint8_t fire; ONEMACHINE_STATE_NAME(n_fire, "fire"); + template static constexpr void each(Self& s, F& f) { f(n_fire(), s.fire); } }; + struct Report { uint16_t fired; ONEMACHINE_STATE_NAME(n_fired, "fired"); + template static constexpr void each(Self& s, F& f) { f(n_fired(), s.fired); } }; + template static void params(V&) {} + template static void apply(const Command& c, Report& r) { if (c.fire) E::fire(); r.fired = E::count(); } + template static void sense(Report& r) { r.fired = E::count(); } + static void safe(Command& c, const Report&) { c.fire = 0; } + }; + + // endpoints with no wiring: variables (one per Id: two roles cannot share an endpoint type), and a counter that an action increments + template struct Var { + static inline uint16_t v = 0; + static bool live() { return true; } + static void set(uint16_t x) { v = x; } static uint16_t get() { return v; } + template static void where(Put& put) { put('r'); put('a'); put('m'); } + }; + template struct Buf { + static inline uint8_t b[N] = {}; + static bool live() { return true; } + static void set(const uint8_t* t) { for (unsigned i = 0; i < N; i++) b[i] = t[i]; } static void get(uint8_t* t) { for (unsigned i = 0; i < N; i++) t[i] = b[i]; } + template static void where(Put& put) { put('r'); put('a'); put('m'); } + }; + struct Counter { + static inline uint16_t n = 0; + static bool live() { return true; } + static void fire() { ++n; } static uint16_t count() { return n; } + template static void where(Put& put) { put('r'); put('a'); put('m'); } + }; +} diff --git a/examples/sila/src/machine.h b/examples/sila/src/machine.h new file mode 100644 index 0000000..334abfc --- /dev/null +++ b/examples/sila/src/machine.h @@ -0,0 +1,33 @@ +// The machine: a switch `led`, a light `lamp`, a discrete `step`, a select `mode`, an analog input `vin`, a text `note`, a scaled `duty` and an action +// `ping`. A consumer sees the roles and their kinds, never the pins: the same roles run on the Nano (pins 13, 9 and A0; the rest have no wiring) and +// on a host (simulated endpoints), so the same gateway serves both. +#pragma once +#include +#include +#include "kinds.h" + +struct Led { ONEMACHINE_STATE_NAME(name, "led"); }; +struct Lamp { ONEMACHINE_STATE_NAME(name, "lamp"); }; +struct Step { ONEMACHINE_STATE_NAME(name, "step"); }; +struct Ping { ONEMACHINE_STATE_NAME(name, "ping"); }; +struct Mode { ONEMACHINE_STATE_NAME(name, "mode"); }; +struct Vin { ONEMACHINE_STATE_NAME(name, "vin"); }; + +struct LabelOff { ONEMACHINE_STATE_NAME(name, "off"); }; +struct LabelLow { ONEMACHINE_STATE_NAME(name, "low"); }; +struct LabelHigh { ONEMACHINE_STATE_NAME(name, "high"); }; +struct Note { ONEMACHINE_STATE_NAME(name, "note"); }; +struct Duty { ONEMACHINE_STATE_NAME(name, "duty"); }; +struct PercentUnit { ONEMACHINE_STATE_NAME(name, "%"); }; +struct VinUnit { ONEMACHINE_STATE_NAME(name, "V"); }; + +template +using MachineOf = role::Machine< + role::Role, LedAt>, + role::Role, LampAt>, + role::Role, extra::Var<0>>, + role::Role, extra::Var<1>>, + role::Role, VinAt>, + role::Role, extra::Buf<16>>, + role::Role, extra::Var<2>>, + role::Role>; diff --git a/examples/sila/src/main.cpp b/examples/sila/src/main.cpp new file mode 100644 index 0000000..8649548 --- /dev/null +++ b/examples/sila/src/main.cpp @@ -0,0 +1,47 @@ +// A Nano as the machine of machine.h: the onboard LED (pin 13) is the role `led`, a PWM output (pin 9) is `lamp`, A0 is the report-only `vin`, and +// `step`, `mode`, `note`, `duty` and `ping` have no wiring. The role::Link runs over the USB serial port at 115200. +// There is no timeout: a value that was set stays set. +#include +#include "machine.h" +#include + +template struct Pin { + static bool live() { return true; } + static void set(bool v) { digitalWrite(P, v ? HIGH : LOW); } + static bool get() { return digitalRead(P) == HIGH; } + template static void where(Put& put) { put('D'); state::put_dec(put, unsigned(P)); } +}; + +template struct Pwm { + static constexpr uint16_t top = 255; + static inline uint16_t v = 0; + static bool live() { return true; } + static void set(uint16_t x) { v = x > top ? top : x; analogWrite(P, int(v)); } + static uint16_t get() { return v; } + template static void where(Put& put) { put('D'); state::put_dec(put, unsigned(P)); put('~'); } +}; + +struct Adc { // report only: nothing is written + static bool live() { return true; } + static uint16_t get() { return uint16_t(analogRead(A0)); } + template static void where(Put& put) { put('A'); put('0'); } +}; + +using M = MachineOf, Pwm<9>, Adc>; +struct Out { static void put(uint8_t b) { Serial.write(b); } }; +static M::Command cmd{}; +static M::Report rep{}; +static role::Link link(rep, 0); + +void setup() { + pinMode(13, OUTPUT); pinMode(9, OUTPUT); + Serial.begin(115200); + M::apply(cmd, rep); +} + +void loop() { + uint32_t now = millis(); + while (Serial.available()) link.feed(uint8_t(Serial.read()), now); + if (link.take(cmd)) { M::apply(cmd, rep); state::get(cmd).fire = 0; } // an action fires once per command, not again when the command is applied again + M::sense(rep); +} From d797dfc20016ecb0afceeec943ab67452ad83884 Mon Sep 17 00:00:00 2001 From: neu-rah Date: Thu, 8 Oct 2026 16:46:14 +0000 Subject: [PATCH 2/2] docs: list examples/sila in the README and link it from docs/role.md Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 +++++ docs/role.md | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 30c99f2..0e596d3 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,11 @@ And one on the output side, needing only a Nano: - [`examples/python`](examples/python) — outputs driven by role name from Python over USB serial, or on the host with the pins simulated: the consumer side of `role::`. +And one that serves a machine to lab software: + +- [`examples/sila`](examples/sila) — one field of each kind (switch, level, discrete, select, analog volts, text, command in presented + units, action) served as SiLA 2 features by a Python gateway, from a Nano or on the host with the endpoints simulated. + And one on a second bus: - [`examples/spi`](examples/spi) — an RC522 RFID reader found on an SPI bus with statically declared chip selects diff --git a/docs/role.md b/docs/role.md index 1fafd9b..ae7efd3 100644 --- a/docs/role.md +++ b/docs/role.md @@ -85,7 +85,7 @@ unit vin raw V the unit symbol of a field of the role (v.unit(field ``` The device holds integers only; the presented value is the consumer's arithmetic. A label is 1 to 32 of `A-Z a-z 0-9 _ -` -(`python/onemachine` refuses the description otherwise). A unit symbol is one token of `A-Z a-z 0-9 / * ^ . % -`, 1 to 16 characters (the same refusal). Kinds that print none of these lines print exactly what they did before. +(`python/onemachine` refuses the description otherwise). A unit symbol is one token of `A-Z a-z 0-9 / * ^ . % -`, 1 to 16 characters (the same refusal). Kinds that print none of these lines print exactly what they did before. [`examples/sila`](../examples/sila) is a machine that uses all three, served over SiLA 2. So rewiring, a device moving to another channel, or new firmware with the same roles changes nothing on the consumer side: the same command frame is accepted as is (`test/role/check.py`, "rewired firmware"). When the roles do change, the device answers