diff --git a/docs/role.md b/docs/role.md index f0f28c5..1fafd9b 100644 --- a/docs/role.md +++ b/docs/role.md @@ -76,6 +76,17 @@ param white safe 0 at white pca9685 0x40 behind 0x70/2 #0 ``` +A kind may also print what its values mean (`Params`, in `role/face.h`; all inside the machine hash): + +``` +value mode 0 off a value the role takes, with an optional label (v.value(raw, label)) +scale vin raw 5 1023 presented = raw * num / den, for a field of the role (v.scale(field, num, den)) +unit vin raw V the unit symbol of a field of the role (v.unit(field, symbol)) +``` + +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. + 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 BadHash; the consumer re-reads, keeps every value whose role and field still exist, and is told (RoleChanged) when a role it diff --git a/include/oneMachine/role/face.h b/include/oneMachine/role/face.h index 04aae4f..3c1a69e 100644 --- a/include/oneMachine/role/face.h +++ b/include/oneMachine/role/face.h @@ -7,6 +7,9 @@ // ref https://... role/ref.h, in item order // role x axis one per role: name, kind // param x steps_mm 80 one per kind parameter, signed decimal: the firmware's value (for a tuned role, its limit) +// value x 50 half a kind may print: a value the role takes, with an optional label (v.value(raw, label)) +// scale x level 5 1023 presented = raw * num / den, for a field of the role (v.scale(field, num, den)) +// unit x level V the unit symbol of a field of the role (v.unit(field, symbol)) // tune x the role is role::Tuned: its parameters' current values are the link's tuning state (ops T, G, S) // at x sim.stepdir(0) where the device routes it: for a person reading the description, not for a consumer. // Not in the hash: rewiring changes nothing a consumer depends on. @@ -30,6 +33,17 @@ namespace role { P& put; state::Name role; void operator()(state::Name n, int32_t v) { ONEMACHINE_ROLE_TEXT(kParam, "param "); ONEMACHINE_ROLE_PUT(put, kParam); state::put_name(put, role); put(' '); state::put_name(put, n); put(' '); put_int(put, v); put('\n'); } + // a value the role takes, with an optional label: presented to a person or a consumer as the label + void value(int32_t raw) { + ONEMACHINE_ROLE_TEXT(kValue, "value "); ONEMACHINE_ROLE_PUT(put, kValue); state::put_name(put, role); put(' '); put_int(put, raw); put('\n'); } + void value(int32_t raw, state::Name label) { + ONEMACHINE_ROLE_TEXT(kValue, "value "); ONEMACHINE_ROLE_PUT(put, kValue); state::put_name(put, role); put(' '); put_int(put, raw); put(' '); state::put_name(put, label); put('\n'); } + // presented = raw * num / den, for a field of the role + void scale(state::Name field, int32_t num, int32_t den) { + ONEMACHINE_ROLE_TEXT(kScale, "scale "); ONEMACHINE_ROLE_PUT(put, kScale); state::put_name(put, role); put(' '); state::put_name(put, field); put(' '); put_int(put, num); put(' '); put_int(put, den); put('\n'); } + // the unit symbol of a field of the role + void unit(state::Name field, state::Name symbol) { + ONEMACHINE_ROLE_TEXT(kUnit, "unit "); ONEMACHINE_ROLE_PUT(put, kUnit); state::put_name(put, role); put(' '); state::put_name(put, field); put(' '); state::put_name(put, symbol); put('\n'); } }; template struct Lines { P& put; bool at; diff --git a/include/oneMachine/role/kinds.h b/include/oneMachine/role/kinds.h index 899b549..bc0af9b 100644 --- a/include/oneMachine/role/kinds.h +++ b/include/oneMachine/role/kinds.h @@ -2,7 +2,8 @@ // oneMachine/role/kinds.h -- the kinds of output a role can be. A kind gives: // name() its word in the machine description ("light") // Command, Report state slots (fixed-width fields, one `each`); the report's `live` is added by role::Machine -// params(v) v(name, int32 value) per parameter: its units and limits, in the machine description +// params(v) v(name, int32 value) per parameter: its units and limits, in the machine description; a kind may also +// call v.value(raw[, label]), v.scale(field, num, den), v.unit(field, symbol) (role/face.h) // apply(cmd, rep) write the command to endpoint E, read back what E actually does // sense(rep) read back only // safe(cmd, rep) the command that makes the output harmless (a per-role choice where there is one, as a parameter) diff --git a/python/onemachine/machine.py b/python/onemachine/machine.py index 28bad5e..6d9c581 100644 --- a/python/onemachine/machine.py +++ b/python/onemachine/machine.py @@ -14,7 +14,7 @@ never used here. A consumer only reconfigures when the device's roles change: push() and poll() re-read the descriptions on BadHash and keep every command value whose role and field still exist. A role this consumer has written that is gone, or has another kind, raises RoleChanged instead of being retargeted.""" -import struct, subprocess +import re, struct, subprocess from .schema import Schema, SchemaError, BadHash OK, BAD_HASH, BAD_LENGTH, BAD_VALUE, UNKNOWN, TOO_LONG = 0, 1, 2, 3, 0x80, 0x81 @@ -90,11 +90,19 @@ def _carry(old, schema, new): return new class RoleInfo: - def __init__(self, name, kind): self.name, self.kind, self.params, self.tuned = name, kind, {}, False + def __init__(self, name, kind): + self.name, self.kind, self.params, self.tuned = name, kind, {}, False + self.values, self.scales, self.units = [], {}, {} # value lines (raw, label|None) in order; field -> (num, den); field -> symbol def __repr__(self): return 'Role(%s %s %r%s)' % (self.name, self.kind, self.params, ' tuned' if self.tuned else '') +LABEL = re.compile(r'[A-Za-z0-9_-]{1,32}') # a value's label: no space, no quote, no markup; the line is split on spaces +SYMBOL = re.compile(r'[A-Za-z0-9/*^.%-]{1,16}') + class Description: """The machine description (role/face.h): refs, roles with kind and parameters, and where each is (for people only).""" + def _role(self, name, line): + if name not in self.roles: raise SchemaError('line for a role not declared above it: %r' % line) + return self.roles[name] def __init__(self, text): lines = [l for l in text.split('\n') if l] if not lines or lines[0] != 'machine 1': raise SchemaError('not a machine 1 description') @@ -113,6 +121,18 @@ def __init__(self, text): elif word == 'param': role, key, value = rest.split(' '); self.roles[role].params[key] = int(value) elif word == 'tune': self.roles[rest].tuned = True + elif word == 'value': + role, raw, *label = rest.split(' ') + if len(label) > 1 or (label and not LABEL.fullmatch(label[0])): raise SchemaError('bad value line %r' % l) + self._role(role, l).values.append((int(raw), label[0] if label else None)) + elif word == 'scale': + role, field, num, den = rest.split(' ') + if int(den) == 0: raise SchemaError('scale with denominator 0: %r' % l) + self._role(role, l).scales[field] = (int(num), int(den)) + elif word == 'unit': + role, field, symbol = rest.split(' ') + if not SYMBOL.fullmatch(symbol): raise SchemaError('bad unit symbol in %r' % l) + self._role(role, l).units[field] = symbol else: raise SchemaError('unknown line %r' % l) if h != self.hash: raise SchemaError('description says hash %08x, its lines hash to %08x' % (self.hash, h)) diff --git a/test/role/build.sh b/test/role/build.sh index 8775544..494c45d 100755 --- a/test/role/build.sh +++ b/test/role/build.sh @@ -32,6 +32,15 @@ for cxx in g++ clang++; do have $cxx || continue done done +echo "== description lines a kind may print: value, scale, unit (values_check: g++ and clang++ with sanitizers; values_check.py reads the text)" +for cxx in g++ clang++; do have $cxx || continue + if ! $cxx -std=c++17 -O1 -g -Wall -Wextra -Wpedantic -Werror -fsanitize=address,undefined -fno-sanitize-recover=all "${F[@]}" values_check.cpp -o "$W/vc" 2>"$W/err"; then bad "values_check [$cxx]" "does not build: $(grep -m1 error "$W/err")"; continue; fi + o=$("$W/vc" "$W/vdesc.txt" 2>&1); [ $? -eq 0 ] && ok "values_check [$cxx]: $(printf '%s' "$o" | tail -1)" || bad "values_check [$cxx]" "$(printf '%s' "$o" | grep FAIL | head -3)" +done +if have python3 && [ -f "$W/vdesc.txt" ]; then + o=$(python3 values_check.py "$W/vdesc.txt" 2>&1); [ $? -eq 0 ] && ok "values_check.py: $(printf '%s' "$o" | grep -c '^ ok') checks" || bad "values_check.py" "$(printf '%s' "$o" | grep FAIL | head -3)" +fi + echo "== rules, each with its own message" rej() { local n=$1 d=$2 m=$3 for cxx in "g++ -std=c++17" "clang++ -std=c++17" "avr-g++ -std=gnu++17 -mmcu=atmega328p"; do have ${cxx%% *} || continue diff --git a/test/role/values_check.cpp b/test/role/values_check.cpp new file mode 100644 index 0000000..5222790 --- /dev/null +++ b/test/role/values_check.cpp @@ -0,0 +1,66 @@ +// The description lines a kind may print besides `param`: value, scale, unit (role/face.h, Params). Kinds here are test kinds: +// a select with labels, and an analog input (report only: its Command has no fields) with a scale and a unit. `values_check ` writes the +// machine description there for values_check.py. +#include +#include +#include +#include +#include + +struct Mode { ONEMACHINE_STATE_NAME(name, "mode"); }; +struct Vin { ONEMACHINE_STATE_NAME(name, "vin"); }; +struct Raw { ONEMACHINE_STATE_NAME(name, "raw"); }; +struct Led { ONEMACHINE_STATE_NAME(name, "led"); }; +struct E { static bool live() { return true; } template static void where(P& put) { put('e'); } }; +struct E2 { static bool live() { return true; } template static void where(P& put) { put('f'); } }; +struct E3 { static bool live() { return true; } static void set(bool) {} static bool get() { return false; } template static void where(P& put) { put('g'); } }; + +struct Select { + 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); } }; + ONEMACHINE_STATE_NAME(l_off, "off"); ONEMACHINE_STATE_NAME(l_high, "high"); + template static void params(V& v) { v.value(0, l_off()); v.value(2); v.value(7, l_high()); } + template static void apply(const Command& c, Report& r) { r.index = c.index; } + template static void sense(Report&) {} + static void safe(Command& c, const Report&) { c.index = 0; } +}; +struct Analog { // report only: Command has no fields + 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"); ONEMACHINE_STATE_NAME(u_v, "V"); + template static void params(V& v) { v.scale(n_raw(), 5, 1023); v.unit(n_raw(), u_v()); } + template static void apply(const Command&, Report& r) { r.raw = 1023; } + template static void sense(Report& r) { r.raw = 1023; } + static void safe(Command&, const Report&) {} +}; + +using M = role::Machine, role::Role, role::Role, E3>>; + +int fails = 0; +void check(const char* what, bool ok) { printf(" %-5s %s\n", ok ? "ok" : "FAIL", what); if (!ok) fails++; } + +int main(int argc, char** argv) { + std::string d; auto put = [&](char c) { d += c; }; + role::describe(put); + if (argc > 1) { FILE* f = fopen(argv[1], "w"); fputs(d.c_str(), f); fclose(f); } + auto has = [&](const char* s) { return d.find(s) != std::string::npos; }; + check("value with a label", has("value mode 0 off\n")); + check("value without a label", has("value mode 2\n")); + check("value, second label", has("value mode 7 high\n")); + check("scale", has("scale vin raw 5 1023\n")); + check("unit", has("unit vin raw V\n")); + check("a kind that prints none of them prints exactly its param line", has("role led switch\nparam led safe 1\nat led g\n")); + check("the new lines come after their role line and before the next role", d.find("role mode select\nvalue mode 0 off\nvalue mode 2\nvalue mode 7 high\nat mode e\nrole vin analog\nscale vin raw 5 1023\nunit vin raw V\n") != std::string::npos); + M::Command c{}; M::Report r{}; M::apply(c, r); M::sense(r); M::safe(c, r); + std::string cd, rd; auto pc = [&](char ch) { cd += ch; }; auto pr = [&](char ch) { rd += ch; }; + state::describe(pc); state::describe(pr); + check("report-only kind: its report has the field", rd.find("vin/raw u16") != std::string::npos && state::get(r).raw == 1023); + check("report-only kind: an empty layer in the command description", cd.find("layer vin\nlayer mode\n") != std::string::npos); + printf("%s\n", fails ? "FAILED" : "ok"); + return fails ? 1 : 0; +} diff --git a/test/role/values_check.py b/test/role/values_check.py new file mode 100644 index 0000000..518dc36 --- /dev/null +++ b/test/role/values_check.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +"""python/onemachine's reading of the value, scale and unit lines: values_check.py """ +import sys, re +sys.path.insert(0, '../../python') +from onemachine.machine import Description, _fnv +from onemachine.schema import SchemaError + +fails = 0 +def check(what, cond): + global fails + print(' %-5s %s' % ('ok' if cond else 'FAIL', what)); fails += 0 if cond else 1 + +def rehash(body): # a description with a correct hash line around `body` (lines, no `at`) + h = 2166136261 + for l in body: h = _fnv(h, (l + '\n').encode()) + return 'machine 1\nhash %08x\n%s\n' % (h, '\n'.join(body)) + +def refused(body, why): + try: Description(rehash(body)) + except SchemaError as e: check('refused: %s -> %s' % (why, e), True); return + check('refused: %s' % why, False) + +d = Description(open(sys.argv[1]).read()) +m, v = d.roles['mode'], d.roles['vin'] +check('values of mode, in order, with and without label', m.values == [(0, 'off'), (2, None), (7, 'high')]) +check('scale of vin raw', v.scales == {'raw': (5, 1023)}) +check('unit of vin raw', v.units == {'raw': 'V'}) +check('a role that prints none has none', d.roles['led'].values == [] and d.roles['led'].scales == {} and d.roles['led'].units == {}) +base = ['role mode select'] +refused(base + ['value mode 1 two words'], 'a label with a space') +refused(base + ['value mode 1 bad"quote'], 'a label with a quote') +refused(base + ['value mode 1 ' + 'x' * 33], 'a label of 33 characters') +refused(base + ['value nobody 1 x'], 'a value line for a role not declared above it') +refused(base + ['scale mode index 1 0'], 'a scale with denominator 0') +refused(base + ['frobnicate mode 1'], 'an unknown line type') +def accepted(body, what): + try: d = Description(rehash(body)); check('accepted: %s' % what, True); return d + except SchemaError as e: check('accepted: %s -> %s' % (what, e), False) +d2 = accepted(base + ['unit mode index %', 'unit mode index2 V/s^2'], 'unit symbols % and V/s^2') +check('the symbol is kept as written', d2 is not None and d2.roles['mode'].units == {'index': '%', 'index2': 'V/s^2'}) +refused(base + ['unit mode index V"'], 'a unit symbol with a quote') +refused(base + ['unit mode index ' + 'V' * 17], 'a unit symbol of 17 characters') +try: Description(open(sys.argv[1]).read().replace('value mode 7 high', 'value mode 7 higher')); check('changed label with the old hash is refused', False) +except SchemaError as e: check('changed label with the old hash is refused -> %s' % e, 'hash' in str(e)) +print('FAILED' if fails else 'ok'); sys.exit(1 if fails else 0)