Skip to content

A truly modular keyboard

C

keyword: side bus a little per pass, a gap before each transfer, chained Keybits drained every 15 ms

Nathan641581ab2a03
diff --git a/firmware/keyword/Core/Inc/keybit_bus.h b/firmware/keyword/Core/Inc/keybit_bus.h
index 38557ec..b5e9829 100644
--- a/firmware/keyword/Core/Inc/keybit_bus.h
+++ b/firmware/keyword/Core/Inc/keybit_bus.h
@@ -25,6 +25,7 @@ typedef struct {
* queued events: saw_down is set when a poll reads it down, pend when
* 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 */
} keybit_info_t;
/* A Keybit further out, known only through events relayed by its
@@ -82,6 +83,14 @@ uint32_t keybit_bus_poll_keys(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n);
int keybit_bus_poll_relay(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n,
keybit_remote_t *r, int *rn);
+/* All the side bus work, a little per call: key polls every 15 ms, event
+ * drains (every 15 ms from a Keybit that relays chained ones, else 60 ms),
+ * and an address scan that looks at one address per call on calls with
+ * nothing else to do, about every 500 ms. Call it every main loop pass. */
+#define KEYBIT_CHANGED 1 /* a key, a Keybit or where one is changed */
+#define KEYBIT_JOINED 2 /* a Keybit joined, touching or chained */
+int keybit_bus_service(I2C_HandleTypeDef *i2c, keybit_info_t *k, int *n, keybit_remote_t *r, int *rn);
+
/* Plain register access for other devices on I2C3, such as the BQ25895
* charger (0x6A, never handed to a Keybit). Everything on the bus runs from
* the main loop, so call these from there too, not from an interrupt.
diff --git a/firmware/keyword/Core/Inc/keymap.h b/firmware/keyword/Core/Inc/keymap.h
index 952a20e..edf5fc5 100644
--- a/firmware/keyword/Core/Inc/keymap.h
+++ b/firmware/keyword/Core/Inc/keymap.h
@@ -17,6 +17,9 @@
void KEYMAP_Init(void);
+/* Run the keys task on the next sequencer pass instead of the next tick. */
+void KEYMAP_Kick(void);
+
/* 0 on success (also when flash already matched), -1 on a flash error. */
int KEYMAP_Save(void);
diff --git a/firmware/keyword/Core/Src/keybit_bus.c b/firmware/keyword/Core/Src/keybit_bus.c
index e62b7a7..a779629 100644
--- a/firmware/keyword/Core/Src/keybit_bus.c
+++ b/firmware/keyword/Core/Src/keybit_bus.c
@@ -80,17 +80,48 @@ int keybit_bus_jammed(void)
return 1;
}
+/* A Keybit serves I2C in software and only looks for a START once per
+ * main loop pass. After a transfer ends it finishes that pass first, so a
+ * transfer straight after another one (the key read, then the event count;
+ * the count, then the events) often found it not listening yet and was
+ * NACKed, costing a whole poll cycle. Leave the bus idle this long first. */
+#ifndef BUS_GAP_US
+#define BUS_GAP_US 200
+#endif
+static uint32_t bus_free_at; /* DWT cycle count when the last transfer ended */
+
+static void bus_gap(void)
+{
+ uint32_t need = BUS_GAP_US * (HAL_RCC_GetHCLKFreq() / 1000000u);
+ while (DWT->CYCCNT - bus_free_at < need) { }
+}
+
+static HAL_StatusTypeDef ended(HAL_StatusTypeDef st)
+{
+ bus_free_at = DWT->CYCCNT;
+ return st;
+}
+
static int is_ready(I2C_HandleTypeDef *i2c, uint8_t addr)
{
/* Just the address byte (~0.5 ms at 20 kHz): a short timeout, or a
* misbehaving bus makes a full scan outlast the bootloader's ~8 s watchdog. */
- return HAL_I2C_IsDeviceReady(i2c, (uint16_t)(addr << 1), 1, 3) == HAL_OK;
+ bus_gap();
+ return ended(HAL_I2C_IsDeviceReady(i2c, (uint16_t)(addr << 1), 1, 3)) == HAL_OK;
}
static int read_regs(I2C_HandleTypeDef *i2c, uint8_t addr, uint8_t reg, uint8_t *buf, uint16_t len)
{
- return HAL_I2C_Mem_Read(i2c, (uint16_t)(addr << 1), reg, I2C_MEMADD_SIZE_8BIT,
- buf, len, I2C_TIMEOUT_MS) == HAL_OK;
+ bus_gap();
+ return ended(HAL_I2C_Mem_Read(i2c, (uint16_t)(addr << 1), reg, I2C_MEMADD_SIZE_8BIT,
+ buf, len, I2C_TIMEOUT_MS)) == HAL_OK;
+}
+
+static int write_regs(I2C_HandleTypeDef *i2c, uint8_t addr, uint8_t reg, const uint8_t *buf, uint16_t len)
+{
+ bus_gap();
+ return ended(HAL_I2C_Mem_Write(i2c, (uint16_t)(addr << 1), reg, I2C_MEMADD_SIZE_8BIT,
+ (uint8_t *)buf, len, I2C_TIMEOUT_MS)) == HAL_OK;
}
static uint8_t free_address(I2C_HandleTypeDef *i2c)
@@ -114,8 +145,7 @@ int keybit_bus_assign(I2C_HandleTypeDef *i2c)
uint8_t addr = free_address(i2c);
if (!addr) break;
msg[12] = addr;
- if (HAL_I2C_Mem_Write(i2c, KEYBIT_DEFAULT_ADDR << 1, REG_ASSIGN, I2C_MEMADD_SIZE_8BIT,
- msg, sizeof(msg), I2C_TIMEOUT_MS) != HAL_OK)
+ if (!write_regs(i2c, KEYBIT_DEFAULT_ADDR, REG_ASSIGN, msg, sizeof(msg)))
break;
HAL_Delay(15); /* it saves the address to flash, about 6 ms */
assigned++;
@@ -168,7 +198,8 @@ uint32_t keybit_bus_poll_keys(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n)
uint32_t changed = 0;
for (int i = 0; i < n; i++) {
uint8_t v;
- if (!read_regs(i2c, k[i].addr, REG_KEY, &v, 1)) continue; /* next scan drops it */
+ if (!read_regs(i2c, k[i].addr, REG_KEY, &v, 1)) continue; /* scans drop it if this keeps up */
+ k[i].last_ok = HAL_GetTick();
if (v & 1) {
k[i].saw_down = 1;
k[i].pend = 0;
@@ -197,81 +228,88 @@ static keybit_remote_t *remote_slot(keybit_remote_t *r, int *rn, uint32_t uid)
return free_slot; /* NULL when the table is full */
}
-int keybit_bus_poll_relay(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n,
- keybit_remote_t *r, int *rn)
+/* Drain one touching Keybit's queued events. Returns 1 if any entry
+ * changed; *remote is set when they included a chained Keybit's. */
+static int relay_one(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n, int i,
+ keybit_remote_t *r, int *rn, int *remote)
{
int changed = 0;
uint32_t now = HAL_GetTick();
+ uint8_t count;
+ if (!read_regs(i2c, k[i].addr, REG_EV_COUNT, &count, 1)) goto done;
+ k[i].last_ok = now;
+ if (count == 0) goto done;
+ if (count > EV_BATCH) count = EV_BATCH;
+ /* v11 Keybits also say where each Keybit is; older ones only uid + flags. */
+ int size = k[i].fw >= 11 ? EV_SIZE11 : 5;
+ uint8_t ev[EV_BATCH * EV_SIZE11];
+ if (!read_regs(i2c, k[i].addr, size == 5 ? REG_EV_DATA : REG_EV_DATA11, ev, (uint16_t)(count * size))) goto done;
+ write_regs(i2c, k[i].addr, REG_EV_POP, &count, 1);
- for (int i = 0; i < n; i++) {
- uint8_t count;
- if (!read_regs(i2c, k[i].addr, REG_EV_COUNT, &count, 1) || count == 0) continue;
- if (count > EV_BATCH) count = EV_BATCH;
- /* v11 Keybits also say where each Keybit is; older ones only uid + flags. */
- int size = k[i].fw >= 11 ? EV_SIZE11 : 5;
- uint8_t ev[EV_BATCH * EV_SIZE11];
- if (!read_regs(i2c, k[i].addr, size == 5 ? REG_EV_DATA : REG_EV_DATA11, ev, (uint16_t)(count * size))) continue;
- HAL_I2C_Mem_Write(i2c, (uint16_t)(k[i].addr << 1), REG_EV_POP, I2C_MEMADD_SIZE_8BIT,
- &count, 1, I2C_TIMEOUT_MS);
-
- for (int e = 0; e < count; e++) {
- const uint8_t *x8 = &ev[e * size];
- uint32_t uid = uid32(x8);
- uint8_t flags = x8[4];
-
- /* Touching Keybits queue their own key events too. Their key is read
- * directly, but a tap shorter than the key poll only shows up here:
- * a press the poll never saw, then its release, is a missed tap. */
- int direct = 0;
- for (int j = 0; j < n; j++) {
- if (uid32(k[j].uid) != uid) continue;
- direct = 1;
- if (flags & EV_HEARTBEAT) continue; /* only key changes count */
- if (flags & EV_PRESSED) {
- if (!k[j].saw_down) k[j].pend = 1;
- } else {
- if (k[j].pend && !k[j].saw_down && !k[j].tap) k[j].tap = 1;
- k[j].pend = 0;
- }
+ for (int e = 0; e < count; e++) {
+ const uint8_t *x8 = &ev[e * size];
+ uint32_t uid = uid32(x8);
+ uint8_t flags = x8[4];
+
+ /* Touching Keybits queue their own key events too. Their key is read
+ * directly, but a tap shorter than the key poll only shows up here:
+ * a press the poll never saw, then its release, is a missed tap. */
+ int direct = 0;
+ for (int j = 0; j < n; j++) {
+ if (uid32(k[j].uid) != uid) continue;
+ direct = 1;
+ if (flags & EV_HEARTBEAT) continue; /* only key changes count */
+ if (flags & EV_PRESSED) {
+ if (!k[j].saw_down) k[j].pend = 1;
+ } else {
+ if (k[j].pend && !k[j].saw_down && !k[j].tap) k[j].tap = 1;
+ k[j].pend = 0;
}
- if (direct) continue;
-
- keybit_remote_t *x = remote_slot(r, rn, uid);
- if (!x) continue;
- uint8_t down = flags & EV_PRESSED;
- uint8_t back = (flags & EV_BACKWARDS) != 0;
- /* Down and up again before the keys task saw the down: keep it as a tap. */
- if (down && !x->key_down) x->fresh_down = 1;
- if (!down && x->key_down && x->fresh_down && !x->tap) x->tap = 1;
- if (x->uid != uid || !x->present || x->key_down != down || x->backwards != back) {
+ }
+ if (direct) continue;
+
+ *remote = 1;
+ keybit_remote_t *x = remote_slot(r, rn, uid);
+ if (!x) continue;
+ uint8_t down = flags & EV_PRESSED;
+ uint8_t back = (flags & EV_BACKWARDS) != 0;
+ /* Down and up again before the keys task saw the down: keep it as a tap. */
+ if (down && !x->key_down) x->fresh_down = 1;
+ if (!down && x->key_down && x->fresh_down && !x->tap) x->tap = 1;
+ if (x->uid != uid || !x->present || x->key_down != down || x->backwards != back) {
+ x->dirty = 1;
+ changed = 1;
+ }
+ x->uid = uid;
+ x->present = 1;
+ x->key_down = down;
+ x->backwards = back;
+ x->depth = flags >> 4;
+ x->via = k[i].addr;
+ if (size == EV_SIZE11 && x8[10] != '?') {
+ uint32_t parent = uid32(&x8[5]);
+ if (parent != x->parent || x8[9] != x->pside || x8[10] != x->face) {
+ x->parent = parent;
+ x->pside = (char)x8[9];
+ x->face = (char)x8[10];
+ x->moved = 1;
x->dirty = 1;
changed = 1;
}
- x->uid = uid;
- x->present = 1;
- x->key_down = down;
- x->backwards = back;
- x->depth = flags >> 4;
- x->via = k[i].addr;
- if (size == EV_SIZE11 && x8[10] != '?') {
- uint32_t parent = uid32(&x8[5]);
- if (parent != x->parent || x8[9] != x->pside || x8[10] != x->face) {
- x->parent = parent;
- x->pside = (char)x8[9];
- x->face = (char)x8[10];
- x->moved = 1;
- x->dirty = 1;
- changed = 1;
- }
- }
- x->last_seen = now;
}
+ x->last_seen = now;
}
+done:
+ /* Its next batch's events are measured against the polls until then. */
+ k[i].saw_down = k[i].key_down;
+ return changed;
+}
- /* The next batch's events are measured against the polls until then. */
- for (int i = 0; i < n; i++) k[i].saw_down = k[i].key_down;
-
- for (int i = 0; i < *rn; i++) {
+static int relay_age(keybit_remote_t *r, int rn)
+{
+ int changed = 0;
+ uint32_t now = HAL_GetTick();
+ for (int i = 0; i < rn; i++) {
if (r[i].present && now - r[i].last_seen > KEYBIT_REMOTE_TIMEOUT_MS) {
r[i].present = 0;
r[i].key_down = 0;
@@ -283,6 +321,154 @@ int keybit_bus_poll_relay(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n,
return changed;
}
+int keybit_bus_poll_relay(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n,
+ keybit_remote_t *r, int *rn)
+{
+ int changed = 0, remote = 0;
+ for (int i = 0; i < n; i++) changed |= relay_one(i2c, k, n, i, r, rn, &remote);
+ return changed | relay_age(r, *rn);
+}
+
+/* ------------------------------------------------------------------------ */
+/* The whole side bus, a little at a time from the main loop */
+
+/* At 20 kHz one register read is ~2 ms, and every Keybit on the bus has to
+ * sit through every transfer in its software I2C target. Keeping the bus
+ * close to 100% busy leaves a Keybit no quiet gap to run a link frame to
+ * its neighbour, so chained Keybits never join. */
+#ifndef KEYS_MS /* the simulator (firmware/sim) tries other values */
+#define KEYS_MS 15
+#endif
+#ifndef RELAY_CHAIN_MS
+#define RELAY_CHAIN_MS 15 /* a Keybit that relays chained ones: their key events */
+#endif
+#define RELAY_MS 60 /* a Keybit with nothing behind it: only its own short taps */
+#define CHAIN_FORGET_MS 3000
+#define SCAN_MS 500
+#ifndef SCAN_GAP_MS
+#define SCAN_GAP_MS 2 /* between scan probes: room for link frames */
+#endif
+#define MISSES_MAX 2 /* scans a Keybit may miss in a row before it counts as gone, */
+#define GONE_MS 1000 /* and no read of any kind worked for this long */
+
+static struct {
+ uint32_t keys_at, scan_at, probe_at;
+ uint32_t relay_at[128], chain_at[128]; /* by address */
+ uint8_t chained[128]; /* relayed a chained Keybit lately */
+ uint8_t cursor; /* next address to look at, 0 = between scans */
+ keybit_info_t found[KEYBIT_MAX];
+ int nfound, assigned;
+ uint8_t missed[KEYBIT_MAX];
+} bs;
+
+/* Look at one address for the running scan. A Keybit we already know only
+ * needs its head read: the UID bits 0-31 in it tell it's still the same one,
+ * and two Keybits sharing the address still arbitrate on them. */
+static void scan_one(I2C_HandleTypeDef *i2c, uint8_t a, const keybit_info_t *k, int n)
+{
+ if (a == KEYBIT_DEFAULT_ADDR || a == LINK_ADDR || a == CHARGER_ADDR || bs.nfound >= KEYBIT_MAX) return;
+ const keybit_info_t *known = NULL;
+ for (int i = 0; i < n; i++) if (k[i].addr == a) known = &k[i];
+ if (!known && !is_ready(i2c, a)) return;
+
+ uint8_t head[10];
+ if (!read_regs(i2c, a, REG_MAGIC, head, sizeof(head)) || head[0] != MAGIC) 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;
+ }
+ f->addr = a;
+ f->last_ok = HAL_GetTick();
+ f->fw = head[1];
+ f->keybit_side = (char)head[7];
+ f->at = keyword_side(f->keybit_side);
+ f->backwards = f->fw >= 6 ? head[9] & 0x0F : 0; /* reg 0x09 is new in v6 */
+ if (!known) f->key_down = head[6] & 1;
+ bs.nfound++;
+}
+
+/* The scan is done: the found list becomes the list, keeping a Keybit that
+ * missed it unless it missed MISSES_MAX scans in a row and nothing else
+ * reached it for GONE_MS either (one busy serving a link misses a read now
+ * and then), so it doesn't flicker in and out. */
+static int scan_commit(keybit_info_t *k, int *n)
+{
+ uint32_t now = HAL_GetTick();
+ uint8_t missed[KEYBIT_MAX] = {0};
+ int m = bs.nfound, joined = bs.assigned > 0;
+ for (int i = 0; i < *n && m < KEYBIT_MAX; i++) {
+ int here = 0;
+ for (int j = 0; j < bs.nfound && !here; j++)
+ here = memcmp(bs.found[j].uid, k[i].uid, sizeof(k[i].uid)) == 0;
+ if (!here && (bs.missed[i] < MISSES_MAX || now - k[i].last_ok < GONE_MS)) {
+ bs.found[m] = k[i];
+ missed[m++] = (uint8_t)(bs.missed[i] < 255 ? bs.missed[i] + 1 : 255);
+ }
+ }
+ 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;
+ joined |= !known;
+ }
+ memcpy(k, bs.found, m * sizeof(k[0]));
+ memcpy(bs.missed, missed, sizeof(missed));
+ *n = m;
+ return joined;
+}
+
+int keybit_bus_service(I2C_HandleTypeDef *i2c, keybit_info_t *k, int *n, keybit_remote_t *r, int *rn)
+{
+ int flags = 0, used = 0;
+ uint32_t now = HAL_GetTick();
+
+ if (now - bs.keys_at >= KEYS_MS) {
+ bs.keys_at = now;
+ if (keybit_bus_poll_keys(i2c, k, *n)) flags |= KEYBIT_CHANGED;
+ used = 1;
+ }
+
+ int had = 0, has = 0;
+ for (int i = 0; i < *rn; i++) had += r[i].present;
+ for (int i = 0; i < *n; i++) {
+ uint8_t a = k[i].addr & 0x7F;
+ if (bs.chained[a] && now - bs.chain_at[a] > CHAIN_FORGET_MS) bs.chained[a] = 0;
+ if (now - bs.relay_at[a] < (bs.chained[a] ? RELAY_CHAIN_MS : RELAY_MS)) continue;
+ bs.relay_at[a] = now;
+ int remote = 0;
+ if (relay_one(i2c, k, *n, i, r, rn, &remote)) flags |= KEYBIT_CHANGED;
+ if (remote) { bs.chained[a] = 1; bs.chain_at[a] = now; }
+ used = 1;
+ }
+ if (relay_age(r, *rn)) flags |= KEYBIT_CHANGED;
+ for (int i = 0; i < *rn; i++) has += r[i].present;
+ if (has > had) flags |= KEYBIT_JOINED;
+
+ /* One address per pass, only on a pass without other transfers and at
+ * most every SCAN_GAP_MS, so a scan never holds up the key polls for
+ * more than one read and leaves the Keybits gaps for their links. */
+ if (used) return flags;
+ if (!bs.cursor) {
+ if (now - bs.scan_at < SCAN_MS) return flags;
+ bs.scan_at = now;
+ bs.assigned = keybit_bus_assign(i2c);
+ bs.nfound = 0;
+ bs.cursor = ADDR_FIRST;
+ return flags;
+ }
+ if (now - bs.probe_at < SCAN_GAP_MS) return flags;
+ bs.probe_at = now;
+ scan_one(i2c, bs.cursor, k, *n);
+ if (++bs.cursor > ADDR_LAST) {
+ bs.cursor = 0;
+ if (scan_commit(k, n)) flags |= KEYBIT_JOINED;
+ flags |= KEYBIT_CHANGED;
+ }
+ return flags;
+}
+
int keybit_bus_read(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, uint8_t *buf, uint8_t len)
{
if (keybit_bus_jammed()) return 0;
@@ -292,6 +478,5 @@ int keybit_bus_read(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, uint8_t
int keybit_bus_write(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, const uint8_t *buf, uint8_t len)
{
if (keybit_bus_jammed()) return 0;
- return HAL_I2C_Mem_Write(i2c, (uint16_t)(addr7 << 1), reg, I2C_MEMADD_SIZE_8BIT,
- (uint8_t *)buf, len, I2C_TIMEOUT_MS) == HAL_OK;
+ return write_regs(i2c, addr7, reg, buf, len);
}
diff --git a/firmware/keyword/Core/Src/keymap.c b/firmware/keyword/Core/Src/keymap.c
index 4eebbc1..a4d5685 100644
--- a/firmware/keyword/Core/Src/keymap.c
+++ b/firmware/keyword/Core/Src/keymap.c
@@ -399,6 +399,11 @@ static void Keys_Task(void)
BATT_Poll(HAL_GetTick());
}
+void KEYMAP_Kick(void)
+{
+ UTIL_SEQ_SetTask(1 << CFG_TASK_KEYS_ID, CFG_SCH_PRIO_0);
+}
+
static void Keys_Tick(void)
{
UTIL_SEQ_SetTask(1 << CFG_TASK_KEYS_ID, CFG_SCH_PRIO_0);
diff --git a/firmware/keyword/Core/Src/main.c b/firmware/keyword/Core/Src/main.c
index 88b0a2f..1c9689f 100644
--- a/firmware/keyword/Core/Src/main.c
+++ b/firmware/keyword/Core/Src/main.c
@@ -28,6 +28,7 @@
#include "ch32v003_swio.h"
#include "keybit_image.h"
#include "keybit_bus.h"
+#include "keymap.h"
#include "proto.h"
/* USER CODE END Includes */
@@ -43,15 +44,7 @@
#define LED_STEP_MS 500
#define GREEN_BLINK_MS 150 /* 3 green blinks, this long on and off, once a Keybit is flashed */
#define KEYBIT_POLL_MS 250
-#define KEYBIT_SCAN_MS 500
-/* At 20 kHz one register read is ~2 ms, and every Keybit on the bus has to
- * sit through every transfer in its software I2C target. Polling keys every
- * 5 ms kept the bus close to 100% busy, which left a Keybit no quiet gap
- * to run a link frame to its neighbour, so chained Keybits never joined. */
-#define KEYBIT_KEYS_MS 15
-#define KEYBIT_RELAY_MS 60
#define HALT_TRIES_MAX 60 /* dock polls (250 ms) with a failed halt before giving up */
-#define KEYBIT_MISSES_MAX 2 /* scans a Keybit may miss in a row before it counts as gone */
/* USER CODE END PD */
@@ -72,7 +65,7 @@ static ch32_swio_t keybit_swio;
uint32_t keybit_dock_pause_until;
uint32_t keyword_reset_csr; /* HAL tick; the dock poll stays off the line until then */
/* Keybits touching the keyword's sides: the list is rebuilt every
- * KEYBIT_SCAN_MS, key_down refreshed every KEYBIT_KEYS_MS. keybit_changed
+ * ~500 ms and key_down refreshed every 15 ms (keybit_bus_service). keybit_changed
* collects bits of entries whose key_down changed; whoever consumes key
* events clears the bits it has handled. */
keybit_info_t keybits[KEYBIT_MAX];
@@ -463,7 +456,7 @@ void Keybit_Dock_Id(char *out, size_t len, int reset)
/* Hand addresses to new Keybits, then refresh the list of who is there. */
static void Keybit_Bus_Poll(void)
{
- static uint32_t last_scan, last_keys, last_relay, held_since;
+ static uint32_t held_since;
/* A backwards Keybit holds SDA low; tell the host once it has lasted
* BUS_HELD_MS and once it clears, and leave the bus alone meanwhile. */
@@ -480,49 +473,12 @@ static void Keybit_Bus_Poll(void)
}
if (keybit_bus_unstick(&hi2c3)) PROTO_Send("OK BUS recovered");
if (keybit_bus_jammed()) return;
- if (HAL_GetTick() - last_keys >= KEYBIT_KEYS_MS) {
- last_keys = HAL_GetTick();
- keybit_changed |= keybit_bus_poll_keys(&hi2c3, keybits, keybit_count);
+ int f = keybit_bus_service(&hi2c3, keybits, &keybit_count, keybit_remotes, &keybit_remote_count);
+ if (f & KEYBIT_CHANGED) {
+ keybit_changed = 1;
+ KEYMAP_Kick(); /* report it now, not at the next 5 ms tick */
}
- if (HAL_GetTick() - last_relay >= KEYBIT_RELAY_MS) {
- last_relay = HAL_GetTick();
- int had = 0, has = 0;
- for (int i = 0; i < keybit_remote_count; i++) had += keybit_remotes[i].present;
- keybit_bus_poll_relay(&hi2c3, keybits, keybit_count, keybit_remotes, &keybit_remote_count);
- for (int i = 0; i < keybit_remote_count; i++) has += keybit_remotes[i].present;
- if (has > had) white_until = HAL_GetTick() + WHITE_BLINK_MS; /* a chained Keybit joined too */
- }
- if (HAL_GetTick() - last_scan < KEYBIT_SCAN_MS) return;
- last_scan = HAL_GetTick();
-
- int fresh = keybit_bus_assign(&hi2c3);
- int before = keybit_count;
- /* A Keybit busy serving a link now and then misses a scan. Keep it
- * through KEYBIT_MISSES_MAX scans in a row before calling it gone, or it
- * flickers in and out. */
- static uint8_t missed[KEYBIT_MAX];
- keybit_info_t found[KEYBIT_MAX];
- uint8_t found_missed[KEYBIT_MAX] = {0};
- int n = keybit_bus_scan(&hi2c3, found, KEYBIT_MAX);
- for (int i = 0; i < keybit_count && n < KEYBIT_MAX; i++) {
- int here = 0;
- for (int j = 0; j < n && !here; j++)
- if (memcmp(found[j].uid, keybits[i].uid, sizeof(found[j].uid)) == 0) {
- here = 1;
- /* keep its tap tracking across the rescan */
- found[j].saw_down = keybits[i].saw_down;
- found[j].pend = keybits[i].pend;
- found[j].tap = keybits[i].tap;
- }
- if (!here && missed[i] < KEYBIT_MISSES_MAX) {
- found[n] = keybits[i];
- found_missed[n++] = (uint8_t)(missed[i] + 1);
- }
- }
- memcpy(keybits, found, n * sizeof(found[0]));
- memcpy(missed, found_missed, sizeof(missed));
- keybit_count = n;
- if (fresh > 0 || keybit_count > before) white_until = HAL_GetTick() + WHITE_BLINK_MS;
+ if (f & KEYBIT_JOINED) white_until = HAL_GetTick() + WHITE_BLINK_MS;
}
/* USER CODE END 0 */
diff --git a/firmware/sim/.gitignore b/firmware/sim/.gitignore
index 003a2e6..cfc0468 100644
--- a/firmware/sim/.gitignore
+++ b/firmware/sim/.gitignore
@@ -1,3 +1,4 @@
sim
-node.bundle
+*.bundle
*.dSYM/
+build_v10/
diff --git a/firmware/sim/Makefile b/firmware/sim/Makefile
index f8da606..94baca8 100644
--- a/firmware/sim/Makefile
+++ b/firmware/sim/Makefile
@@ -7,16 +7,29 @@ KEYWORD := ../keyword/Core
all : sim node.bundle
+# Keyword timing experiments: make sim KW_DEFS="-DKEYS_MS=10"
+.PHONY : sim
+
+# The Keybit firmware some Keybits still run, rebuilt from git, to check a
+# Keyword change against them: make node_v10.bundle
+V10_REV := 6039864
+node_v10.bundle : node.c ch32fun.h sim.h
+ rm -rf build_v10 && mkdir -p build_v10
+ for f in main.c link.c link.h soft_i2c.c soft_i2c.h; do git show $(V10_REV):firmware/keybit/$$f > build_v10/$$f; done
+ sed -i '' 's/(\*f->in \& f->ck)/(READ_PORT(f->in) \& f->ck)/; s/(\*d->in \& d->dt)/(READ_PORT(d->in) \& d->dt)/' build_v10/link.c
+ sed -i '' 's/^#define CONFIG_PAGE .*/#ifndef CONFIG_PAGE\n#define CONFIG_PAGE 0x08003FC0u\n#endif/' build_v10/main.c
+ $(CC) $(CFLAGS) -I. -Ibuild_v10 -bundle -undefined dynamic_lookup -o $@ node.c build_v10/link.c build_v10/soft_i2c.c
+
node.bundle : node.c $(KEYBIT)/main.c $(KEYBIT)/link.c $(KEYBIT)/soft_i2c.c $(KEYBIT)/link.h $(KEYBIT)/soft_i2c.h ch32fun.h sim.h
$(CC) $(CFLAGS) -I. -I$(KEYBIT) -bundle -undefined dynamic_lookup -o $@ node.c $(KEYBIT)/link.c $(KEYBIT)/soft_i2c.c
sim : sim.c kw.c ctx_arm64.S sim.h ch32fun.h stm32wbxx_hal.h $(KEYWORD)/Src/keybit_bus.c $(KEYWORD)/Inc/keybit_bus.h
- $(CC) $(CFLAGS) -I. -I$(KEYWORD)/Inc -o $@ sim.c kw.c ctx_arm64.S
+ $(CC) $(CFLAGS) $(KW_DEFS) -I. -I$(KEYWORD)/Inc -o $@ sim.c kw.c ctx_arm64.S
test : all
./sim node.bundle all
clean :
- rm -rf sim node.bundle *.dSYM
+ rm -rf sim *.bundle *.dSYM build_v10
.PHONY : all test clean
diff --git a/firmware/sim/bench.sh b/firmware/sim/bench.sh
new file mode 100755
index 0000000..fa63589
--- /dev/null
+++ b/firmware/sim/bench.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# Pooled latency over several seeds, run in parallel:
+# ./bench.sh <bundle> <scenario> <len> <presses> <seeds>
+# Prints p50/p99/max per depth and lost presses.
+b=$1 sc=$2 len=$3 np=$4 seeds=${5:-8}
+out=$(mktemp)
+seq 1 "$seeds" | xargs -P 8 -I{} sh -c "SEED={} LAT_DUMP=$out ./sim $b $sc $len $np > /dev/null"
+python3 - "$out" <<'P'
+import sys, collections
+d = collections.defaultdict(list); lost = collections.Counter()
+for line in open(sys.argv[1]):
+ k, v = line.split(); k = int(k); v = float(v)
+ if v < 0: lost[k] += 1
+ else: d[k].append(v)
+for k in sorted(set(d) | set(lost)):
+ v = sorted(d[k]); n = len(v)
+ q = lambda p: v[min(n - 1, int(n * p))] if n else 0
+ print(f" depth {k}: n={n + lost[k]:4d} lost={lost[k]} p50={q(.5):6.1f} p90={q(.9):6.1f} p99={q(.99):6.1f} max={v[-1] if n else 0:6.1f} ms")
+P
+rm -f "$out"
diff --git a/firmware/sim/bench_base.sh b/firmware/sim/bench_base.sh
new file mode 100755
index 0000000..4f87e52
--- /dev/null
+++ b/firmware/sim/bench_base.sh
@@ -0,0 +1,20 @@
+#!/bin/sh
+# Pooled latency over several seeds, run in parallel:
+# ./bench.sh <bundle> <scenario> <len> <presses> <seeds>
+# Prints p50/p99/max per depth and lost presses.
+b=$1 sc=$2 len=$3 np=$4 seeds=${5:-8}
+out=$(mktemp)
+seq 1 "$seeds" | xargs -P 8 -I{} sh -c "SEED={} LAT_DUMP=$out ./sim_base $b $sc $len $np > /dev/null"
+python3 - "$out" <<'P'
+import sys, collections
+d = collections.defaultdict(list); lost = collections.Counter()
+for line in open(sys.argv[1]):
+ k, v = line.split(); k = int(k); v = float(v)
+ if v < 0: lost[k] += 1
+ else: d[k].append(v)
+for k in sorted(set(d) | set(lost)):
+ v = sorted(d[k]); n = len(v)
+ q = lambda p: v[min(n - 1, int(n * p))] if n else 0
+ print(f" depth {k}: n={n + lost[k]:4d} lost={lost[k]} p50={q(.5):6.1f} p90={q(.9):6.1f} p99={q(.99):6.1f} max={v[-1] if n else 0:6.1f} ms")
+P
+rm -f "$out"
diff --git a/firmware/sim/build_base/Inc/keybit_bus.h b/firmware/sim/build_base/Inc/keybit_bus.h
new file mode 100644
index 0000000..38557ec
--- /dev/null
+++ b/firmware/sim/build_base/Inc/keybit_bus.h
@@ -0,0 +1,92 @@
+/*
+ * Keybits on the keyword's side bus (I2C3): hand out addresses and list
+ * who is there. See firmware/keybit/main.c for the Keybit's register map.
+ */
+#ifndef KEYBIT_BUS_H
+#define KEYBIT_BUS_H
+
+#include <stdint.h>
+#include "stm32wbxx_hal.h"
+
+#define KEYBIT_DEFAULT_ADDR 0x30
+#define KEYBIT_MAX 8
+#define KEYBIT_REMOTE_MAX 112
+#define KEYBIT_REMOTE_TIMEOUT_MS 3000
+
+typedef struct {
+ uint8_t addr;
+ uint8_t uid[12]; /* factory 96-bit ID, little endian */
+ uint8_t fw;
+ uint8_t key_down;
+ char keybit_side; /* the Keybit's own side touching us: N/E/S/W */
+ char at; /* where it is on the keyword: L, R or T, '?' if unknown */
+ uint8_t backwards; /* its sides with a Keybit on backwards: bit 0 N, 1 E, 2 S, 3 W */
+ /* Taps too short for the key poll to see, caught from the Keybit's own
+ * queued events: saw_down is set when a poll reads it down, pend when
+ * its press event arrived unseen, tap 1 = report a down next, 2 = then up. */
+ uint8_t saw_down, pend, tap;
+} keybit_info_t;
+
+/* A Keybit further out, known only through events relayed by its
+ * neighbours. Entries are never moved, so an index stays valid. */
+typedef struct {
+ uint32_t uid; /* low 32 bits of its UID */
+ uint8_t present; /* 0 once it has gone quiet for KEYBIT_REMOTE_TIMEOUT_MS */
+ uint8_t key_down;
+ uint8_t depth; /* hops from the keyword, 2 or more */
+ uint8_t backwards; /* it has a neighbour on backwards (side unknown) */
+ uint8_t via; /* address of the touching Keybit it came through */
+ uint8_t dirty; /* set on any change; the consumer clears it */
+ uint8_t fresh_down; /* went down in a relay batch the consumer hasn't seen yet */
+ /* Where it is (v11 Keybits): the Keybit it hangs off (low 32 bits of its
+ * UID), that Keybit's side it's on and its own side facing it, as
+ * N/E/S/W; 0 / '?' until known. moved: these changed since last reported. */
+ uint32_t parent;
+ char pside, face;
+ uint8_t moved;
+ uint8_t tap; /* a press and release came in one batch: 1 = report down, 2 = then up */
+ uint32_t last_seen; /* HAL_GetTick() */
+} keybit_remote_t;
+
+/* SDA low with SCL high while we aren't using the bus. A Keybit turned the
+ * wrong way round on the keyword does this: its GND lands on our SDA and
+ * its 3V3 on our SCL, so every SCL low we drive pulls its supply down
+ * through its SCL clamp diode. keybit_bus_held() reports the state;
+ * keybit_bus_jammed() is the same but lets one attempt through about once
+ * a second, so a Keybit stuck mid-byte still gets clocked free. Check
+ * keybit_bus_jammed() before starting any transfer. */
+int keybit_bus_held(void);
+int keybit_bus_jammed(void);
+
+/* SCL low with the bus idle for over 5 ms means something stopped
+ * mid-transfer and is waiting on a clock. Clock it free: I2C3 off, 9 SCL
+ * pulses and a STOP by hand, I2C3 back on. Returns 1 when it did that. */
+int keybit_bus_unstick(I2C_HandleTypeDef *i2c);
+
+/* Give every Keybit still on the default address its own address. Returns
+ * how many were assigned. */
+int keybit_bus_assign(I2C_HandleTypeDef *i2c);
+
+/* Read every assigned Keybit into out. Returns the count. Probes all
+ * addresses, so it takes tens of ms; run it every few hundred ms. */
+int keybit_bus_scan(I2C_HandleTypeDef *i2c, keybit_info_t *out, int max);
+
+/* Fast path for typing: refresh key_down of the n Keybits from the last
+ * scan, one 1-byte read each (well under 1 ms apiece at 100 kHz). Returns a
+ * bitmask of entries whose key state changed. */
+uint32_t keybit_bus_poll_keys(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n);
+
+/* Drain relayed events from the n touching Keybits into the remote table
+ * (r, with *rn entries in use) and age out silent ones. Run it with
+ * keybit_bus_poll_keys. Returns 1 if any entry changed. */
+int keybit_bus_poll_relay(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n,
+ keybit_remote_t *r, int *rn);
+
+/* Plain register access for other devices on I2C3, such as the BQ25895
+ * charger (0x6A, never handed to a Keybit). Everything on the bus runs from
+ * the main loop, so call these from there too, not from an interrupt.
+ * Return 1 on success. */
+int keybit_bus_read(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, uint8_t *buf, uint8_t len);
+int keybit_bus_write(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, const uint8_t *buf, uint8_t len);
+
+#endif
diff --git a/firmware/sim/build_base/Src/keybit_bus.c b/firmware/sim/build_base/Src/keybit_bus.c
new file mode 100644
index 0000000..e62b7a7
--- /dev/null
+++ b/firmware/sim/build_base/Src/keybit_bus.c
@@ -0,0 +1,297 @@
+#include "keybit_bus.h"
+#include <string.h>
+
+#define I2C_TIMEOUT_MS 50 /* at 20 kHz a full 8-event relay read alone takes ~19 ms */
+#define ADDR_FIRST 0x08
+#define ADDR_LAST 0x77
+#define CHARGER_ADDR 0x6A /* BQ25895 shares I2C3 */
+#define LINK_ADDR 0x31 /* Keybit-to-Keybit links */
+
+#define REG_MAGIC 0x00
+#define REG_KEY 0x06
+#define REG_UID 0x10
+#define REG_ASSIGN 0x20
+#define REG_EV_COUNT 0x52
+#define REG_EV_DATA 0x53
+#define REG_EV_POP 0x7B
+#define REG_EV_DATA11 0x80 /* v11: 11-byte events with where the Keybit is */
+#define EV_SIZE11 11
+#define EV_BATCH 8
+#define EV_PRESSED 0x01
+#define EV_HEARTBEAT 0x02
+#define EV_BACKWARDS 0x04
+#define MAGIC 0x4B
+
+/* I2C3's pins (see stm32wbxx_hal_msp.c); IDR still reads them in AF mode. */
+#define BUS_PORT GPIOB
+#define BUS_SCL GPIO_PIN_13
+#define BUS_SDA GPIO_PIN_14
+#define JAM_RETRY_MS 1000
+
+int keybit_bus_held(void)
+{
+ return HAL_GPIO_ReadPin(BUS_PORT, BUS_SDA) == GPIO_PIN_RESET &&
+ HAL_GPIO_ReadPin(BUS_PORT, BUS_SCL) == GPIO_PIN_SET;
+}
+
+int keybit_bus_unstick(I2C_HandleTypeDef *i2c)
+{
+ static uint32_t low_since;
+ uint32_t now = HAL_GetTick();
+ if (HAL_GPIO_ReadPin(BUS_PORT, BUS_SCL) == GPIO_PIN_SET || HAL_I2C_GetState(i2c) != HAL_I2C_STATE_READY) {
+ low_since = now;
+ return 0;
+ }
+ if (now - low_since < 5) return 0;
+
+ HAL_I2C_DeInit(i2c);
+ GPIO_InitTypeDef g = {0};
+ g.Pin = BUS_SCL | BUS_SDA;
+ g.Mode = GPIO_MODE_OUTPUT_OD;
+ g.Pull = GPIO_NOPULL;
+ g.Speed = GPIO_SPEED_FREQ_LOW;
+ HAL_GPIO_WritePin(BUS_PORT, BUS_SCL | BUS_SDA, GPIO_PIN_SET);
+ HAL_GPIO_Init(BUS_PORT, &g);
+ for (int i = 0; i < 9; i++) { /* 9 clocks finish any byte and its ACK */
+ HAL_GPIO_WritePin(BUS_PORT, BUS_SCL, GPIO_PIN_RESET);
+ HAL_Delay(1);
+ HAL_GPIO_WritePin(BUS_PORT, BUS_SCL, GPIO_PIN_SET);
+ HAL_Delay(1);
+ }
+ HAL_GPIO_WritePin(BUS_PORT, BUS_SDA, GPIO_PIN_RESET); /* STOP: SDA rises while SCL is high */
+ HAL_Delay(1);
+ HAL_GPIO_WritePin(BUS_PORT, BUS_SDA, GPIO_PIN_SET);
+ HAL_I2C_Init(i2c); /* MspInit puts the pins back on I2C3 */
+ low_since = HAL_GetTick();
+ return 1;
+}
+
+int keybit_bus_jammed(void)
+{
+ static uint32_t last_try;
+ if (!keybit_bus_held()) return 0;
+ /* Let one attempt through now and then: its few clocks free a Keybit
+ * that really did get stuck mid-byte, at a tiny fraction of the usual
+ * poll rate. */
+ if (HAL_GetTick() - last_try >= JAM_RETRY_MS) {
+ last_try = HAL_GetTick();
+ return 0;
+ }
+ return 1;
+}
+
+static int is_ready(I2C_HandleTypeDef *i2c, uint8_t addr)
+{
+ /* Just the address byte (~0.5 ms at 20 kHz): a short timeout, or a
+ * misbehaving bus makes a full scan outlast the bootloader's ~8 s watchdog. */
+ return HAL_I2C_IsDeviceReady(i2c, (uint16_t)(addr << 1), 1, 3) == HAL_OK;
+}
+
+static int read_regs(I2C_HandleTypeDef *i2c, uint8_t addr, uint8_t reg, uint8_t *buf, uint16_t len)
+{
+ return HAL_I2C_Mem_Read(i2c, (uint16_t)(addr << 1), reg, I2C_MEMADD_SIZE_8BIT,
+ buf, len, I2C_TIMEOUT_MS) == HAL_OK;
+}
+
+static uint8_t free_address(I2C_HandleTypeDef *i2c)
+{
+ for (uint8_t a = ADDR_FIRST; a <= ADDR_LAST; a++) {
+ if (a == KEYBIT_DEFAULT_ADDR || a == LINK_ADDR || a == CHARGER_ADDR) continue;
+ if (!is_ready(i2c, a)) return a;
+ }
+ return 0;
+}
+
+int keybit_bus_assign(I2C_HandleTypeDef *i2c)
+{
+ int assigned = 0;
+ /* Each round, all unassigned Keybits answer the UID read together and
+ * arbitrate down to the lowest UID; that one gets an address and leaves
+ * the default address, so the next round finds the next one. */
+ for (int round = 0; round < KEYBIT_MAX; round++) {
+ uint8_t msg[13];
+ if (!read_regs(i2c, KEYBIT_DEFAULT_ADDR, REG_UID, msg, 12)) break;
+ uint8_t addr = free_address(i2c);
+ if (!addr) break;
+ msg[12] = addr;
+ if (HAL_I2C_Mem_Write(i2c, KEYBIT_DEFAULT_ADDR << 1, REG_ASSIGN, I2C_MEMADD_SIZE_8BIT,
+ msg, sizeof(msg), I2C_TIMEOUT_MS) != HAL_OK)
+ break;
+ HAL_Delay(15); /* it saves the address to flash, about 6 ms */
+ assigned++;
+ }
+ return assigned;
+}
+
+/* The Keybit's side touching us gives its place on the keyword. It can only
+ * mate upright, so its east side means it sits on our left, and so on. */
+static char keyword_side(char keybit_side)
+{
+ switch (keybit_side) {
+ case 'E': return 'L';
+ case 'W': return 'R';
+ case 'N': return 'R'; /* turned 90 degrees: only the right side meets an N side the right way round */
+ case 'S': return 'T';
+ default: return '?';
+ }
+}
+
+int keybit_bus_scan(I2C_HandleTypeDef *i2c, keybit_info_t *out, int max)
+{
+ int n = 0;
+ for (uint8_t a = ADDR_FIRST; a <= ADDR_LAST && n < max; a++) {
+ IWDG->KR = 0xAAAA;
+ if (a == KEYBIT_DEFAULT_ADDR || a == LINK_ADDR || a == CHARGER_ADDR) continue;
+ if (!is_ready(i2c, a)) continue;
+
+ uint8_t head[10];
+ if (!read_regs(i2c, a, REG_MAGIC, head, sizeof(head)) || head[0] != MAGIC) continue;
+
+ keybit_info_t *k = &out[n];
+ memset(k, 0, sizeof(*k));
+ /* Reading the UID also catches two Keybits on one address: the loser of
+ * the arbitration drops its address and turns up on the default one. */
+ if (!read_regs(i2c, a, REG_UID, k->uid, sizeof(k->uid))) continue;
+ k->addr = a;
+ k->fw = head[1];
+ k->key_down = head[6] & 1;
+ k->keybit_side = (char)head[7];
+ k->at = keyword_side(k->keybit_side);
+ k->backwards = k->fw >= 6 ? head[9] & 0x0F : 0; /* reg 0x09 is new in v6 */
+ n++;
+ }
+ return n;
+}
+
+uint32_t keybit_bus_poll_keys(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n)
+{
+ uint32_t changed = 0;
+ for (int i = 0; i < n; i++) {
+ uint8_t v;
+ if (!read_regs(i2c, k[i].addr, REG_KEY, &v, 1)) continue; /* next scan drops it */
+ if (v & 1) {
+ k[i].saw_down = 1;
+ k[i].pend = 0;
+ }
+ if ((v & 1) != k[i].key_down) {
+ k[i].key_down = v & 1;
+ changed |= 1u << i;
+ }
+ }
+ return changed;
+}
+
+static uint32_t uid32(const uint8_t *b)
+{
+ return (uint32_t)b[0] | (uint32_t)b[1] << 8 | (uint32_t)b[2] << 16 | (uint32_t)b[3] << 24;
+}
+
+static keybit_remote_t *remote_slot(keybit_remote_t *r, int *rn, uint32_t uid)
+{
+ keybit_remote_t *free_slot = NULL;
+ for (int i = 0; i < *rn; i++) {
+ if (r[i].uid == uid) return &r[i];
+ if (!r[i].present && !r[i].dirty && !free_slot) free_slot = &r[i];
+ }
+ if (*rn < KEYBIT_REMOTE_MAX) return &r[(*rn)++];
+ return free_slot; /* NULL when the table is full */
+}
+
+int keybit_bus_poll_relay(I2C_HandleTypeDef *i2c, keybit_info_t *k, int n,
+ keybit_remote_t *r, int *rn)
+{
+ int changed = 0;
+ uint32_t now = HAL_GetTick();
+
+ for (int i = 0; i < n; i++) {
+ uint8_t count;
+ if (!read_regs(i2c, k[i].addr, REG_EV_COUNT, &count, 1) || count == 0) continue;
+ if (count > EV_BATCH) count = EV_BATCH;
+ /* v11 Keybits also say where each Keybit is; older ones only uid + flags. */
+ int size = k[i].fw >= 11 ? EV_SIZE11 : 5;
+ uint8_t ev[EV_BATCH * EV_SIZE11];
+ if (!read_regs(i2c, k[i].addr, size == 5 ? REG_EV_DATA : REG_EV_DATA11, ev, (uint16_t)(count * size))) continue;
+ HAL_I2C_Mem_Write(i2c, (uint16_t)(k[i].addr << 1), REG_EV_POP, I2C_MEMADD_SIZE_8BIT,
+ &count, 1, I2C_TIMEOUT_MS);
+
+ for (int e = 0; e < count; e++) {
+ const uint8_t *x8 = &ev[e * size];
+ uint32_t uid = uid32(x8);
+ uint8_t flags = x8[4];
+
+ /* Touching Keybits queue their own key events too. Their key is read
+ * directly, but a tap shorter than the key poll only shows up here:
+ * a press the poll never saw, then its release, is a missed tap. */
+ int direct = 0;
+ for (int j = 0; j < n; j++) {
+ if (uid32(k[j].uid) != uid) continue;
+ direct = 1;
+ if (flags & EV_HEARTBEAT) continue; /* only key changes count */
+ if (flags & EV_PRESSED) {
+ if (!k[j].saw_down) k[j].pend = 1;
+ } else {
+ if (k[j].pend && !k[j].saw_down && !k[j].tap) k[j].tap = 1;
+ k[j].pend = 0;
+ }
+ }
+ if (direct) continue;
+
+ keybit_remote_t *x = remote_slot(r, rn, uid);
+ if (!x) continue;
+ uint8_t down = flags & EV_PRESSED;
+ uint8_t back = (flags & EV_BACKWARDS) != 0;
+ /* Down and up again before the keys task saw the down: keep it as a tap. */
+ if (down && !x->key_down) x->fresh_down = 1;
+ if (!down && x->key_down && x->fresh_down && !x->tap) x->tap = 1;
+ if (x->uid != uid || !x->present || x->key_down != down || x->backwards != back) {
+ x->dirty = 1;
+ changed = 1;
+ }
+ x->uid = uid;
+ x->present = 1;
+ x->key_down = down;
+ x->backwards = back;
+ x->depth = flags >> 4;
+ x->via = k[i].addr;
+ if (size == EV_SIZE11 && x8[10] != '?') {
+ uint32_t parent = uid32(&x8[5]);
+ if (parent != x->parent || x8[9] != x->pside || x8[10] != x->face) {
+ x->parent = parent;
+ x->pside = (char)x8[9];
+ x->face = (char)x8[10];
+ x->moved = 1;
+ x->dirty = 1;
+ changed = 1;
+ }
+ }
+ x->last_seen = now;
+ }
+ }
+
+ /* The next batch's events are measured against the polls until then. */
+ for (int i = 0; i < n; i++) k[i].saw_down = k[i].key_down;
+
+ for (int i = 0; i < *rn; i++) {
+ if (r[i].present && now - r[i].last_seen > KEYBIT_REMOTE_TIMEOUT_MS) {
+ r[i].present = 0;
+ r[i].key_down = 0;
+ r[i].backwards = 0;
+ r[i].dirty = 1;
+ changed = 1;
+ }
+ }
+ return changed;
+}
+
+int keybit_bus_read(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, uint8_t *buf, uint8_t len)
+{
+ if (keybit_bus_jammed()) return 0;
+ return read_regs(i2c, addr7, reg, buf, len);
+}
+
+int keybit_bus_write(I2C_HandleTypeDef *i2c, uint8_t addr7, uint8_t reg, const uint8_t *buf, uint8_t len)
+{
+ if (keybit_bus_jammed()) return 0;
+ return HAL_I2C_Mem_Write(i2c, (uint16_t)(addr7 << 1), reg, I2C_MEMADD_SIZE_8BIT,
+ (uint8_t *)buf, len, I2C_TIMEOUT_MS) == HAL_OK;
+}
diff --git a/firmware/sim/build_base/ctx.o b/firmware/sim/build_base/ctx.o
new file mode 100644
index 0000000..8d1c239
Binary files /dev/null and b/firmware/sim/build_base/ctx.o differ
diff --git a/firmware/sim/build_base/kw.c b/firmware/sim/build_base/kw.c
new file mode 100644
index 0000000..a441e30
--- /dev/null
+++ b/firmware/sim/build_base/kw.c
@@ -0,0 +1,339 @@
+/*
+ * The Keyword in the simulator: the real keybit_bus.c over an I2C3 model
+ * with the real timing (0xF0426363 at 64 MHz: 25 us low, 25 us high, ~20
+ * kHz, clock stretching honoured), the bus poll loop from main.c and the
+ * key handling from keymap.c, reporting every key change it would send.
+ */
+#include <stdio.h>
+#include <stdlib.h>
+#include "stm32wbxx_hal.h"
+#include "Src/keybit_bus.c"
+
+GPIO_TypeDef sim_gpiob;
+IWDG_TypeDef sim_iwdg;
+
+/* Timing knobs, settable from sim.c */
+int kw_keys_ms = 15, kw_relay_ms = 60, kw_scan_ms = 500, kw_task_ms = 5;
+int64_t kw_loop_ps = 50 * PS_US; /* rest of the main loop: BLE, USB */
+int64_t kw_t_low = 25 * PS_US, kw_t_high = 25 * PS_US;
+#define T_SDADEL (500 * PS_NS)
+#define T_POLL (250 * PS_NS)
+#define T_HAL (20 * PS_US) /* HAL call overhead */
+
+/* ------------------------------------------------------------------------ */
+/* I2C3 controller */
+
+static int64_t deadline;
+static int timed_out;
+
+static int scl_up(void)
+{
+ sim_kw_drive(0, 1);
+ while (!sim_kw_read(0)) {
+ if (sim_now() > deadline) { timed_out = 1; return 0; }
+ sim_sleep(T_POLL);
+ }
+ return 1;
+}
+
+/* SCL is low on entry and on return. */
+static int put_bit(int b)
+{
+ sim_sleep(T_SDADEL);
+ sim_kw_drive(1, b);
+ sim_sleep(kw_t_low - T_SDADEL);
+ if (!scl_up()) return 0;
+ sim_sleep(kw_t_high);
+ sim_kw_drive(0, 0);
+ return 1;
+}
+
+static int get_bit(int *b)
+{
+ sim_sleep(T_SDADEL);
+ sim_kw_drive(1, 1);
+ sim_sleep(kw_t_low - T_SDADEL);
+ if (!scl_up()) return 0;
+ sim_sleep(kw_t_high);
+ *b = sim_kw_read(1);
+ sim_kw_drive(0, 0);
+ return 1;
+}
+
+/* 1 ack, 0 nack, -1 timeout */
+static int put_byte(uint8_t v)
+{
+ for (int i = 7; i >= 0; i--)
+ if (!put_bit((v >> i) & 1)) return -1;
+ int b;
+ if (!get_bit(&b)) return -1;
+ return !b;
+}
+
+static int get_byte(uint8_t *v, int ack)
+{
+ uint8_t x = 0;
+ for (int i = 0; i < 8; i++) {
+ int b;
+ if (!get_bit(&b)) return 0;
+ x = (uint8_t)(x << 1 | b);
+ }
+ *v = x;
+ return put_bit(!ack);
+}
+
+/* A START, or a repeated START (SCL low on entry: a full low period first). */
+static int start(void)
+{
+ int repeated = !sim_kw_read(0);
+ sim_sleep(T_SDADEL);
+ sim_kw_drive(1, 1);
+ if (repeated) sim_sleep(kw_t_low - T_SDADEL);
+ if (!scl_up()) return 0;
+ sim_sleep(kw_t_high);
+ sim_kw_drive(1, 0);
+ sim_sleep(kw_t_high);
+ sim_kw_drive(0, 0);
+ return 1;
+}
+
+static void stop(void)
+{
+ sim_sleep(T_SDADEL);
+ sim_kw_drive(1, 0);
+ sim_sleep(kw_t_low);
+ scl_up();
+ sim_sleep(kw_t_high);
+ sim_kw_drive(1, 1);
+ sim_sleep(kw_t_low); /* bus free time */
+}
+
+static HAL_StatusTypeDef fail(void)
+{
+ if (getenv("KW_TRACE2")) printf("%9.3f ms fail%s\n", sim_now() / 1e9, timed_out ? " (timeout)" : "");
+ if (timed_out) {
+ sim_kw_drive(0, 1);
+ sim_kw_drive(1, 1);
+ return HAL_TIMEOUT;
+ }
+ stop();
+ return HAL_ERROR;
+}
+
+static void begin(uint32_t timeout)
+{
+ sim_sleep(T_HAL);
+ deadline = sim_now() + (int64_t)timeout * PS_MS;
+ timed_out = 0;
+}
+
+HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *h, uint16_t addr, uint32_t trials, uint32_t timeout)
+{
+ (void)h; (void)trials;
+ begin(timeout);
+ if (!start()) return fail();
+ int a = put_byte((uint8_t)addr);
+ if (a < 0) return fail();
+ stop();
+ return a ? HAL_OK : HAL_ERROR;
+}
+
+HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *h, uint16_t addr, uint16_t reg, uint16_t regsize,
+ uint8_t *buf, uint16_t len, uint32_t timeout)
+{
+ (void)h; (void)regsize;
+ begin(timeout);
+ if (!start() || put_byte((uint8_t)addr) != 1 || put_byte((uint8_t)reg) != 1) return fail();
+ if (!start() || put_byte((uint8_t)(addr | 1)) != 1) return fail();
+ for (int i = 0; i < len; i++)
+ if (!get_byte(&buf[i], i < len - 1)) return fail();
+ stop();
+ if (getenv("KW_TRACE")) {
+ printf("%9.3f ms read %02x reg %02x:", sim_now() / 1e9, addr >> 1, reg);
+ for (int i = 0; i < len; i++) printf(" %02x", buf[i]);
+ printf("\n");
+ }
+ return HAL_OK;
+}
+
+HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *h, uint16_t addr, uint16_t reg, uint16_t regsize,
+ uint8_t *buf, uint16_t len, uint32_t timeout)
+{
+ (void)h; (void)regsize;
+ begin(timeout);
+ if (!start() || put_byte((uint8_t)addr) != 1 || put_byte((uint8_t)reg) != 1) return fail();
+ for (int i = 0; i < len; i++)
+ if (put_byte(buf[i]) != 1) return fail();
+ stop();
+ return HAL_OK;
+}
+
+uint32_t HAL_GetTick(void) { return (uint32_t)(sim_now() / PS_MS); }
+void HAL_Delay(uint32_t ms) { sim_sleep((int64_t)ms * PS_MS); }
+GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *port, uint16_t pin)
+{
+ (void)port;
+ return sim_kw_read(pin == GPIO_PIN_13 ? 0 : 1) ? GPIO_PIN_SET : GPIO_PIN_RESET;
+}
+void HAL_GPIO_WritePin(GPIO_TypeDef *port, uint16_t pin, GPIO_PinState s)
+{
+ (void)port;
+ if (pin & GPIO_PIN_13) sim_kw_drive(0, s == GPIO_PIN_SET);
+ if (pin & GPIO_PIN_14) sim_kw_drive(1, s == GPIO_PIN_SET);
+}
+void HAL_GPIO_Init(GPIO_TypeDef *port, GPIO_InitTypeDef *init) { (void)port; (void)init; }
+HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *h) { (void)h; sim_kw_drive(0, 1); sim_kw_drive(1, 1); return HAL_OK; }
+HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *h) { (void)h; return HAL_OK; }
+HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *h) { (void)h; return HAL_I2C_STATE_READY; }
+
+/* ------------------------------------------------------------------------ */
+/* main.c: Keybit_Bus_Poll, without the host messages */
+
+#define KEYBIT_MISSES_MAX 2
+
+static I2C_HandleTypeDef hi2c3;
+keybit_info_t keybits[KEYBIT_MAX];
+int keybit_count;
+keybit_remote_t keybit_remotes[KEYBIT_REMOTE_MAX];
+int keybit_remote_count;
+
+static void Keybit_Bus_Poll(void)
+{
+ static uint32_t last_scan, last_keys, last_relay;
+
+ keybit_bus_unstick(&hi2c3);
+ if (keybit_bus_jammed()) return;
+ if (HAL_GetTick() - last_keys >= (uint32_t)kw_keys_ms) {
+ last_keys = HAL_GetTick();
+ keybit_bus_poll_keys(&hi2c3, keybits, keybit_count);
+ }
+ if (HAL_GetTick() - last_relay >= (uint32_t)kw_relay_ms) {
+ last_relay = HAL_GetTick();
+ keybit_bus_poll_relay(&hi2c3, keybits, keybit_count, keybit_remotes, &keybit_remote_count);
+ }
+ if (HAL_GetTick() - last_scan < (uint32_t)kw_scan_ms) return;
+ last_scan = HAL_GetTick();
+
+ keybit_bus_assign(&hi2c3);
+ static uint8_t missed[KEYBIT_MAX];
+ keybit_info_t found[KEYBIT_MAX];
+ uint8_t found_missed[KEYBIT_MAX] = {0};
+ int n = keybit_bus_scan(&hi2c3, found, KEYBIT_MAX);
+ for (int i = 0; i < keybit_count && n < KEYBIT_MAX; i++) {
+ int here = 0;
+ for (int j = 0; j < n && !here; j++)
+ if (memcmp(found[j].uid, keybits[i].uid, sizeof(found[j].uid)) == 0) {
+ here = 1;
+ found[j].saw_down = keybits[i].saw_down;
+ found[j].pend = keybits[i].pend;
+ found[j].tap = keybits[i].tap;
+ }
+ if (!here && missed[i] < KEYBIT_MISSES_MAX) {
+ found[n] = keybits[i];
+ found_missed[n++] = (uint8_t)(missed[i] + 1);
+ }
+ }
+ memcpy(keybits, found, n * sizeof(found[0]));
+ memcpy(missed, found_missed, sizeof(missed));
+ keybit_count = n;
+}
+
+/* ------------------------------------------------------------------------ */
+/* keymap.c: what the keys task would report, per Keybit */
+
+#define SHOWN_MAX 64
+static struct { uint32_t uid; uint8_t down; } shown[SHOWN_MAX];
+static int shown_n;
+
+static void show(uint32_t uid, int down)
+{
+ for (int i = 0; i < shown_n; i++)
+ if (shown[i].uid == uid) {
+ if (shown[i].down != down) { shown[i].down = (uint8_t)down; kw_report(uid, down); }
+ return;
+ }
+ if (shown_n < SHOWN_MAX) {
+ shown[shown_n].uid = uid;
+ shown[shown_n++].down = (uint8_t)down;
+ if (down) kw_report(uid, down);
+ }
+}
+
+static void Keys_Task(void)
+{
+ for (int i = 0; i < keybit_count; i++) {
+ int down = keybits[i].key_down;
+ if (keybits[i].tap == 1) { down = 1; keybits[i].tap = 2; }
+ else if (keybits[i].tap == 2) keybits[i].tap = 0;
+ show(uid32(keybits[i].uid), down);
+ }
+ for (int r = 0; r < keybit_remote_count; r++) {
+ keybit_remote_t *k = &keybit_remotes[r];
+ int down = k->present && (k->key_down || k->tap == 1);
+ if (k->tap == 1) { k->tap = 2; k->dirty = 1; }
+ else if (k->tap == 2) k->tap = 0;
+ if (down) k->fresh_down = 0;
+ k->dirty = 0;
+ k->moved = 0;
+ show(k->uid, down);
+ }
+}
+
+/* Probe mode: instead of the poll loop, IsDeviceReady the first Keybit at
+ * the given half period, like I2CSCAN after I2CSPEED. */
+int kw_probe_left, kw_probe_acks;
+int64_t kw_probe_half;
+
+void kw_main(void)
+{
+ sim_kw_drive(0, 1);
+ sim_kw_drive(1, 1);
+ sim_sleep(5 * PS_MS);
+ uint32_t last_task = 0;
+ for (;;) {
+ if (kw_probe_left > 0 && keybit_count > 0) {
+ /* I2CSCAN: every address in a row, as proto.c does it */
+ int64_t lo = kw_t_low, hi = kw_t_high;
+ kw_t_low = kw_t_high = kw_probe_half;
+ for (uint8_t a = 0x08; a <= 0x77; a++) {
+ int ok = HAL_I2C_IsDeviceReady(&hi2c3, (uint16_t)(a << 1), 1, 10) == HAL_OK;
+ if (a == keybits[0].addr) {
+ kw_probe_acks += ok;
+ if (getenv("KW_TRACE")) printf("probe %02x at %.3f ms: %s\n", a, sim_now() / 1e9, ok ? "ack" : "NACK");
+ }
+ }
+ kw_probe_left--;
+ kw_t_low = lo; kw_t_high = hi;
+ /* the normal poll loop runs between I2CSCAN commands */
+ int64_t until = sim_now() + (100 + rand() % 200) * PS_MS;
+ while (sim_now() < until) { Keybit_Bus_Poll(); sim_sleep(kw_loop_ps); }
+ continue;
+ }
+ Keybit_Bus_Poll();
+ if (HAL_GetTick() - last_task >= (uint32_t)kw_task_ms) {
+ last_task = HAL_GetTick();
+ Keys_Task();
+ }
+ sim_sleep(kw_loop_ps);
+ }
+}
+
+int kw_present(uint32_t uid)
+{
+ for (int i = 0; i < keybit_count; i++) if (uid32(keybits[i].uid) == uid) return 1;
+ for (int r = 0; r < keybit_remote_count; r++) if (keybit_remotes[r].uid == uid && keybit_remotes[r].present) return 2;
+ return 0;
+}
+
+/* The face a v11 Keybit reported, or 0. */
+int kw_where(uint32_t uid, uint32_t *parent, char *pside, char *face)
+{
+ for (int r = 0; r < keybit_remote_count; r++)
+ if (keybit_remotes[r].uid == uid && keybit_remotes[r].present && keybit_remotes[r].face) {
+ *parent = keybit_remotes[r].parent;
+ *pside = keybit_remotes[r].pside;
+ *face = keybit_remotes[r].face;
+ return 1;
+ }
+ return 0;
+}
diff --git a/firmware/sim/build_base/kw.o b/firmware/sim/build_base/kw.o
new file mode 100644
index 0000000..2b02691
Binary files /dev/null and b/firmware/sim/build_base/kw.o differ
diff --git a/firmware/sim/build_base/sim.o b/firmware/sim/build_base/sim.o
new file mode 100644
index 0000000..1bf0ce3
Binary files /dev/null and b/firmware/sim/build_base/sim.o differ
diff --git a/firmware/sim/build_base/stub.c b/firmware/sim/build_base/stub.c
new file mode 100644
index 0000000..c2e02ee
--- /dev/null
+++ b/firmware/sim/build_base/stub.c
@@ -0,0 +1 @@
+int kw_probe_read;
diff --git a/firmware/sim/build_base/stub.o b/firmware/sim/build_base/stub.o
new file mode 100644
index 0000000..2889953
Binary files /dev/null and b/firmware/sim/build_base/stub.o differ
diff --git a/firmware/sim/kw.c b/firmware/sim/kw.c
index dee5736..4835118 100644
--- a/firmware/sim/kw.c
+++ b/firmware/sim/kw.c
@@ -9,11 +9,12 @@
#include "stm32wbxx_hal.h"
#include "../keyword/Core/Src/keybit_bus.c"
+
GPIO_TypeDef sim_gpiob;
IWDG_TypeDef sim_iwdg;
/* Timing knobs, settable from sim.c */
-int kw_keys_ms = 15, kw_relay_ms = 60, kw_scan_ms = 500, kw_task_ms = 5;
+int kw_task_ms = 5;
int64_t kw_loop_ps = 50 * PS_US; /* rest of the main loop: BLE, USB */
int64_t kw_t_low = 25 * PS_US, kw_t_high = 25 * PS_US;
#define T_SDADEL (500 * PS_NS)
@@ -168,6 +169,15 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *h, uint16_t addr, uint16_
return HAL_OK;
}
+/* The cycle counter at 64 MHz; each look costs a few cycles. */
+DWT_TypeDef *sim_dwt(void)
+{
+ static DWT_TypeDef d;
+ sim_sleep(100 * PS_NS);
+ d.CYCCNT = (uint32_t)(sim_now() / 15625);
+ return &d;
+}
+uint32_t HAL_RCC_GetHCLKFreq(void) { return 64000000u; }
uint32_t HAL_GetTick(void) { return (uint32_t)(sim_now() / PS_MS); }
void HAL_Delay(uint32_t ms) { sim_sleep((int64_t)ms * PS_MS); }
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *port, uint16_t pin)
@@ -189,53 +199,19 @@ HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *h) { (void)h; return HA
/* ------------------------------------------------------------------------ */
/* main.c: Keybit_Bus_Poll, without the host messages */
-#define KEYBIT_MISSES_MAX 2
-
static I2C_HandleTypeDef hi2c3;
keybit_info_t keybits[KEYBIT_MAX];
int keybit_count;
keybit_remote_t keybit_remotes[KEYBIT_REMOTE_MAX];
int keybit_remote_count;
+static int kick; /* KEYMAP_Kick: the keys task runs on the next pass */
static void Keybit_Bus_Poll(void)
{
- static uint32_t last_scan, last_keys, last_relay;
-
keybit_bus_unstick(&hi2c3);
if (keybit_bus_jammed()) return;
- if (HAL_GetTick() - last_keys >= (uint32_t)kw_keys_ms) {
- last_keys = HAL_GetTick();
- keybit_bus_poll_keys(&hi2c3, keybits, keybit_count);
- }
- if (HAL_GetTick() - last_relay >= (uint32_t)kw_relay_ms) {
- last_relay = HAL_GetTick();
- keybit_bus_poll_relay(&hi2c3, keybits, keybit_count, keybit_remotes, &keybit_remote_count);
- }
- if (HAL_GetTick() - last_scan < (uint32_t)kw_scan_ms) return;
- last_scan = HAL_GetTick();
-
- keybit_bus_assign(&hi2c3);
- static uint8_t missed[KEYBIT_MAX];
- keybit_info_t found[KEYBIT_MAX];
- uint8_t found_missed[KEYBIT_MAX] = {0};
- int n = keybit_bus_scan(&hi2c3, found, KEYBIT_MAX);
- for (int i = 0; i < keybit_count && n < KEYBIT_MAX; i++) {
- int here = 0;
- for (int j = 0; j < n && !here; j++)
- if (memcmp(found[j].uid, keybits[i].uid, sizeof(found[j].uid)) == 0) {
- here = 1;
- found[j].saw_down = keybits[i].saw_down;
- found[j].pend = keybits[i].pend;
- found[j].tap = keybits[i].tap;
- }
- if (!here && missed[i] < KEYBIT_MISSES_MAX) {
- found[n] = keybits[i];
- found_missed[n++] = (uint8_t)(missed[i] + 1);
- }
- }
- memcpy(keybits, found, n * sizeof(found[0]));
- memcpy(missed, found_missed, sizeof(missed));
- keybit_count = n;
+ if (keybit_bus_service(&hi2c3, keybits, &keybit_count, keybit_remotes, &keybit_remote_count) & KEYBIT_CHANGED)
+ kick = 1;
}
/* ------------------------------------------------------------------------ */
@@ -281,7 +257,7 @@ static void Keys_Task(void)
/* Probe mode: instead of the poll loop, IsDeviceReady the first Keybit at
* the given half period, like I2CSCAN after I2CSPEED. */
-int kw_probe_left, kw_probe_acks;
+int kw_probe_left, kw_probe_acks, kw_probe_read;
int64_t kw_probe_half;
void kw_main(void)
@@ -295,8 +271,10 @@ void kw_main(void)
/* I2CSCAN: every address in a row, as proto.c does it */
int64_t lo = kw_t_low, hi = kw_t_high;
kw_t_low = kw_t_high = kw_probe_half;
- for (uint8_t a = 0x08; a <= 0x77; a++) {
- int ok = HAL_I2C_IsDeviceReady(&hi2c3, (uint16_t)(a << 1), 1, 10) == HAL_OK;
+ for (uint8_t a = kw_probe_read ? keybits[0].addr : 0x08; a <= (kw_probe_read ? keybits[0].addr : 0x77); a++) {
+ uint8_t b4[4];
+ int ok = kw_probe_read ? HAL_I2C_Mem_Read(&hi2c3, (uint16_t)(a << 1), 0, 1, b4, 4, 10) == HAL_OK && b4[0] == 0x4B
+ : HAL_I2C_IsDeviceReady(&hi2c3, (uint16_t)(a << 1), 1, 10) == HAL_OK;
if (a == keybits[0].addr) {
kw_probe_acks += ok;
if (getenv("KW_TRACE")) printf("probe %02x at %.3f ms: %s\n", a, sim_now() / 1e9, ok ? "ack" : "NACK");
@@ -305,15 +283,16 @@ void kw_main(void)
kw_probe_left--;
kw_t_low = lo; kw_t_high = hi;
/* the normal poll loop runs between I2CSCAN commands */
- int64_t until = sim_now() + (100 + rand() % 200) * PS_MS;
+ int64_t until = sim_now() + (kw_probe_read ? 150 : 100 + rand() % 200) * PS_MS;
while (sim_now() < until) { Keybit_Bus_Poll(); sim_sleep(kw_loop_ps); }
continue;
}
- Keybit_Bus_Poll();
- if (HAL_GetTick() - last_task >= (uint32_t)kw_task_ms) {
+ if (kick || HAL_GetTick() - last_task >= (uint32_t)kw_task_ms) {
+ kick = 0;
last_task = HAL_GetTick();
Keys_Task();
}
+ Keybit_Bus_Poll();
sim_sleep(kw_loop_ps);
}
}
diff --git a/firmware/sim/node.c b/firmware/sim/node.c
index 44b11df..0706a4a 100644
--- a/firmware/sim/node.c
+++ b/firmware/sim/node.c
@@ -1,9 +1,21 @@
/* One Keybit: its real main.c, plus a few getters for the simulator. */
#define main keybit_main
-#include "../keybit/main.c"
+#include "main.c" /* the Keybit's, found through -I */
#undef main
uint8_t sim_node_depth(void) { return my_depth; }
uint8_t sim_node_qcount(void) { return q_count; }
const uint8_t *sim_node_diag(void) { return &diag[0][0]; }
uint8_t sim_node_backwards(void) { return backwards; }
+
+/* Is a press event from this UID (low 32 bits) in our queue? */
+int sim_node_has_press(uint32_t u)
+{
+ for (int i = 0; i < q_count; i++) {
+ const event_t *e = queue_at(i);
+ uint32_t v = (uint32_t)e->uid[0] | (uint32_t)e->uid[1] << 8 | (uint32_t)e->uid[2] << 16 | (uint32_t)e->uid[3] << 24;
+ if (v == u && (e->flags & EV_PRESSED)) return 1;
+ }
+ return 0;
+}
+uint8_t sim_node_key(void) { return key_down; }
diff --git a/firmware/sim/sim.c b/firmware/sim/sim.c
index 698bacf..c18cfcd 100644
--- a/firmware/sim/sim.c
+++ b/firmware/sim/sim.c
@@ -27,6 +27,7 @@
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
+#include <sys/wait.h>
#include "sim.h"
#include "ch32fun.h"
@@ -57,6 +58,8 @@ typedef struct {
uint8_t (*depth)(void);
uint8_t (*qcount)(void);
const uint8_t *(*diag)(void);
+ int (*has_press)(uint32_t);
+ uint8_t (*key)(void);
sim_systick_t st;
sim_gpio_t gpio[4];
sim_esig_t esig;
@@ -89,9 +92,11 @@ static int op_cycles = 16; /* a pin or SysTick access, with the code around i
static int spin_cycles = 5; /* one pass of link.c's tight spin on the input register */
/* The main loop's own work between register accesses (depth, doorbell,
* side bookkeeping), charged once per pass on its one read of the key pin.
- * Fitted to the real Keybits: they answer every address at 25 kHz, half at
- * 30 kHz and none at 35 kHz (I2CSPEED sweep, 2026-10-29). */
-static int pass_cycles = 300;
+ * Fitted to the real v10 Keybits on 2026-10-29: `I2CRD 0a 00 4` after
+ * I2CSPEED succeeded 29/30 at 10 kHz, 30/30 at 15, 26/30 at 20, 13/20 at 25,
+ * 7/20 at 35 and 0/20 at 50 kHz. With 1100 the sim gets 20, 20, 18, 12, 10
+ * and 3 of 20 (`PROBE_READ=1 ./sim node_v10.bundle speed`). */
+static int pass_cycles = 1100;
static double c_pf = 15, kw_pullup_k = 4.7;
static unsigned seed = 1;
static uint32_t tick0_all;
@@ -221,6 +226,7 @@ static void wire_update(int wi, int64_t t)
/* Topology */
static int uf[MAXN * NPIN];
+static int vv[MAXN][MAXN]; /* the right way round to each other (3V3 meets 3V3) */
static int find(int a) { while (uf[a] != a) a = uf[a] = uf[uf[a]]; return a; }
static int side_facing(const node_t *n, int dx, int dy)
@@ -251,7 +257,6 @@ static void build(void)
int ties[MAXN * NPIN];
memset(ties, 0, sizeof(ties));
for (int i = 0; i < MAXN * NPIN; i++) uf[i] = i;
- int vv[MAXN][MAXN];
memset(vv, 0, sizeof(vv));
for (int a = 1; a < n_nodes; a++) {
@@ -340,6 +345,8 @@ static void build(void)
k->depth = (uint8_t (*)(void))dlsym(dl, "sim_node_depth");
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->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));
k->t = k->t_boot = sim_t + (int64_t)(1 + 2 * frand()) * PS_MS;
@@ -459,7 +466,7 @@ static int n_presses;
extern int kw_present(uint32_t uid);
extern int kw_where(uint32_t uid, uint32_t *parent, char *pside, char *face);
-extern int kw_keys_ms, kw_relay_ms, kw_scan_ms, kw_task_ms;
+extern int kw_task_ms;
static uint32_t uid_of(int n) { return nodes[n].esig.UNIID1; }
@@ -527,6 +534,10 @@ static void measure(lat_t *by_depth, int max_depth, const int *depth_of)
if (reports[r].uid == uid_of(p->node) && reports[r].down && reports[r].t >= p->down && reports[r].t < until) {
got = reports[r].t; break;
}
+ static FILE *dump;
+ static int dump_init;
+ if (!dump_init) { dump_init = 1; const char *f = getenv("LAT_DUMP"); if (f) dump = fopen(f, "a"); }
+ if (dump) fprintf(dump, "%d %.3f\n", d, got < 0 ? -1.0 : (got - p->down) / 1e9);
if (got < 0) by_depth[d].lost++;
else if (nb[d] < LOG_MAX / 8) buf[d][nb[d]++] = got - p->down;
}
@@ -558,6 +569,7 @@ 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%). */
+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)
{
for (int i = 0; i < count; i++) {
@@ -570,6 +582,11 @@ static void type_keys(int count, int hold_ms, int gap_ms)
run_until(sim_t + hold);
nodes[n].button = 0;
run_until(sim_t + gap);
+ for (int k = 1; k < n_nodes; k++)
+ if (nodes[k].powered && !kw_present(uid_of(k))) {
+ dropouts++;
+ if (getenv("SHOW_DROPS")) printf(" kb%d missing at %.0f ms\n", k, sim_t / 1e9);
+ }
}
run_until(sim_t + 200 * PS_MS); /* let the last ones arrive */
}
@@ -609,38 +626,243 @@ 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);
+ CHECK(dropouts == 0, "%s: Keybits dropped out of the Keyword's list %d times", name, dropouts);
+}
+
+/* Hops from the Keyword over contacts the right way round, 0 if unpowered. */
+static void expected_depths(int *depth)
+{
+ for (int n = 0; n < n_nodes; n++) depth[n] = 0;
+ int q[MAXN], h = 0, t = 0, seen[MAXN] = { 1 };
+ q[t++] = 0;
+ while (h < t) {
+ int a = q[h++];
+ for (int b = 1; b < n_nodes; b++)
+ if (!seen[b] && vv[a][b] && nodes[b].placed) { seen[b] = 1; depth[b] = depth[a] + 1; q[t++] = b; }
+ }
+}
+
+static const char COMPASS[4] = { 'N', 'E', 'S', 'W' };
+
+static int node_by_uid(uint32_t uid)
+{
+ for (int n = 1; n < n_nodes; n++) if (nodes[n].placed && uid_of(n) == uid) return n;
+ return -1;
+}
+
+/* Depths, and for v11+ Keybits where the Keyword thinks each chained one is. */
+static void check_places(void)
+{
+ int want[MAXN];
+ expected_depths(want);
+ int placed = 0;
+ for (int n = 1; n < n_nodes; n++) {
+ if (!want[n]) continue;
+ CHECK(nodes[n].powered && nodes[n].depth() == want[n], "kb%d depth %d, want %d", n,
+ nodes[n].powered ? nodes[n].depth() : -1, want[n]);
+ uint32_t parent;
+ 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];
+ 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;
+ }
+ CHECK(ok, "kb%d reported on kb%d's %c side facing it with %c: wrong", n, p, pside, face);
+ placed += ok;
+ }
+ printf(" depths checked, %d chained Keybits placed right\n", placed);
+}
+
+typedef struct { int x, y, rot; } cell_t;
+
+static void settle(const char *name)
+{
+ int64_t t = wait_present(10000 * PS_MS);
+ printf(" %s: all present after %.0f ms\n", name, t / 1e9);
+ CHECK(t >= 0, "%s: not every powered Keybit showed up", name);
+ run_until(sim_t + 1500 * PS_MS); /* positions settle after the first heartbeats */
+ check_places();
+}
+
+static void finish(void)
+{
+ 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);
+}
+
+static void sc_layout(const char *name, const cell_t *c, int n, int presses_n)
+{
+ printf("%s (%d Keybits)\n", name, n);
+ reset_world();
+ for (int i = 0; i < n; i++) add_keybit(c[i].x, c[i].y, c[i].rot);
+ build();
+ settle(name);
+ type_keys(presses_n, 60, 120);
+ report_latency("tap", 8);
+ CHECK(shorts == 0, "a pin drove against a supply %ld times", shorts);
+ finish();
}
/* A straight line out of the Keyword's right side, every Keybit the usual way round. */
static void sc_chain(int len, int presses_n)
{
- printf("chain of %d\n", len);
+ cell_t c[MAXN];
+ for (int i = 0; i < len; i++) c[i] = (cell_t){ i + 1, 0, 0 };
+ sc_layout("chain", c, len, presses_n);
+}
+
+/* The same, every other Keybit in the second turn that meets its neighbours
+ * the right way: N to the west instead of W, so S to the east. */
+static void sc_turns(int len, int presses_n)
+{
+ cell_t c[MAXN];
+ for (int i = 0; i < len; i++) c[i] = (cell_t){ i + 1, 0, i & 1 ? 3 : 0 };
+ sc_layout("turns", c, len, presses_n);
+}
+
+/* The Keyword in a corner of a 2x2 square. */
+static void sc_square(int presses_n)
+{
+ static const cell_t c[] = { { -1, 0, 0 }, { 0, -1, 0 }, { -1, -1, 0 } };
+ sc_layout("square", c, 3, presses_n);
+}
+
+/* 20 Keybits around the Keyword, three of them touching it. */
+static void sc_block(int presses_n)
+{
+ cell_t c[MAXN];
+ int n = 0;
+ for (int y = -2; y <= 0; y++)
+ for (int x = -3; x <= 3; x++)
+ if (y < 0 || x != 0) c[n++] = (cell_t){ x, y, 0 };
+ sc_layout("block", c, n, presses_n);
+}
+
+/* A chain of 3 with a 4th turned the wrong way round at the end: it gets no
+ * power, kb3 must flag it and leave that side alone, the rest keep working. */
+static void sc_reversed(int presses_n)
+{
+ static const cell_t c[] = { { 1, 0, 0 }, { 2, 0, 0 }, { 3, 0, 0 }, { 4, 0, 2 } };
+ printf("reversed\n");
reset_world();
- for (int i = 1; i <= len; i++) add_keybit(i, 0, 0);
+ for (int i = 0; i < 4; i++) add_keybit(c[i].x, c[i].y, c[i].rot);
build();
- int64_t t = wait_present(10000 * PS_MS);
- printf(" all present after %.0f ms\n", t / 1e9);
- CHECK(t >= 0, "not every Keybit showed up");
- for (int n = 1; n < n_nodes; n++) CHECK(nodes[n].depth() == n, "kb%d depth %d, want %d", n, nodes[n].depth(), n);
+ CHECK(!nodes[4].powered, "the backwards Keybit has power");
+ settle("reversed");
type_keys(presses_n, 60, 120);
- report_latency("tap", len);
- 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);
+ report_latency("tap", 8);
+ CHECK(shorts == 0, "a pin drove against a supply %ld times", shorts);
+ finish();
+}
+
+/* Pull the middle of a chain out and put it back. */
+static void sc_joinleave(int presses_n)
+{
+ printf("join/leave\n");
+ reset_world();
+ for (int i = 1; i <= 4; i++) add_keybit(i, 0, 0);
+ build();
+ settle("start");
+ type_keys(presses_n / 2, 60, 120);
+ nodes[2].placed = 0;
+ build();
+ CHECK(!nodes[3].powered && !nodes[4].powered, "the Keybits behind the gap kept power");
+ run_until(sim_t + 4000 * PS_MS);
+ CHECK(kw_present(uid_of(1)) && !kw_present(uid_of(2)) && !kw_present(uid_of(3)), "the Keyword still lists Keybits that left");
+ nodes[2].placed = 1;
+ build();
+ settle("rejoined");
+ n_presses = n_reports = 0;
+ type_keys(presses_n / 2, 60, 120);
+ report_latency("tap", 8);
+ finish();
+}
+
+/* A Keybit pushed onto the end of a chain bounces: contact on and off every
+ * 1-3 ms for 40 ms while someone types on the others. */
+static void sc_bounce(int presses_n)
+{
+ printf("bounce\n");
+ reset_world();
+ for (int i = 1; i <= 4; i++) add_keybit(i, 0, 0);
+ nodes[4].placed = 0;
+ build();
+ settle("start");
+ nodes[1].button = 1;
+ presses[n_presses++] = (press_t){ 1, sim_t, sim_t + 30 * PS_MS };
+ for (int64_t end = sim_t + 40 * PS_MS; sim_t < end;) {
+ nodes[4].placed ^= 1;
+ build();
+ run_until(sim_t + (1 + rnd() % 3) * PS_MS);
+ if (nodes[1].button && sim_t >= presses[0].up) nodes[1].button = 0;
+ }
+ nodes[1].button = 0;
+ nodes[4].placed = 1;
+ build();
+ settle("after");
+ type_keys(presses_n, 60, 120);
+ report_latency("tap", 8);
+ CHECK(shorts == 0, "a pin drove against a supply %ld times", shorts);
+ finish();
+}
+
+/* Fast typing: 15-22 ms taps 30-60 ms apart. */
+/* Where one press spends its time, hop by hop, on a chain of len. */
+static void sc_trace(int len, int presses_n)
+{
+ printf("trace, chain of %d\n", len);
+ reset_world();
+ for (int i = 1; i <= len; i++) add_keybit(i, 0, 0);
+ build();
+ settle("trace");
+ for (int p = 0; p < presses_n; p++) {
+ int n = len;
+ int64_t t0 = sim_t, seen[MAXN] = { 0 }, deb = 0, rep = 0;
+ int r0 = n_reports;
+ nodes[n].button = 1;
+ while (sim_t - t0 < 400 * PS_MS && !rep) {
+ run_until(sim_t + 250 * PS_US);
+ if (!deb && nodes[n].key()) deb = sim_t - t0;
+ for (int k = 1; k <= len; k++) if (!seen[k] && nodes[k].has_press(uid_of(n))) seen[k] = sim_t - t0;
+ for (int r = r0; r < n_reports; r++) if (reports[r].uid == uid_of(n) && reports[r].down) rep = reports[r].t - t0;
+ if (sim_t - t0 > 60 * PS_MS) nodes[n].button = 0;
+ }
+ nodes[n].button = 0;
+ printf(" press %2d at %.1f ms: debounced %.1f", p, t0 / 1e9, deb / 1e9);
+ for (int k = len; k >= 1; k--) printf(" kb%d %.1f", k, seen[k] / 1e9);
+ printf(" reported %.1f ms\n", rep / 1e9);
+ run_until(sim_t + (100 + rnd() % 100) * PS_MS);
+ }
+}
+
+static void sc_fast(int presses_n)
+{
+ printf("fast taps, chain of 5\n");
+ reset_world();
+ for (int i = 1; i <= 5; i++) add_keybit(i, 0, 0);
+ build();
+ settle("fast");
+ type_keys(presses_n, 15, 30);
+ report_latency("fast", 8);
+ finish();
}
/* How often the first Keybit answers an address at each bus speed. */
static void sc_speed(void)
{
- extern int kw_probe_left, kw_probe_acks;
+ extern int kw_probe_left, kw_probe_acks, kw_probe_read;
+ kw_probe_read = getenv("PROBE_READ") != NULL; /* I2CRD 0a 00 4 instead of I2CSCAN */
extern int64_t kw_probe_half;
printf("speed (1 direct + 3 chained)\n");
reset_world();
for (int i = 1; i <= 4; i++) add_keybit(i, 0, 0);
build();
CHECK(wait_present(10000 * PS_MS) >= 0, "not every Keybit showed up");
- static const int khz[] = { 20, 25, 28, 30, 32, 35, 40 };
- for (int i = 0; i < 7; i++) {
+ static const int khz[] = { 10, 15, 20, 25, 35, 50 };
+ for (int i = 0; i < 6; i++) {
kw_probe_half = PS_MS / khz[i] / 2;
kw_probe_acks = 0;
kw_probe_left = 20;
@@ -656,9 +878,6 @@ int main(int argc, char **argv)
snprintf(tmpdir, sizeof(tmpdir), "/tmp/keybit-sim-XXXXXX");
if (!mkdtemp(tmpdir)) return 1;
const char *e;
- if ((e = getenv("KW_KEYS_MS"))) kw_keys_ms = atoi(e);
- if ((e = getenv("KW_RELAY_MS"))) kw_relay_ms = atoi(e);
- if ((e = getenv("KW_SCAN_MS"))) kw_scan_ms = atoi(e);
if ((e = getenv("OP_CYCLES"))) op_cycles = atoi(e);
if ((e = getenv("SPIN_CYCLES"))) spin_cycles = atoi(e);
if ((e = getenv("PASS_CYCLES"))) pass_cycles = atoi(e);
@@ -667,8 +886,29 @@ int main(int argc, char **argv)
const char *sc = argc > 2 ? argv[2] : "chain";
int len = argc > 3 ? atoi(argv[3]) : 5;
int np = argc > 4 ? atoi(argv[4]) : 40;
- if (!strcmp(sc, "chain")) sc_chain(len, np);
+ static const char *suite[] = { "chain", "turns", "square", "block", "reversed", "joinleave", "bounce", "fast" };
+ int all = !strcmp(sc, "all");
+ for (int i = 0; i < (int)(sizeof(suite) / sizeof(suite[0])); i++) {
+ if (!all && strcmp(sc, suite[i])) continue;
+ pid_t pid = all ? fork() : 0; /* each scenario in its own process: the Keyword keeps state */
+ if (pid == 0) {
+ if (i == 0) sc_chain(len, np);
+ if (i == 1) sc_turns(len, np);
+ if (i == 2) sc_square(np);
+ if (i == 3) sc_block(np);
+ if (i == 4) sc_reversed(np);
+ if (i == 5) sc_joinleave(np);
+ if (i == 6) sc_bounce(np);
+ if (i == 7) sc_fast(np);
+ if (all) { fflush(stdout); _exit(fails != 0); }
+ } else {
+ int st;
+ waitpid(pid, &st, 0);
+ if (!WIFEXITED(st) || WEXITSTATUS(st)) fails++;
+ }
+ }
if (!strcmp(sc, "speed")) sc_speed();
+ if (!strcmp(sc, "trace")) sc_trace(len, np);
char cmd[600];
snprintf(cmd, sizeof(cmd), "rm -rf '%s'", tmpdir);
system(cmd);
diff --git a/firmware/sim/sim_base b/firmware/sim/sim_base
new file mode 100755
index 0000000..6c22880
Binary files /dev/null and b/firmware/sim/sim_base differ
diff --git a/firmware/sim/stm32wbxx_hal.h b/firmware/sim/stm32wbxx_hal.h
index 27113a7..6d90c65 100644
--- a/firmware/sim/stm32wbxx_hal.h
+++ b/firmware/sim/stm32wbxx_hal.h
@@ -14,6 +14,11 @@ typedef struct { int unused; } GPIO_TypeDef;
typedef struct { uint32_t Pin, Mode, Pull, Speed; } GPIO_InitTypeDef;
typedef struct { volatile uint32_t KR; } IWDG_TypeDef;
+typedef struct { volatile uint32_t CYCCNT; } DWT_TypeDef;
+DWT_TypeDef *sim_dwt(void);
+#define DWT (sim_dwt())
+uint32_t HAL_RCC_GetHCLKFreq(void);
+
extern GPIO_TypeDef sim_gpiob;
extern IWDG_TypeDef sim_iwdg;
#define GPIOB (&sim_gpiob)