A truly modular keyboard
C
keyword: v12 stream with event numbers and CRCs, scans keep each Keybit's live entry, addresses never handed out twice
Nathan87ff83dd3861
diff --git a/firmware/keyword/Core/Inc/keybit_bus.h b/firmware/keyword/Core/Inc/keybit_bus.hindex b5e9829..2737adc 100644--- a/firmware/keyword/Core/Inc/keybit_bus.h+++ b/firmware/keyword/Core/Inc/keybit_bus.h@@ -26,6 +26,8 @@ typedef struct {* its press event arrived unseen, tap 1 = report a down next, 2 = then up. */uint8_t saw_down, pend, tap;uint32_t last_ok; /* HAL_GetTick() of its last good read, any kind */+ uint8_t next_num; /* v12: number of the first event we haven't taken yet */+ uint8_t num_ok; /* next_num is known */} keybit_info_t;/* A Keybit further out, known only through events relayed by itsdiff --git a/firmware/keyword/Core/Src/keybit_bus.c b/firmware/keyword/Core/Src/keybit_bus.cindex 59583c6..d4a39e6 100644--- a/firmware/keyword/Core/Src/keybit_bus.c+++ b/firmware/keyword/Core/Src/keybit_bus.c@@ -21,7 +21,7 @@#define EV_HEARTBEAT 0x02#define EV_BACKWARDS 0x04#define EV_WHERE 0x08 /* v12: this event's place fields are news */-#define REG_STREAM 0xE0 /* v12: key state, event count, then 5-byte events */+#define REG_STREAM 0x7F /* v12: status stream; 0x80 | n drops events before n first */#define STREAM_EV 5#define MAGIC 0x4B@@ -182,10 +182,20 @@ static int write_regs(I2C_HandleTypeDef *i2c, uint8_t addr, uint8_t reg, const u(uint8_t *)buf, len, I2C_TIMEOUT_MS)) == HAL_OK;}+/* A Keybit busy with a link frame can miss a probe, so an address only+ * counts as free if it doesn't answer, isn't on the list, and wasn't+ * handed out in the last GIVEN_MS (the scan may not have found it yet).+ * Handing one out twice made the pair fight it out and one start over. */+#define GIVEN_MS 5000+static uint8_t listed[128]; /* addresses on the list, by address */+static uint32_t given_at[128]; /* HAL tick + 1 it was handed out, 0 = never */+static uint8_t free_address(I2C_HandleTypeDef *i2c){+ uint32_t now = HAL_GetTick();for (uint8_t a = ADDR_FIRST; a <= ADDR_LAST; a++) {- if (a == KEYBIT_DEFAULT_ADDR || a == LINK_ADDR || a == CHARGER_ADDR) continue;+ if (a == KEYBIT_DEFAULT_ADDR || a == LINK_ADDR || a == CHARGER_ADDR || listed[a]) continue;+ if (given_at[a] && now - (given_at[a] - 1) < GIVEN_MS) continue;if (!is_ready(i2c, a)) return a;}return 0;@@ -205,6 +215,7 @@ int keybit_bus_assign(I2C_HandleTypeDef *i2c)msg[12] = addr;if (!write_regs(i2c, KEYBIT_DEFAULT_ADDR, REG_ASSIGN, msg, sizeof(msg)))break;+ given_at[addr] = HAL_GetTick() + 1;HAL_Delay(15); /* it saves the address to flash, about 6 ms */assigned++;}@@ -370,19 +381,30 @@ done:return changed;}-/* v12: key state, event count and the first events in one read. Events- * are 5 bytes, or 11 with their place (EV_WHERE). The Keybit drops the- * events a read covered whole once the read has gone through. Returns 1- * if anything changed; *ok is set if the first read worked. */+static uint8_t crc8(uint8_t crc, uint8_t v)+{+ crc ^= v;+ for (int i = 0; i < 8; i++) crc = (uint8_t)(crc & 0x80 ? (crc << 1) ^ 0x07 : crc << 1);+ return crc;+}++/* v12: key state, event count and the first events in one read. Each event+ * is 5 bytes, or 11 with its place (EV_WHERE), then a CRC-8. Reading from+ * 0x80 | n tells the Keybit we have everything before event n, so it drops+ * those; asking twice drops nothing more, and an event that came through+ * damaged is just sent again. Returns 1 if anything changed; *ok is set if+ * the first read worked. */static int stream_one(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n, int i,keybit_remote_t *r, int *rn, int *remote, int *ok){int changed = 0;- uint16_t len = 2 + STREAM_EV; /* most often: nothing, or one key event */+ uint16_t len = 3 + STREAM_EV + 1; /* most often: nothing, or one key event */for (int round = 0, tries = 0; round < 3; round++) {- uint8_t b[2 + EV_BATCH * EV_SIZE11];- if (!read_regs(i2c, k[i].addr, REG_STREAM, b, len)) {- /* busy with a link frame for a moment: one more try */+ uint8_t b[3 + EV_BATCH * (EV_SIZE11 + 1)];+ uint8_t reg = k[i].num_ok ? (uint8_t)(0x80 | k[i].next_num) : REG_STREAM;+ int good = read_regs(i2c, k[i].addr, reg, b, len) && (b[1] >> 4) == (~b[0] & 0x0F);+ if (!good) {+ /* busy with a link frame for a moment, or noise: one more try */if (round == 0 && !tries++) { round--; continue; }break;}@@ -393,17 +415,23 @@ static int stream_one(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n, int i,if (down) { k[i].saw_down = 1; k[i].pend = 0; }if (down != k[i].key_down) { k[i].key_down = down; changed = 1; }}- int count = b[1] > EV_BATCH ? EV_BATCH : b[1], e = 0, pos = 2;- while (e < count && pos + STREAM_EV <= len) {+ int count = b[1] & 0x0F, e = 0, pos = 3, damaged = 0;+ if (count > EV_BATCH) count = EV_BATCH;+ while (e < count && pos + STREAM_EV < len) {int size = b[pos + 4] & EV_WHERE ? EV_SIZE11 : STREAM_EV;- if (pos + size > len) break; /* not all of it: it stays queued */+ if (pos + size + 1 > len) break; /* not all of it in this read */+ uint8_t crc = 0;+ for (int j = 0; j < size; j++) crc = crc8(crc, b[pos + j]);+ if (crc != b[pos + size]) { damaged = 1; break; }changed |= take_event(k, n, i, &b[pos], size, r, rn, remote);- pos += size;+ pos += size + 1;e++;}- if (e >= count) break;- /* the rest: room for the first to carry its place, 5 bytes for the others */- len = (uint16_t)(2 + EV_SIZE11 + (count - e - 1) * STREAM_EV);+ k[i].next_num = (uint8_t)((b[2] + e) & 0x7F);+ k[i].num_ok = 1;+ if (e >= count || damaged) break;+ /* the rest: room for the first to carry its place, 6 bytes for the others */+ len = (uint16_t)(3 + EV_SIZE11 + 1 + (count - e - 1) * (STREAM_EV + 1));}k[i].saw_down = k[i].key_down;return changed;@@ -480,14 +508,20 @@ static void scan_one(I2C_HandleTypeDef *i2c, uint8_t a, const keybit_info_t *k,for (int i = 0; i < n; i++) if (k[i].addr == a) known = &k[i];if (!known && !is_ready(i2c, a)) return;+ /* It answered, so a failed read is most likely it being busy with a+ * link frame for a moment: try again rather than wait a whole scan. */uint8_t head[10];- if (!read_regs(i2c, a, REG_MAGIC, head, sizeof(head)) || head[0] != MAGIC) return;+ int got = 0;+ for (int t = 0; t < 3 && !got; t++) got = read_regs(i2c, a, REG_MAGIC, head, sizeof(head)) && head[0] == MAGIC;+ if (!got) return;keybit_info_t *f = &bs.found[bs.nfound];if (known && uid32(known->uid) == uid32(&head[2])) {*f = *known; /* keeps its tap tracking */} else {memset(f, 0, sizeof(*f));- if (!read_regs(i2c, a, REG_UID, f->uid, sizeof(f->uid))) return;+ got = 0;+ for (int t = 0; t < 3 && !got; t++) got = read_regs(i2c, a, REG_UID, f->uid, sizeof(f->uid));+ if (!got) return;}f->addr = a;f->last_ok = HAL_GetTick();@@ -517,14 +551,33 @@ static int scan_commit(keybit_info_t *k, int *n)missed[m++] = (uint8_t)(bs.missed[i] < 255 ? bs.missed[i] + 1 : 255);}}+ /* A Keybit already on the list keeps its live entry (key state, taps,+ * event number): the copy taken when the scan passed its address can be+ * most of a scan old, and putting it back brought back a key that had+ * been let go since. Only what a scan reads is refreshed. */for (int j = 0; j < bs.nfound; j++) {int known = 0;- for (int i = 0; i < *n && !known; i++) known = memcmp(bs.found[j].uid, k[i].uid, sizeof(k[i].uid)) == 0;+ for (int i = 0; i < *n && !known; i++)+ if (memcmp(bs.found[j].uid, k[i].uid, sizeof(k[i].uid)) == 0) {+ known = 1;+ keybit_info_t *f = &bs.found[j];+ uint8_t fw = f->fw, backwards = f->backwards, addr = f->addr;+ char side = f->keybit_side, at = f->at;+ *f = k[i];+ if (f->addr != addr) f->num_ok = 0; /* it lost its address and got another */+ f->addr = addr;+ f->fw = fw;+ f->backwards = backwards;+ f->keybit_side = side;+ f->at = at;+ }joined |= !known;}memcpy(k, bs.found, m * sizeof(k[0]));memcpy(bs.missed, missed, sizeof(missed));*n = m;+ memset(listed, 0, sizeof(listed));+ for (int i = 0; i < m; i++) listed[k[i].addr & 0x7F] = 1;return joined;}diff --git a/firmware/sim/kw.c b/firmware/sim/kw.cindex ce3fd89..6c46147 100644--- a/firmware/sim/kw.c+++ b/firmware/sim/kw.c@@ -139,6 +139,8 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *h, uint16_t addr, uinint a = put_byte((uint8_t)addr);if (a < 0) return fail();stop();+ if (getenv("KW_TRACE_ADDR") && strtol(getenv("KW_TRACE_ADDR"), NULL, 16) == addr >> 1)+ printf("%9.3f ms probe %02x: %s\n", sim_now() / 1e9, addr >> 1, a ? "ack" : "nack");return a ? HAL_OK : HAL_ERROR;}diff --git a/firmware/sim/node.c b/firmware/sim/node.cindex 0706a4a..6019f15 100644--- a/firmware/sim/node.c+++ b/firmware/sim/node.c@@ -19,3 +19,4 @@ int sim_node_has_press(uint32_t u)return 0;}uint8_t sim_node_key(void) { return key_down; }+uint8_t sim_node_addr(void) { return my_addr; }diff --git a/firmware/sim/sim.c b/firmware/sim/sim.cindex 8487925..5c44f63 100644--- a/firmware/sim/sim.c+++ b/firmware/sim/sim.c@@ -59,6 +59,7 @@ typedef struct {uint8_t (*qcount)(void);const uint8_t *(*diag)(void);int (*has_press)(uint32_t);+ uint8_t (*addr)(void);uint8_t (*key)(void);sim_systick_t st;sim_gpio_t gpio[4];@@ -101,6 +102,9 @@ static double c_pf = 15, kw_pullup_k = 4.7;static unsigned seed = 1;static uint32_t tick0_all;static char bundle[1024], tmpdir[512];+static const char *bundle2; /* BUNDLE2: firmware for the Keybits listed in MIX */+static int mixed[MAXN];+static double noise_per_s; /* NOISE: glitches per second on random wires */static const uint8_t SDA_PIN[4] = { PA1, PC1, PC4, PD4 }; /* N E S W */static const uint8_t SCL_PIN[4] = { PA2, PC2, PD2, PD5 };@@ -337,7 +341,7 @@ static void build(void)char path[700];snprintf(path, sizeof(path), "%s/n%d_%d.bundle", tmpdir, n, k->boots);char cmd[1600];- snprintf(cmd, sizeof(cmd), "cp '%s' '%s'", bundle, path);+ snprintf(cmd, sizeof(cmd), "cp '%s' '%s'", mixed[n] && bundle2 ? bundle2 : bundle, path);if (system(cmd) != 0) { fprintf(stderr, "copy failed\n"); exit(1); }void *dl = dlopen(path, RTLD_NOW | RTLD_LOCAL);if (!dl) { fprintf(stderr, "%s\n", dlerror()); exit(1); }@@ -346,6 +350,7 @@ static void build(void)k->qcount = (uint8_t (*)(void))dlsym(dl, "sim_node_qcount");k->diag = (const uint8_t *(*)(void))dlsym(dl, "sim_node_diag");k->has_press = (int (*)(uint32_t))dlsym(dl, "sim_node_has_press");+ k->addr = (uint8_t (*)(void))dlsym(dl, "sim_node_addr");k->key = (uint8_t (*)(void))dlsym(dl, "sim_node_key");memset(k->mode, GPIO_CFGLR_IN_FLOATING, sizeof(k->mode));memset(k->out, 1, sizeof(k->out));@@ -569,6 +574,50 @@ static int64_t wait_present(int64_t limit)}/* Taps on random powered Keybits: hold hold_ms (+ up to 50%), gap gap_ms (+ up to 100%). */+/* Run until t, in 1 ms steps with random short glitches low on random+ * wires when NOISE is set (EMI or a contact chattering). */+static long glitches;+static void run_noisy(int64_t t)+{+ static int track = -2;+ static int64_t track_from;+ if (track == -2) {+ track = getenv("TRACK_NODE") ? atoi(getenv("TRACK_NODE")) : -1;+ track_from = getenv("TRACK_FROM") ? (int64_t)(atof(getenv("TRACK_FROM")) * PS_MS) : 0;+ }+ if (track > 0 && sim_t + 1000 * PS_MS > track_from && sim_t < track_from + 1500 * PS_MS) {+ /* where a press of node `track` sits, every 0.5 ms */+ static int64_t had[MAXN];+ while (sim_t < t) {+ run_until(sim_t + PS_MS / 2 < t ? sim_t + PS_MS / 2 : t);+ if (sim_t < track_from) continue;+ static uint8_t last_addr[MAXN];+ for (int k = 1; k < n_nodes; k++) {+ if (nodes[k].powered && nodes[k].addr() != last_addr[k]) {+ printf(" %.1f ms: kb%d address %02x -> %02x\n", sim_t / 1e9, k, last_addr[k], nodes[k].addr());+ last_addr[k] = nodes[k].addr();+ }+ int h = nodes[k].powered && nodes[k].has_press(uid_of(track));+ if (h && !had[k]) printf(" %.1f ms: kb%d (depth %d, q=%d) has it\n", sim_t / 1e9, k, nodes[k].depth(), nodes[k].qcount());+ if (!h && had[k]) printf(" %.1f ms: kb%d passed it on\n", sim_t / 1e9, k);+ had[k] = h;+ }+ }+ return;+ }+ if (noise_per_s <= 0) { run_until(t); return; }+ while (sim_t < t) {+ int64_t step = t - sim_t < PS_MS ? t - sim_t : PS_MS;+ if (frand() < noise_per_s / 1000) {+ wire_t *w = &wires[rnd() % (unsigned)n_wires];+ w->glitch_from = sim_t + (int64_t)(frand() * step);+ w->glitch_to = w->glitch_from + (int64_t)((0.1 + 1.9 * frand()) * PS_US);+ glitches++;+ }+ run_until(sim_t + step);+ }+}+static int dropouts; /* times a powered Keybit wasn't in the Keyword's list between taps */static void type_keys(int count, int hold_ms, int gap_ms){@@ -579,9 +628,9 @@ static void type_keys(int count, int hold_ms, int gap_ms)int64_t gap = (int64_t)(gap_ms * (1 + frand()) * PS_MS);nodes[n].button = 1;presses[n_presses++] = (press_t){ n, sim_t, sim_t + hold };- run_until(sim_t + hold);+ run_noisy(sim_t + hold);nodes[n].button = 0;- run_until(sim_t + gap);+ run_noisy(sim_t + gap);for (int k = 1; k < n_nodes; k++)if (nodes[k].powered && !kw_present(uid_of(k))) {dropouts++;@@ -626,6 +675,23 @@ static void report_latency(const char *name, int max_depth)lost += lat[d].lost;}CHECK(lost == 0, "%s: %d presses never reached the Keyword", name, lost);+ /* A down the Keyword reported with no press of that Keybit in the 500 ms+ * before it: a phantom key (or a UID nobody has). */+ int phantom = 0;+ for (int r = 0; r < n_reports; r++) {+ if (!reports[r].down) continue;+ int real = 0;+ for (int p = 0; p < n_presses && !real; p++)+ real = uid_of(presses[p].node) == reports[r].uid && presses[p].down <= reports[r].t &&+ reports[r].t - presses[p].down < 500 * PS_MS;+ if (!real && getenv("SHOW_PHANTOMS")) {+ printf(" phantom down uid %08x at %.1f ms; its presses:", reports[r].uid, reports[r].t / 1e9);+ for (int p = 0; p < n_presses; p++) if (uid_of(presses[p].node) == reports[r].uid) printf(" %.0f", presses[p].down / 1e9);+ printf("\n");+ }+ phantom += !real;+ }+ CHECK(phantom == 0, "%s: %d key downs with no press behind them", name, phantom);CHECK(dropouts == 0, "%s: Keybits dropped out of the Keyword's list %d times", name, dropouts);}@@ -664,7 +730,9 @@ static void check_places(void)char pside, face;if (want[n] < 2 || !kw_where(uid_of(n), &parent, &pside, &face)) continue;int p = node_by_uid(parent);- int ok = p > 0 && want[p] == want[n] - 1 && vv[p][n];+ /* any neighbour it really meets the right way round: a Keybit may hang+ * off a longer path for a moment when its nearest parent is busy */+ int ok = p > 0 && vv[p][n];if (ok) {int dx = nodes[n].x - nodes[p].x, dy = nodes[n].y - nodes[p].y;ok = COMPASS[side_facing(&nodes[p], dx, dy)] == pside && COMPASS[side_facing(&nodes[n], -dx, -dy)] == face;@@ -689,7 +757,8 @@ static void settle(const char *name)static void finish(void){extern unsigned kw_bus_khz(void);- printf(" fast bus at %u kHz by the end\n", kw_bus_khz());+ printf(" fast bus at %u kHz by the end%s\n", kw_bus_khz(), glitches ? "" : "");+ if (glitches) printf(" %ld glitches injected\n", glitches);print_diag();printf(" shorts=%ld fights=%ld kb1 main loop pass %.1f us\n", shorts, fights,btn_reads[1] ? (sim_t - nodes[1].t_boot) / 1e6 / btn_reads[1] : 0);@@ -891,6 +960,10 @@ int main(int argc, char **argv)if ((e = getenv("PASS_CYCLES"))) pass_cycles = atoi(e);if ((e = getenv("KW_HALF_US"))) { extern int64_t kw_t_low, kw_t_high; kw_t_low = kw_t_high = (int64_t)(atof(e) * PS_US); }if ((e = getenv("SEED"))) seed = (unsigned)atoi(e);+ if ((e = getenv("TICK0"))) tick0_all = (uint32_t)strtoul(e, NULL, 0); /* SysTick start, e.g. 2 s before it wraps */+ if ((e = getenv("NOISE"))) noise_per_s = atof(e);+ bundle2 = getenv("BUNDLE2");+ for (e = getenv("MIX"); e && *e; e++) if (*e >= '0' && *e <= '9') { mixed[atoi(e)] = 1; while (e[1] >= '0' && e[1] <= '9') e++; }const char *sc = argc > 2 ? argv[2] : "chain";int len = argc > 3 ? atoi(argv[3]) : 5;int np = argc > 4 ? atoi(argv[4]) : 40;