From a487521cb6fe5e64100bf813daf80b286ca541ae Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Wed, 18 Nov 2026 10:04:46 -0600 Subject: [PATCH 1/3] process-node 0.3.2: RS-485 mock, a Modbus RTU device behind a transceiver model `modbus start [fmt] [delay ] [de on|off]` turns USART3 (LA8 -> PC11 as DI, PC10 -> LA7 as RO) into an RS-485 bus with one Modbus RTU device, with the LA6 wire into PA8 as the transceiver's DE + /RE. With DE honored, a byte the pod sends while DE is low never reaches the device and a reply byte while DE is high never reaches the pod, so a master's direction handling is tested as on a real bus; `de off` models an automatic-direction transceiver. modbus.c: functions 01/03/04/05/06/08/0F/10, exceptions 01-03, broadcast, CRC; frames by t3.5 silence, dropped on a t1.5 gap or a framing / parity error. Host-tested in tests/test_modbus.c. Co-Authored-By: Claude Opus 5.5 --- process-node-stm32/Makefile | 4 +- process-node-stm32/bench_cmds.c | 116 ++++++++++++++++ process-node-stm32/main.c | 5 +- process-node-stm32/modbus.c | 158 ++++++++++++++++++++++ process-node-stm32/modbus.h | 51 +++++++ process-node-stm32/rs485mock.c | 177 +++++++++++++++++++++++++ process-node-stm32/rs485mock.h | 50 +++++++ process-node-stm32/tests/test_modbus.c | 120 +++++++++++++++++ process-node-stm32/uart3.c | 11 ++ process-node-stm32/uart3.h | 3 + 10 files changed, 693 insertions(+), 2 deletions(-) create mode 100644 process-node-stm32/modbus.c create mode 100644 process-node-stm32/modbus.h create mode 100644 process-node-stm32/rs485mock.c create mode 100644 process-node-stm32/rs485mock.h create mode 100644 process-node-stm32/tests/test_modbus.c diff --git a/process-node-stm32/Makefile b/process-node-stm32/Makefile index 8b0583b..5229593 100644 --- a/process-node-stm32/Makefile +++ b/process-node-stm32/Makefile @@ -46,7 +46,7 @@ LDFLAGS := \ -specs=nano.specs \ -specs=nosys.specs -APP_SRCS := main.c rl78emu.c rl78emu_port.c analog.c env.c i2cbus.c i2ctarget.c spi2.c uart3.c bench_cmds.c mcp2515.c syscalls.c sysmem.c system_stm32f4xx.c +APP_SRCS := main.c rl78emu.c rl78emu_port.c modbus.c rs485mock.c analog.c env.c i2cbus.c i2ctarget.c spi2.c uart3.c bench_cmds.c mcp2515.c syscalls.c sysmem.c system_stm32f4xx.c HAL_SRCS := \ stm32f4xx_hal.c \ @@ -104,5 +104,7 @@ test-host: | $(BUILD_DIR) $(BUILD_DIR)/test_proc $(HOSTCC) -std=c11 -Wall -Wextra -Werror -I. tests/test_rl78emu.c rl78emu.c -o $(BUILD_DIR)/test_rl78emu $(BUILD_DIR)/test_rl78emu + $(HOSTCC) -std=c11 -Wall -Wextra -Werror -I. tests/test_modbus.c modbus.c -o $(BUILD_DIR)/test_modbus + $(BUILD_DIR)/test_modbus .PHONY: all clean flash test-host diff --git a/process-node-stm32/bench_cmds.c b/process-node-stm32/bench_cmds.c index 035d849..10ff592 100644 --- a/process-node-stm32/bench_cmds.c +++ b/process-node-stm32/bench_cmds.c @@ -5,6 +5,7 @@ #include "i2ctarget.h" #include "spi2.h" #include "stm32f4xx_hal.h" +#include "rs485mock.h" #include "uart3.h" #include #include @@ -527,6 +528,7 @@ static void nmea_line_done(void) void bench_service(void) { + rs485_service(); if (!g_nmea_on) { return; @@ -972,6 +974,116 @@ static void handle_env(char *args) /* ---------------------------------------------------------------- entry points */ +/* ---------------------------------------------------------------- modbus (RS-485 mock) */ + +static void print_modbus_stat(void) +{ + const rs485_stats_t *st = rs485_stats(); + const mb_slave_t *s = rs485_slave(); + printf("MODBUS stat on=%u addr=%u baud=%lu format=%s delay_us=%lu de=%u requests=%lu replies=%lu " + "exceptions=%lu crc=%lu frame=%lu other=%lu broadcast=%lu undriven=%lu collisions=%lu " + "last_fn=%02X\r\n", + st->on, s->addr, (unsigned long)st->baud, st->on ? st->format : "-", + (unsigned long)st->delay_us, st->de, (unsigned long)s->requests, (unsigned long)s->replies, + (unsigned long)s->exceptions, (unsigned long)s->crc_errors, + (unsigned long)st->frame_errors, (unsigned long)s->other_addr, + (unsigned long)s->broadcasts, (unsigned long)st->undriven, + (unsigned long)st->collisions, s->last_fn); +} + +/* modbus start [8N1|8E1|...] [delay ] [de on|off] | stop | stat | delay | reg [] */ +static void handle_modbus(char *args) +{ + char *sub = strtok(args, " "); + if (sub == NULL || strcmp(sub, "stat") == 0) + { + print_modbus_stat(); + return; + } + if (strcmp(sub, "start") == 0) + { + uint32_t addr, baud, delay = 5000U, de = 1U; + const char *fmt = "8E1"; + int bad = parse_dec(strtok(NULL, " "), &addr, 247U) != 0 || + parse_dec(strtok(NULL, " "), &baud, 1000000U) != 0; + for (char *t = strtok(NULL, " "); !bad && t != NULL; t = strtok(NULL, " ")) + { + if (strcmp(t, "delay") == 0) + { + bad = parse_dec(strtok(NULL, " "), &delay, 100000U) != 0; + } + else if (strcmp(t, "de") == 0) + { + const char *v = strtok(NULL, " "); + bad = v == NULL || (strcmp(v, "on") != 0 && strcmp(v, "off") != 0); + de = (v != NULL && strcmp(v, "on") == 0) ? 1U : 0U; + } + else if (strlen(t) == 3U && t[0] == '8' && (t[2] == '1' || t[2] == '2')) + { + fmt = t; + } + else + { + bad = 1; + } + } + if (!bad && de && !strobe_is_off()) + { + printf("MODBUS err PA8 is the strobe: strobe off first (PA8 reads DE)\r\n"); + return; + } + if (bad || rs485_start((uint8_t)addr, baud, fmt[1], (uint8_t)(fmt[2] - '0'), delay, (uint8_t)de) != 0) + { + printf("MODBUS err usage: modbus start <1..247> <1200..1000000> [8N1|8E1|8O1|8N2|8E2|8O2] " + "[delay <0..100000 us>] [de on|off]\r\n"); + return; + } + printf("MODBUS ok on addr=%lu baud=%lu format=%s delay_us=%lu de=%s\r\n", (unsigned long)addr, + (unsigned long)baud, fmt, (unsigned long)delay, de ? "on" : "off"); + return; + } + if (strcmp(sub, "stop") == 0) + { + rs485_stop(); + printf("MODBUS ok off\r\n"); + return; + } + if (strcmp(sub, "delay") == 0) + { + uint32_t d; + if (parse_dec(strtok(NULL, " "), &d, 100000U) != 0) + { + printf("MODBUS err usage: modbus delay <0..100000 us>\r\n"); + return; + } + rs485_set_delay(d); + printf("MODBUS ok delay_us=%lu\r\n", (unsigned long)d); + return; + } + if (strcmp(sub, "reg") == 0) + { + uint32_t i, v; + int bad = parse_dec(strtok(NULL, " "), &i, MB_HOLD_REGS - 1U) != 0; + const char *vs = bad ? NULL : strtok(NULL, " "); + if (!bad && vs != NULL) + { + bad = parse_dec(vs, &v, 0xFFFFU) != 0; + if (!bad) + { + rs485_slave()->hold[i] = (uint16_t)v; + } + } + if (bad) + { + printf("MODBUS err usage: modbus reg <0..63> [<0..65535>]\r\n"); + return; + } + printf("MODBUS reg i=%lu v=%u\r\n", (unsigned long)i, rs485_slave()->hold[i]); + return; + } + printf("MODBUS err usage: modbus start|stop|stat|delay|reg\r\n"); +} + void bench_init(void) { dwt_init(); @@ -1005,6 +1117,10 @@ int bench_command(char *cmd) { handle_uart3(args); } + else if (is_cmd(cmd, "modbus", &args)) + { + handle_modbus(args); + } else if (is_cmd(cmd, "drdy", &args)) { handle_drdy(args); diff --git a/process-node-stm32/main.c b/process-node-stm32/main.c index 708c287..ae6d27e 100644 --- a/process-node-stm32/main.c +++ b/process-node-stm32/main.c @@ -44,7 +44,7 @@ #include #define FW_NAME "process-node" -#define FW_VERSION "0.3.1" +#define FW_VERSION "0.3.2" #define CMD_BUF_SIZE 200 @@ -843,6 +843,9 @@ static void print_help(void) printf(" uart3 read [t ] [n ] [until ] bytes from PC11 (hex and text)\r\n"); printf(" uart3 nmea [on|off] print each NMEA sentence from PC11 with its checksum check\r\n"); printf(" drdy | drdy wait rise|fall|high|low [ms] | drdy count PA8 data ready (strobe off)\r\n"); + printf(" modbus start [8E1..] [delay ] [de on|off] | stop | stat | delay | reg []\r\n"); + printf(" RS-485 mock: a Modbus RTU device on USART3, DE on PA8 (strobe off;\r\n"); + printf(" de off: an automatic-direction transceiver, no DE wire)\r\n"); printf(" status | can status counters, mode, error state\r\n"); printf(" can init [bitrate] reset + configure the MCP2515 (default 500000)\r\n"); printf(" can osc module crystal (8 or 16), then re-init\r\n"); diff --git a/process-node-stm32/modbus.c b/process-node-stm32/modbus.c new file mode 100644 index 0000000..e154cab --- /dev/null +++ b/process-node-stm32/modbus.c @@ -0,0 +1,158 @@ +/* + * modbus.c - the Modbus RTU slave of the RS-485 mock (see modbus.h). Modbus Application Protocol + * V1.1b3 for the function codes and exceptions, Modbus over Serial Line V1.02 for the RTU frame. + */ +#include "modbus.h" + +#include + +uint16_t mb_crc16(const uint8_t *p, size_t n) +{ + uint16_t crc = 0xFFFFu; + for (size_t i = 0; i < n; i++) { + crc ^= p[i]; + for (int b = 0; b < 8; b++) + crc = (crc & 1u) ? (uint16_t)((crc >> 1) ^ 0xA001u) : (uint16_t)(crc >> 1); + } + return crc; +} + +void mb_init(mb_slave_t *s, uint8_t addr) +{ + memset(s, 0, sizeof(*s)); + s->addr = addr; + for (unsigned i = 0; i < MB_INPUT_REGS; i++) + s->input[i] = (uint16_t)(0x1000u + i); +} + +static uint16_t be16(const uint8_t *p) { return (uint16_t)((p[0] << 8) | p[1]); } +static void put16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)(v >> 8); p[1] = (uint8_t)v; } + +static int coil_get(const mb_slave_t *s, unsigned i) { return (s->coil[i / 8u] >> (i % 8u)) & 1; } +static void coil_set(mb_slave_t *s, unsigned i, int on) +{ + if (on) s->coil[i / 8u] = (uint8_t)(s->coil[i / 8u] | (1u << (i % 8u))); + else s->coil[i / 8u] = (uint8_t)(s->coil[i / 8u] & ~(1u << (i % 8u))); +} + +/* in range: first .. first + qty - 1 inside a table of `size` */ +static int fits(unsigned first, unsigned qty, unsigned size) { return first < size && qty <= size - first; } + +/* The PDU (function code onwards) of request `q` (qn bytes) -> reply PDU in r. Returns its length, + or a negative exception code. */ +static int pdu(mb_slave_t *s, const uint8_t *q, size_t qn, uint8_t *r) +{ + uint8_t fn = q[0]; + r[0] = fn; + switch (fn) { + case 0x01: { /* Read Coils */ + if (qn != 5) return -MB_EX_VALUE; + unsigned first = be16(q + 1), qty = be16(q + 3); + if (qty < 1u || qty > 2000u) return -MB_EX_VALUE; + if (!fits(first, qty, MB_COILS)) return -MB_EX_ADDRESS; + unsigned nb = (qty + 7u) / 8u; + r[1] = (uint8_t)nb; + memset(r + 2, 0, nb); + for (unsigned i = 0; i < qty; i++) + if (coil_get(s, first + i)) r[2 + i / 8u] = (uint8_t)(r[2 + i / 8u] | (1u << (i % 8u))); + return (int)(2u + nb); + } + case 0x03: /* Read Holding Registers */ + case 0x04: { /* Read Input Registers */ + if (qn != 5) return -MB_EX_VALUE; + unsigned first = be16(q + 1), qty = be16(q + 3); + if (qty < 1u || qty > 125u) return -MB_EX_VALUE; + const uint16_t *tab = fn == 0x03 ? s->hold : s->input; + unsigned size = fn == 0x03 ? MB_HOLD_REGS : MB_INPUT_REGS; + if (!fits(first, qty, size)) return -MB_EX_ADDRESS; + r[1] = (uint8_t)(2u * qty); + for (unsigned i = 0; i < qty; i++) put16(r + 2 + 2u * i, tab[first + i]); + return (int)(2u + 2u * qty); + } + case 0x05: { /* Write Single Coil */ + if (qn != 5) return -MB_EX_VALUE; + unsigned a = be16(q + 1), v = be16(q + 3); + if (v != 0xFF00u && v != 0x0000u) return -MB_EX_VALUE; + if (a >= MB_COILS) return -MB_EX_ADDRESS; + coil_set(s, a, v == 0xFF00u); + memcpy(r, q, 5); + return 5; + } + case 0x06: { /* Write Single Register */ + if (qn != 5) return -MB_EX_VALUE; + unsigned a = be16(q + 1); + if (a >= MB_HOLD_REGS) return -MB_EX_ADDRESS; + s->hold[a] = be16(q + 3); + memcpy(r, q, 5); + return 5; + } + case 0x08: { /* Diagnostics */ + if (qn < 3) return -MB_EX_VALUE; + if (be16(q + 1) != 0x0000u) return -MB_EX_FUNCTION; /* only "return query data" */ + memcpy(r, q, qn); + return (int)qn; + } + case 0x0F: { /* Write Multiple Coils */ + if (qn < 6) return -MB_EX_VALUE; + unsigned first = be16(q + 1), qty = be16(q + 3), nb = q[5]; + if (qty < 1u || qty > 1968u || nb != (qty + 7u) / 8u || qn != 6u + nb) return -MB_EX_VALUE; + if (!fits(first, qty, MB_COILS)) return -MB_EX_ADDRESS; + for (unsigned i = 0; i < qty; i++) coil_set(s, first + i, (q[6 + i / 8u] >> (i % 8u)) & 1); + memcpy(r, q, 5); + return 5; + } + case 0x10: { /* Write Multiple Registers */ + if (qn < 6) return -MB_EX_VALUE; + unsigned first = be16(q + 1), qty = be16(q + 3), nb = q[5]; + if (qty < 1u || qty > 123u || nb != 2u * qty || qn != 6u + nb) return -MB_EX_VALUE; + if (!fits(first, qty, MB_HOLD_REGS)) return -MB_EX_ADDRESS; + for (unsigned i = 0; i < qty; i++) s->hold[first + i] = be16(q + 6 + 2u * i); + memcpy(r, q, 5); + return 5; + } + default: + return -MB_EX_FUNCTION; + } +} + +size_t mb_frame(mb_slave_t *s, const uint8_t *f, size_t n, uint8_t *out) +{ + if (n < 4u || n > MB_FRAME_MAX) { + s->crc_errors++; + return 0; + } + uint16_t crc = mb_crc16(f, n - 2u); + if (f[n - 2u] != (uint8_t)crc || f[n - 1u] != (uint8_t)(crc >> 8)) { + s->crc_errors++; + return 0; + } + uint8_t a = f[0]; + if (a != 0u && a != s->addr) { + s->other_addr++; + return 0; + } + s->requests++; + s->last_fn = f[1]; + uint8_t r[MB_FRAME_MAX]; + int len = pdu(s, f + 1, n - 3u, r); + if (a == 0u) { /* broadcast: done, never answered */ + s->broadcasts++; + return 0; + } + size_t rn; + out[0] = s->addr; + if (len < 0) { + s->exceptions++; + out[1] = (uint8_t)(f[1] | 0x80u); + out[2] = (uint8_t)(-len); + rn = 3; + } else { + memcpy(out + 1, r, (size_t)len); + rn = 1u + (size_t)len; + } + crc = mb_crc16(out, rn); + out[rn] = (uint8_t)crc; + out[rn + 1u] = (uint8_t)(crc >> 8); + s->replies++; + return rn + 2u; +} diff --git a/process-node-stm32/modbus.h b/process-node-stm32/modbus.h new file mode 100644 index 0000000..cb19427 --- /dev/null +++ b/process-node-stm32/modbus.h @@ -0,0 +1,51 @@ +/* + * modbus.h - a Modbus RTU slave (server), the device end of the node's RS-485 mock (rs485mock.c). + * + * The protocol only: a whole frame in (address, PDU, CRC), the reply out. Pure C, no HAL, so + * tests/test_modbus.c runs it on the host. Function codes: + * + * 01 Read Coils, 03 Read Holding Registers, 04 Read Input Registers, 05 Write Single Coil, + * 06 Write Single Register, 08 Diagnostics (sub-function 0000, return query data), + * 0F Write Multiple Coils, 10 Write Multiple Registers. + * + * Anything else is exception 01, an address outside the tables 02, a bad quantity, byte count or + * coil value 03. Address 0 is a broadcast: writes are done, nothing is answered. A frame for + * another address, or with a bad CRC, gets no answer either (Modbus over Serial Line V1.02). + */ +#ifndef MODBUS_H +#define MODBUS_H + +#include +#include + +#define MB_HOLD_REGS 64u /* holding registers 0..63, 0 at start */ +#define MB_INPUT_REGS 16u /* input registers 0..15, 1000H + index */ +#define MB_COILS 64u /* coils 0..63, off at start */ +#define MB_FRAME_MAX 256u /* RTU ADU limit */ + +#define MB_EX_FUNCTION 0x01u +#define MB_EX_ADDRESS 0x02u +#define MB_EX_VALUE 0x03u + +typedef struct { + uint8_t addr; + uint16_t hold[MB_HOLD_REGS]; + uint16_t input[MB_INPUT_REGS]; + uint8_t coil[MB_COILS / 8u]; + /* counters */ + uint32_t requests; /* good frames for this address (or broadcast) */ + uint32_t replies; + uint32_t exceptions; + uint32_t crc_errors; /* also frames shorter than 4 bytes */ + uint32_t other_addr; /* good frames for another slave */ + uint32_t broadcasts; + uint8_t last_fn; +} mb_slave_t; + +void mb_init(mb_slave_t *s, uint8_t addr); +/* Modbus CRC-16 (polynomial A001H reflected, start FFFFH); sent low byte first. */ +uint16_t mb_crc16(const uint8_t *p, size_t n); +/* One frame. Returns the reply's length in out (MB_FRAME_MAX bytes), 0 for no reply. */ +size_t mb_frame(mb_slave_t *s, const uint8_t *f, size_t n, uint8_t *out); + +#endif diff --git a/process-node-stm32/rs485mock.c b/process-node-stm32/rs485mock.c new file mode 100644 index 0000000..e8fe6c3 --- /dev/null +++ b/process-node-stm32/rs485mock.c @@ -0,0 +1,177 @@ +/* + * rs485mock.c - the RS-485 bus and Modbus RTU device of rs485mock.h, on USART3 and PA8 (DE). + */ +#include "rs485mock.h" + +#include + +#include "dwt.h" +#include "stm32f4xx_hal.h" +#include "uart3.h" + +#define DE_PORT GPIOA +#define DE_PIN GPIO_PIN_8 +#define DELAY_MAX_US 100000U + +static mb_slave_t s_mb; +static rs485_stats_t s_st; + +/* the frame being received (USART3 interrupt) and the one waiting for the main loop */ +static volatile uint8_t s_rx[MB_FRAME_MAX]; +static volatile uint16_t s_rx_len; +static volatile uint8_t s_rx_bad; +static volatile uint32_t s_rx_last; /* cycle count of the last byte */ +static uint32_t s_char_cyc, s_t15_cyc, s_t35_cyc; + +static int de_high(void) +{ + return (DE_PORT->IDR & DE_PIN) != 0U; +} + +static void on_byte(uint8_t b, uint32_t sr) +{ + if (s_st.de && !de_high()) + { + s_st.undriven++; /* the pod's driver was off: the byte never reached the bus */ + return; + } + uint32_t now = dwt_cycles(); + if (s_rx_len > 0U && now - s_rx_last > s_t15_cyc) + { + s_rx_bad = 1U; /* a gap inside the frame (the main loop ends frames at 3.5) */ + } + if (sr & (USART_SR_FE | USART_SR_PE | USART_SR_NE | USART_SR_ORE)) + { + s_rx_bad = 1U; + } + if (s_rx_len < MB_FRAME_MAX) + { + s_rx[s_rx_len++] = b; + } + else + { + s_rx_bad = 1U; + } + s_rx_last = now; +} + +static uint32_t us_to_cyc(uint32_t us) +{ + return us * (SystemCoreClock / 1000000U); +} + +int rs485_start(uint8_t addr, uint32_t baud, char parity, uint8_t stop_bits, uint32_t delay_us, + uint8_t de) +{ + if (addr < 1U || addr > 247U || delay_us > DELAY_MAX_US) + { + return -1; + } + rs485_stop(); + if (uart3_open_format(baud, parity, stop_bits) != 0) + { + return -1; + } + dwt_init(); + mb_init(&s_mb, addr); + memset(&s_st, 0, sizeof(s_st)); + s_st.on = 1U; + s_st.baud = baud; + s_st.format[0] = '8'; + s_st.format[1] = parity; + s_st.format[2] = (char)('0' + stop_bits); + s_st.delay_us = delay_us; + s_st.de = de ? 1U : 0U; + uint32_t bits = 1U + 8U + (parity != 'N' ? 1U : 0U) + stop_bits; + s_char_cyc = (uint32_t)(((uint64_t)SystemCoreClock * bits) / baud); + /* above 19200 baud the spec fixes t1.5 = 750 us and t3.5 = 1750 us */ + s_t15_cyc = baud > 19200U ? us_to_cyc(750U) : (s_char_cyc * 3U) / 2U; + s_t35_cyc = baud > 19200U ? us_to_cyc(1750U) : (s_char_cyc * 7U) / 2U; + s_rx_len = 0U; + s_rx_bad = 0U; + uart3_set_rx_hook(on_byte); + return 0; +} + +void rs485_stop(void) +{ + if (!s_st.on) + { + return; + } + uart3_set_rx_hook(NULL); + uart3_close(); + s_st.on = 0U; +} + +void rs485_set_delay(uint32_t delay_us) +{ + s_st.delay_us = delay_us > DELAY_MAX_US ? DELAY_MAX_US : delay_us; +} + +const rs485_stats_t *rs485_stats(void) +{ + return &s_st; +} + +mb_slave_t *rs485_slave(void) +{ + return &s_mb; +} + +static void wait_until(uint32_t start, uint32_t cycles) +{ + while (dwt_cycles() - start < cycles) + { + } +} + +void rs485_service(void) +{ + if (!s_st.on || s_rx_len == 0U) + { + return; + } + /* the frame ends after 3.5 characters of silence */ + NVIC_DisableIRQ(USART3_IRQn); + uint32_t last = s_rx_last; + if (dwt_cycles() - last <= s_t35_cyc) + { + NVIC_EnableIRQ(USART3_IRQn); + return; + } + uint8_t f[MB_FRAME_MAX]; + uint16_t n = s_rx_len; + uint8_t bad = s_rx_bad; + memcpy(f, (const uint8_t *)s_rx, n); + s_rx_len = 0U; + s_rx_bad = 0U; + NVIC_EnableIRQ(USART3_IRQn); + if (bad) + { + s_st.frame_errors++; + return; + } + uint8_t reply[MB_FRAME_MAX]; + size_t rn = mb_frame(&s_mb, f, n, reply); + if (rn == 0U) + { + return; + } + /* answer delay_us after the request ended, never inside the 3.5-character silence */ + uint32_t wait = us_to_cyc(s_st.delay_us); + wait_until(last, wait > s_t35_cyc ? wait : s_t35_cyc); + for (size_t i = 0; i < rn; i++) + { + uint32_t t = dwt_cycles(); + if (s_st.de && de_high()) + { + /* the pod is still driving the bus with its receiver off: this byte is lost to it + (and collides on a real bus), but it takes its time on the wire all the same */ + s_st.collisions++; + wait_until(t, s_char_cyc); + continue; + } + uart3_write(&reply[i], 1U); + } +} diff --git a/process-node-stm32/rs485mock.h b/process-node-stm32/rs485mock.h new file mode 100644 index 0000000..56adfb8 --- /dev/null +++ b/process-node-stm32/rs485mock.h @@ -0,0 +1,50 @@ +/* + * rs485mock.h - an RS-485 bus with one Modbus RTU device on it, as a half-duplex transceiver + * would present it to the pod, on the bench's TTL wires: + * + * transceiver DI (the pod sends) LA8 -> PC11, USART3 RX + * transceiver RO (the pod listens) LA7 <- PC10, USART3 TX + * transceiver DE + /RE LA6 -> PA8 (through 1 kOhm; pulled down, so it listens) + * + * The rules a real transceiver enforces, so a master's direction handling is tested too: + * - a byte from the pod reaches the bus only while DE is high (sampled as the byte completes); + * others are counted as `undriven` and never reach the device; + * - the device's reply reaches the pod only while DE is low (DE high also turns the pod's + * receiver off); a reply byte sent while DE is high is lost and counted as a `collision`. + * + * With `de off` the DE rules are not applied: a transceiver with automatic direction control (it + * turns its driver on while its DI input is active), so only the protocol is tested. + * + * Frames are delimited by 3.5 characters of silence (1750 us above 19200 baud); a gap of more than + * 1.5 characters inside a frame, a framing or parity error drops it (Modbus over Serial Line + * V1.02). The device (modbus.c) answers `delay_us` after the request, never sooner than 3.5 + * characters. Console: `modbus start|stop|stat|reg|delay` (bench_cmds.c help). + */ +#ifndef RS485MOCK_H +#define RS485MOCK_H + +#include + +#include "modbus.h" + +typedef struct { + uint8_t on; + uint32_t baud; + char format[4]; + uint32_t delay_us; + uint8_t de; /* 1: DE on PA8 is honored; 0: automatic direction (no DE wire) */ + uint32_t undriven; /* bytes from the pod while DE was low: not on the bus */ + uint32_t collisions; /* reply bytes while DE was high: the pod could not hear them */ + uint32_t frame_errors; /* a gap over 1.5 characters, a framing / parity error, too long */ +} rs485_stats_t; + +int rs485_start(uint8_t addr, uint32_t baud, char parity, uint8_t stop_bits, uint32_t delay_us, + uint8_t de); +void rs485_stop(void); +void rs485_set_delay(uint32_t delay_us); +/* Main loop: end of frame detection and the reply. */ +void rs485_service(void); +const rs485_stats_t *rs485_stats(void); +mb_slave_t *rs485_slave(void); + +#endif diff --git a/process-node-stm32/tests/test_modbus.c b/process-node-stm32/tests/test_modbus.c new file mode 100644 index 0000000..a04974c --- /dev/null +++ b/process-node-stm32/tests/test_modbus.c @@ -0,0 +1,120 @@ +/* Host unit test for modbus.c, the Modbus RTU slave of the RS-485 mock: CRC, every function + * code, the exceptions, broadcast and other addresses. Run: make test-host */ +#include "modbus.h" + +#include +#include +#include + +static int failures; +#define CHECK(c, ...) do { if (!(c)) { printf("FAIL %s:%d: ", __func__, __LINE__); \ + printf(__VA_ARGS__); printf("\n"); failures++; } } while (0) + +static mb_slave_t S; +static uint8_t out[MB_FRAME_MAX]; + +/* Send the bytes given (address + PDU), with the CRC appended; returns the reply length. */ +static size_t req(int n, ...) +{ + uint8_t f[MB_FRAME_MAX]; + va_list ap; + va_start(ap, n); + for (int i = 0; i < n; i++) f[i] = (uint8_t)va_arg(ap, int); + va_end(ap); + uint16_t c = mb_crc16(f, (size_t)n); + f[n] = (uint8_t)c; + f[n + 1] = (uint8_t)(c >> 8); + return mb_frame(&S, f, (size_t)n + 2u, out); +} + +static int crc_ok(size_t n) +{ + uint16_t c = mb_crc16(out, n - 2u); + return out[n - 2u] == (uint8_t)c && out[n - 1u] == (uint8_t)(c >> 8); +} + +static int exception(size_t n, int fn, int code) +{ + return n == 5 && out[0] == S.addr && out[1] == (fn | 0x80) && out[2] == code && crc_ok(n); +} + +static void test_crc(void) +{ + /* the spec's example: 02 07 -> CRC 1241H, sent 41 12 */ + const uint8_t a[] = {0x02, 0x07}; + CHECK(mb_crc16(a, 2) == 0x1241, "crc %04x", mb_crc16(a, 2)); + /* a well-known read request: 01 03 00 00 00 01 -> 84 0A */ + const uint8_t b[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x01}; + CHECK(mb_crc16(b, 6) == 0x0A84, "crc %04x", mb_crc16(b, 6)); +} + +static void test_registers(void) +{ + mb_init(&S, 1); + size_t n = req(6, 1, 0x03, 0, 0, 0, 2); + CHECK(n == 9 && out[2] == 4 && out[3] == 0 && out[6] == 0 && crc_ok(n), "read holding"); + n = req(6, 1, 0x06, 0, 5, 0x12, 0x34); + CHECK(n == 8 && out[1] == 0x06 && out[4] == 0x12 && out[5] == 0x34 && S.hold[5] == 0x1234, "write single"); + n = req(11, 1, 0x10, 0, 10, 0, 2, 4, 0xAB, 0xCD, 0x00, 0x01); + CHECK(n == 8 && out[1] == 0x10 && out[5] == 2 && S.hold[10] == 0xABCD && S.hold[11] == 1, "write multiple"); + n = req(6, 1, 0x03, 0, 10, 0, 2); + CHECK(n == 9 && out[3] == 0xAB && out[4] == 0xCD && out[5] == 0 && out[6] == 1, "read back"); + n = req(6, 1, 0x04, 0, 14, 0, 2); + CHECK(n == 9 && out[3] == 0x10 && out[4] == 0x0E && out[5] == 0x10 && out[6] == 0x0F, "input regs"); + /* the last register is fine, one past it is not */ + CHECK(req(6, 1, 0x03, 0, 63, 0, 1) == 7, "last holding register"); + CHECK(exception(req(6, 1, 0x03, 0, 63, 0, 2), 0x03, MB_EX_ADDRESS), "past the end"); + CHECK(exception(req(6, 1, 0x04, 0, 16, 0, 1), 0x04, MB_EX_ADDRESS), "input past the end"); + CHECK(exception(req(6, 1, 0x03, 0, 0, 0, 0), 0x03, MB_EX_VALUE), "quantity 0"); + CHECK(exception(req(6, 1, 0x03, 0, 0, 0, 126), 0x03, MB_EX_VALUE), "quantity 126"); + CHECK(exception(req(6, 1, 0x06, 0, 64, 0, 1), 0x06, MB_EX_ADDRESS), "write past the end"); + CHECK(exception(req(11, 1, 0x10, 0, 0, 0, 2, 3, 0, 0, 0, 0), 0x10, MB_EX_VALUE), "byte count"); +} + +static void test_coils(void) +{ + mb_init(&S, 7); + size_t n = req(6, 7, 0x05, 0, 3, 0xFF, 0x00); + CHECK(n == 8 && out[4] == 0xFF, "coil 3 on"); + n = req(9, 7, 0x0F, 0, 8, 0, 10, 2, 0x05, 0x02); /* coils 8..17: 8, 10 and 17 on */ + CHECK(n == 8 && out[1] == 0x0F, "write coils"); + n = req(6, 7, 0x01, 0, 0, 0, 20); + CHECK(n == 8 && out[2] == 3 && out[3] == 0x08 && out[4] == 0x05 && out[5] == 0x02 && crc_ok(n), + "read coils %02x %02x %02x", out[3], out[4], out[5]); + CHECK(exception(req(6, 7, 0x05, 0, 0, 0x12, 0x34), 0x05, MB_EX_VALUE), "coil value 1234H"); + CHECK(exception(req(6, 7, 0x01, 0, 60, 0, 5), 0x01, MB_EX_ADDRESS), "coils past the end"); +} + +static void test_diagnostics_and_unknown(void) +{ + mb_init(&S, 1); + size_t n = req(6, 1, 0x08, 0, 0, 0xA5, 0x37); + CHECK(n == 8 && out[1] == 0x08 && out[4] == 0xA5 && out[5] == 0x37, "echo"); + CHECK(exception(req(6, 1, 0x08, 0, 1, 0, 0), 0x08, MB_EX_FUNCTION), "sub-function 1"); + CHECK(exception(req(2, 1, 0x2B), 0x2B, MB_EX_FUNCTION), "function 2BH"); + CHECK(S.exceptions == 2 && S.replies == 3, "counters %u %u", (unsigned)S.exceptions, (unsigned)S.replies); +} + +static void test_addressing_and_crc(void) +{ + mb_init(&S, 1); + CHECK(req(6, 2, 0x03, 0, 0, 0, 1) == 0 && S.other_addr == 1, "another slave answered"); + CHECK(req(6, 0, 0x06, 0, 1, 0, 9) == 0 && S.hold[1] == 9 && S.broadcasts == 1, "broadcast write"); + uint8_t f[] = {1, 0x03, 0, 0, 0, 1, 0x84, 0x0B}; /* last CRC byte off by one */ + CHECK(mb_frame(&S, f, sizeof(f), out) == 0 && S.crc_errors == 1, "bad CRC answered"); + CHECK(mb_frame(&S, f, 3, out) == 0 && S.crc_errors == 2, "a 3-byte frame"); + f[7] = 0x0A; + CHECK(mb_frame(&S, f, sizeof(f), out) == 7, "good CRC refused"); +} + +int main(void) +{ + test_crc(); + test_registers(); + test_coils(); + test_diagnostics_and_unknown(); + test_addressing_and_crc(); + if (failures) { printf("test_modbus: %d FAILED\n", failures); return 1; } + printf("test_modbus: all passed\n"); + return 0; +} diff --git a/process-node-stm32/uart3.c b/process-node-stm32/uart3.c index 5c04a58..84937bb 100644 --- a/process-node-stm32/uart3.c +++ b/process-node-stm32/uart3.c @@ -10,6 +10,7 @@ static volatile uint16_t g_head; static volatile uint16_t g_tail; static volatile uart3_stats_t g_st; static volatile uint8_t g_echo; +static void (*volatile g_hook)(uint8_t byte, uint32_t sr); static void pins_input(void) { @@ -128,6 +129,11 @@ uint16_t uart3_pending(void) return (uint16_t)((g_head + UART3_RING_SIZE - g_tail) % UART3_RING_SIZE); } +void uart3_set_rx_hook(void (*hook)(uint8_t byte, uint32_t sr)) +{ + g_hook = hook; +} + void uart3_set_echo(uint8_t on) { g_echo = on; @@ -165,6 +171,11 @@ void USART3_IRQHandler(void) continue; } g_st.rx_total++; + if (g_hook != NULL) + { + g_hook(byte, sr); + continue; + } if (g_echo && (USART3->SR & USART_SR_TXE)) { USART3->DR = byte; /* same baud both ways, so TX keeps up byte for byte */ diff --git a/process-node-stm32/uart3.h b/process-node-stm32/uart3.h index ecef8e3..e9a6c1c 100644 --- a/process-node-stm32/uart3.h +++ b/process-node-stm32/uart3.h @@ -37,5 +37,8 @@ uint16_t uart3_pending(void); void uart3_flush(void); /* Echo every received byte straight back on TX (from the interrupt), for loopback tests. */ void uart3_set_echo(uint8_t on); +/* Hand every received byte (with the status register it came with) to hook, from the interrupt, + instead of the ring: the RS-485 mock (rs485mock.c) times its frames this way. NULL: the ring. */ +void uart3_set_rx_hook(void (*hook)(uint8_t byte, uint32_t sr)); #endif From a4325f930ecbfd26bb81bcb056392ac460dbd719 Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Wed, 18 Nov 2026 10:04:48 -0600 Subject: [PATCH 2/3] process-node: Modbus RTU over RS-485 HIL tests against the mock tests/modbus_master.py and tests/test_rs485.py (marker rs485): registers, coils, exceptions, silent cases, four frame formats, a parity mismatch, DE never raised / released too early / too late, the docs page's example, and the turnaround a host-switched DE allows (measured: ~25 ms DE release lag on LAN; devices answering after >= 30 ms work, 20 ms 2/10, 5 ms never). Co-Authored-By: Claude Opus 5.5 --- process-node-stm32/README.md | 36 +++ process-node-stm32/tests/conftest.py | 1 + process-node-stm32/tests/modbus_master.py | 162 ++++++++++++++ process-node-stm32/tests/test_rs485.py | 254 ++++++++++++++++++++++ 4 files changed, 453 insertions(+) create mode 100644 process-node-stm32/tests/modbus_master.py create mode 100644 process-node-stm32/tests/test_rs485.py diff --git a/process-node-stm32/README.md b/process-node-stm32/README.md index e6d680c..f427f5a 100644 --- a/process-node-stm32/README.md +++ b/process-node-stm32/README.md @@ -164,6 +164,42 @@ verify and checksum, data flash, parameter errors, every baud rate, security, an afterwards. The protocol core (`rl78emu.c`) is also covered on the host by `tests/test_rl78emu.c` (`make test-host`). +## RS-485 mock (Modbus RTU) + +`modbus start [8E1|8N2|...] [delay ] [de on|off]` turns USART3 into an RS-485 +bus with one Modbus RTU device on it, as a half-duplex transceiver presents it to the pod. It +uses the wires the UART sensors use, plus the LA6 data-ready wire as the transceiver's DE: + +| Transceiver | Pod | Node | +| --- | --- | --- | +| DI (the pod sends) | LA8 | PC11, USART3 RX | +| RO (the pod listens) | LA7 | PC10, USART3 TX | +| DE + /RE | LA6 (GPIO) | PA8, through 1 kOhm (strobe off) | + +- The device: holding registers 0-63 (0 at start), input registers 0-15 (1000H + index), coils + 0-63; functions 01, 03, 04, 05, 06, 08 (return query data), 0F and 10; exceptions 01, 02 and + 03; broadcasts (address 0) are carried out and not answered; a bad CRC or another address gets + no answer. `modbus reg []` reads or sets a holding register from the console. +- Frames end after 3.5 characters of silence (1750 us above 19200 baud); a gap of more than 1.5 + characters, or a framing or parity error, drops the frame. The device answers `delay` us after + the request (default 5000), never sooner than 3.5 characters. +- With `de on` the transceiver's rules apply: a byte the pod sends while DE is low never reaches + the device (`undriven`), and a reply byte while DE is still high never reaches the pod + (`collisions`), as the pod's receiver is off then. `de off` is a transceiver with automatic + direction control: no DE wire, only the protocol is tested. +- `modbus stat` reports the requests, replies, exceptions, CRC and frame errors, other addresses, + broadcasts, `undriven` bytes and `collisions`. + +`tests/modbus_master.py` is a Modbus RTU master over the pod, and `tests/test_rs485.py` (marker +`rs485`, BENCH_NEW_WIRING=1 BENCH_LA6_RESISTOR=1) runs it: registers, coils, exceptions, the silent +cases, four frame formats, a parity mismatch, DE never raised, released too early and too late, +the docs page's example unchanged, and the turnaround a host-switched DE allows. + +Measured on the bench (LAN): switching DE with a GPIO command from the host takes about 27 ms, so +DE drops about 25 ms after the request's last byte. A device answering after 30 ms or more works +every time, after 20 ms about 2 times in 10, after 5 ms never. A device that answers faster needs +a transceiver with automatic direction control (`de off` here). + ## HIL tests ```bash diff --git a/process-node-stm32/tests/conftest.py b/process-node-stm32/tests/conftest.py index 2b996bc..b0da477 100644 --- a/process-node-stm32/tests/conftest.py +++ b/process-node-stm32/tests/conftest.py @@ -60,6 +60,7 @@ "needs_new_wiring": "skips unless BENCH_NEW_WIRING=1 (SPI2 on LA9/LA10/LA13/LA14, USART3 on LA7/LA8)", "needs_la6_resistor": "skips unless BENCH_LA6_RESISTOR=1 (1 kOhm between PA8 and LA6)", "rl78": "RL78 Protocol A programming on LA3 against the node's RL78 boot ROM emulator", + "rs485": "Modbus RTU through the node's RS-485 mock: LA8/LA7 data, LA6 DE (needs both wire sets)", } diff --git a/process-node-stm32/tests/modbus_master.py b/process-node-stm32/tests/modbus_master.py new file mode 100644 index 0000000..632da43 --- /dev/null +++ b/process-node-stm32/tests/modbus_master.py @@ -0,0 +1,162 @@ +"""A Modbus RTU master over the BenchPod and a half-duplex RS-485 transceiver, the way +www.embeddedci.com/docs/benchpod-targets/5v-rs485 wires it: the pod's UART TX to the +transceiver's DI, its RX to RO, and a GPIO to DE + /RE (high: the pod drives the bus; low: it +listens). On the bench the node's RS-485 mock (rs485mock.c) stands in for transceiver, bus and +device, and enforces the same direction rules. +""" + +from __future__ import annotations + +import struct +import time +from typing import List, Optional + + +def crc16(data: bytes) -> bytes: + """Modbus RTU CRC, low byte first.""" + crc = 0xFFFF + for b in data: + crc ^= b + for _ in range(8): + crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1 + return struct.pack(" None: + super().__init__(f"function {fn:02X}H: exception {code:02X}H") + self.fn = fn + self.code = code + + +class NoReply(Exception): + pass + + +class ModbusMaster: + def __init__(self, bp, *, rx, tx, de, baud: int = 19200, parity: str = "even", + stop_bits: int = 1, release_margin: float = 0.002) -> None: + self.bp = bp + self.rx, self.tx, self.de_pin = rx, tx, de + self.baud, self.parity, self.stop_bits = baud, parity, stop_bits + self.release_margin = release_margin + self.uart = None + self.de = None + + @property + def char_s(self) -> float: + return (1 + 8 + (self.parity != "none") + self.stop_bits) / self.baud + + def open(self) -> "ModbusMaster": + if self.de is None and self.de_pin is not None: + self.de = self.bp.gpio(self.de_pin, "output", level=0) # listen until we send + if self.uart is None: + self.uart = self.bp.open_uart(rx=self.rx, tx=self.tx, baud=self.baud, + parity=self.parity, stop_bits=self.stop_bits, + encoding="latin-1") + return self + + def close_uart(self) -> None: + """Leave the UART (the pod runs one UART session at a time); DE stays low.""" + if self.uart is not None: + self.uart.close() + self.uart = None + + def close(self) -> None: + self.close_uart() + if self.de is not None: + self.bp.release_gpio(self.de_pin) + self.de = None + + # -- the wire ---------------------------------------------------------------------------- + + def send(self, frame: bytes, *, drive: bool = True, hold: Optional[float] = None) -> None: + """Drive DE, send, wait until the last byte is out, release DE. ``hold`` overrides how + long DE stays high after the write (the tests use it to get it wrong on purpose); + ``drive=False`` never raises DE. Without a DE pin (an automatic-direction transceiver) it + only sends.""" + self.uart.read() # forget what came before + if self.de is None: + self.uart.write(frame.decode("latin-1")) + return + if drive: + self.de.high() + self.uart.write(frame.decode("latin-1")) + time.sleep(len(frame) * self.char_s + self.release_margin if hold is None else hold) + if drive: + self.de.low() + + def receive(self, want: Optional[int] = None, timeout: float = 0.5) -> bytes: + """Read a reply: ``want`` bytes, or as many as the reply's header says.""" + data = b"" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + data += self.uart.read(timeout=0.02).encode("latin-1") + n = want if want is not None else self._reply_len(data) + if n is not None and len(data) >= n: + return data[:n] + return data + + @staticmethod + def _reply_len(d: bytes) -> Optional[int]: + if len(d) < 3: + return None + fn = d[1] + if fn & 0x80: + return 5 + if fn in (0x01, 0x02, 0x03, 0x04): + return 5 + d[2] + return 8 + + def transact(self, slave: int, pdu: bytes, *, want: Optional[int] = None, **send_kw) -> bytes: + """One request and its reply PDU (function code onwards).""" + req = bytes([slave]) + pdu + self.send(req + crc16(req), **send_kw) + r = self.receive(want) + if not r: + raise NoReply(f"no answer from slave {slave}") + n = want if want is not None else self._reply_len(r) + if n is None or len(r) < n: + raise NoReply(f"short answer from slave {slave}: {r.hex()}") + if crc16(r[:-2]) != r[-2:]: + raise ValueError(f"bad CRC: {r.hex()}") + if r[0] != slave: + raise ValueError(f"answer from slave {r[0]}, asked {slave}") + if r[1] & 0x80: + raise ModbusException(r[1] & 0x7F, r[2]) + return r[1:-2] + + # -- functions --------------------------------------------------------------------------- + + def read_holding(self, slave: int, first: int, count: int = 1) -> List[int]: + p = self.transact(slave, struct.pack(">BHH", 0x03, first, count)) + return list(struct.unpack(f">{count}H", p[2:2 + 2 * count])) + + def read_input(self, slave: int, first: int, count: int = 1) -> List[int]: + p = self.transact(slave, struct.pack(">BHH", 0x04, first, count)) + return list(struct.unpack(f">{count}H", p[2:2 + 2 * count])) + + def write_register(self, slave: int, addr: int, value: int) -> None: + self.transact(slave, struct.pack(">BHH", 0x06, addr, value)) + + def write_registers(self, slave: int, first: int, values: List[int], **send_kw) -> None: + self.transact(slave, struct.pack(">BHHB", 0x10, first, len(values), 2 * len(values)) + + struct.pack(f">{len(values)}H", *values), **send_kw) + + def read_coils(self, slave: int, first: int, count: int) -> List[bool]: + p = self.transact(slave, struct.pack(">BHH", 0x01, first, count)) + return [bool(p[2 + i // 8] >> (i % 8) & 1) for i in range(count)] + + def write_coil(self, slave: int, addr: int, on: bool) -> None: + self.transact(slave, struct.pack(">BHH", 0x05, addr, 0xFF00 if on else 0)) + + def write_coils(self, slave: int, first: int, values: List[bool]) -> None: + packed = bytearray((len(values) + 7) // 8) + for i, v in enumerate(values): + if v: + packed[i // 8] |= 1 << (i % 8) + self.transact(slave, struct.pack(">BHHB", 0x0F, first, len(values), len(packed)) + bytes(packed)) + + def echo(self, slave: int, data: int) -> int: + p = self.transact(slave, struct.pack(">BHH", 0x08, 0, data)) + return struct.unpack(">H", p[3:5])[0] diff --git a/process-node-stm32/tests/test_rs485.py b/process-node-stm32/tests/test_rs485.py new file mode 100644 index 0000000..3cb1fc3 --- /dev/null +++ b/process-node-stm32/tests/test_rs485.py @@ -0,0 +1,254 @@ +"""Modbus RTU over RS-485, against the node's RS-485 mock (rs485mock.c, ``modbus start``). + +The pod is wired as the docs wire it to a half-duplex transceiver, and the node plays +transceiver, bus and device in one: LA8 (pod TX, the transceiver's DI) -> PC11, LA7 (pod RX, RO) +<- PC10, LA6 (a pod GPIO on DE + /RE) -> PA8 through 1 kOhm. With DE honored (``de on``) a byte the +pod sends with DE low never reaches the device, and a reply byte while DE is still high never +reaches the pod, as on a real bus. The protocol tests run with ``de off``, an automatic-direction +transceiver, so they do not depend on the host's DE timing. + +Measured on the bench (LAN): a GPIO command from the host takes about 27 ms, so DE drops about +25 ms after the request's last byte. A device that answers sooner loses its reply to a master +that switches DE from the host; the DE tests use a device that answers after 100 ms, and +test_turnaround reports where it breaks. Needs the USART3 wires and the LA6 resistor +(BENCH_NEW_WIRING=1 BENCH_LA6_RESISTOR=1). +""" + +from __future__ import annotations + +import re +import struct +import time + +import pytest + +from modbus_master import ModbusException, ModbusMaster, NoReply, crc16 + +pytestmark = [pytest.mark.hardware, pytest.mark.rs485, pytest.mark.needs_new_wiring, + pytest.mark.needs_la6_resistor] + +SLAVE = 1 + + +class Bus: + """The master and the mock's console take turns: the pod runs one UART session at a time, and + the node's console (LA3/LA4) and the master (LA7/LA8) are two. Switching closes one and opens + the other; neither the node nor the mock is reset by it.""" + + def __init__(self, benchpod, wiring, node): + self.bp, self.wiring, self.node = benchpod, wiring, node + self.master = None + + def cmd(self, line, pattern): + if self.master is not None: + self.master.close_uart() + if self.node.uart is None: + self.node.open() + return self.node.cmd(line, pattern) + + def stat(self): + m = self.cmd("modbus stat", r"MODBUS stat ([^\r\n]*)\r\n") + return {k: v for k, v in re.findall(r"(\w+)=(\S+)", m.group(1))} + + def start(self, baud=19200, fmt="8E1", delay_us=5000, addr=SLAVE, parity=None, stop_bits=None, + de=False): + """Start the mock and set the master up for the same line (or for parity / stop_bits). + ``de``: the master switches DE on LA6 and the mock enforces it; else neither does.""" + if self.master is not None: + self.master.close() + self.cmd(f"modbus start {addr} {baud} {fmt} delay {delay_us} de {'on' if de else 'off'}", + r"MODBUS ok on") + par = {"N": "none", "E": "even", "O": "odd"}[fmt[1]] if parity is None else parity + self.master = ModbusMaster(self.bp, rx=self.wiring.sensor_uart_rx, + tx=self.wiring.sensor_uart_tx, de=self.wiring.drdy if de else None, + baud=baud, + parity=par, stop_bits=int(fmt[2]) if stop_bits is None else stop_bits) + return self.master + + @property + def m(self): + """The master, its UART open (the console closed).""" + self.node.close() + return self.master.open() + + def stop(self): + if self.master is not None: + self.master.close() + self.master = None + self.cmd("modbus stop", r"MODBUS ok off") + + +DE_DELAY_US = 100000 # a device slow enough for a master that switches DE from the host + + +@pytest.fixture +def bus(benchpod, wiring, node): + """The mock at 19200 8E1 (Modbus RTU's default), answering 5 ms after a request, through an + automatic-direction transceiver (no DE).""" + b = Bus(benchpod, wiring, node) + b.start() + try: + yield b + finally: + b.stop() + + +def test_registers(bus): + m = bus.m + assert m.read_holding(SLAVE, 0, 4) == [0, 0, 0, 0] + m.write_register(SLAVE, 3, 0xBEEF) + m.write_registers(SLAVE, 10, [1, 2, 3, 0xFFFF]) + assert m.read_holding(SLAVE, 0, 14)[3] == 0xBEEF + assert m.read_holding(SLAVE, 10, 4) == [1, 2, 3, 0xFFFF] + assert m.read_input(SLAVE, 0, 16) == [0x1000 + i for i in range(16)] + # the node's own view of the same table, both ways + assert bus.cmd("modbus reg 3", r"MODBUS reg i=3 v=(\d+)\r\n").group(1) == str(0xBEEF) + bus.cmd("modbus reg 20 4660", r"MODBUS reg i=20 v=4660\r\n") + assert bus.m.read_holding(SLAVE, 20) == [4660] + + +def test_coils_and_echo(bus): + m = bus.m + m.write_coil(SLAVE, 2, True) + m.write_coils(SLAVE, 8, [True, False, True, True, False, False, False, False, True]) + got = m.read_coils(SLAVE, 0, 17) + assert [i for i, v in enumerate(got) if v] == [2, 8, 10, 11, 16] + assert m.echo(SLAVE, 0xA55A) == 0xA55A + + +@pytest.mark.parametrize("pdu,code", [ + (struct.pack(">BHH", 0x2B, 0, 0), 0x01), # no such function + (struct.pack(">BHH", 0x03, 63, 2), 0x02), # past the last holding register + (struct.pack(">BHH", 0x03, 0, 0), 0x03), # a quantity of 0 + (struct.pack(">BHH", 0x05, 0, 0x1234), 0x03), # a coil value other than FF00H / 0000H +], ids=["function", "address", "quantity", "coil-value"]) +def test_exceptions(bus, pdu, code): + with pytest.raises(ModbusException) as err: + bus.m.transact(SLAVE, pdu) + assert err.value.code == code + + +def test_silent_cases(bus): + """No answer to a bad CRC, to another slave, or to a broadcast (which is still carried out).""" + m = bus.m + req = bytes([SLAVE]) + struct.pack(">BHH", 0x03, 0, 1) + m.send(req + bytes([crc16(req)[0], crc16(req)[1] ^ 1])) + assert m.receive(timeout=0.2) == b"" + with pytest.raises(NoReply): + m.read_holding(2, 0, 1) + req = bytes([0]) + struct.pack(">BHH", 0x06, 5, 777) + m.send(req + crc16(req)) + assert m.receive(timeout=0.2) == b"" + assert m.read_holding(SLAVE, 5) == [777] + s = bus.stat() + assert (s["crc"], s["other"], s["broadcast"], s["frame"]) == ("1", "1", "1", "0") + + +def test_de_never_raised(bus): + """The pod sends with its driver off: nothing reaches the device, nothing comes back.""" + bus.start(delay_us=DE_DELAY_US, de=True) + m = bus.m + req = bytes([SLAVE]) + struct.pack(">BHH", 0x03, 0, 1) + m.send(req + crc16(req), drive=False) + assert m.receive(timeout=0.3) == b"" + s = bus.stat() + assert int(s["undriven"]) == len(req) + 2 and s["requests"] == "0" + + +def test_de_driven_right(bus): + """The master switches DE around every request, the device answers after DE_DELAY_US.""" + bus.start(delay_us=DE_DELAY_US, de=True) + m = bus.m + m.write_registers(SLAVE, 0, [11, 22, 33]) + assert m.read_holding(SLAVE, 0, 3) == [11, 22, 33] + s = bus.stat() + assert (s["undriven"], s["collisions"], s["frame"]) == ("0", "0", "0") + + +def test_de_released_too_early(bus): + """DE drops while the request is still going out: the tail never reaches the device.""" + bus.start(delay_us=DE_DELAY_US, de=True) + with pytest.raises(NoReply): + bus.m.write_registers(SLAVE, 0, list(range(60)), hold=0.02) # 129 bytes, ~74 ms + s = bus.stat() + assert int(s["undriven"]) > 0 and s["replies"] == "0" + + +def test_de_released_too_late(bus): + """DE stays high after the device has started to answer: the pod's receiver is off, the reply + is lost (and on a real bus it would collide with the pod's driver).""" + bus.start(delay_us=20000, de=True) + m = bus.m + req = bytes([SLAVE]) + struct.pack(">BHH", 0x03, 0, 1) + m.send(req + crc16(req), hold=0.15) # the device answers after 20 ms + assert m.receive(timeout=0.2) == b"" + assert bus.stat()["collisions"] == "7" + + +@pytest.mark.parametrize("baud,fmt", [(9600, "8N2"), (19200, "8E1"), (38400, "8O1"), (115200, "8N1")]) +def test_frame_formats(bus, baud, fmt): + bus.start(baud=baud, fmt=fmt) + m = bus.m + m.write_registers(SLAVE, 0, [baud & 0xFFFF, 0x1234]) + assert m.read_holding(SLAVE, 0, 2) == [baud & 0xFFFF, 0x1234] + assert bus.stat()["frame"] == "0" + + +def test_wrong_parity_is_dropped(bus): + """A master at 8N2 against a device at 8E1: the device drops every frame.""" + bus.start(fmt="8E1", parity="none", stop_bits=2) + with pytest.raises(NoReply): + bus.m.read_holding(SLAVE, 0, 1) + s = bus.stat() + assert s["replies"] == "0" and int(s["frame"]) >= 1 + + +@pytest.mark.parametrize("delay_us", [100000, 50000, 30000, 20000, 5000]) +def test_turnaround(bus, delay_us): + """How soon a device may answer before this master, which switches DE through the pod's + network API, loses the reply. Only the 50 ms and slower cases must pass; the rest report.""" + bus.start(delay_us=delay_us, de=True) + m = bus.m + ok = 0 + for _ in range(10): + try: + m.read_holding(SLAVE, 0, 1) + ok += 1 + except (NoReply, ValueError): # nothing, or the tail of a reply whose start was lost + pass + print(f"device answering after {delay_us} us: {ok}/10 replies, collisions {bus.stat()['collisions']}") + if delay_us >= 50000: + assert ok == 10 + + +def test_docs_example(bus): + """The read_holding_registers helper from the 5 V and RS-485 docs page, unchanged, against a + device slow enough for host-switched DE (DE_DELAY_US).""" + BAUD = 19200 + + def read_holding_registers(uart, de, slave, first, count=1, timeout=1.0): + request = struct.pack(">BBHH", slave, 0x03, first, count) + request += crc16(request) + de.high() # drive the bus + uart.write(request) + time.sleep(len(request) * 11 / BAUD + 0.002) # 11 bits a byte at 8E1 + de.low() # release it: the device answers + want = 5 + 2 * count # address, function, length, data, CRC + reply = b"" + deadline = time.monotonic() + timeout + while len(reply) < want and time.monotonic() < deadline: + reply += uart.read(timeout=0.05).encode("latin-1") + assert len(reply) >= want, f"no answer from slave {slave}: {reply.hex()}" + reply = reply[:want] + assert crc16(reply[:-2]) == reply[-2:], f"bad CRC: {reply.hex()}" + assert reply[1] == 0x03, f"exception {reply[2]} from slave {slave}" + return list(struct.unpack(f">{count}H", reply[3:3 + 2 * count])) + + bus.start(baud=BAUD, delay_us=DE_DELAY_US, de=True) + bus.cmd("modbus reg 0 4242", r"MODBUS reg i=0 v=4242\r\n") + m = bus.m # the console closed, DE claimed and low + m.close_uart() + with bus.bp.open_uart(rx=bus.wiring.sensor_uart_rx, tx=bus.wiring.sensor_uart_tx, baud=BAUD, + parity="even", encoding="latin-1") as uart: + assert read_holding_registers(uart, m.de, SLAVE, 0) == [4242] + assert not bus.bp.status().get("uart_rx_parity_error") From 570df29658d5db2ac1a0f1502e94f5f2289aa2bb Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Wed, 18 Nov 2026 10:50:03 -0600 Subject: [PATCH 3/3] process-node: RS-485 mock times DE's falling edge; tests for the pod's own DE The mock sampled DE when a byte's receive interrupt ran, around the middle of its stop bit or later; the pod's DE (gateware v58) drops at the end of the last stop bit, so at one stop bit the last byte counted as undriven. EXTI line 8 now times DE's falling edge on PA8, and a byte counts as driven when DE fell within its stop bit. test_pod_de: open_uart(de=6), 9600 8N2 / 19200 8E1 / 115200 8N1, the device answering after 3.5 characters, 1 ms and 5 ms, every reply, 0 undriven, 0 collisions (skips without uart_de). Co-Authored-By: Claude Opus 5.5 --- process-node-stm32/README.md | 9 ++++- process-node-stm32/main.c | 9 ++++- process-node-stm32/rs485mock.c | 47 +++++++++++++++++++++-- process-node-stm32/rs485mock.h | 7 +++- process-node-stm32/tests/modbus_master.py | 11 ++++-- process-node-stm32/tests/test_rs485.py | 22 ++++++++++- 6 files changed, 93 insertions(+), 12 deletions(-) diff --git a/process-node-stm32/README.md b/process-node-stm32/README.md index f427f5a..3220212 100644 --- a/process-node-stm32/README.md +++ b/process-node-stm32/README.md @@ -198,7 +198,14 @@ the docs page's example unchanged, and the turnaround a host-switched DE allows. Measured on the bench (LAN): switching DE with a GPIO command from the host takes about 27 ms, so DE drops about 25 ms after the request's last byte. A device answering after 30 ms or more works every time, after 20 ms about 2 times in 10, after 5 ms never. A device that answers faster needs -a transceiver with automatic direction control (`de off` here). +the pod to switch DE itself: `open_uart(de=6)` (gateware v58, feature `uart_de`) drives DE from +before the first start bit to the end of the last stop bit, and `test_pod_de` gets every reply at +9600, 19200 and 115200 baud with the device answering 3.5 characters after the request. A +transceiver with automatic direction control (`de off` here) works too. + +DE's falling edge is timed by EXTI line 8 on PA8: a byte counts as driven when DE fell within its +stop bit, as a master that drives DE well drops it at the end of the last stop bit, often before +the byte's receive interrupt has run. ## HIL tests diff --git a/process-node-stm32/main.c b/process-node-stm32/main.c index ae6d27e..2a970fb 100644 --- a/process-node-stm32/main.c +++ b/process-node-stm32/main.c @@ -30,6 +30,7 @@ */ #include "rl78emu.h" +#include "rs485mock.h" #include "stm32f4xx_hal.h" #include "alarm.h" #include "analog.h" @@ -1422,9 +1423,15 @@ static void SPI1_Init(void) SPI1->CR1 |= SPI_CR1_SPE; } -/* Only here to wake the main loop; can_service() reads the INT level. */ +/* Wakes the main loop for the MCP2515 (can_service() reads the INT level), and times the RS-485 + mock's DE falling edge on PA8 (rs485mock.c). */ void EXTI9_5_IRQHandler(void) { + if (EXTI->PR & GPIO_PIN_8) + { + EXTI->PR = GPIO_PIN_8; + rs485_de_edge(); + } EXTI->PR = INT_PIN; } diff --git a/process-node-stm32/rs485mock.c b/process-node-stm32/rs485mock.c index e8fe6c3..8019dda 100644 --- a/process-node-stm32/rs485mock.c +++ b/process-node-stm32/rs485mock.c @@ -21,21 +21,46 @@ static volatile uint8_t s_rx[MB_FRAME_MAX]; static volatile uint16_t s_rx_len; static volatile uint8_t s_rx_bad; static volatile uint32_t s_rx_last; /* cycle count of the last byte */ -static uint32_t s_char_cyc, s_t15_cyc, s_t35_cyc; +static uint32_t s_char_cyc, s_t15_cyc, s_t35_cyc, s_late_cyc; +static volatile uint32_t s_de_fell; /* cycle count of DE's last falling edge (EXTI line 8) */ +#define DE_EXTI (1UL << 8) static int de_high(void) { return (DE_PORT->IDR & DE_PIN) != 0U; } +/* From EXTI9_5_IRQHandler (main.c): DE fell. */ +void rs485_de_edge(void) +{ + s_de_fell = dwt_cycles(); +} + +/* Was the pod's driver on for the byte that just completed? RXNE comes in the middle of its + (first) stop bit, and a master that drives DE well drops it at the end of the last stop bit, + often before this interrupt runs: a byte still counts when DE fell within its stop bit (or the + edge is still pending, EXTI9_5 being lower priority than USART3). */ +static int byte_driven(uint32_t now) +{ + if (de_high()) + { + return 1; + } + if (EXTI->PR & DE_EXTI) + { + return 1; /* it fell just now, the edge not yet taken */ + } + return now - s_de_fell < s_late_cyc; +} + static void on_byte(uint8_t b, uint32_t sr) { - if (s_st.de && !de_high()) + uint32_t now = dwt_cycles(); + if (s_st.de && !byte_driven(now)) { s_st.undriven++; /* the pod's driver was off: the byte never reached the bus */ return; } - uint32_t now = dwt_cycles(); if (s_rx_len > 0U && now - s_rx_last > s_t15_cyc) { s_rx_bad = 1U; /* a gap inside the frame (the main loop ends frames at 3.5) */ @@ -87,6 +112,20 @@ int rs485_start(uint8_t addr, uint32_t baud, char parity, uint8_t stop_bits, uin /* above 19200 baud the spec fixes t1.5 = 750 us and t3.5 = 1750 us */ s_t15_cyc = baud > 19200U ? us_to_cyc(750U) : (s_char_cyc * 3U) / 2U; s_t35_cyc = baud > 19200U ? us_to_cyc(1750U) : (s_char_cyc * 7U) / 2U; + /* a DE that fell up to 2 bit times (the stop bits) plus 20 us of interrupt latency ago */ + s_late_cyc = (s_char_cyc / bits) * 2U + us_to_cyc(20U); + s_de_fell = dwt_cycles() - s_late_cyc - 1U; + if (s_st.de) + { + /* EXTI line 8 on PA8, falling edge (the pin stays the strobe's input with its pull-down) */ + __HAL_RCC_SYSCFG_CLK_ENABLE(); + SYSCFG->EXTICR[2] &= ~SYSCFG_EXTICR3_EXTI8; /* port A */ + EXTI->FTSR |= DE_EXTI; + EXTI->RTSR &= ~DE_EXTI; + EXTI->PR = DE_EXTI; + EXTI->IMR |= DE_EXTI; + NVIC_EnableIRQ(EXTI9_5_IRQn); + } s_rx_len = 0U; s_rx_bad = 0U; uart3_set_rx_hook(on_byte); @@ -101,6 +140,8 @@ void rs485_stop(void) } uart3_set_rx_hook(NULL); uart3_close(); + EXTI->IMR &= ~DE_EXTI; + EXTI->PR = DE_EXTI; s_st.on = 0U; } diff --git a/process-node-stm32/rs485mock.h b/process-node-stm32/rs485mock.h index 56adfb8..e3a0ac4 100644 --- a/process-node-stm32/rs485mock.h +++ b/process-node-stm32/rs485mock.h @@ -7,8 +7,9 @@ * transceiver DE + /RE LA6 -> PA8 (through 1 kOhm; pulled down, so it listens) * * The rules a real transceiver enforces, so a master's direction handling is tested too: - * - a byte from the pod reaches the bus only while DE is high (sampled as the byte completes); - * others are counted as `undriven` and never reach the device; + * - a byte from the pod reaches the bus only while DE is high, up to the end of its stop bit (a + * falling edge of DE is timed by EXTI line 8); others are counted as `undriven` and never + * reach the device; * - the device's reply reaches the pod only while DE is low (DE high also turns the pod's * receiver off); a reply byte sent while DE is high is lost and counted as a `collision`. * @@ -42,6 +43,8 @@ int rs485_start(uint8_t addr, uint32_t baud, char parity, uint8_t stop_bits, ui uint8_t de); void rs485_stop(void); void rs485_set_delay(uint32_t delay_us); +/* From EXTI9_5_IRQHandler: DE (PA8) fell. */ +void rs485_de_edge(void); /* Main loop: end of frame detection and the reply. */ void rs485_service(void); const rs485_stats_t *rs485_stats(void); diff --git a/process-node-stm32/tests/modbus_master.py b/process-node-stm32/tests/modbus_master.py index 632da43..ab96aa9 100644 --- a/process-node-stm32/tests/modbus_master.py +++ b/process-node-stm32/tests/modbus_master.py @@ -35,9 +35,13 @@ class NoReply(Exception): class ModbusMaster: def __init__(self, bp, *, rx, tx, de, baud: int = 19200, parity: str = "even", - stop_bits: int = 1, release_margin: float = 0.002) -> None: + stop_bits: int = 1, release_margin: float = 0.002, pod_de: bool = False) -> None: + """``de``: the LA channel on DE + /RE, or None (an automatic-direction transceiver). + ``pod_de``: the pod switches DE itself (``open_uart(de=...)``, gateware v58) instead of + the host's GPIO calls around each request.""" self.bp = bp self.rx, self.tx, self.de_pin = rx, tx, de + self.pod_de = pod_de and de is not None self.baud, self.parity, self.stop_bits = baud, parity, stop_bits self.release_margin = release_margin self.uart = None @@ -48,12 +52,13 @@ def char_s(self) -> float: return (1 + 8 + (self.parity != "none") + self.stop_bits) / self.baud def open(self) -> "ModbusMaster": - if self.de is None and self.de_pin is not None: + if self.de is None and self.de_pin is not None and not self.pod_de: self.de = self.bp.gpio(self.de_pin, "output", level=0) # listen until we send if self.uart is None: + extra = {"de": self.de_pin} if self.pod_de else {} self.uart = self.bp.open_uart(rx=self.rx, tx=self.tx, baud=self.baud, parity=self.parity, stop_bits=self.stop_bits, - encoding="latin-1") + encoding="latin-1", **extra) return self def close_uart(self) -> None: diff --git a/process-node-stm32/tests/test_rs485.py b/process-node-stm32/tests/test_rs485.py index 3cb1fc3..b91a903 100644 --- a/process-node-stm32/tests/test_rs485.py +++ b/process-node-stm32/tests/test_rs485.py @@ -51,7 +51,7 @@ def stat(self): return {k: v for k, v in re.findall(r"(\w+)=(\S+)", m.group(1))} def start(self, baud=19200, fmt="8E1", delay_us=5000, addr=SLAVE, parity=None, stop_bits=None, - de=False): + de=False, pod_de=False): """Start the mock and set the master up for the same line (or for parity / stop_bits). ``de``: the master switches DE on LA6 and the mock enforces it; else neither does.""" if self.master is not None: @@ -61,7 +61,7 @@ def start(self, baud=19200, fmt="8E1", delay_us=5000, addr=SLAVE, parity=None, s par = {"N": "none", "E": "even", "O": "odd"}[fmt[1]] if parity is None else parity self.master = ModbusMaster(self.bp, rx=self.wiring.sensor_uart_rx, tx=self.wiring.sensor_uart_tx, de=self.wiring.drdy if de else None, - baud=baud, + baud=baud, pod_de=pod_de, parity=par, stop_bits=int(fmt[2]) if stop_bits is None else stop_bits) return self.master @@ -252,3 +252,21 @@ def read_holding_registers(uart, de, slave, first, count=1, timeout=1.0): parity="even", encoding="latin-1") as uart: assert read_holding_registers(uart, m.de, SLAVE, 0) == [4242] assert not bus.bp.status().get("uart_rx_parity_error") + + +@pytest.mark.parametrize("baud,fmt", [(9600, "8N2"), (19200, "8E1"), (115200, "8N1")]) +@pytest.mark.parametrize("delay_us", [0, 1000, 5000]) +def test_pod_de(bus, baud, fmt, delay_us): + """The pod switches DE itself (``open_uart(de=...)``, gateware v58): the transceiver rules on, + and the device answering as soon as the spec allows (3.5 characters after the request, with + ``delay 0``), after 1 ms and after 5 ms. No reply byte may be lost and nothing undriven.""" + if not bus.bp.supports("uart_de"): + pytest.skip("the pod's firmware does not drive DE (uart_de, gateware v58)") + bus.start(baud=baud, fmt=fmt, delay_us=delay_us, de=True, pod_de=True) + m = bus.m + for i in range(10): + m.write_registers(SLAVE, 0, [i, 0x5A5A, baud & 0xFFFF]) + assert m.read_holding(SLAVE, 0, 3) == [i, 0x5A5A, baud & 0xFFFF] + s = bus.stat() + assert (s["undriven"], s["collisions"], s["frame"], s["replies"]) == ("0", "0", "0", "20") +