From 76fbf3c713c27c3690f0ea95e87934fce0835362 Mon Sep 17 00:00:00 2001 From: cpq Date: Mon, 23 Nov 2026 14:46:23 +0000 Subject: [PATCH] BLE radio support --- mongoose.c | 3744 +++++++++-------- mongoose.h | 468 +-- src/config.h | 8 +- src/drivers/esp32.c | 147 + src/drivers/esp32.h | 30 + src/drivers/esp32_802154.c | 192 - src/drivers/esp32_802154.h | 38 - src/drivers/mcxw71.c | 262 +- src/drivers/mcxw71.h | 7 - src/drivers/mg24.c | 171 +- src/drivers/mg24.h | 7 - src/drivers/nrf52.c | 149 +- src/drivers/nrf52.h | 7 - src/drivers/radio.c | 718 ++++ src/drivers/radio.h | 74 + src/drivers/rw612w.c | 86 +- src/drivers/rw612w.h | 7 - src/drivers/usb.c | 465 +- src/drivers/usb.h | 131 +- src/drivers/usb_dwc2.c | 365 ++ src/drivers/usb_dwc2.h | 57 + src/drivers/usb_nrf52.c | 320 +- src/drivers/usb_nrf52.h | 15 +- src/drivers/usb_rp.c | 349 +- src/drivers/usb_rp.h | 18 +- src/l2_mesh.c | 677 --- src/l2_mesh.h | 111 - src/net_builtin.c | 3 +- src/net_builtin.h | 4 +- test/Makefile | 2 +- test/mesh/Makefile | 5 +- test/mesh/README.md | 379 +- test/mesh/mesh_a.c | 261 -- test/mesh/simulator.c | 271 +- test/mesh/simulator.h | 70 +- .../minimal-802.15.4/main/mongoose_config.h | 3 +- .../wifi-to-802.15.4-bridge/CMakeLists.txt | 4 + .../esp32/wifi-to-802.15.4-bridge/Makefile | 22 + .../main/CMakeLists.txt | 12 + .../main/Kconfig.projbuild | 16 + .../esp32/wifi-to-802.15.4-bridge/main/main.c | 476 +++ .../main/mongoose_config.h | 9 + .../sdkconfig.defaults | 10 + tutorials/nordic/xiao-52840/usb/README.md | 67 - .../minimal/Makefile | 0 .../minimal/hal.c | 0 .../minimal/hal.h | 0 .../minimal/link.ld | 0 .../minimal/main.c | 4 +- .../minimal/mongoose_config.h | 12 +- .../xiao-nrf52840/usb-to-ble-bridge/Makefile | 51 + .../xiao-nrf52840/usb-to-ble-bridge/hal.c | 129 + .../usb-to-ble-bridge}/hal.h | 0 .../usb-to-ble-bridge}/link.ld | 0 .../xiao-nrf52840/usb-to-ble-bridge/main.c | 70 + .../usb-to-ble-bridge/mongoose_config.h | 29 + .../usb/Makefile | 0 .../{xiao-52840 => xiao-nrf52840}/usb/hal.c | 0 tutorials/nordic/xiao-nrf52840/usb/hal.h | 67 + tutorials/nordic/xiao-nrf52840/usb/link.ld | 62 + .../{xiao-52840 => xiao-nrf52840}/usb/main.c | 0 .../usb/mongoose_config.h | 10 + tutorials/nxp/frdm-mcxw71/minimal/hal.c | 70 +- tutorials/nxp/frdm-mcxw71/minimal/hal.h | 2 +- .../nxp/frdm-mcxw71/minimal/mongoose_config.h | 3 + .../ethernet-to-802.15.4-bridge/main.c | 44 +- .../mongoose_config.h | 1 + tutorials/rp/usb/README.md | 99 - tutorials/rp/usb/mongoose_config.h | 1 + tutorials/silabs/xiao-mg24/minimal/Makefile | 17 +- .../nucleo-u5a5zj-q/minimal-usb/Makefile | 37 + .../stm32/nucleo-u5a5zj-q/minimal-usb/hal.c | 131 + .../stm32/nucleo-u5a5zj-q/minimal-usb/hal.h | 184 + .../stm32/nucleo-u5a5zj-q/minimal-usb/link.ld | 31 + .../stm32/nucleo-u5a5zj-q/minimal-usb/main.c | 90 + .../minimal-usb/mongoose_config.h | 32 + .../stm32/portenta-h7/minimal-usb/Makefile | 43 + tutorials/stm32/portenta-h7/minimal-usb/hal.c | 131 + tutorials/stm32/portenta-h7/minimal-usb/hal.h | 198 + .../stm32/portenta-h7/minimal-usb/link.ld | 33 + .../stm32/portenta-h7/minimal-usb/main.c | 91 + .../portenta-h7/minimal-usb/mongoose_config.h | 31 + 82 files changed, 7047 insertions(+), 4893 deletions(-) create mode 100644 src/drivers/esp32.c create mode 100644 src/drivers/esp32.h delete mode 100644 src/drivers/esp32_802154.c delete mode 100644 src/drivers/esp32_802154.h create mode 100644 src/drivers/radio.c create mode 100644 src/drivers/radio.h create mode 100644 src/drivers/usb_dwc2.c create mode 100644 src/drivers/usb_dwc2.h delete mode 100644 src/l2_mesh.c delete mode 100644 src/l2_mesh.h delete mode 100644 test/mesh/mesh_a.c create mode 100644 tutorials/esp32/wifi-to-802.15.4-bridge/CMakeLists.txt create mode 100644 tutorials/esp32/wifi-to-802.15.4-bridge/Makefile create mode 100644 tutorials/esp32/wifi-to-802.15.4-bridge/main/CMakeLists.txt create mode 100644 tutorials/esp32/wifi-to-802.15.4-bridge/main/Kconfig.projbuild create mode 100644 tutorials/esp32/wifi-to-802.15.4-bridge/main/main.c create mode 100644 tutorials/esp32/wifi-to-802.15.4-bridge/main/mongoose_config.h create mode 100644 tutorials/esp32/wifi-to-802.15.4-bridge/sdkconfig.defaults delete mode 100644 tutorials/nordic/xiao-52840/usb/README.md rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/minimal/Makefile (100%) rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/minimal/hal.c (100%) rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/minimal/hal.h (100%) rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/minimal/link.ld (100%) rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/minimal/main.c (96%) rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/minimal/mongoose_config.h (76%) create mode 100644 tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/Makefile create mode 100644 tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/hal.c rename tutorials/nordic/{xiao-52840/usb => xiao-nrf52840/usb-to-ble-bridge}/hal.h (100%) rename tutorials/nordic/{xiao-52840/usb => xiao-nrf52840/usb-to-ble-bridge}/link.ld (100%) create mode 100644 tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/main.c create mode 100644 tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/mongoose_config.h rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/usb/Makefile (100%) rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/usb/hal.c (100%) create mode 100644 tutorials/nordic/xiao-nrf52840/usb/hal.h create mode 100644 tutorials/nordic/xiao-nrf52840/usb/link.ld rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/usb/main.c (100%) rename tutorials/nordic/{xiao-52840 => xiao-nrf52840}/usb/mongoose_config.h (75%) delete mode 100644 tutorials/rp/usb/README.md create mode 100644 tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/Makefile create mode 100644 tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.c create mode 100644 tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.h create mode 100644 tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/link.ld create mode 100644 tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/main.c create mode 100644 tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/mongoose_config.h create mode 100644 tutorials/stm32/portenta-h7/minimal-usb/Makefile create mode 100644 tutorials/stm32/portenta-h7/minimal-usb/hal.c create mode 100644 tutorials/stm32/portenta-h7/minimal-usb/hal.h create mode 100644 tutorials/stm32/portenta-h7/minimal-usb/link.ld create mode 100644 tutorials/stm32/portenta-h7/minimal-usb/main.c create mode 100644 tutorials/stm32/portenta-h7/minimal-usb/mongoose_config.h diff --git a/mongoose.c b/mongoose.c index 1bb15253..de5d7b10 100644 --- a/mongoose.c +++ b/mongoose.c @@ -6468,687 +6468,6 @@ uint8_t mg_l2_eth_ip6put(struct mg_l2addr *l2addr, uint8_t *opts) { #endif -#ifdef MG_ENABLE_LINES -#line 1 "src/l2_mesh.c" -#endif -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved - - - - - - -#if MG_ENABLE_TCPIP - -#define MGI_ETH_MAX 1514 -#define MGI_TX_DST_LEN 2 - -// Mesh header, after the radio header: type, then burst: the fragment's -// index << 4 | the last fragment's index. Common to every radio -#define MG_MESH_HDR_LEN 2 - -#define MG_MESH_FRAME_HDR_LEN (MG_802154_HEADER_LEN + MG_MESH_HDR_LEN) - -// MAC header, 9 bytes: frame control 0x8841, a data frame, PAN ID -// compression, short destination and source addresses; sequence number, 0, -// as nothing uses it yet; PAN ID; destination; source. Little endian, as -// the standard says -static void mgi_802154_print_hdr(const struct mg_radio *radio, uint8_t *buf, - uint16_t dst, uint16_t src) { - buf[0] = 0x41, buf[1] = 0x88, buf[2] = 0; - buf[3] = (uint8_t) MG_802154_PAN_ID; - buf[4] = (uint8_t) (MG_802154_PAN_ID >> 8); - buf[5] = (uint8_t) dst, buf[6] = (uint8_t) (dst >> 8); - buf[7] = (uint8_t) src, buf[8] = (uint8_t) (src >> 8); - (void) radio; -} - -static size_t mgi_802154_parse_hdr(const struct mg_radio *radio, - const uint8_t *buf, size_t len, - uint16_t *dst, uint16_t *src) { - (void) radio; - if (len < MG_802154_HEADER_LEN || buf[0] != 0x41 || buf[1] != 0x88 || - buf[3] != (uint8_t) MG_802154_PAN_ID || - buf[4] != (uint8_t) (MG_802154_PAN_ID >> 8)) { - return 0; - } - *dst = (uint16_t) (buf[5] | buf[6] << 8); - *src = (uint16_t) (buf[7] | buf[8] << 8); - return MG_802154_HEADER_LEN; -} - -const struct mg_radio mg_radio_802154 = { - "802.15.4", // name - 125, // max_frame_size: 127 minus FCS - 250000, // bitrate - 8, // overhead - 320, // slot_us - 128, // cca_us - 100, // turnaround_us - 640, // ifs_us - 3, // backoff_min - 5, // backoff_max - true, // csma - MG_802154_HEADER_LEN, // header_len - mgi_802154_print_hdr, // print_hdr - mgi_802154_parse_hdr // parse_hdr -}; - -static uint64_t mgi_mesh_b_airtime(size_t len) { - const struct mg_radio *radio = &mg_radio_802154; - return ((uint64_t) (len + radio->overhead) * 8000000 + radio->bitrate - 1) / - radio->bitrate; -} - -// Each queue record holds a destination and a complete burst. -static size_t mgi_mesh_b_queue(struct mg_mesh_node *node, struct mg_queue *q, - const void *buf, size_t len, uint16_t dst, - uint8_t type) { - const struct mg_radio *radio = &mg_radio_802154; - const uint8_t *eth = (const uint8_t *) buf; - size_t hdr = MG_MESH_FRAME_HDR_LEN, cap = radio->max_frame_size - hdr; - size_t frames, size, i; - char *record; - uint8_t *out; - if (len < 14 || len > MGI_ETH_MAX) return 0; - frames = (len + cap - 1) / cap; - size = MGI_TX_DST_LEN + len + frames * (1 + hdr); - if (mg_queue_next(q, NULL) == 0) mg_queue_init(q, q->buf, q->size); - if (mg_queue_book(q, &record, size) < size) return 0; - out = (uint8_t *) record; - *out++ = (uint8_t) (dst >> 8); - *out++ = (uint8_t) dst; - for (i = 0; i < frames; i++) { - size_t chunk = len - i * cap; - if (chunk > cap) chunk = cap; - *out++ = (uint8_t) (hdr + chunk); - radio->print_hdr(radio, out, dst, node->radio_address); - out[radio->header_len] = type; - out[radio->header_len + 1] = (uint8_t) (i << 4 | (frames - 1)); - memcpy(out + hdr, eth + i * cap, chunk); - out += hdr + chunk; - } - mg_queue_add(q, size); - return len; -} - -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved - -#define MGI_JOIN_WINDOW_US 3000 -#define MGI_JOIN_TURN_US 192 -#define MGI_JOIN_JITTER_US 640 -#define MGI_DATA_QUEUE_SIZE 2048 -#define MGI_TX_RETRY_US 32 -#define MGI_ANSWER_MARGIN_US 500 // Node: finish the first answer frame this - // much before the bridge stops waiting -// Our frames: the radio header, with the radio addresses, then the mesh -// header MG_MESH_HDR_LEN, then the payload -#define MGI_JOIN_UP_LEN \ - (MG_MESH_FRAME_HDR_LEN + 6) // MGI_JOIN_UP's payload: MAC addr -#define MGI_MAX_FRAGMENTS 14 - -enum { MGI_JOIN_DOWN = 1, MGI_JOIN_UP, MGI_DATA_DOWN, MGI_DATA_UP }; - -enum { MGI_TURN_IDLE, MGI_TURN_JOIN, MGI_TURN_DATA }; - -struct mgi_mesh_b_data { - uint8_t rx_buf[MGI_ETH_MAX]; // Ethernet frame being reassembled - uint8_t rx_expected; // Expected index | last index, 0xff if idle - struct mg_mesh_node *node; // Owner of the TCP/IP interface - struct mg_queue tx; // One record per burst of RF fragments - size_t tx_offset; // Next queued fragment; zero for an empty frame - uint64_t tx_at; // Next fragment or JOIN transmission time - uint64_t deadline; // End of the current JOIN or DATA turn - struct mgi_mesh_b_peer *fanout; // Next broadcast recipient - char tx_buf[MGI_DATA_QUEUE_SIZE]; // Transmit queue storage - uint32_t random; // PRNG state for join timing - struct mgi_mesh_b_peer *members; // Bridge membership list - struct mgi_mesh_b_peer *current; // Member whose turn is active or next - int8_t missed_rounds; // -1 after a grant; otherwise completed rounds missed - uint16_t coordinator; // Coordinator radio address - uint8_t phase; // MGI_TURN_IDLE, MGI_TURN_JOIN, or MGI_TURN_DATA - uint64_t answer_by; // Node: first answer frame must end on air by then -}; - -struct mgi_mesh_b_peer { - struct mgi_mesh_b_peer *next; // Next member in round-robin order - uint16_t radio_address; // Source address supplied in MGI_JOIN_UP - uint8_t mac[6]; // Ethernet MAC supplied in MGI_JOIN_UP - uint8_t misses; // Turns in a row it did not answer -}; - -static uint32_t mgi_mesh_b_random(struct mg_mesh_node *node, - struct mgi_mesh_b_data *data) { - uint32_t *random = &data->random; - if (*random == 0) { - size_t i; - *random = (uint32_t) mg_now(); - for (i = 0; i < 6; i++) *random = *random * 33u + node->radio->mac[i]; - if (*random == 0) *random = 1; - } - *random ^= *random << 13; - *random ^= *random >> 17; - *random ^= *random << 5; - return *random; -} - -static const struct mg_radio *const s_mesh_default_radio = &mg_radio_802154; - -// Read a frame's radio addresses to dst and src, see mg_radio::parse_hdr(), and -// return its type, from the mesh header. 0: not a frame of ours -static unsigned mgi_mesh_b_frame_parse(const uint8_t *frame, size_t len, - uint16_t *dst, uint16_t *src) { - if (len < MG_MESH_FRAME_HDR_LEN || - s_mesh_default_radio->parse_hdr(s_mesh_default_radio, frame, len, dst, - src) != - s_mesh_default_radio->header_len) { - return 0; - } - return frame[s_mesh_default_radio->header_len]; -} - -// Write a frame's headers: the radio's, to dst from src, then ours: type, -// and burst: high nibble is the index, low nibble is the last index -static void mgi_mesh_b_frame_header(uint8_t *frame, uint16_t dst, uint16_t src, - uint8_t type, uint8_t burst) { - size_t h = s_mesh_default_radio->header_len; - s_mesh_default_radio->print_hdr(s_mesh_default_radio, frame, dst, src); - frame[h] = type, frame[h + 1] = burst; -} - -static bool mgi_mesh_b_control_send(struct mg_mesh_node *node, uint16_t dst, - uint8_t command) { - struct mg_tcpip_if *ifp = node->radio; - uint8_t frame[MGI_JOIN_UP_LEN] = {0}; - size_t len = MG_MESH_FRAME_HDR_LEN; - mgi_mesh_b_frame_header(frame, dst, node->radio_address, command, 0); - if (command == MGI_JOIN_UP) { - memcpy(frame + MG_MESH_FRAME_HDR_LEN, node->radio->mac, 6); - len = MGI_JOIN_UP_LEN; - } - return node->now >= node->tx_at && node->tx(ifp, frame, len) == len; -} - -static size_t mgi_mesh_b_fragment_capacity(void) { - return s_mesh_default_radio->max_frame_size - MG_MESH_FRAME_HDR_LEN; -} - -static uint64_t mgi_mesh_b_burst_time(size_t len) { - size_t cap = mgi_mesh_b_fragment_capacity(); - size_t frames = len == 0 ? 1 : (len + cap - 1) / cap; - return (frames - 1) * - (mgi_mesh_b_airtime(s_mesh_default_radio->max_frame_size) + - s_mesh_default_radio->ifs_us) + - mgi_mesh_b_airtime(MG_MESH_FRAME_HDR_LEN + len - (frames - 1) * cap); -} - -static void mgi_mesh_b_tx_finish(struct mgi_mesh_b_data *data) { - if (data->tx_offset != 0) { - if (data->fanout != NULL) data->fanout = data->fanout->next; - if (data->fanout == NULL) { - size_t len = mg_queue_next(&data->tx, NULL); - mg_queue_del(&data->tx, len); - } - } - data->tx_offset = 0; - data->tx_at = (uint64_t) -1; -} - -static void mgi_mesh_b_tx_step(struct mgi_mesh_b_data *data, uint64_t now) { - struct mg_mesh_node *node = data->node; - struct mg_tcpip_if *radio = node->radio; - uint8_t empty[MG_MESH_FRAME_HDR_LEN], *frame = empty; - size_t len = MG_MESH_FRAME_HDR_LEN, record_len = 0; - uint16_t dst; - uint8_t command; - if (now < data->tx_at) return; - if (now >= data->deadline) { - mgi_mesh_b_tx_finish(data); - return; - } - dst = node->lan == NULL ? data->coordinator : data->current->radio_address; - command = node->lan == NULL ? MGI_DATA_UP : MGI_DATA_DOWN; - if (data->tx_offset != 0) { - char *record; - uint8_t *part; - record_len = mg_queue_next(&data->tx, &record); - part = (uint8_t *) record + data->tx_offset; - len = part[0]; - frame = part + 1; - s_mesh_default_radio->print_hdr(s_mesh_default_radio, frame, dst, - node->radio_address); - } else { - mgi_mesh_b_frame_header(frame, dst, node->radio_address, command, 0); - } - // A node's first answer frame: if it cannot end on air before the bridge - // stops waiting, stay silent. The queued frame waits for the next turn - if (node->lan == NULL && - (data->tx_offset == 0 || data->tx_offset == MGI_TX_DST_LEN) && - now + mgi_mesh_b_airtime(len) > data->answer_by) { - data->tx_offset = 0; - data->tx_at = (uint64_t) -1; - return; - } - if (now < data->node->tx_at || data->node->tx(radio, frame, len) != len) { - data->tx_at = now + MGI_TX_RETRY_US; - return; - } - if (data->tx_offset == 0 || (data->tx_offset += len + 1) == record_len) { - // Bridge: the turn's last frame is out, wait for the answer - if (node->lan != NULL) - data->deadline = - now + mgi_mesh_b_airtime(len) + MG_MESH_ANSWER_TIMEOUT_US; - mgi_mesh_b_tx_finish(data); - } else { - data->tx_at = now + mgi_mesh_b_airtime(len) + s_mesh_default_radio->ifs_us; - } -} - -static void mgi_mesh_b_tx_begin(struct mgi_mesh_b_data *data, bool burst, - uint64_t now, uint64_t deadline) { - data->phase = MGI_TURN_DATA; - data->answer_by = (uint64_t) -1; // Node sets it after a grant - data->tx_offset = burst ? MGI_TX_DST_LEN : 0; - data->tx_at = now; - data->deadline = deadline; -} - -// Return the assembled length, zero for an empty frame, or -1 if incomplete -// or invalid. Full non-final fragments make the write offset derivable. -static int mgi_mesh_b_data_receive(struct mgi_mesh_b_data *data, - const uint8_t *frame, size_t len, - uint64_t now) { - unsigned burst = frame[MG_MESH_FRAME_HDR_LEN - 1], index = burst >> 4, - last = burst & 15; - size_t chunk = len - MG_MESH_FRAME_HDR_LEN, - cap = mgi_mesh_b_fragment_capacity(); - size_t offset = index * cap; - if (index == 0) { - data->rx_expected = (uint8_t) burst; - if (data->node->lan == NULL) - data->deadline = now + mgi_mesh_b_burst_time(MGI_ETH_MAX) + - 2 * s_mesh_default_radio->ifs_us + MGI_JOIN_TURN_US; - } - if (last >= MGI_MAX_FRAGMENTS || index > last || burst != data->rx_expected || - chunk > cap || now > data->deadline || (index < last && chunk != cap) || - (last != 0 && chunk == 0) || offset + chunk > sizeof(data->rx_buf)) { - data->rx_expected = 0xff; - return -1; - } - memcpy(data->rx_buf + offset, frame + MG_MESH_FRAME_HDR_LEN, chunk); - if (index < last) { - data->rx_expected = (uint8_t) (burst + 0x10); - // Bridge: an answer is under way, wait for its next fragment - if (data->node->lan != NULL) - data->deadline = - now + mgi_mesh_b_airtime(s_mesh_default_radio->max_frame_size) + - s_mesh_default_radio->ifs_us + MG_MESH_ANSWER_TIMEOUT_US; - return -1; - } - data->rx_expected = 0xff; - return offset + chunk == 0 || offset + chunk >= 14 ? (int) (offset + chunk) - : -1; -} - -// Bridge scheduling and Ethernet forwarding. - - -static uint16_t mgi_mesh_b_join_field(const uint8_t *p) { - return (uint16_t) ((unsigned) p[0] * 256 + p[1]); -} - -// Return chaddr for an Ethernet DHCP server reply, even when broadcast. -static const uint8_t *mgi_mesh_b_dhcp_client(const uint8_t *frame, size_t len) { - size_t ip_len, ihl, udp_len; - const uint8_t *udp, *dhcp; - if (len < 34 || mgi_mesh_b_join_field(frame + 12) != 0x0800 || - (frame[14] >> 4) != 4 || frame[23] != 17 || - (mgi_mesh_b_join_field(frame + 20) & 0x3fff) != 0) - return NULL; - ip_len = mgi_mesh_b_join_field(frame + 16); - ihl = (size_t) (frame[14] & 15) * 4; - if (ihl < 20 || ip_len > len - 14 || ip_len < ihl + 8 + 240) return NULL; - udp = frame + 14 + ihl; - udp_len = mgi_mesh_b_join_field(udp + 4); - if (mgi_mesh_b_join_field(udp) != 67 || - mgi_mesh_b_join_field(udp + 2) != 68 || udp_len < 8 + 240 || - udp_len > ip_len - ihl) - return NULL; - dhcp = udp + 8; - if (dhcp[0] != 2 || dhcp[1] != 1 || dhcp[2] != 6 || - memcmp(dhcp + 236, "\x63\x82\x53\x63", 4) != 0) - return NULL; - return dhcp + 28; -} - -static size_t mgi_mesh_b_enqueue(struct mg_mesh_node *node, const void *buf, - size_t len) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) node->data; - const uint8_t *frame = (const uint8_t *) buf; - if (node->lan == NULL) - return mgi_mesh_b_queue(node, &data->tx, buf, len, data->coordinator, - MGI_DATA_UP); - if (len >= 14 && len <= MGI_ETH_MAX) { - const uint8_t *client = mgi_mesh_b_dhcp_client(frame, len); - const uint8_t *dst = client == NULL ? frame : client; - bool multicast = client == NULL && (frame[0] & 1) != 0; - struct mgi_mesh_b_peer *peer; - for (peer = data->members; peer != NULL; peer = peer->next) { - if (multicast || memcmp(dst, peer->mac, 6) == 0) { - uint16_t addr = multicast ? 0xffffu : peer->radio_address; - return mgi_mesh_b_queue(node, &data->tx, buf, len, addr, MGI_DATA_DOWN); - } - } - } - return 0; -} - -static void mgi_mesh_b_bridge_queue_lan(struct mg_mesh_node *bridge) { - struct mg_queue *rx = &bridge->lan->recv_queue; - char *buf; - size_t len; - while ((len = mg_queue_next(rx, &buf)) > 0) { - bridge->strategy->tx(bridge, buf, len); - mg_queue_del(rx, len); - } -} - -static void mgi_mesh_b_bridge_rx(uint64_t now, struct mg_mesh_node *b, - const uint8_t *frame, size_t len) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) b->data; - struct mgi_mesh_b_peer *peer; - uint16_t dst = 0, src = 0; - unsigned command = mgi_mesh_b_frame_parse(frame, len, &dst, &src); - if (command == MGI_DATA_UP && dst == b->radio_address && - data->phase == MGI_TURN_DATA && data->current != NULL && - src == data->current->radio_address && now <= data->deadline) { - int received = mgi_mesh_b_data_receive(data, frame, len, now); - if (received < 0) return; - if (received != 0) { - b->lan->driver->tx(data->rx_buf, (size_t) received, b->lan); - } - data->current->misses = 0; - data->current = data->current->next; - data->phase = MGI_TURN_IDLE; - data->deadline = now; - return; - } - if (len != MGI_JOIN_UP_LEN || command != MGI_JOIN_UP || - dst != b->radio_address || data->phase != MGI_TURN_JOIN || - now >= data->deadline) { - return; - } - if (src == 0 || src == 0xffffu) return; - for (peer = data->members; peer != NULL; peer = peer->next) { - if (peer->radio_address == src) break; - } - if (peer == NULL) { - peer = (struct mgi_mesh_b_peer *) mg_calloc(1, sizeof(*peer)); - if (peer == NULL) return; - peer->radio_address = src; - peer->next = data->members; - data->members = peer; - } - memcpy(peer->mac, frame + MG_MESH_FRAME_HDR_LEN, sizeof(peer->mac)); -} - -// Member peer did not answer its turn. After MG_MESH_MAX_MISSES in a row, it -// is gone: remove it, and its queued downlink frames -static void mgi_mesh_b_member_missed(struct mgi_mesh_b_data *data, - struct mgi_mesh_b_peer *peer) { - if (++peer->misses < MG_MESH_MAX_MISSES) return; - MG_INFO(("Member %M removed: no answer %d times", mg_print_mac, peer->mac, - MG_MESH_MAX_MISSES)); - if (data->fanout == peer) { - data->fanout = peer->next; - if (data->fanout == NULL) { - size_t len = mg_queue_next(&data->tx, NULL); - mg_queue_del(&data->tx, len); - } - } - LIST_DELETE(struct mgi_mesh_b_peer, &data->members, peer); - mg_free(peer); -} - -// A broadcast occupies one record and is sent once to each member in list -// order. -static size_t mgi_mesh_b_bridge_burst(struct mgi_mesh_b_data *data, - struct mgi_mesh_b_peer *peer) { - char *record; - size_t len; - while ((len = mg_queue_next(&data->tx, &record)) != 0) { - uint16_t dst = mgi_mesh_b_join_field((const uint8_t *) record); - struct mgi_mesh_b_peer *member; - if (dst == 0xffffu) { - if (data->fanout == NULL) data->fanout = data->members; - return data->fanout == peer ? len : 0; - } - if (dst == peer->radio_address) return len; - for (member = data->members; member != NULL; member = member->next) { - if (member->radio_address == dst) return 0; - } - mg_queue_del(&data->tx, len); // Its destination has left. - } - return 0; -} - -static uint64_t mgi_mesh_b_queued_burst_time(struct mgi_mesh_b_data *data, - size_t len) { - char *record; - size_t frames; - if (len == 0) return mgi_mesh_b_burst_time(0); - mg_queue_next(&data->tx, &record); - // Fragment zero carries the final index. Count overhead and IFS per frame. - frames = - ((uint8_t) record[MGI_TX_DST_LEN + MG_MESH_FRAME_HDR_LEN] & 15u) + 1u; - return mgi_mesh_b_airtime(len - MGI_TX_DST_LEN - frames + - (frames - 1) * s_mesh_default_radio->overhead) + - (frames - 1) * s_mesh_default_radio->ifs_us; -} - -static void mgi_mesh_b_bridge_io(uint64_t now, struct mg_mesh_node *b) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) b->data; - mgi_mesh_b_bridge_queue_lan(b); - if (now >= data->deadline) { - if (data->tx_at != (uint64_t) -1) mgi_mesh_b_tx_finish(data); - if (data->phase == MGI_TURN_DATA && data->current != NULL) { - struct mgi_mesh_b_peer *peer = data->current; - data->current = peer->next; - mgi_mesh_b_member_missed(data, peer); - } else if (data->phase == MGI_TURN_JOIN) { - data->current = data->members; - } - data->phase = MGI_TURN_IDLE; - if (data->current != NULL) { - size_t burst = mgi_mesh_b_bridge_burst(data, data->current); - uint64_t down = mgi_mesh_b_queued_burst_time(data, burst); - data->rx_expected = 0xff; - mgi_mesh_b_tx_begin(data, burst != 0, now, - now + down + mgi_mesh_b_burst_time(MGI_ETH_MAX) + - 2 * s_mesh_default_radio->ifs_us + - MGI_JOIN_TURN_US); - } else if (mgi_mesh_b_control_send(b, 0xffffu, MGI_JOIN_DOWN)) { - data->phase = MGI_TURN_JOIN; - data->deadline = now + MGI_JOIN_WINDOW_US; - } - if (data->deadline <= now) data->deadline = now + MGI_JOIN_TURN_US; - } -} - -static void mgi_mesh_b_bridge_free(struct mgi_mesh_b_data *data) { - while (data->members != NULL) { - struct mgi_mesh_b_peer *peer = data->members; - data->members = peer->next; - mg_free(peer); - } -} - -static void mgi_mesh_b_node_rx(struct mg_mesh_node *n, uint64_t now, - uint8_t *frame, size_t len) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) n->data; - uint16_t dst = 0, src = 0; - unsigned command = mgi_mesh_b_frame_parse(frame, len, &dst, &src); - if (command == MGI_JOIN_DOWN && len == MG_MESH_FRAME_HDR_LEN && - dst == 0xffffu) { - if (n->joined && src == data->coordinator && - ++data->missed_rounds >= MG_MESH_MAX_MISSES) { - n->joined = false; - data->phase = MGI_TURN_IDLE; - data->tx_at = (uint64_t) -1; - data->tx_offset = 0; - data->rx_expected = 0xff; - } - if (!n->joined && (mgi_mesh_b_random(n, data) % 64) == 0) { - // Spread contenders across windows as well as within the reply window. - data->coordinator = src; - data->phase = MGI_TURN_JOIN; - data->tx_at = now + MGI_JOIN_TURN_US + - mgi_mesh_b_random(n, data) % MGI_JOIN_JITTER_US; - } - } else if (command == MGI_DATA_DOWN && data->coordinator != 0 && - dst == n->radio_address && src == data->coordinator) { - int received = mgi_mesh_b_data_receive(data, frame, len, now); - if (received < 0) return; - n->joined = true; - data->missed_rounds = - -1; // This round had a grant; do not count it as missed. - if (received != 0) { - struct mg_tcpip_if *ifp = n->radio; - if (n->rx_len != 0 || (size_t) received > ifp->recv_queue.size) { - ifp->ndrop++; - } else { - memcpy(ifp->recv_queue.buf, data->rx_buf, (size_t) received); - n->rx_len = (size_t) received; - } - } - if (data->tx_at != (uint64_t) -1) mgi_mesh_b_tx_finish(data); - mgi_mesh_b_tx_begin(data, mg_queue_next(&data->tx, NULL) != 0, now, - now + mgi_mesh_b_burst_time(MGI_ETH_MAX) + - 2 * s_mesh_default_radio->ifs_us + - MGI_JOIN_TURN_US); - data->answer_by = now + MG_MESH_ANSWER_TIMEOUT_US - MGI_ANSWER_MARGIN_US; - } -} - -// Receive timing counts from the frame's arrival, see mg_mesh_rx_drain(). -// Without an arrival time, e.g. when called directly, use the poll time -static void mgi_mesh_b_input(struct mg_mesh_node *node, void *buf, size_t len) { - uint64_t ready = node->now + node->strategy->radio->turnaround_us; - uint64_t arrived = node->rx_at != 0 ? node->rx_at : node->now; - if (node->tx_at < ready) node->tx_at = ready; - node->next_tick = node->now; - if (node->lan != NULL) { - mgi_mesh_b_bridge_rx(arrived, node, (const uint8_t *) buf, len); - } else { - mgi_mesh_b_node_rx(node, arrived, (uint8_t *) buf, len); - } -} - -static void mgi_mesh_b_tick(struct mg_mesh_node *node, uint64_t now) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) node->data; - node->now = now; - if (node->lan != NULL) { - mgi_mesh_b_bridge_io(now, node); - mgi_mesh_b_tx_step(data, now); - node->next_tick = data->deadline; - if (data->tx_at < node->next_tick) node->next_tick = data->tx_at; - return; - } - if (data->phase == MGI_TURN_JOIN) { - if (data->tx_at <= now) { - if (now - data->tx_at <= MGI_JOIN_TURN_US && !node->joined) - mgi_mesh_b_control_send(node, data->coordinator, MGI_JOIN_UP); - data->tx_at = (uint64_t) -1; - data->phase = MGI_TURN_IDLE; - } - } else { - mgi_mesh_b_tx_step(data, now); - } - node->next_tick = data->tx_at; -} - -static bool mgi_mesh_b_init(struct mg_mesh_node *node, - struct mg_tcpip_if *radio, struct mg_tcpip_if *lan, - uint16_t radio_address) { - struct mgi_mesh_b_data *data = - (struct mgi_mesh_b_data *) mg_calloc(1, sizeof(*data)); - memset(node, 0, sizeof(*node)); - node->radio = radio; - node->lan = lan; - node->radio_address = radio_address; - node->next_tick = (uint64_t) -1; - node->ram_used = node->ram_peak = sizeof(*node); - if (data == NULL) return false; - node->ram_used += sizeof(*data); - node->ram_peak = node->ram_used; - data->rx_expected = 0xff; - node->data = data; - data->node = node; - data->tx_at = (uint64_t) -1; - mg_queue_init(&data->tx, data->tx_buf, sizeof(data->tx_buf)); - if (lan != NULL) node->next_tick = 0; - return true; -} - -static void mgi_mesh_b_free(struct mg_mesh_node *node) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) node->data; - if (data == NULL) return; - mgi_mesh_b_bridge_free(data); - mg_free(data); - node->data = NULL; -} - -// Receive queue record: arrival time, then the radio frame -#define MGI_RX_STAMP_LEN sizeof(uint64_t) - -void mg_mesh_rx_queue(struct mg_queue *q, struct mg_tcpip_if *ifp, - const void *frame, size_t len) { - uint64_t arrived = mg_micros(); - size_t need = MGI_RX_STAMP_LEN + len; - char *dst; - - if (mg_queue_book(q, &dst, need) < need) { - if (ifp != NULL) ifp->ndrop++; - return; - } - memcpy(dst, &arrived, MGI_RX_STAMP_LEN); - memcpy(dst + MGI_RX_STAMP_LEN, frame, len); - mg_queue_add(q, need); -} - -void mg_mesh_rx_drain(struct mg_mesh_node *node, struct mg_queue *q) { - char *record; - size_t len; - - while (node->rx_len == 0) { - len = mg_queue_next(q, &record); - if (len == 0) break; - if (len > MGI_RX_STAMP_LEN) { - memcpy(&node->rx_at, record, MGI_RX_STAMP_LEN); - node->strategy->rx(node, record + MGI_RX_STAMP_LEN, - len - MGI_RX_STAMP_LEN); - node->rx_at = 0; - } - mg_queue_del(q, len); - } -} - -const struct mg_mesh mg_mesh_default = { - "default", - mgi_mesh_b_init, - mgi_mesh_b_tick, - mgi_mesh_b_free, - mgi_mesh_b_enqueue, - mgi_mesh_b_input, - true, - true, - &mg_radio_802154, -}; - -#endif - #ifdef MG_ENABLE_LINES #line 1 "src/l2_ppp.c" #endif @@ -10051,6 +9370,7 @@ void mg_tcpip_call(struct mg_tcpip_if *ifp, int ev, void *ev_data) { "TCPIP_EV_TIMER_1S", "TCPIP_EV_WIFI_SCAN_RESULT", "TCPIP_EV_WIFI_SCAN_END", "TCPIP_EV_WIFI_CONNECT_ERR", "TCPIP_EV_DRIVER", "TCPIP_EV_STATE6_CHANGE", + "TCPIP_EV_PHY_RX", "TCPIP_EV_PHY_TX", "TCPIP_EV_USER"}; if (ev != MG_TCPIP_EV_TIMER_1S && ev < (int) (sizeof(names) / sizeof(names[0]))) { MG_PROF_ADD(ifp, names[ev]); // TODO(): call MG_PROF_DUMP() MG_PROF_FREE() @@ -12092,7 +11412,6 @@ void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) { } void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) { - mg_usb_init(); // Early, so that the log reaches the USB serial port // If L2 address is not set, make a random one; fill MTU mg_l2_init(ifp); ifp->mtu = ifp->l2mtu; @@ -12259,7 +11578,6 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) { mg_timer_poll(&mgr->timers, now); mg_ota_poll(mgr); mg_mdash_poll(mgr); - mg_usb_poll(); // Also without a TCP/IP interface: USB serial only if (mgr->ifp == NULL || mgr->ifp->driver == NULL) return; mg_tcpip_poll(mgr->ifp, now); for (c = mgr->conns; c != NULL; c = tmp) { @@ -32711,49 +32029,45 @@ bool mg_wifi_ap_stop(void) { #endif #ifdef MG_ENABLE_LINES -#line 1 "src/drivers/esp32_802154.c" +#line 1 "src/drivers/esp32.c" #endif -#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32_802154) && \ - MG_ENABLE_DRIVER_ESP32_802154 +#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32) && MG_ENABLE_DRIVER_ESP32 + +#if MG_RADIO != MG_RADIO_802154 +#error "MG_ENABLE_DRIVER_ESP32 supports MG_RADIO_802154 only" +#endif #if MG_ARCH != MG_ARCH_ESP32 -#error "MG_ENABLE_DRIVER_ESP32_802154 needs MG_ARCH_ESP32 (ESP-IDF)" +#error "MG_ENABLE_DRIVER_ESP32 needs MG_ARCH_ESP32 (ESP-IDF)" #endif // ESP-IDF owns the PHY, coexistence and interrupts. Its callbacks run in // interrupt context and pass radio frames through a lock-free queue, read by -// mgi_esp32_802154_poll(). In both directions frame[0] is the PHR, the length +// mgi_esp32_poll(). In both directions frame[0] is the PHR, the length // including FCS #include #include #include -static struct mg_tcpip_if *s_esp32_802154_ifp; -static struct mg_queue s_esp32_802154_rx; -static char s_esp32_802154_rxbuf[2048]; -static volatile bool s_esp32_802154_txing, s_esp32_802154_tx_done; -static uint64_t s_esp32_802154_txstart; // Send start, us +static struct mg_tcpip_if *s_esp32_ifp; +static volatile bool s_esp32_txing, s_esp32_tx_done; +static uint64_t s_esp32_txstart; // Send start, us // Frame for the radio: PHR, the length including FCS, then the PSDU -static uint8_t s_esp32_802154_txframe[128] __attribute__((aligned(4))); - -// Queue a received PSDU without its FCS -static void mg_esp32_802154_rx_frame(const uint8_t *psdu, size_t len) { - mg_mesh_rx_queue(&s_esp32_802154_rx, s_esp32_802154_ifp, psdu, len); -} +static uint8_t s_esp32_txframe[128] __attribute__((aligned(4))); // ESP-IDF only: it accepts a frame and may refuse it later, because of Wi-Fi // coexistence, a busy channel or an abort. Such a frame is sent again after -// this pause, until MG_MESH_TX_TIMEOUT_US. Without it, the mesh would count +// this pause, until MG_RADIO_TX_TIMEOUT_US. Without it, the mesh would count // the refused frame as sent -#define MGI_ESP32_802154_RETRY_US 200 +#define MGI_ESP32_RETRY_US 200 -static volatile bool s_esp32_802154_retry; // A resend is pending -static volatile uint32_t s_esp32_802154_retry_at; // When to resend, us +static volatile bool s_esp32_retry; // A resend is pending +static volatile uint32_t s_esp32_retry_at; // When to resend, us // ESP-IDF's esp_ieee802154 driver calls the three functions below by name, // from interrupt context. They are global only for that reason, and IRAM_ATTR @@ -32761,7 +32075,7 @@ static volatile uint32_t s_esp32_802154_retry_at; // When to resend, us void IRAM_ATTR esp_ieee802154_receive_done(uint8_t *frame, esp_ieee802154_frame_info_t *info) { (void) info; - if (frame[0] > 2) mg_esp32_802154_rx_frame(frame + 1, frame[0] - 2U); + if (frame[0] > 2) mg_radio_rx_queue(s_esp32_ifp, frame + 1, frame[0] - 2U); esp_ieee802154_receive_handle_done(frame); } @@ -32770,7 +32084,7 @@ void IRAM_ATTR esp_ieee802154_transmit_done(const uint8_t *frame, esp_ieee802154_frame_info_t *info) { (void) frame, (void) info; if (ack != NULL) esp_ieee802154_receive_handle_done(ack); - s_esp32_802154_tx_done = true; + s_esp32_tx_done = true; } void IRAM_ATTR esp_ieee802154_transmit_failed(const uint8_t *frame, @@ -32779,131 +32093,90 @@ void IRAM_ATTR esp_ieee802154_transmit_failed(const uint8_t *frame, if (err == ESP_IEEE802154_TX_ERR_COEXIST || err == ESP_IEEE802154_TX_ERR_CCA_BUSY || err == ESP_IEEE802154_TX_ERR_ABORT) { - s_esp32_802154_retry_at = - (uint32_t) esp_timer_get_time() + MGI_ESP32_802154_RETRY_US; - s_esp32_802154_retry = true; // Set last: the poll reads it first + s_esp32_retry_at = (uint32_t) esp_timer_get_time() + MGI_ESP32_RETRY_US; + s_esp32_retry = true; // Set last: the poll reads it first } else { - s_esp32_802154_tx_done = true; + s_esp32_tx_done = true; } } -static bool mg_esp32_802154_hw_init(uint16_t address) { - // rx_when_idle: the driver returns to receive after each transmission - return esp_ieee802154_enable() == ESP_OK && - esp_ieee802154_set_promiscuous(false) == ESP_OK && - esp_ieee802154_set_coordinator(false) == ESP_OK && - esp_ieee802154_set_rx_when_idle(true) == ESP_OK && - esp_ieee802154_set_panid(MG_802154_PAN_ID) == ESP_OK && - esp_ieee802154_set_short_address(address) == ESP_OK && - esp_ieee802154_set_channel(MG_802154_CHANNEL) == ESP_OK && - esp_ieee802154_set_txpower(0) == ESP_OK && - esp_ieee802154_receive() == ESP_OK; +// rx_when_idle: the driver returns to receive after each transmission +static bool mgi_esp32_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + s_esp32_ifp = ifp; + if (esp_ieee802154_enable() == ESP_OK && + esp_ieee802154_set_promiscuous(false) == ESP_OK && + esp_ieee802154_set_coordinator(false) == ESP_OK && + esp_ieee802154_set_rx_when_idle(true) == ESP_OK && + esp_ieee802154_set_panid(MG_RADIO_NETWORK) == ESP_OK && + esp_ieee802154_set_short_address(addr) == ESP_OK && + esp_ieee802154_set_channel(MG_RADIO_CHANNEL) == ESP_OK && + esp_ieee802154_set_txpower(0) == ESP_OK && + esp_ieee802154_receive() == ESP_OK) { + return true; + } + MG_ERROR(("802.15.4 radio init failed")); + return false; } -static bool mg_esp32_802154_hw_tx(void) { - s_esp32_802154_retry = false; - return esp_ieee802154_transmit(s_esp32_802154_txframe, false) == ESP_OK; +static bool mg_esp32_hw_tx(void) { + s_esp32_retry = false; + return esp_ieee802154_transmit(s_esp32_txframe, false) == ESP_OK; } -static void mg_esp32_802154_hw_abort(void) { - s_esp32_802154_retry = false; +static void mg_esp32_hw_abort(void) { + s_esp32_retry = false; esp_ieee802154_receive(); // Stops the current operation } // Resend a refused frame when its pause is over. If the radio does not take // it, give up: the frame counts as done -static void mg_esp32_802154_hw_poll(void) { +static void mg_esp32_hw_poll(void) { uint32_t now; - if (!s_esp32_802154_retry) return; + if (!s_esp32_retry) return; now = (uint32_t) esp_timer_get_time(); - if ((int32_t) (now - s_esp32_802154_retry_at) < 0) return; - s_esp32_802154_retry = false; - if (esp_ieee802154_transmit(s_esp32_802154_txframe, false) != ESP_OK) { - s_esp32_802154_tx_done = true; + if ((int32_t) (now - s_esp32_retry_at) < 0) return; + s_esp32_retry = false; + if (esp_ieee802154_transmit(s_esp32_txframe, false) != ESP_OK) { + s_esp32_tx_done = true; } } // Mesh radio transmit. The hardware adds the FCS -static size_t mgi_esp32_802154_radio_tx(struct mg_tcpip_if *ifp, - const void *buf, size_t len) { +static size_t mgi_esp32_radio_tx(struct mg_tcpip_if *ifp, const void *buf, + size_t len) { (void) ifp; - if (len > 125 || s_esp32_802154_txing) return 0; - s_esp32_802154_txframe[0] = (uint8_t) (len + 2); - memcpy(s_esp32_802154_txframe + 1, buf, len); - s_esp32_802154_tx_done = false; - s_esp32_802154_txing = true, s_esp32_802154_txstart = mg_micros(); - if (!mg_esp32_802154_hw_tx()) { - s_esp32_802154_txing = false; + if (len > 125 || s_esp32_txing) return 0; + s_esp32_txframe[0] = (uint8_t) (len + 2); + memcpy(s_esp32_txframe + 1, buf, len); + s_esp32_tx_done = false; + s_esp32_txing = true, s_esp32_txstart = mg_micros(); + if (!mg_esp32_hw_tx()) { + s_esp32_txing = false; return 0; } return len; } -static size_t mgi_esp32_802154_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_esp32_802154_rx(void *buf, size_t cap, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_esp32_802154_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; - node->now = now; - mg_esp32_802154_hw_poll(); - if (s_esp32_802154_txing && - (s_esp32_802154_tx_done || - now - s_esp32_802154_txstart > MG_MESH_TX_TIMEOUT_US)) { - if (!s_esp32_802154_tx_done) mg_esp32_802154_hw_abort(); - s_esp32_802154_txing = false; - node->tx_at = now + node->strategy->radio->ifs_us; +static bool mgi_esp32_radio_poll(struct mg_tcpip_if *ifp) { + bool done = false; + (void) ifp; + mg_esp32_hw_poll(); + if (s_esp32_txing && (s_esp32_tx_done || mg_micros() - s_esp32_txstart > + MG_RADIO_TX_TIMEOUT_US)) { + if (!s_esp32_tx_done) mg_esp32_hw_abort(); + s_esp32_txing = false; + done = true; } - mg_mesh_rx_drain(node, &s_esp32_802154_rx); - node->strategy->tick(node, now); - return node->joined; + return done; } -static bool mgi_esp32_802154_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_esp32_802154_radio_tx; - mg_queue_init(&s_esp32_802154_rx, s_esp32_802154_rxbuf, - sizeof(s_esp32_802154_rxbuf)); - s_esp32_802154_ifp = ifp; - if (mg_esp32_802154_hw_init(address)) return true; - MG_ERROR(("802.15.4 radio init failed")); - data->mesh->strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; +static bool mgi_esp32_init(struct mg_tcpip_if *ifp) { + return mg_radio_init(ifp, mgi_esp32_radio_init, mgi_esp32_radio_poll, + mgi_esp32_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_esp32_802154 = { - mgi_esp32_802154_init, mgi_esp32_802154_tx, mgi_esp32_802154_rx, - mgi_esp32_802154_poll}; +struct mg_tcpip_driver mg_tcpip_driver_esp32 = {mgi_esp32_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif #ifdef MG_ENABLE_LINES @@ -33147,6 +32420,126 @@ struct mg_tcpip_driver mg_tcpip_driver_imxrt = {mg_tcpip_driver_imxrt_init, #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MCXW71) && \ MG_ENABLE_DRIVER_MCXW71 +// TrustZone: code built for the secure state (-mcmse) uses the secure alias +// of the radio registers, 0x5xxxxxxx. Otherwise, the non-secure alias +#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE & 2) +#define MGI_RF_BASE 0x58A00000U +#define MGI_PKT_RAM ((volatile uint8_t *) 0x58A08000) +#else +#define MGI_RF_BASE 0x48A00000U +#define MGI_PKT_RAM ((volatile uint8_t *) 0x48A08000) +#endif + +#define MGI_NVIC_ISER ((volatile uint32_t *) 0xE000E100) // Enable IRQ +#define MGI_NVIC_ICER ((volatile uint32_t *) 0xE000E180) // Disable IRQ +#if MG_RADIO == MG_RADIO_BLE +#define MGI_IRQN 54 // RF_Generic_IRQn +#else +#define MGI_IRQN 53 // RF_802_15_4_IRQn +#endif + +// Keep the IRQ handler out while we change the radio. The NVIC disable is +// atomic, so register updates here and there do not race +static void mg_mcxw71_lock(void) { + MGI_NVIC_ICER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); + __asm volatile("dsb; isb" ::: "memory"); +} + +static struct mg_tcpip_if *s_mcxw71_ifp; +static volatile bool s_mcxw71_txing, s_mcxw71_done; +static uint64_t s_mcxw71_sendstart; + +#if MG_RADIO == MG_RADIO_BLE + +// GENFSK Bluetooth LE uncoded mode, RM Table 489. S0 + 8-bit length, then +// our frame. The PHY supplies the preamble, whitening and 24-bit CRC. +struct mg_genfsk { + volatile uint32_t IRQ_CTRL, EVENT_TMR, T1_CMP, T2_CMP, TIMESTAMP, XCVR_CTRL, + XCVR_STS, XCVR_CFG, CHANNEL_NUM0, TX_POWER, NTW_ADR_CTRL, NTW_ADR[4], + RX_WATERMARK, DSM_CTRL, PART_ID, SLOT_PRELOAD, SLOT_TIME, TURNAROUND_TIME, + ACKDELAY, RXDELAY, TXDELAY, PACKET_CFG, H0_CFG, H1_CFG, CRC_CFG, + LENGTH_ADJ, TIMESTAMP_RX_DONE, TIMESTAMP_TX_DONE, MULT_PKT_CTRL, + RPA_WL_STATUS, LENGTH_MAX, EVENT_TMR_LD, EVENT_TMR_ADD, ENH_FEATURE; + uint32_t reserved[21]; + volatile uint32_t SEQ_STS; +}; +#define MGI_GFSK ((struct mg_genfsk *) (MGI_RF_BASE + 0x2000)) +#define MGI_TX_PB MGI_PKT_RAM // Access address, S0, length, frame; no CRC +#define MGI_RX_PB (MGI_PKT_RAM + 0x1000) // S0, length, frame, CRC; no AA +#define MGI_RADIO_MAX 251 +#define MGI_GFSK_IRQ_EN (MG_BIT(26) | MG_BIT(16)) // Master + sequence end +// BLE preamble starts with the access address's first bit; transmit LSBit +// first. +#define MGI_GFSK_CFG \ + (MG_BIT(24) | (((MG_RADIO_NETWORK & 1U) ? 0x55U : 0xaaU) << 16) | (1U << 4)) + +static void mg_mcxw71_abort(void) { + // NXP CONNRF-767: do not abort during TX warmup. + while (MGI_GFSK->SEQ_STS & MG_BIT(2)) (void) 0; + MGI_GFSK->XCVR_CTRL = 11; // ABORT_ALL + while (MGI_GFSK->XCVR_CTRL & MG_BIT(31)) (void) 0; + MGI_GFSK->IRQ_CTRL = MGI_GFSK_IRQ_EN | 0xffffU; // W1C status +} + +static void mg_mcxw71_listen(void) { + MGI_GFSK->IRQ_CTRL = MGI_GFSK_IRQ_EN | 0xffffU; + MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG; + MGI_GFSK->XCVR_CTRL = 5; // RX_START_NOW + MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); +} + +static void mg_mcxw71_go(void) { + mg_mcxw71_abort(); + MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG; // ABORT disables packet processing + MGI_GFSK->XCVR_CTRL = 1; // TX_START_NOW +} + +void RF_Generic_IRQHandler(void); +void RF_Generic_IRQHandler(void) { + uint32_t status = MGI_GFSK->IRQ_CTRL; + if (!(status & MG_BIT(0))) return; + mg_mcxw71_abort(); + if (s_mcxw71_txing) { + s_mcxw71_txing = false; + s_mcxw71_done = true; + } else if ((status & (MG_BIT(2) | MG_BIT(10))) == + (MG_BIT(2) | MG_BIT(10))) { // RX and CRC valid + uint8_t frame[MGI_RADIO_MAX]; + size_t i, n = MGI_RX_PB[1]; + if (n > 0 && n <= sizeof(frame)) { + for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i + 2]; + mg_radio_rx_queue(s_mcxw71_ifp, frame, n); + } + } + mg_mcxw71_listen(); +} + +static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + s_mcxw71_ifp = ifp; + (void) addr; // Frames are filtered by mg_radio_rx_queue() + MGI_GFSK->IRQ_CTRL = 0xffffU; + mg_mcxw71_abort(); + // GENFSK channels are MHz above 2360; MG_RADIO_CHANNEL is a BLE data index. + MGI_GFSK->CHANNEL_NUM0 = MG_RADIO_CHANNEL < 11 ? 44 + 2 * MG_RADIO_CHANNEL + : 46 + 2 * MG_RADIO_CHANNEL; + MGI_GFSK->TX_POWER = 0x3f; + MGI_GFSK->NTW_ADR_CTRL = 0x301; // 32-bit access address, match address 0 + MGI_GFSK->NTW_ADR[0] = MG_RADIO_NETWORK; + MGI_GFSK->PACKET_CFG = 0x000800c8; // H0=8 bits, length=8, AA=4 bytes + MGI_GFSK->H0_CFG = MGI_GFSK->H1_CFG = 0; // No header filtering + MGI_GFSK->LENGTH_ADJ = 3; // Length excludes the three CRC bytes + MGI_GFSK->MULT_PKT_CTRL = 0; + MGI_GFSK->LENGTH_MAX = 16U << 16; // 256 bytes; software caps at 251 + MGI_GFSK->ENH_FEATURE = 9 | MG_BIT(6); // BLE uncoded, alternate rate: 2M + MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG; + mg_mcxw71_listen(); + return true; +} + +#else +#define MGI_ZLL ((struct mg_zll *) (MGI_RF_BASE + 0x1000)) +#define MGI_RADIO_MAX 125 + // ZLL, 802.15.4 link layer. See MCXW71 reference manual and NXP // ieee_802_15_4 PHY sources: PhyPacketProcessor.c, PhyPlmeData.c, PhyISR.c struct mg_zll { @@ -33161,16 +32554,6 @@ struct mg_zll { COEX_PRIORITY, ENHACK_CTRL0; }; -// TrustZone: code built for the secure state (-mcmse) uses the secure alias -// of the radio registers, 0x5xxxxxxx. Otherwise, the non-secure alias -#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE & 2) -#define MGI_ZLL ((struct mg_zll *) 0x58A01000) -#define MGI_PKT_RAM ((volatile uint8_t *) 0x58A08000) -#else -#define MGI_ZLL ((struct mg_zll *) 0x48A01000) -#define MGI_PKT_RAM ((volatile uint8_t *) 0x48A08000) -#endif - #define MGI_TX_PB MGI_PKT_RAM // Length byte (incl. FCS), then frame #define MGI_RX_PB (MGI_PKT_RAM + 0x80) // Received frame, no length byte @@ -33183,9 +32566,6 @@ struct mg_zll { #define MGI_PHY_CTRL_ALL_IRQ_MASKS 0x8007ff00U // Bits 8..18, 31: mask all IRQs #define MGI_PHY_CTRL_SEQMSK MG_BIT(8) // Mask the sequence end IRQ #define MGI_PHY_CTRL_TRCV_MSK MG_BIT(31) // Mask all transceiver IRQs -#define MGI_IRQN 53 // RF_802_15_4_IRQn -#define MGI_NVIC_ISER ((volatile uint32_t *) 0xE000E100) // Enable IRQ -#define MGI_NVIC_ICER ((volatile uint32_t *) 0xE000E180) // Disable IRQ #define MGI_SEQ_STATE_MASK 0x1fU #define MGI_SEQ_STATE_RX_WU 0x10U // RX warm up #define MGI_SEQ_CTRL_NO_RX_RECYCLE MG_BIT(5) @@ -33194,12 +32574,6 @@ struct mg_zll { // PHY_CTRL[XCVSEQ] enum { MGI_SEQ_IDLE = 0, MGI_SEQ_RX = 1, MGI_SEQ_TX = 2 }; -static struct mg_tcpip_if *s_mcxw71_ifp; -static struct mg_queue s_mcxw71_rx; -static char s_mcxw71_queue[2048]; -static volatile bool s_mcxw71_txing, s_mcxw71_done; -static uint64_t s_mcxw71_sendstart; - // Stop the current sequence, wait for the sequencer to go idle. See PhyAbort() static void mg_mcxw71_abort(void) { if (MGI_ZLL->PHY_CTRL & MGI_PHY_CTRL_XCVSEQ) { @@ -33219,13 +32593,6 @@ static void mg_mcxw71_listen(void) { MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); } -// Keep the IRQ handler out while we change the radio. The NVIC disable is -// atomic, so PHY_CTRL updates here and there do not race -static void mg_mcxw71_lock(void) { - MGI_NVIC_ICER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); - __asm volatile("dsb; isb" ::: "memory"); -} - // Start the TX sequence for the loaded frame. Its end: see the IRQ handler static void mg_mcxw71_go(void) { MGI_ZLL->PHY_CTRL |= MGI_PHY_CTRL_TRCV_MSK | MGI_PHY_CTRL_SEQMSK; @@ -33251,22 +32618,49 @@ void RF_802_15_4_IRQHandler(void) { n = n >= 2 ? n - 2 : 0; if (n > 0 && n <= sizeof(frame)) { for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i]; - mg_mesh_rx_queue(&s_mcxw71_rx, s_mcxw71_ifp, frame, n); + mg_radio_rx_queue(s_mcxw71_ifp, frame, n); } } mg_mcxw71_listen(); } } +static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + s_mcxw71_ifp = ifp; + MGI_ZLL->SEQ_CTRL_STS |= MGI_SEQ_CTRL_NO_RX_RECYCLE; + MGI_ZLL->PHY_CTRL = MGI_PHY_CTRL_ALL_IRQ_MASKS; + MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS; + MGI_ZLL->SAM_CTRL = 0; + MGI_ZLL->RX_FRAME_FILTER = MGI_FRAME_FILTER; + MGI_ZLL->CHANNEL_NUM0 = MG_RADIO_CHANNEL; + MGI_ZLL->MACSHORTADDRS0 = ((uint32_t) addr << 16) | MG_RADIO_NETWORK; + MGI_ZLL->PA_PWR = 0x3f; + mg_mcxw71_listen(); + return true; +} + +#endif + static size_t mgi_mcxw71_radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) { size_t i; (void) ifp; - if (len > 125 || s_mcxw71_txing) return 0; + if (len > MGI_RADIO_MAX || s_mcxw71_txing) return 0; mg_mcxw71_lock(); +#if MG_RADIO == MG_RADIO_BLE + if (MGI_GFSK->SEQ_STS & MG_BIT(11)) { // Do not interrupt a received frame + MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); + return 0; + } + for (i = 0; i < 4; i++) + MGI_TX_PB[i] = (uint8_t) (MG_RADIO_NETWORK >> (8 * i)); + MGI_TX_PB[4] = 0, MGI_TX_PB[5] = (uint8_t) len; + for (i = 0; i < len; i++) MGI_TX_PB[i + 6] = ((const uint8_t *) buf)[i]; +#else MGI_TX_PB[0] = (uint8_t) (len + 2); // FCS is added by hardware for (i = 0; i < len; i++) MGI_TX_PB[i + 1] = ((const uint8_t *) buf)[i]; // 8-bit access only +#endif s_mcxw71_done = false; s_mcxw71_txing = true; s_mcxw71_sendstart = mg_millis(); @@ -33275,46 +32669,11 @@ static size_t mgi_mcxw71_radio_tx(struct mg_tcpip_if *ifp, const void *buf, return len; } -static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - s_mcxw71_ifp = ifp; - MGI_ZLL->SEQ_CTRL_STS |= MGI_SEQ_CTRL_NO_RX_RECYCLE; - MGI_ZLL->PHY_CTRL = MGI_PHY_CTRL_ALL_IRQ_MASKS; - MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS; - MGI_ZLL->SAM_CTRL = 0; - MGI_ZLL->RX_FRAME_FILTER = MGI_FRAME_FILTER; - MGI_ZLL->CHANNEL_NUM0 = MG_802154_CHANNEL; - MGI_ZLL->MACSHORTADDRS0 = - ((uint32_t) node->radio_address << 16) | MG_802154_PAN_ID; - MGI_ZLL->PA_PWR = 0x3f; - mg_mcxw71_listen(); - return true; -} - -static size_t mgi_mcxw71_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_mcxw71_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_mcxw71_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; +static bool mgi_mcxw71_radio_poll(struct mg_tcpip_if *ifp) { + bool done; + (void) ifp; if (s_mcxw71_txing && - mg_millis() > s_mcxw71_sendstart + MG_MESH_TX_TIMEOUT_US / 1000) { + mg_millis() > s_mcxw71_sendstart + MG_RADIO_TX_TIMEOUT_US / 1000) { mg_mcxw71_lock(); if (s_mcxw71_txing) { mg_mcxw71_abort(); @@ -33325,42 +32684,18 @@ static bool mgi_mcxw71_poll(struct mg_tcpip_if *ifp, bool s1) { MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); } } - if (s_mcxw71_done) { - s_mcxw71_done = false; - node->tx_at = now + node->strategy->radio->ifs_us; - } - node->now = now; - mg_mesh_rx_drain(node, &s_mcxw71_rx); - node->strategy->tick(node, now); - return node->joined; + done = s_mcxw71_done; + s_mcxw71_done = false; + return done; } static bool mgi_mcxw71_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address; - address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_mcxw71_radio_tx; - mg_queue_init(&s_mcxw71_rx, s_mcxw71_queue, sizeof(s_mcxw71_queue)); - if (mgi_mcxw71_radio_init(ifp)) return true; - strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_mcxw71_radio_init, mgi_mcxw71_radio_poll, + mgi_mcxw71_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_mcxw71 = { - mgi_mcxw71_init, mgi_mcxw71_tx, mgi_mcxw71_rx, mgi_mcxw71_poll}; +struct mg_tcpip_driver mg_tcpip_driver_mcxw71 = {mgi_mcxw71_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif #ifdef MG_ENABLE_LINES @@ -33374,33 +32709,51 @@ struct mg_tcpip_driver mg_tcpip_driver_mcxw71 = { #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MG24) && MG_ENABLE_DRIVER_MG24 #include + +// A packet in the RAIL FIFOs: the radio header, then the frame +#if MG_RADIO == MG_RADIO_BLE +#include +#define MGI_MG24_HDR 2 // S0 byte, unused, then the frame length +#define MGI_MG24_MAX 251 // Largest frame. RAIL adds and strips the CRC +// RAIL channel: the RF channel, 2402 MHz + 2 MHz steps. Data channels 0-10 +// are RF channels 1-11, data channels 11-36 are RF channels 13-38 +#define MGI_MG24_CHANNEL \ + (MG_RADIO_CHANNEL < 11 ? MG_RADIO_CHANNEL + 1 : MG_RADIO_CHANNEL + 2) +#else #include +#define MGI_MG24_HDR 1 // PHR: the frame length, FCS included +#define MGI_MG24_MAX 125 // Largest frame, without the 2 byte FCS +#define MGI_MG24_CHANNEL MG_RADIO_CHANNEL +#endif // RAIL delivers raw frames and transmit completion from interrupt context. static struct mg_tcpip_if *s_mg24_ifp; static RAIL_Handle_t s_mg24_rail; -static struct mg_queue s_mg24_rx; -static char s_mg24_rxbuf[2048]; static volatile bool s_mg24_txing, s_mg24_tx_done; static RAIL_Time_t s_mg24_txstart; // Send start, us static uint8_t s_mg24_txfifo[256] __attribute__((aligned(4))); // Power of 2 -// Copy a received PSDU, stripping the PHR and any stored FCS. +// Copy a received frame, stripping the radio header and any stored CRC static void mg_mg24_rx_frame(RAIL_Handle_t h) { + static uint8_t f[MGI_MG24_HDR + MGI_MG24_MAX + 2]; // Interrupt use only RAIL_RxPacketInfo_t info; - uint8_t f[128]; size_t n; if (RAIL_GetRxPacketInfo(h, RAIL_RX_PACKET_HANDLE_NEWEST, &info) == RAIL_RX_PACKET_HANDLE_INVALID || info.packetStatus != RAIL_RX_PACKET_READY_SUCCESS || - info.packetBytes <= 1 || info.packetBytes > sizeof(f)) { + info.packetBytes <= MGI_MG24_HDR || info.packetBytes > sizeof(f)) { return; } RAIL_CopyRxPacket(f, &info); +#if MG_RADIO == MG_RADIO_BLE + n = f[1]; + if (n + MGI_MG24_HDR > (size_t) info.packetBytes) return; +#else n = info.packetBytes - 1U; // Strip PHR if (n == f[0]) n -= 2; // FCS stored, strip it - mg_mesh_rx_queue(&s_mg24_rx, s_mg24_ifp, f + 1, n); +#endif + mg_radio_rx_queue(s_mg24_ifp, f + MGI_MG24_HDR, n); } // RAIL event callback, runs in interrupt context @@ -33412,17 +32765,21 @@ static void mg_mg24_events(RAIL_Handle_t h, RAIL_Events_t events) { if (events & RAIL_EVENTS_TX_COMPLETION) s_mg24_tx_done = true; } -// RAIL adds the FCS. +// RAIL adds the CRC or FCS static size_t mgi_mg24_radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) { - uint8_t phr = (uint8_t) (len + 2); // FCS is added by hardware +#if MG_RADIO == MG_RADIO_BLE + uint8_t hdr[MGI_MG24_HDR] = {0, (uint8_t) len}; +#else + uint8_t hdr[MGI_MG24_HDR] = {(uint8_t) (len + 2)}; // FCS added by hardware +#endif (void) ifp; - if (len > 125 || s_mg24_txing) return 0; - RAIL_WriteTxFifo(s_mg24_rail, &phr, 1, true); // Reset FIFO, write PHR + if (len > MGI_MG24_MAX || s_mg24_txing) return 0; + RAIL_WriteTxFifo(s_mg24_rail, hdr, sizeof(hdr), true); // Reset, write hdr RAIL_WriteTxFifo(s_mg24_rail, (const uint8_t *) buf, (uint16_t) len, false); s_mg24_tx_done = false; s_mg24_txing = true, s_mg24_txstart = RAIL_GetTime(); - if (RAIL_StartTx(s_mg24_rail, MG_802154_CHANNEL, RAIL_TX_OPTIONS_DEFAULT, + if (RAIL_StartTx(s_mg24_rail, MGI_MG24_CHANNEL, RAIL_TX_OPTIONS_DEFAULT, NULL) != RAIL_STATUS_NO_ERROR) { s_mg24_txing = false; return 0; @@ -33430,11 +32787,46 @@ static size_t mgi_mg24_radio_tx(struct mg_tcpip_if *ifp, const void *buf, return len; } -static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - RAIL_Config_t cfg = {0}; +#if MG_RADIO == MG_RADIO_BLE +// Raw BLE 2 Mbit/s PHY, standard packet as in nrf52.c. The 100 us state +// transitions fit within the mesh's 300 us gap between frames +static bool mgi_mg24_protocol_init(uint16_t addr) { + RAIL_StateTiming_t timing = {0}; + (void) addr; + timing.idleToRx = 100, timing.idleToTx = 100; + timing.rxToTx = 100, timing.txToRx = 100; + return RAIL_BLE_Init(s_mg24_rail) == RAIL_STATUS_NO_ERROR && + RAIL_BLE_ConfigPhy2MbpsViterbi(s_mg24_rail) == RAIL_STATUS_NO_ERROR && + RAIL_BLE_ConfigChannelRadioParams(s_mg24_rail, 0x555555, + MG_RADIO_NETWORK, MG_RADIO_CHANNEL, + false) == RAIL_STATUS_NO_ERROR && + RAIL_SetStateTiming(s_mg24_rail, &timing) == RAIL_STATUS_NO_ERROR; +} +#else +// IEEE 802.15.4 with hardware filtering by PAN ID and our short address +static bool mgi_mg24_protocol_init(uint16_t addr) { RAIL_IEEE802154_Config_t cfg154 = {0}; + RAIL_StateTransitions_t to_rx = {RAIL_RF_STATE_RX, RAIL_RF_STATE_RX}; + cfg154.ackConfig.enable = false; + cfg154.ackConfig.ackTimeout = 864; + cfg154.ackConfig.rxTransitions = to_rx; + cfg154.ackConfig.txTransitions = to_rx; + cfg154.timings.idleToRx = 100, cfg154.timings.idleToTx = 100; + cfg154.timings.rxToTx = 192, cfg154.timings.txToRx = 182; + cfg154.framesMask = RAIL_IEEE802154_ACCEPT_STANDARD_FRAMES; + cfg154.promiscuousMode = false; + return RAIL_IEEE802154_Config2p4GHzRadio(s_mg24_rail) == + RAIL_STATUS_NO_ERROR && + RAIL_IEEE802154_Init(s_mg24_rail, &cfg154) == RAIL_STATUS_NO_ERROR && + RAIL_IEEE802154_SetPanId(s_mg24_rail, MG_RADIO_NETWORK, 0) == + RAIL_STATUS_NO_ERROR && + RAIL_IEEE802154_SetShortAddress(s_mg24_rail, addr, 0) == + RAIL_STATUS_NO_ERROR; +} +#endif + +static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + RAIL_Config_t cfg = {0}; RAIL_TxPowerConfig_t pwr; RAIL_StateTransitions_t to_rx = {RAIL_RF_STATE_RX, RAIL_RF_STATE_RX}; RAIL_Events_t events = RAIL_EVENT_CAL_NEEDED | RAIL_EVENT_RX_PACKET_RECEIVED | @@ -33444,25 +32836,12 @@ static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp) { MG_ERROR(("RAIL_Init failed")); return false; } - cfg154.ackConfig.enable = false; - cfg154.ackConfig.ackTimeout = 864; - cfg154.ackConfig.rxTransitions = to_rx; - cfg154.ackConfig.txTransitions = to_rx; - cfg154.timings.idleToRx = 100, cfg154.timings.idleToTx = 100; - cfg154.timings.rxToTx = 192, cfg154.timings.txToRx = 182; - cfg154.framesMask = RAIL_IEEE802154_ACCEPT_STANDARD_FRAMES; - cfg154.promiscuousMode = false; // Filter by PAN ID and our short address pwr.mode = RAIL_TX_POWER_MODE_2P4GIG_HP, pwr.voltage = 3300; pwr.rampTime = 10; if (RAIL_ConfigCal(s_mg24_rail, RAIL_CAL_ALL) != RAIL_STATUS_NO_ERROR || RAIL_ConfigEvents(s_mg24_rail, RAIL_EVENTS_ALL, events) != RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_Config2p4GHzRadio(s_mg24_rail) != RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_Init(s_mg24_rail, &cfg154) != RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_SetPanId(s_mg24_rail, MG_802154_PAN_ID, 0) != - RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_SetShortAddress(s_mg24_rail, node->radio_address, 0) != - RAIL_STATUS_NO_ERROR || + !mgi_mg24_protocol_init(addr) || RAIL_SetTxTransitions(s_mg24_rail, &to_rx) != RAIL_STATUS_NO_ERROR || RAIL_SetRxTransitions(s_mg24_rail, &to_rx) != RAIL_STATUS_NO_ERROR || RAIL_ConfigTxPower(s_mg24_rail, &pwr) != RAIL_STATUS_NO_ERROR || @@ -33474,69 +32853,32 @@ static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp) { return false; } s_mg24_ifp = ifp; - return RAIL_StartRx(s_mg24_rail, MG_802154_CHANNEL, NULL) == + return RAIL_StartRx(s_mg24_rail, MGI_MG24_CHANNEL, NULL) == RAIL_STATUS_NO_ERROR; } -static size_t mgi_mg24_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_mg24_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_mg24_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; - node->now = now; +static bool mgi_mg24_radio_poll(struct mg_tcpip_if *ifp) { + bool done = false; + (void) ifp; if (s_mg24_txing && (s_mg24_tx_done || RAIL_GetTime() - s_mg24_txstart > - MG_MESH_TX_TIMEOUT_US)) { + MG_RADIO_TX_TIMEOUT_US)) { if (!s_mg24_tx_done) { RAIL_Idle(s_mg24_rail, RAIL_IDLE_ABORT, true); - RAIL_StartRx(s_mg24_rail, MG_802154_CHANNEL, NULL); + RAIL_StartRx(s_mg24_rail, MGI_MG24_CHANNEL, NULL); } s_mg24_txing = false; - node->tx_at = now + node->strategy->radio->ifs_us; + done = true; } - mg_mesh_rx_drain(node, &s_mg24_rx); - node->strategy->tick(node, now); - return node->joined; + return done; } + static bool mgi_mg24_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_mg24_radio_tx; - mg_queue_init(&s_mg24_rx, s_mg24_rxbuf, sizeof(s_mg24_rxbuf)); - if (mgi_mg24_radio_init(ifp)) return true; - data->mesh->strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_mg24_radio_init, mgi_mg24_radio_poll, + mgi_mg24_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_mg24 = {mgi_mg24_init, mgi_mg24_tx, - mgi_mg24_rx, mgi_mg24_poll}; + +struct mg_tcpip_driver mg_tcpip_driver_mg24 = {mgi_mg24_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif #ifdef MG_ENABLE_LINES @@ -34025,11 +33367,25 @@ struct mg_tcpip_driver mg_tcpip_driver_netc = {mg_tcpip_driver_netc_init, #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NRF52) && MG_ENABLE_DRIVER_NRF52 #include +// A packet in RAM: the radio header, then the frame +#if MG_RADIO == MG_RADIO_BLE +#define MGI_NRF52_HDR 2 // S0 byte, unused, then the frame length +#define MGI_NRF52_MAX 251 // Largest frame. The CRC is not in RAM +#define MGI_NRF52_RXSTART EVENTS_ADDRESS // A frame is being received +#define MGI_NRF52_MHZ \ + (MG_RADIO_CHANNEL < 11 ? 2404 + 2 * MG_RADIO_CHANNEL \ + : 2406 + 2 * MG_RADIO_CHANNEL) +#else +#define MGI_NRF52_HDR 1 // PHR: the frame length, FCS included +#define MGI_NRF52_MAX 125 // Largest frame, without the 2 byte FCS +#define MGI_NRF52_RXSTART EVENTS_FRAMESTART // A frame is being received +#endif + +#define MGI_NRF52_IOLEN (MGI_NRF52_HDR + MGI_NRF52_MAX + 2) + static struct mg_tcpip_if *s_nrf52_ifp; -static struct mg_queue s_nrf52_rx; -static char s_nrf52_queue[2048]; -static uint8_t s_nrf52_rxbuf[128] __attribute__((aligned(4))); -static uint8_t s_nrf52_txbuf[128] __attribute__((aligned(4))); +static uint8_t s_nrf52_rxbuf[MGI_NRF52_IOLEN] MG_8BYTE_ALIGNED; +static uint8_t s_nrf52_txbuf[MGI_NRF52_IOLEN] MG_8BYTE_ALIGNED; static volatile bool s_nrf52_txing, s_nrf52_done; static uint64_t s_nrf52_started; @@ -34037,10 +33393,11 @@ static void mgi_nrf52_listen(void) { NRF_RADIO->PACKETPTR = (uint32_t) s_nrf52_rxbuf; NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk | RADIO_SHORTS_END_DISABLE_Msk; - NRF_RADIO->EVENTS_FRAMESTART = 0; + NRF_RADIO->MGI_NRF52_RXSTART = 0; NRF_RADIO->EVENTS_END = 0; NRF_RADIO->TASKS_RXEN = 1; } + static void mgi_nrf52_disable(void) { NRF_RADIO->SHORTS = 0; NRF_RADIO->EVENTS_DISABLED = 0; @@ -34048,6 +33405,7 @@ static void mgi_nrf52_disable(void) { while (!NRF_RADIO->EVENTS_DISABLED) (void) 0; NRF_RADIO->EVENTS_DISABLED = 0; } + void RADIO_IRQHandler(void); void RADIO_IRQHandler(void) { if (!NRF_RADIO->EVENTS_DISABLED) return; @@ -34056,32 +33414,31 @@ void RADIO_IRQHandler(void) { s_nrf52_txing = false; s_nrf52_done = true; } else if (NRF_RADIO->CRCSTATUS) { - struct mg_tcpip_driver_nrf52_data *data = s_nrf52_ifp->driver_data; - struct mg_mesh_node *node = data->mesh; +#if MG_RADIO == MG_RADIO_BLE + size_t len = s_nrf52_rxbuf[1]; +#else size_t len = s_nrf52_rxbuf[0] >= 2 ? s_nrf52_rxbuf[0] - 2U : 0; - uint8_t *frame = s_nrf52_rxbuf + 1; - uint16_t dst, src; - if (len <= 125 && - mg_radio_802154.parse_hdr(&mg_radio_802154, frame, len, &dst, &src) != - 0 && - (dst == 0xffffu || dst == node->radio_address)) { - mg_mesh_rx_queue(&s_nrf52_rx, s_nrf52_ifp, frame, len); - } +#endif + mg_radio_rx_queue(s_nrf52_ifp, s_nrf52_rxbuf + MGI_NRF52_HDR, len); } mgi_nrf52_listen(); } static size_t mgi_nrf52_radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) { (void) ifp; - if (len > 125) return 0; + if (len > MGI_NRF52_MAX) return 0; NVIC_DisableIRQ(RADIO_IRQn); - if (s_nrf52_txing || NRF_RADIO->EVENTS_FRAMESTART) { + if (s_nrf52_txing || NRF_RADIO->MGI_NRF52_RXSTART) { NVIC_EnableIRQ(RADIO_IRQn); return 0; } mgi_nrf52_disable(); +#if MG_RADIO == MG_RADIO_BLE + s_nrf52_txbuf[0] = 0, s_nrf52_txbuf[1] = (uint8_t) len; +#else s_nrf52_txbuf[0] = (uint8_t) (len + 2); - memcpy(s_nrf52_txbuf + 1, buf, len); +#endif + memcpy(s_nrf52_txbuf + MGI_NRF52_HDR, buf, len); s_nrf52_done = false; s_nrf52_txing = true; s_nrf52_started = mg_micros(); @@ -34092,9 +33449,33 @@ static size_t mgi_nrf52_radio_tx(struct mg_tcpip_if *ifp, const void *buf, NVIC_EnableIRQ(RADIO_IRQn); return len; } -static bool mgi_nrf52_radio_init(struct mg_tcpip_if *ifp) { +static bool mgi_nrf52_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { s_nrf52_ifp = ifp; + (void) addr; // Frames are filtered by mg_radio_rx_queue() NRF_RADIO->POWER = 1; +#if MG_RADIO == MG_RADIO_BLE + // Standard BLE packet: 2 byte preamble, access address, S0 byte, 8 bit + // length, payload, 24 bit CRC over everything after the access address, + // initial value 0x555555. Whitening seeded by the channel index + NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_2Mbit; + NRF_RADIO->PCNF0 = (1UL << RADIO_PCNF0_S0LEN_Pos) | + (8UL << RADIO_PCNF0_LFLEN_Pos) | + (RADIO_PCNF0_PLEN_16bit << RADIO_PCNF0_PLEN_Pos); + NRF_RADIO->PCNF1 = ((uint32_t) MGI_NRF52_MAX << RADIO_PCNF1_MAXLEN_Pos) | + (3UL << RADIO_PCNF1_BALEN_Pos) | RADIO_PCNF1_WHITEEN_Msk; + NRF_RADIO->BASE0 = (uint32_t) MG_RADIO_NETWORK << 8; + NRF_RADIO->PREFIX0 = ((uint32_t) MG_RADIO_NETWORK >> 24) & 0xff; + NRF_RADIO->TXADDRESS = 0; + NRF_RADIO->RXADDRESSES = 1; + NRF_RADIO->CRCCNF = + 3 | (RADIO_CRCCNF_SKIPADDR_Skip << RADIO_CRCCNF_SKIPADDR_Pos); + NRF_RADIO->CRCPOLY = 0x65b; + NRF_RADIO->CRCINIT = 0x555555; + NRF_RADIO->DATAWHITEIV = MG_RADIO_CHANNEL; + NRF_RADIO->FREQUENCY = MGI_NRF52_MHZ - 2400; + NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_DTX_Center << RADIO_MODECNF0_DTX_Pos) | + RADIO_MODECNF0_RU_Fast; +#else NRF_RADIO->MODE = RADIO_MODE_MODE_Ieee802154_250Kbit; NRF_RADIO->PCNF0 = (8UL << RADIO_PCNF0_LFLEN_Pos) | (RADIO_PCNF0_PLEN_32bitZero << RADIO_PCNF0_PLEN_Pos) | @@ -34106,42 +33487,26 @@ static bool mgi_nrf52_radio_init(struct mg_tcpip_if *ifp) { NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_DTX_Center << RADIO_MODECNF0_DTX_Pos) | RADIO_MODECNF0_RU_Fast; NRF_RADIO->SFD = 0xa7; - NRF_RADIO->FREQUENCY = 5 * (MG_802154_CHANNEL - 10); - NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Pos8dBm; + NRF_RADIO->FREQUENCY = 5 * (MG_RADIO_CHANNEL - 10); // Correlator threshold 45 matches the RADIO reset value. A threshold of // 20 caused false busy detections and persistent L2 retries. NRF_RADIO->CCACTRL = (RADIO_CCACTRL_CCAMODE_CarrierMode << RADIO_CCACTRL_CCAMODE_Pos) | (2UL << RADIO_CCACTRL_CCACORRCNT_Pos) | (45UL << RADIO_CCACTRL_CCACORRTHRES_Pos); +#endif + NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Pos8dBm; NRF_RADIO->INTENSET = RADIO_INTENSET_DISABLED_Msk; NVIC_SetPriority(RADIO_IRQn, 0); NVIC_EnableIRQ(RADIO_IRQn); mgi_nrf52_listen(); return true; } -static size_t mgi_nrf52_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} -static size_t mgi_nrf52_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; - if (s_nrf52_txing && mg_micros() - s_nrf52_started > MG_MESH_TX_TIMEOUT_US) { +static bool mgi_nrf52_radio_poll(struct mg_tcpip_if *ifp) { + bool done; + (void) ifp; + if (s_nrf52_txing && mg_micros() - s_nrf52_started > MG_RADIO_TX_TIMEOUT_US) { NVIC_DisableIRQ(RADIO_IRQn); mgi_nrf52_disable(); s_nrf52_txing = false; @@ -34149,42 +33514,18 @@ static bool mgi_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { mgi_nrf52_listen(); NVIC_EnableIRQ(RADIO_IRQn); } - if (s_nrf52_done) { - s_nrf52_done = false; - node->tx_at = now + node->strategy->radio->ifs_us; - } - node->now = now; - mg_mesh_rx_drain(node, &s_nrf52_rx); - node->strategy->tick(node, now); - return node->joined; + done = s_nrf52_done; + s_nrf52_done = false; + return done; } static bool mgi_nrf52_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address; - address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_nrf52_radio_tx; - mg_queue_init(&s_nrf52_rx, s_nrf52_queue, sizeof(s_nrf52_queue)); - if (mgi_nrf52_radio_init(ifp)) return true; - strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_nrf52_radio_init, mgi_nrf52_radio_poll, + mgi_nrf52_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_nrf52 = {mgi_nrf52_init, mgi_nrf52_tx, - mgi_nrf52_rx, mgi_nrf52_poll}; +struct mg_tcpip_driver mg_tcpip_driver_nrf52 = {mgi_nrf52_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif #ifdef MG_ENABLE_LINES @@ -34956,6 +34297,728 @@ struct mg_tcpip_driver mg_tcpip_driver_ra = {mg_tcpip_driver_ra_init, #endif +#ifdef MG_ENABLE_LINES +#line 1 "src/drivers/radio.c" +#endif +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + + + + + + +#if MG_ENABLE_TCPIP + +#define MGI_ETH_MAX 1514 +#define MGI_TX_DST_LEN 2 + +// The radio, chosen by MG_RADIO. A frame starts with the radio header, with +// the radio addresses, then the mesh header: type, then burst: the +// fragment's index << 4 | the last fragment's index. Then the payload +#if MG_RADIO == MG_RADIO_BLE +#define MGI_RADIO_MTU 251 // Largest frame: BLE 5 data length +#define MGI_RADIO_BITRATE 2000000 // Bits per second on air +#define MGI_RADIO_OVERHEAD 11 // Preamble, access address, length, CRC +#define MGI_RADIO_TURNAROUND_US 40 // Receive to transmit: nRF52840 fast ramp +#define MGI_RADIO_IFS_US 300 // Gap between transmissions +#define MGI_RADIO_HDR_LEN 4 // Destination, source + +// Write the radio header. Little endian +static void mgi_radio_write_hdr(uint8_t *buf, uint16_t dst, uint16_t src) { + buf[0] = (uint8_t) dst, buf[1] = (uint8_t) (dst >> 8); + buf[2] = (uint8_t) src, buf[3] = (uint8_t) (src >> 8); +} + +// Read the radio header. The access address already keeps other networks out +static bool mgi_radio_parse_hdr(const uint8_t *buf, size_t len, uint16_t *dst, + uint16_t *src) { + if (len < MGI_RADIO_HDR_LEN) return false; + *dst = (uint16_t) (buf[0] | buf[1] << 8); + *src = (uint16_t) (buf[2] | buf[3] << 8); + return true; +} +#else +#define MGI_RADIO_MTU 125 // 127 minus FCS +#define MGI_RADIO_BITRATE 250000 // Bits per second on air +#define MGI_RADIO_OVERHEAD 8 // Preamble, SFD, PHR, FCS +#define MGI_RADIO_TURNAROUND_US 100 // Receive to transmit +#define MGI_RADIO_IFS_US 640 // Gap between transmissions +#define MGI_RADIO_HDR_LEN 9 // MAC header, short addresses + +// MAC header: frame control 0x8841, a data frame, PAN ID compression, short +// destination and source addresses; sequence number, 0, as nothing uses it +// yet; PAN ID; destination; source. Little endian, as the standard says +static void mgi_radio_write_hdr(uint8_t *buf, uint16_t dst, uint16_t src) { + buf[0] = 0x41, buf[1] = 0x88, buf[2] = 0; + buf[3] = (uint8_t) MG_RADIO_NETWORK; + buf[4] = (uint8_t) (MG_RADIO_NETWORK >> 8); + buf[5] = (uint8_t) dst, buf[6] = (uint8_t) (dst >> 8); + buf[7] = (uint8_t) src, buf[8] = (uint8_t) (src >> 8); +} + +// Read the MAC header. Other networks' frames fail the check +static bool mgi_radio_parse_hdr(const uint8_t *buf, size_t len, uint16_t *dst, + uint16_t *src) { + if (len < MGI_RADIO_HDR_LEN || buf[0] != 0x41 || buf[1] != 0x88 || + buf[3] != (uint8_t) MG_RADIO_NETWORK || + buf[4] != (uint8_t) (MG_RADIO_NETWORK >> 8)) { + return false; + } + *dst = (uint16_t) (buf[5] | buf[6] << 8); + *src = (uint16_t) (buf[7] | buf[8] << 8); + return true; +} +#endif + +#define MGI_FRAME_HDR_LEN (MGI_RADIO_HDR_LEN + 2) // Radio and mesh headers +#define MGI_FRAG_CAP (MGI_RADIO_MTU - MGI_FRAME_HDR_LEN) // Payload per frame +#define MGI_TX_QUEUE_SIZE 2048 // Ethernet frames to send, as bursts +#define MGI_RX_STAMP_LEN sizeof(uint64_t) +#define MGI_RX_QUEUE_SIZE (16 * (MGI_RX_STAMP_LEN + MGI_RADIO_MTU + 8)) + +// A radio interface's state, its driver_data, allocated by mg_radio_init() +struct mg_radio_node { + bool (*hw_poll)(struct mg_tcpip_if *); // Hardware: service it + size_t (*hw_tx)(struct mg_tcpip_if *, const void *, size_t); // Start TX + struct mg_tcpip_if *ifp; // Radio interface + struct mg_tcpip_if *lan; // Bridge: LAN interface. NULL: a node + struct mg_queue frames; // Received radio frames, with arrival times + struct mg_queue tx; // Ethernet frames to send, one burst each + uint64_t now; // Current poll time, us + uint64_t tx_at; // Earliest next radio TX, us + uint64_t burst_at; // Next fragment TX, us + uint64_t deadline; // End of the current turn, us + uint64_t expire_at; // Node: no turn by then, leave. 0: had one + uint64_t answer_by; // Node: first answer frame must end by then + size_t rx_len; // Ethernet frame waiting for the stack + size_t tx_offset; // Next fragment of the queued burst + struct mgi_radio_peer *members; // Bridge: members, round-robin order + struct mgi_radio_peer *current; // Bridge: member whose turn is active/next + struct mgi_radio_peer *fanout; // Bridge: next broadcast recipient + uint32_t random; // PRNG state, for join timing + uint16_t radio_address; // Our radio address, made from the MAC + uint16_t coordinator; // Node: the bridge's radio address + uint8_t phase; // Turn: idle, join or data + uint8_t rx_expected; // Next fragment: index << 4 | last index. 0xff: idle + bool joined; // Node: member of the mesh + bool granted; // Node: had a turn this round + uint8_t rx_buf[MGI_ETH_MAX]; // Ethernet frame being reassembled + char tx_buf[MGI_TX_QUEUE_SIZE]; // Storage of the tx queue + char frames_buf[MGI_RX_QUEUE_SIZE]; // Storage of the frames queue +}; + +// Time on air of a len byte frame, us +static uint64_t mgi_radio_airtime(size_t len) { + return ((uint64_t) (len + MGI_RADIO_OVERHEAD) * 8000000 + MGI_RADIO_BITRATE - + 1) / + MGI_RADIO_BITRATE; +} + +// Each queue record holds a destination and a complete burst. +static size_t mgi_radio_queue(struct mg_radio_node *node, struct mg_queue *q, + const void *buf, size_t len, uint16_t dst, + uint8_t type) { + const uint8_t *eth = (const uint8_t *) buf; + size_t hdr = MGI_FRAME_HDR_LEN, cap = MGI_RADIO_MTU - hdr; + size_t frames, size, i; + char *record; + uint8_t *out; + if (len < 14 || len > MGI_ETH_MAX) return 0; + frames = (len + cap - 1) / cap; + size = MGI_TX_DST_LEN + len + frames * (1 + hdr); + if (mg_queue_next(q, NULL) == 0) mg_queue_init(q, q->buf, q->size); + if (mg_queue_book(q, &record, size) < size) { + MG_ERROR(("TX queue full: need %u, head %u, tail %u, size %u", + (unsigned) size, (unsigned) q->head, (unsigned) q->tail, + (unsigned) q->size)); + return 0; + } + out = (uint8_t *) record; + *out++ = (uint8_t) (dst >> 8); + *out++ = (uint8_t) dst; + for (i = 0; i < frames; i++) { + size_t chunk = len - i * cap; + if (chunk > cap) chunk = cap; + *out++ = (uint8_t) (hdr + chunk); + mgi_radio_write_hdr(out, dst, node->radio_address); + out[MGI_RADIO_HDR_LEN] = type; + out[MGI_RADIO_HDR_LEN + 1] = (uint8_t) (i << 4 | (frames - 1)); + memcpy(out + hdr, eth + i * cap, chunk); + out += hdr + chunk; + } + mg_queue_add(q, size); + return len; +} + +#define MGI_JOIN_WINDOW_US 3000 +#define MGI_JOIN_TURN_US 192 +#define MGI_JOIN_JITTER_US 640 +#define MGI_TX_RETRY_US 32 +// Node: finish the first answer frame this much before the bridge stops +// waiting +#define MGI_ANSWER_MARGIN_US 500 +#define MGI_JOIN_UP_LEN (MGI_FRAME_HDR_LEN + 6) // Payload: the MAC address +#define MGI_MAX_FRAGMENTS 14 + +enum { MGI_JOIN_DOWN = 1, MGI_JOIN_UP, MGI_DATA_DOWN, MGI_DATA_UP }; + +enum { MGI_TURN_IDLE, MGI_TURN_JOIN, MGI_TURN_DATA }; + +struct mgi_radio_peer { + struct mgi_radio_peer *next; // Next member in round-robin order + uint16_t radio_address; // Source address supplied in MGI_JOIN_UP + uint8_t mac[6]; // Ethernet MAC supplied in MGI_JOIN_UP + uint64_t expire_at; // First missed turn + MG_RADIO_TIMEOUT_MS, 0: answering +}; + +static uint32_t mgi_radio_random(struct mg_radio_node *node) { + uint32_t *random = &node->random; + if (*random == 0) { + size_t i; + *random = (uint32_t) mg_now(); + for (i = 0; i < 6; i++) *random = *random * 33u + node->ifp->mac[i]; + if (*random == 0) *random = 1; + } + *random ^= *random << 13; + *random ^= *random >> 17; + *random ^= *random << 5; + return *random; +} + +// Read a frame's radio addresses to dst and src, and return its type, from +// the mesh header. 0: not a frame of ours +static unsigned mgi_radio_frame_parse(const uint8_t *frame, size_t len, + uint16_t *dst, uint16_t *src) { + if (len < MGI_FRAME_HDR_LEN || !mgi_radio_parse_hdr(frame, len, dst, src)) { + return 0; + } + return frame[MGI_RADIO_HDR_LEN]; +} + +// Write a frame's headers: the radio's, to dst from src, then ours: type, +// and burst: high nibble is the index, low nibble is the last index +static void mgi_radio_frame_header(uint8_t *frame, uint16_t dst, uint16_t src, + uint8_t type, uint8_t burst) { + mgi_radio_write_hdr(frame, dst, src); + frame[MGI_RADIO_HDR_LEN] = type, frame[MGI_RADIO_HDR_LEN + 1] = burst; +} + +// Hand a radio frame to the hardware. The interface's fn sees it first +static bool mgi_radio_send(struct mg_radio_node *node, const void *frame, + size_t len) { + struct mg_str s = mg_str_n((const char *) frame, len); + mg_tcpip_call(node->ifp, MG_TCPIP_EV_PHY_TX, &s); + return node->hw_tx(node->ifp, frame, len) == len; +} + +static bool mgi_radio_control_send(struct mg_radio_node *node, uint16_t dst, + uint8_t command) { + uint8_t frame[MGI_JOIN_UP_LEN] = {0}; + size_t len = MGI_FRAME_HDR_LEN; + mgi_radio_frame_header(frame, dst, node->radio_address, command, 0); + if (command == MGI_JOIN_UP) { + memcpy(frame + MGI_FRAME_HDR_LEN, node->ifp->mac, 6); + len = MGI_JOIN_UP_LEN; + } + return node->now >= node->tx_at && mgi_radio_send(node, frame, len); +} + +// Time on air of a burst carrying len bytes, gaps between frames included +static uint64_t mgi_radio_burst_time(size_t len) { + size_t frames = len == 0 ? 1 : (len + MGI_FRAG_CAP - 1) / MGI_FRAG_CAP; + return (frames - 1) * (mgi_radio_airtime(MGI_RADIO_MTU) + MGI_RADIO_IFS_US) + + mgi_radio_airtime(MGI_FRAME_HDR_LEN + len - + (frames - 1) * MGI_FRAG_CAP); +} + +// End the current turn. A queued burst is used up only when done: all its +// frames went out. Otherwise it stays queued, and a later turn sends it again +static void mgi_radio_tx_finish(struct mg_radio_node *node, bool done) { + if (node->tx_offset != 0 && done) { + if (node->fanout != NULL) node->fanout = node->fanout->next; + if (node->fanout == NULL) { + size_t len = mg_queue_next(&node->tx, NULL); + mg_queue_del(&node->tx, len); + } + } + node->tx_offset = 0; + node->burst_at = (uint64_t) -1; +} + +static void mgi_radio_tx_step(struct mg_radio_node *node, uint64_t now) { + uint8_t empty[MGI_FRAME_HDR_LEN], *frame = empty; + size_t len = MGI_FRAME_HDR_LEN, record_len = 0; + uint16_t dst; + uint8_t command; + if (now < node->burst_at) return; + if (now >= node->deadline) { + mgi_radio_tx_finish(node, false); + return; + } + dst = node->lan == NULL ? node->coordinator : node->current->radio_address; + command = node->lan == NULL ? MGI_DATA_UP : MGI_DATA_DOWN; + if (node->tx_offset != 0) { + char *record; + uint8_t *part; + record_len = mg_queue_next(&node->tx, &record); + part = (uint8_t *) record + node->tx_offset; + len = part[0]; + frame = part + 1; + mgi_radio_write_hdr(frame, dst, node->radio_address); + } else { + mgi_radio_frame_header(frame, dst, node->radio_address, command, 0); + } + // A node's first answer frame: if it cannot end on air before the bridge + // stops waiting, stay silent. The queued frame waits for the next turn + if (node->lan == NULL && + (node->tx_offset == 0 || node->tx_offset == MGI_TX_DST_LEN) && + now + mgi_radio_airtime(len) > node->answer_by) { + node->tx_offset = 0; + node->burst_at = (uint64_t) -1; + return; + } + if (now < node->tx_at || !mgi_radio_send(node, frame, len)) { + node->burst_at = now + MGI_TX_RETRY_US; + return; + } + if (node->tx_offset == 0 || (node->tx_offset += len + 1) == record_len) { + // Bridge: the turn's last frame is out, wait for the answer + if (node->lan != NULL) + node->deadline = + now + mgi_radio_airtime(len) + MG_RADIO_ANSWER_TIMEOUT_US; + mgi_radio_tx_finish(node, true); + } else { + node->burst_at = now + mgi_radio_airtime(len) + MGI_RADIO_IFS_US; + } +} + +static void mgi_radio_tx_begin(struct mg_radio_node *node, bool burst, + uint64_t now, uint64_t deadline) { + node->phase = MGI_TURN_DATA; + node->answer_by = (uint64_t) -1; // Node sets it after a grant + node->tx_offset = burst ? MGI_TX_DST_LEN : 0; + node->burst_at = now; + node->deadline = deadline; +} + +// Return the assembled length, zero for an empty frame, or -1 if incomplete +// or invalid. Full non-final fragments make the write offset derivable. +static int mgi_radio_data_receive(struct mg_radio_node *node, + const uint8_t *frame, size_t len, + uint64_t now) { + unsigned burst = frame[MGI_FRAME_HDR_LEN - 1], index = burst >> 4, + last = burst & 15; + size_t chunk = len - MGI_FRAME_HDR_LEN, cap = MGI_FRAG_CAP; + size_t offset = index * cap; + if (index == 0) { + node->rx_expected = (uint8_t) burst; + if (node->lan == NULL) + node->deadline = now + mgi_radio_burst_time(MGI_ETH_MAX) + + 2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US; + } + if (last >= MGI_MAX_FRAGMENTS || index > last || burst != node->rx_expected || + chunk > cap || now > node->deadline || (index < last && chunk != cap) || + (last != 0 && chunk == 0) || offset + chunk > sizeof(node->rx_buf)) { + MG_ERROR( + ("%s: fragment %u/%u dropped, expected %u/%u, %u bytes, %lld us " + "past deadline", + node->lan == NULL ? "Node" : "Bridge", index, last, + (unsigned) node->rx_expected >> 4, node->rx_expected & 15U, + (unsigned) chunk, (long long) (now - node->deadline))); + node->rx_expected = 0xff; + return -1; + } + memcpy(node->rx_buf + offset, frame + MGI_FRAME_HDR_LEN, chunk); + if (index < last) { + node->rx_expected = (uint8_t) (burst + 0x10); + // Bridge: an answer is under way, wait for its next fragment + if (node->lan != NULL) + node->deadline = now + mgi_radio_airtime(MGI_RADIO_MTU) + + MGI_RADIO_IFS_US + MG_RADIO_ANSWER_TIMEOUT_US; + return -1; + } + node->rx_expected = 0xff; + return offset + chunk == 0 || offset + chunk >= 14 ? (int) (offset + chunk) + : -1; +} + +// Bridge scheduling and Ethernet forwarding. + +static uint16_t mgi_radio_join_field(const uint8_t *p) { + return (uint16_t) ((unsigned) p[0] * 256 + p[1]); +} + +// Return chaddr for an Ethernet DHCP server reply, even when broadcast. +static const uint8_t *mgi_radio_dhcp_client(const uint8_t *frame, size_t len) { + size_t ip_len, ihl, udp_len; + const uint8_t *udp, *dhcp; + if (len < 34 || mgi_radio_join_field(frame + 12) != 0x0800 || + (frame[14] >> 4) != 4 || frame[23] != 17 || + (mgi_radio_join_field(frame + 20) & 0x3fff) != 0) + return NULL; + ip_len = mgi_radio_join_field(frame + 16); + ihl = (size_t) (frame[14] & 15) * 4; + if (ihl < 20 || ip_len > len - 14 || ip_len < ihl + 8 + 240) return NULL; + udp = frame + 14 + ihl; + udp_len = mgi_radio_join_field(udp + 4); + if (mgi_radio_join_field(udp) != 67 || mgi_radio_join_field(udp + 2) != 68 || + udp_len < 8 + 240 || udp_len > ip_len - ihl) + return NULL; + dhcp = udp + 8; + if (dhcp[0] != 2 || dhcp[1] != 1 || dhcp[2] != 6 || + memcmp(dhcp + 236, "\x63\x82\x53\x63", 4) != 0) + return NULL; + return dhcp + 28; +} + +static size_t mgi_radio_enqueue(struct mg_radio_node *node, const void *buf, + size_t len) { + const uint8_t *frame = (const uint8_t *) buf; + if (node->lan == NULL) + return mgi_radio_queue(node, &node->tx, buf, len, node->coordinator, + MGI_DATA_UP); + if (len >= 14 && len <= MGI_ETH_MAX) { + const uint8_t *client = mgi_radio_dhcp_client(frame, len); + const uint8_t *dst = client == NULL ? frame : client; + bool multicast = client == NULL && (frame[0] & 1) != 0; + struct mgi_radio_peer *peer; + for (peer = node->members; peer != NULL; peer = peer->next) { + if (multicast || memcmp(dst, peer->mac, 6) == 0) { + uint16_t addr = multicast ? 0xffffu : peer->radio_address; + return mgi_radio_queue(node, &node->tx, buf, len, addr, MGI_DATA_DOWN); + } + } + } + return 0; +} + +static void mgi_radio_bridge_queue_lan(struct mg_radio_node *bridge) { + struct mg_queue *rx = &bridge->lan->recv_queue; + char *buf; + size_t len; + while ((len = mg_queue_next(rx, &buf)) > 0) { + bridge->ifp->driver->tx(buf, len, bridge->ifp); + mg_queue_del(rx, len); + } +} + +static void mgi_radio_bridge_rx(uint64_t now, struct mg_radio_node *b, + const uint8_t *frame, size_t len) { + struct mgi_radio_peer *peer; + uint16_t dst = 0, src = 0; + unsigned command = mgi_radio_frame_parse(frame, len, &dst, &src); + if (command == MGI_DATA_UP && dst == b->radio_address && + b->phase == MGI_TURN_DATA && b->current != NULL && + src == b->current->radio_address && now <= b->deadline) { + int received = mgi_radio_data_receive(b, frame, len, now); + if (received < 0) return; + if (received != 0) { + b->lan->driver->tx(b->rx_buf, (size_t) received, b->lan); + } + b->current->expire_at = 0; + b->current = b->current->next; + b->phase = MGI_TURN_IDLE; + b->deadline = now; + return; + } + if (command == MGI_DATA_UP && dst == b->radio_address) { + MG_ERROR( + ("Bridge: fragment %u/%u from %04x outside its turn: phase %u, " + "turn of %04x, %lld us past deadline", + frame[MGI_FRAME_HDR_LEN - 1] >> 4U, frame[MGI_FRAME_HDR_LEN - 1] & 15U, + src, b->phase, b->current == NULL ? 0 : b->current->radio_address, + (long long) (now - b->deadline))); + return; + } + if (len != MGI_JOIN_UP_LEN || command != MGI_JOIN_UP || + dst != b->radio_address || b->phase != MGI_TURN_JOIN || + now >= b->deadline) { + return; + } + if (src == 0 || src == 0xffffu) return; + for (peer = b->members; peer != NULL; peer = peer->next) { + if (peer->radio_address == src) break; + } + if (peer == NULL) { + peer = (struct mgi_radio_peer *) mg_calloc(1, sizeof(*peer)); + if (peer == NULL) return; + peer->radio_address = src; + peer->next = b->members; + b->members = peer; + MG_DEBUG(("Member %M joined, radio address %04x", mg_print_mac, + frame + MGI_FRAME_HDR_LEN, src)); + } + memcpy(peer->mac, frame + MGI_FRAME_HDR_LEN, sizeof(peer->mac)); + peer->expire_at = 0; +} + +// Member peer did not answer its turn. The first miss starts the timeout. If +// it is still silent when that ends, it is gone: remove it, and its queued +// downlink frames +static void mgi_radio_member_missed(struct mg_radio_node *node, + struct mgi_radio_peer *peer, uint64_t now) { + if (peer->expire_at == 0) peer->expire_at = now + MG_RADIO_TIMEOUT_MS * 1000; + if (now < peer->expire_at) return; + MG_DEBUG(("Member %M removed: no answer for %d ms", mg_print_mac, peer->mac, + MG_RADIO_TIMEOUT_MS)); + if (node->fanout == peer) { + node->fanout = peer->next; + if (node->fanout == NULL) { + size_t len = mg_queue_next(&node->tx, NULL); + mg_queue_del(&node->tx, len); + } + } + LIST_DELETE(struct mgi_radio_peer, &node->members, peer); + mg_free(peer); +} + +// A broadcast occupies one record and is sent once to each member in list +// order. +static size_t mgi_radio_bridge_burst(struct mg_radio_node *node, + struct mgi_radio_peer *peer) { + char *record; + size_t len; + while ((len = mg_queue_next(&node->tx, &record)) != 0) { + uint16_t dst = mgi_radio_join_field((const uint8_t *) record); + struct mgi_radio_peer *member; + if (dst == 0xffffu) { + if (node->fanout == NULL) node->fanout = node->members; + return node->fanout == peer ? len : 0; + } + if (dst == peer->radio_address) return len; + for (member = node->members; member != NULL; member = member->next) { + if (member->radio_address == dst) return 0; + } + mg_queue_del(&node->tx, len); // Its destination has left. + } + return 0; +} + +static uint64_t mgi_radio_queued_burst_time(struct mg_radio_node *node, + size_t len) { + char *record; + size_t frames; + if (len == 0) return mgi_radio_burst_time(0); + mg_queue_next(&node->tx, &record); + // Fragment zero carries the final index. Count overhead and IFS per frame. + frames = ((uint8_t) record[MGI_TX_DST_LEN + MGI_FRAME_HDR_LEN] & 15u) + 1u; + return mgi_radio_airtime(len - MGI_TX_DST_LEN - frames + + (frames - 1) * MGI_RADIO_OVERHEAD) + + (frames - 1) * MGI_RADIO_IFS_US; +} + +static void mgi_radio_bridge_io(uint64_t now, struct mg_radio_node *b) { + mgi_radio_bridge_queue_lan(b); + if (now >= b->deadline) { + if (b->burst_at != (uint64_t) -1) mgi_radio_tx_finish(b, false); + if (b->phase == MGI_TURN_DATA && b->current != NULL) { + struct mgi_radio_peer *peer = b->current; + b->current = peer->next; + mgi_radio_member_missed(b, peer, now); + } else if (b->phase == MGI_TURN_JOIN) { + b->current = b->members; + } + b->phase = MGI_TURN_IDLE; + if (b->current != NULL) { + size_t burst = mgi_radio_bridge_burst(b, b->current); + uint64_t down = mgi_radio_queued_burst_time(b, burst); + b->rx_expected = 0xff; + down += mgi_radio_burst_time(MGI_ETH_MAX); + mgi_radio_tx_begin(b, burst != 0, now, + now + down + 2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US); + } else if (mgi_radio_control_send(b, 0xffffu, MGI_JOIN_DOWN)) { + b->phase = MGI_TURN_JOIN; + b->deadline = now + MGI_JOIN_WINDOW_US; + } + if (b->deadline <= now) b->deadline = now + MGI_JOIN_TURN_US; + } +} + +static void mgi_radio_node_rx(struct mg_radio_node *n, uint64_t now, + uint8_t *frame, size_t len) { + uint16_t dst = 0, src = 0; + unsigned command = mgi_radio_frame_parse(frame, len, &dst, &src); + if (command == MGI_JOIN_DOWN && len == MGI_FRAME_HDR_LEN && dst == 0xffffu) { + // A round without our turn starts the timeout, a turn clears it + if (n->joined && src == n->coordinator && n->granted) { + n->granted = false; + } else if (n->joined && src == n->coordinator && n->expire_at == 0) { + n->expire_at = now + MG_RADIO_TIMEOUT_MS * 1000; + } else if (n->joined && src == n->coordinator && now >= n->expire_at) { + MG_INFO(("Left the mesh: no turn for %d ms", MG_RADIO_TIMEOUT_MS)); + n->joined = false; + n->phase = MGI_TURN_IDLE; + n->burst_at = (uint64_t) -1; + n->tx_offset = 0; + n->rx_expected = 0xff; + } + if (!n->joined && (mgi_radio_random(n) % 64) == 0) { + // Spread contenders across windows as well as within the reply window. + n->coordinator = src; + n->phase = MGI_TURN_JOIN; + n->burst_at = + now + MGI_JOIN_TURN_US + mgi_radio_random(n) % MGI_JOIN_JITTER_US; + } + } else if (command == MGI_DATA_DOWN && n->coordinator != 0 && + dst == n->radio_address && src == n->coordinator) { + int received = mgi_radio_data_receive(n, frame, len, now); + if (received < 0) return; + if (!n->joined) MG_INFO(("Joined the mesh, bridge address %04x", src)); + n->joined = true; + n->granted = true; + n->expire_at = 0; + if (received != 0) { + struct mg_tcpip_if *ifp = n->ifp; + if (n->rx_len != 0 || (size_t) received > ifp->recv_queue.size) { + ifp->ndrop++; + } else { + memcpy(ifp->recv_queue.buf, n->rx_buf, (size_t) received); + n->rx_len = (size_t) received; + } + } + // A grant that waited in the receive queue while the node was busy, e.g. + // computing TLS keys, is too old to answer. Leave the turn state alone: + // queued frames go out on the first grant that can still be answered + if (n->now + MGI_ANSWER_MARGIN_US >= now + MG_RADIO_ANSWER_TIMEOUT_US) { + return; + } + if (n->burst_at != (uint64_t) -1) mgi_radio_tx_finish(n, false); + mgi_radio_tx_begin(n, mg_queue_next(&n->tx, NULL) != 0, now, + now + mgi_radio_burst_time(MGI_ETH_MAX) + + 2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US); + n->answer_by = now + MG_RADIO_ANSWER_TIMEOUT_US - MGI_ANSWER_MARGIN_US; + } +} + +// Handle a received radio frame. Its timing counts from its arrival, us +static void mgi_radio_input(struct mg_radio_node *node, uint64_t arrived, + void *buf, size_t len) { + uint64_t ready = node->now + MGI_RADIO_TURNAROUND_US; + if (node->tx_at < ready) node->tx_at = ready; + if (node->lan != NULL) { + mgi_radio_bridge_rx(arrived, node, (const uint8_t *) buf, len); + } else { + mgi_radio_node_rx(node, arrived, (uint8_t *) buf, len); + } +} + +static void mgi_radio_tick(struct mg_radio_node *node, uint64_t now) { + node->now = now; + if (node->lan != NULL) { + mgi_radio_bridge_io(now, node); + mgi_radio_tx_step(node, now); + return; + } + if (node->phase == MGI_TURN_JOIN) { + if (node->burst_at <= now) { + if (now - node->burst_at <= MGI_JOIN_TURN_US && !node->joined) + mgi_radio_control_send(node, node->coordinator, MGI_JOIN_UP); + node->burst_at = (uint64_t) -1; + node->phase = MGI_TURN_IDLE; + } + } else { + mgi_radio_tx_step(node, now); + } +} + +bool mg_radio_init(struct mg_tcpip_if *ifp, + bool (*hw_init)(struct mg_tcpip_if *, uint16_t addr), + bool (*hw_poll)(struct mg_tcpip_if *), + size_t (*hw_tx)(struct mg_tcpip_if *, const void *, + size_t)) { + struct mg_radio_node *node = + (struct mg_radio_node *) mg_calloc(1, sizeof(*node)); + if (node == NULL) return false; + node->hw_poll = hw_poll, node->hw_tx = hw_tx; + node->ifp = ifp; + node->radio_address = + (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); + node->burst_at = (uint64_t) -1; + node->rx_expected = 0xff; + mg_queue_init(&node->tx, node->tx_buf, sizeof(node->tx_buf)); + mg_queue_init(&node->frames, node->frames_buf, sizeof(node->frames_buf)); + ifp->driver_data = node; + if (hw_init(ifp, node->radio_address)) return true; + ifp->driver_data = NULL; + mg_free(node); + return false; +} + +void mg_radio_bridge(struct mg_tcpip_if *ifp, struct mg_tcpip_if *lan) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + node->lan = lan; +} + +size_t mg_radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + size_t n = mgi_radio_enqueue(node, buf, len); + if (n != len) { // Mongoose ignores a failed send: count and report it + ifp->nerr++; + MG_ERROR(("Mesh refused a %u byte frame", (unsigned) len)); + } + return n; +} + +size_t mg_radio_rx(void *buf, size_t len, struct mg_tcpip_if *ifp) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + size_t n = node->rx_len; + if (n > len) return 0; + if (n != 0 && buf != ifp->recv_queue.buf) memcpy(buf, ifp->recv_queue.buf, n); + node->rx_len = 0; + return n; +} + +void mg_radio_rx_queue(struct mg_tcpip_if *ifp, const void *frame, size_t len) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + uint64_t arrived = mg_micros(); + size_t need = MGI_RX_STAMP_LEN + len; + uint16_t dst, src; + char *p; + if (len > MGI_RADIO_MTU || + !mgi_radio_parse_hdr((const uint8_t *) frame, len, &dst, &src) || + (dst != 0xffffu && dst != node->radio_address)) { + return; + } + if (mg_queue_book(&node->frames, &p, need) < need) { + ifp->ndrop++; + return; + } + memcpy(p, &arrived, MGI_RX_STAMP_LEN); + memcpy(p + MGI_RX_STAMP_LEN, frame, len); + mg_queue_add(&node->frames, need); +} + +// Process queued radio frames, oldest first, each with its arrival time. +// Stop while the node holds an Ethernet frame the TCP/IP stack has not taken +// yet +bool mg_radio_poll(struct mg_tcpip_if *ifp, bool s1) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + bool tx_done = node->hw_poll(ifp); + uint64_t now = mg_micros(); + char *record; + size_t len; + (void) s1; + if (tx_done) node->tx_at = now + MGI_RADIO_IFS_US; + node->now = now; + while (node->rx_len == 0 && + (len = mg_queue_next(&node->frames, &record)) != 0) { + if (len > MGI_RX_STAMP_LEN) { + struct mg_str s = + mg_str_n(record + MGI_RX_STAMP_LEN, len - MGI_RX_STAMP_LEN); + uint64_t arrived; + memcpy(&arrived, record, MGI_RX_STAMP_LEN); + mg_tcpip_call(ifp, MG_TCPIP_EV_PHY_RX, &s); + mgi_radio_input(node, arrived, s.buf, s.len); + } + mg_queue_del(&node->frames, len); + } + mgi_radio_tick(node, now); + return node->joined; +} + +#endif + #ifdef MG_ENABLE_LINES #line 1 "src/drivers/rw612.c" #endif @@ -35171,6 +35234,10 @@ struct mg_tcpip_driver mg_tcpip_driver_rw612 = {mg_tcpip_driver_rw612_init, #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612W) && \ MG_ENABLE_DRIVER_RW612W +#if MG_RADIO != MG_RADIO_802154 +#error "MG_ENABLE_DRIVER_RW612W supports MG_RADIO_802154 only" +#endif + #ifdef ENET @@ -35279,8 +35346,6 @@ struct mg_rw612 { struct mg_tcpip_if *ifp; // Our interface, for the L2 receive pool }; static struct mg_rw612 s_rw612; -static struct mg_queue s_rw612w_rx; -static char s_rw612w_queue[2048]; static void mg_rw612_imu_send(uint8_t type, uint8_t subtype, const uint32_t *payload, uint8_t len) { @@ -35304,7 +35369,7 @@ static void mg_rw612_control(uint8_t subtype, uint32_t a, uint32_t b, } static void mg_rw612_queue_rx(const uint8_t *frame, size_t len) { - mg_mesh_rx_queue(&s_rw612w_rx, s_rw612.ifp, frame, len); + mg_radio_rx_queue(s_rw612.ifp, frame, len); } // Spinel packed unsigned integer: 7 bits per byte, LSB first @@ -35527,7 +35592,7 @@ static size_t mgi_rw612w_radio_tx(struct mg_tcpip_if *ifp, const void *buf, memcpy(f + n, buf, len), n += len; f[n++] = 0, f[n++] = 0; // FCS, filled in by the radio (void) ifp; - f[n++] = MG_802154_CHANNEL; + f[n++] = MG_RADIO_CHANNEL; f[n++] = 0; // Max CSMA backoffs f[n++] = 0; // Max frame retries f[n++] = 0; // CSMA disabled for scheduled turns @@ -35536,11 +35601,9 @@ static size_t mgi_rw612w_radio_tx(struct mg_tcpip_if *ifp, const void *buf, return len; } -static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp) { +static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp, uint16_t address) { struct mg_rw612 *s = &s_rw612; - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint8_t f[8], one = 1, zero = 0, pan[2], addr[2], channel = MG_802154_CHANNEL; + uint8_t f[8], one = 1, zero = 0, pan[2], addr[2], channel = MG_RADIO_CHANNEL; uint64_t expire; if (MGI_MBOX->magic[0] != MGI_SYNC_MAGIC) { MG_ERROR(("Radio firmware is not running on CPU2")); @@ -35579,10 +35642,10 @@ static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp) { if (!mg_rw612_set(MGI_PROP_PHY_ENABLED, &one, 1)) { return mg_rw612_fail("PHY enable failed"); } - pan[0] = (uint8_t) MG_802154_PAN_ID; - pan[1] = (uint8_t) (MG_802154_PAN_ID >> 8); - addr[0] = (uint8_t) node->radio_address; - addr[1] = (uint8_t) (node->radio_address >> 8); + pan[0] = (uint8_t) MG_RADIO_NETWORK; + pan[1] = (uint8_t) (MG_RADIO_NETWORK >> 8); + addr[0] = (uint8_t) address; + addr[1] = (uint8_t) (address >> 8); if (!mg_rw612_set(MGI_PROP_PHY_CHAN, &channel, 1) || !mg_rw612_set(MGI_PROP_PANID, pan, 2) || !mg_rw612_set(MGI_PROP_SADDR, addr, 2) || @@ -35595,74 +35658,32 @@ static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp) { return true; } -static size_t mgi_rw612w_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_rw612w_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_rw612w_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; +static bool mgi_rw612w_radio_poll(struct mg_tcpip_if *ifp) { bool was_sending = s_rw612.txing; + (void) ifp; mg_rw612_poll_imu(); if (s_rw612.txing && (s_rw612.rsp || mg_millis() > s_rw612.txstart + MGI_TX_TIMEOUT_MS)) { if (!s_rw612.rsp) MG_ERROR(("TX timeout")); s_rw612.txing = false; } - if (was_sending && !s_rw612.txing) - node->tx_at = now + node->strategy->radio->ifs_us; - node->now = now; - mg_mesh_rx_drain(node, &s_rw612w_rx); - node->strategy->tick(node, now); - return node->joined; + return was_sending && !s_rw612.txing; } +// The MAC comes from the chip's unique ID static bool mgi_rw612w_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; uint8_t uid[FSL_OCOTP_UID_LENGTH] = {0}, digest[32]; uint32_t uid_len = sizeof(uid); - uint16_t address; OCOTP_ReadUniqueID(uid, &uid_len); mg_sha256(digest, uid, sizeof(uid)); memcpy(ifp->mac, digest, 6); ifp->mac[0] = 0x02; - address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_rw612w_radio_tx; - mg_queue_init(&s_rw612w_rx, s_rw612w_queue, sizeof(s_rw612w_queue)); - if (mgi_rw612w_radio_init(ifp)) return true; - strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_rw612w_radio_init, mgi_rw612w_radio_poll, + mgi_rw612w_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_rw612w = { - mgi_rw612w_init, mgi_rw612w_tx, mgi_rw612w_rx, mgi_rw612w_poll}; +struct mg_tcpip_driver mg_tcpip_driver_rw612w = {mgi_rw612w_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif #ifdef MG_ENABLE_LINES @@ -37784,53 +37805,65 @@ struct mg_tcpip_driver mg_tcpip_driver_tms570 = {mg_tcpip_driver_tms570_init, -#if MG_ENABLE_USB -// Interfaces: NCM control and data 0/1 if enabled, then ACM control and data -#define MG_USB_SERIAL_IF (2 * MG_ENABLE_USB_ETHERNET) -#define MG_USB_NUM_IFS (2 * MG_ENABLE_USB_ETHERNET + 2 * MG_ENABLE_USB_SERIAL) -#define MG_USB_CONFIG_LEN \ + + +// USB Ethernet needs the TCP/IP stack, the serial console does not +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + (MG_ENABLE_DRIVER_USB_RP || MG_ENABLE_DRIVER_USB_NRF52 || \ + MG_ENABLE_DRIVER_USB_DWC2) && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// Interfaces: ACM control and data 0/1 if enabled, then NCM control and data. +// The serial port comes first, so that its name on macOS does not depend on +// Ethernet: /dev/cu.usbmodem...01 +#define MGI_USB_ETH_IF (MG_USB_IF_ETH_DATA - 1) +#define MGI_USB_NUM_IFS (2 * MG_ENABLE_USB_ETHERNET + 2 * MG_ENABLE_USB_SERIAL) +#define MGI_USB_CONFIG_LEN \ (9 + 85 * MG_ENABLE_USB_ETHERNET + 66 * MG_ENABLE_USB_SERIAL) #if MG_ENABLE_USB_ETHERNET -#define MG_USB_PRODUCT "MongooseUsbEthernet" +#define MGI_USB_PRODUCT "MongooseUsbEthernet" #else -#define MG_USB_PRODUCT "MongooseUsbSerial" +#define MGI_USB_PRODUCT "MongooseUsbSerial" #endif -// 0xdead is our example VID, for development only +// VID 0xadde, PID 0x40e4: an example, for development only static const uint8_t s_device_desc[] = { 18, 1, 1, 2, 0xef, 2, 1, 64, 0xde, 0xad, 0xe4, 0x40, 0, 1, 1, 2, 3, 1}; // NCM: endpoints 0x81, 0x02/0x82. ACM: endpoints 0x83, 0x04/0x84 +// clang-format off static const uint8_t s_config_desc[] = { - 9, 2, MG_USB_CONFIG_LEN, 0, MG_USB_NUM_IFS, 1, 0, 0x80, 50, // Config -#if MG_ENABLE_USB_ETHERNET - 8, 11, 0, 2, 2, 13, 0, 4, // NCM association - 9, 4, 0, 0, 1, 2, 13, 0, 4, // NCM control interface - 5, 0x24, 0, 0x20, 1, // CDC header - 5, 0x24, 6, 0, 1, // Union - 13, 0x24, 15, 5, 0, 0, 0, 0, 0xea, - 5, 0, 0, 0, // Eth, 1514 bytes - 6, 0x24, 0x1a, 0, 1, 0x21, // NCM 1.0 - 7, 5, 0x81, 3, 16, 0, 16, // Notification endpoint - 9, 4, 1, 0, 0, 10, 0, 1, 0, // Data interface, off - 9, 4, 1, 1, 2, 10, 0, 1, 0, // Data interface, on - 7, 5, 0x02, 2, 64, 0, 0, // Data OUT - 7, 5, 0x82, 2, 64, 0, 0, // Data IN -#endif + 9, 2, MGI_USB_CONFIG_LEN, 0, MGI_USB_NUM_IFS, 1, 0, 0x80, + 50, // Config #if MG_ENABLE_USB_SERIAL - 8, 11, MG_USB_SERIAL_IF, 2, 2, 2, 1, 6, // ACM association - 9, 4, MG_USB_SERIAL_IF, 0, 1, 2, 2, 1, 6, // ACM control interface - 5, 0x24, 0, 0x20, 1, // CDC header - 5, 0x24, 1, 0, MG_USB_SERIAL_IF + 1, // Call management - 4, 0x24, 2, 2, // ACM - 5, 0x24, 6, MG_USB_SERIAL_IF, MG_USB_SERIAL_IF + 1, // Union - 7, 5, 0x83, 3, 16, 0, 16, // Notification endpoint - 9, 4, MG_USB_SERIAL_IF + 1, 0, 2, 10, 0, 0, 0, // Data interface - 7, 5, 0x04, 2, 64, 0, 0, // Data OUT - 7, 5, 0x84, 2, 64, 0, 0, // Data IN + 8, 11, 0, 2, 2, 2, 1, 6, // ACM association + 9, 4, 0, 0, 1, 2, 2, 1, 6, // ACM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 1, 0, 1, // Call management + 4, 0x24, 2, 2, // ACM + 5, 0x24, 6, 0, 1, // Union + 7, 5, 0x83, 3, 16, 0, 16, // Notification endpoint + 9, 4, 1, 0, 2, 10, 0, 0, 0, // Data interface + 7, 5, 0x04, 2, 64, 0, 0, // Data OUT + 7, 5, 0x84, 2, 64, 0, 0, // Data IN +#endif +#if MG_ENABLE_USB_ETHERNET + 8, 11, MGI_USB_ETH_IF, 2, 2, 13, 0, 4, // NCM association + 9, 4, MGI_USB_ETH_IF, 0, 1, 2, 13, 0, 4, // NCM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 6, MGI_USB_ETH_IF, MGI_USB_ETH_IF + 1, // Union + 13, 0x24, 15, 5, 0, 0, 0, 0, 0xea, + 5, 0, 0, 0, // Eth, 1514 bytes + 6, 0x24, 0x1a, 0, 1, 0x21, // NCM 1.0 + 7, 5, 0x81, 3, 16, 0, 16, // Notification endpoint + 9, 4, MGI_USB_ETH_IF + 1, 0, 0, 10, 0, 1, 0, // Data interface, off + 9, 4, MGI_USB_ETH_IF + 1, 1, 2, 10, 0, 1, 0, // Data interface, on + 7, 5, 0x02, 2, 64, 0, 0, // Data OUT + 7, 5, 0x82, 2, 64, 0, 0, // Data IN #endif }; +// clang-format on // Endpoint addresses, for CLEAR_FEATURE(ENDPOINT_HALT) static const uint8_t s_endpoints[] = { @@ -37844,12 +37877,14 @@ static const uint8_t s_endpoints[] = { #if MG_ENABLE_USB_ETHERNET // Windows 11 binds its NCM driver through a Microsoft OS 2.0 compatible ID +// clang-format off static const uint8_t s_ms_os_desc[] = { 10, 0, 0, 0, 0, 0, 3, 6, 46, 0, // Set header, Windows 8.1+ 8, 0, 1, 0, 0, 0, 36, 0, // Configuration subset - 8, 0, 2, 0, 0, 0, 28, 0, // Function subset, NCM + 8, 0, 2, 0, MGI_USB_ETH_IF, 0, 28, 0, // Function subset, NCM 20, 0, 3, 0, 'W', 'I', 'N', 'N', 'C', 'M', // Compatible ID 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +// clang-format on static const uint8_t s_bos_desc[] = { 5, 15, 33, 0, 1, 28, 16, 5, 0, 0xdf, 0x60, 0xdd, 0xd8, 0x89, 0x45, 0xc7, 0x4c, 0x9c, 0xd2, 0x65, @@ -37876,51 +37911,123 @@ static const uint8_t s_nth[30] = {'N', 'C', 'M', 'H', 12, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0}; #endif -// Build string descriptor i in u->buf. Returns its length, 0 if none -static int string_desc(struct mg_usb *u, unsigned i) { - static const char *strings[] = { - NULL, "Mongoose", MG_USB_PRODUCT, NULL, - "USB Ethernet", NULL, "USB Serial"}; - const char *s = i < 7 ? strings[i] : NULL; +// An IN transfer on an endpoint, sent a packet at a time +struct mgi_usb_in { + const uint8_t *data; // Bytes still to send + size_t left; // How many + unsigned packets; // Packets still to send: a short or empty one ends it + bool busy; // A packet is waiting for the host +}; + +// The USB device. There is one +static struct mgi_usb { + const struct mg_usb_hw *hw; // Controller, NULL until mg_usb_init() + struct mgi_usb_in in[5]; // IN transfers, by endpoint + char serial[17]; // Serial number, from the controller + bool configured; // Host has set the configuration + uint8_t buf[66]; // Generated control replies #if MG_ENABLE_USB_ETHERNET - char mac[13]; + struct mg_tcpip_if *ifp; // Ethernet interface, NULL: serial only + bool alt; // Ethernet open: data interface setting 1 + uint16_t filter, sequence; // Host packet filter, next IN block number + uint32_t input_size; // Largest IN block the host accepts + uint8_t notify; // Pending link notifications + struct mg_queue txq; // Transfer blocks for the host, see tx + char txq_buf[MG_USB_TX_SIZE]; // Its storage + uint8_t rx[MG_USB_NTB_SIZE]; // OUT transfer block being received + size_t rxlen; // How much of it arrived + bool discard; // It is too long: drop it #endif - size_t k, n; - if (i == 0) return u->buf[0] = 4, u->buf[1] = 3, u->buf[2] = 9, u->buf[3] = 4; - if (i == 3) s = u->serial; +#if MG_ENABLE_USB_SERIAL + bool dtr; // Terminal open + uint64_t reboot; // mg_millis() to enter the bootloader, or 0 + uint8_t line[7]; // Serial line coding + char log[MG_USB_LOG_SIZE]; // Log ring + unsigned head, tail; // Log ring write and read counters + char out[64]; // Log output being sent +#endif +} s_usb; + +// Send the next packet of the IN transfer on ep. False if it is over +static bool mgi_usb_in_next(unsigned ep) { + struct mgi_usb_in *e = &s_usb.in[ep]; + size_t n = e->left > 64 ? 64 : e->left; + if (e->packets == 0) return false; + s_usb.hw->in((enum mg_usb_ep) ep, e->data, n); + e->data += n, e->left -= n, e->packets--; + return true; +} + +// Start an IN transfer. zlp: end a multiple of 64 bytes with an empty packet +static void mgi_usb_in_start(unsigned ep, const void *data, size_t len, + bool zlp) { + struct mgi_usb_in *e = &s_usb.in[ep]; + e->data = (const uint8_t *) data, e->left = len; + e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); + e->busy = mgi_usb_in_next(ep); +} + +// Cancel the transfers on ep +static void mgi_usb_idle(unsigned ep) { + memset(&s_usb.in[ep], 0, sizeof(s_usb.in[ep])); #if MG_ENABLE_USB_ETHERNET - if (i == 5) { // Host end of the link: the device MAC, first byte changed - uint8_t *m = u->ifp->mac; - mg_snprintf(mac, sizeof(mac), "%02X%02X%02X%02X%02X%02X", + if (ep == MG_USB_EP_ETH_DATA) s_usb.rxlen = 0, s_usb.discard = false; +#endif +} + +// Unconfigured, on start, bus reset and SET_CONFIGURATION. Keeps the log +static void mgi_usb_unconfigure(void) { +#if MG_ENABLE_USB_SERIAL + static const uint8_t line[7] = {0, 0xc2, 1, 0, 0, 0, 8}; // 115200 8N1 + s_usb.dtr = false; + memcpy(s_usb.line, line, sizeof(line)); +#endif +#if MG_ENABLE_USB_ETHERNET + s_usb.alt = false, s_usb.filter = s_usb.sequence = 0, s_usb.notify = 0; + s_usb.input_size = MG_USB_NTB_SIZE; +#endif + s_usb.configured = false; +} + +// Build string descriptor i in s_usb.buf. Returns its length, 0 if none +static int mgi_usb_string(unsigned i) { + static const char *strings[] = {NULL, "Mongoose", MGI_USB_PRODUCT, + NULL, "USB Ethernet", NULL, + "USB Serial"}; + const char *s = i < 7 ? strings[i] : NULL; + char tmp[33]; // Built strings: product name, host MAC + uint8_t *b = s_usb.buf; + size_t k, n; + if (i == 0) return b[0] = 4, b[1] = 3, b[2] = 9, b[3] = 4; + if (i == 2) { // Serial's last 4 digits: tell devices apart + size_t len = strlen(s_usb.serial); + mg_snprintf(tmp, sizeof(tmp), "%s_%s", MGI_USB_PRODUCT, + s_usb.serial + (len > 4 ? len - 4 : 0)); + s = tmp; + } + if (i == 3) s = s_usb.serial; +#if MG_ENABLE_USB_ETHERNET + if (i == 5 && s_usb.ifp != NULL) { // Host end: our MAC, first byte changed + uint8_t *m = s_usb.ifp->mac; + mg_snprintf(tmp, sizeof(tmp), "%02X%02X%02X%02X%02X%02X", ((m[0] ^ 4) | 2) & ~1, m[1], m[2], m[3], m[4], m[5]); - s = mac; + s = tmp; } #endif if (s == NULL) return 0; n = strlen(s) > 32 ? 32 : strlen(s); - memset(u->buf, 0, sizeof(u->buf)); - for (k = 0; k < n; k++) u->buf[2 + k * 2] = (uint8_t) s[k]; - u->buf[0] = (uint8_t) (2 + n * 2), u->buf[1] = 3; - return u->buf[0]; + memset(b, 0, sizeof(s_usb.buf)); + for (k = 0; k < n; k++) b[2 + k * 2] = (uint8_t) s[k]; + b[0] = (uint8_t) (2 + n * 2), b[1] = 3; + return b[0]; } -void mg_usb_reset(struct mg_usb *u) { -#if MG_ENABLE_USB_SERIAL - static const uint8_t line[7] = {0, 0xc2, 1, 0, 0, 0, 8}; // 115200 8N1 - u->dtr = false; - memcpy(u->line, line, sizeof(line)); -#endif -#if MG_ENABLE_USB_ETHERNET - u->alt = false, u->filter = u->sequence = 0, u->notify = 0; - u->input_size = MG_USB_NTB_SIZE; -#endif - u->configured = false; -} - -int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { +// Answer a control request r, its OUT data at r + 8. Returns -1 to stall, +// else the IN reply length in *reply, 0 for status only +static int mgi_usb_request(const uint8_t *r, const void **reply) { unsigned value = MG_LOAD_LE16(r + 2), index = MG_LOAD_LE16(r + 4); - unsigned wlen = MG_LOAD_LE16(r + 6); - const void *d = u->buf; + unsigned wlen = MG_LOAD_LE16(r + 6), i; + const void *d = s_usb.buf; int n = 0; switch ((r[0] << 8) | r[1]) { case 0x8006: // GET_DESCRIPTOR @@ -37929,32 +38036,37 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { #if MG_ENABLE_USB_ETHERNET if (value >> 8 == 15) d = s_bos_desc, n = sizeof(s_bos_desc); #endif - if (value >> 8 == 3) n = string_desc(u, value & 255); + if (value >> 8 == 3) n = mgi_usb_string(value & 255); if (n == 0) return -1; break; - case 0x0005: // SET_ADDRESS, applied by the driver after the status + case 0x0005: // SET_ADDRESS, applied by the controller if (value > 127) return -1; break; case 0x0009: // SET_CONFIGURATION if (value > 1) return -1; - mg_usb_reset(u); - u->configured = value == 1; + mgi_usb_unconfigure(); + for (i = 1; i < 5; i++) mgi_usb_idle(i); + s_usb.configured = value == 1; break; case 0x8008: // GET_CONFIGURATION - u->buf[0] = u->configured, n = 1; + s_usb.buf[0] = s_usb.configured, n = 1; break; case 0x010b: // SET_INTERFACE: only the Ethernet data interface has 1 - if (index >= MG_USB_NUM_IFS || - value > (unsigned) (MG_ENABLE_USB_ETHERNET && index == 1)) + if (index >= MGI_USB_NUM_IFS || + value > (unsigned) (MG_ENABLE_USB_ETHERNET && + index == MG_USB_IF_ETH_DATA)) return -1; #if MG_ENABLE_USB_ETHERNET - if (index == 1) u->alt = value == 1, u->notify = 1; + if (index == MG_USB_IF_ETH_DATA) { + s_usb.alt = value == 1, s_usb.notify = 1; + mgi_usb_idle(MG_USB_EP_ETH_DATA); + } #endif break; case 0x810a: // GET_INTERFACE - u->buf[0] = 0, n = 1; + s_usb.buf[0] = 0, n = 1; #if MG_ENABLE_USB_ETHERNET - if (index == 1) u->buf[0] = u->alt; + if (index == MG_USB_IF_ETH_DATA) s_usb.buf[0] = s_usb.alt; #endif break; #if MG_ENABLE_USB_ETHERNET @@ -37963,9 +38075,9 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { case 0x8000: // GET_STATUS: device, interface, endpoint case 0x8100: case 0x8200: - u->buf[0] = u->buf[1] = 0, n = 2; + s_usb.buf[0] = s_usb.buf[1] = 0, n = 2; break; - case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT), applied by the driver + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT), applied by the controller if (value || index > 255 || !memchr(s_endpoints, (int) index, sizeof(s_endpoints))) return -1; @@ -37976,7 +38088,7 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { d = s_ms_os_desc, n = sizeof(s_ms_os_desc); break; case 0x2143: // SET_ETHERNET_PACKET_FILTER - u->filter = (uint16_t) value; + s_usb.filter = (uint16_t) value; break; case 0xa180: // GET_NTB_PARAMETERS d = s_ntb_params, n = sizeof(s_ntb_params); @@ -37985,30 +38097,31 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { if (value) return -1; break; case 0xa185: // GET_NTB_INPUT_SIZE, one datagram per block - memset(u->buf, 0, 8); - MG_STORE_LE32(u->buf, u->input_size); - u->buf[4] = 1, n = 8; + memset(s_usb.buf, 0, 8); + MG_STORE_LE32(s_usb.buf, s_usb.input_size); + s_usb.buf[4] = 1, n = 8; break; case 0x2186: // SET_NTB_INPUT_SIZE if ((wlen != 4 && wlen != 8) || MG_LOAD_LE32(r + 8) < 2048 || MG_LOAD_LE32(r + 8) > 65535) return -1; - u->input_size = MG_LOAD_LE32(r + 8); - if (u->input_size > MG_USB_NTB_SIZE) u->input_size = MG_USB_NTB_SIZE; + s_usb.input_size = MG_LOAD_LE32(r + 8); + if (s_usb.input_size > MG_USB_NTB_SIZE) + s_usb.input_size = MG_USB_NTB_SIZE; break; #endif #if MG_ENABLE_USB_SERIAL case 0xa121: // GET_LINE_CODING - d = u->line, n = sizeof(u->line); + d = s_usb.line, n = sizeof(s_usb.line); break; case 0x2120: // SET_LINE_CODING - if (wlen != sizeof(u->line)) return -1; - memcpy(u->line, r + 8, sizeof(u->line)); + if (wlen != sizeof(s_usb.line)) return -1; + memcpy(s_usb.line, r + 8, sizeof(s_usb.line)); break; case 0x2122: // SET_CONTROL_LINE_STATE. Closed at 1200 baud: bootloader, - u->dtr = value & 1; // after a delay that lets this request complete - if (!u->dtr && MG_LOAD_LE32(u->line) == 1200) - u->reboot = mg_millis() + 100; + s_usb.dtr = value & 1; // after a delay that lets this request complete + if (!s_usb.dtr && MG_LOAD_LE32(s_usb.line) == 1200) + s_usb.reboot = mg_millis() + 100; break; case 0x2123: // SEND_BREAK break; @@ -38021,32 +38134,12 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { } #if MG_ENABLE_USB_ETHERNET -size_t mg_usb_notify(struct mg_usb *u, const void **msg) { - if (!u->notify) return 0; - if (u->notify == 1 && u->alt) return u->notify = 2, *msg = s_speed, 16; - u->notify = 0, *msg = u->alt ? s_up : s_down; - return 8; -} - -size_t mg_usb_encode(struct mg_usb *u, uint8_t *p, const void *buf, - size_t len) { - if (!u->alt || !u->filter || len < 14 || len > 1514 || - len + 30 > u->input_size) - return 0; - memcpy(p, s_nth, sizeof(s_nth)); - MG_STORE_LE16(p + 6, u->sequence); - MG_STORE_LE16(p + 8, len + 30); - MG_STORE_LE16(p + 22, len); - memcpy(p + 30, buf, len); - u->sequence++; - return len + 30; -} - +// Queue the frames of a received transfer block to the TCP/IP stack. // Offsets come from the host: bound every datagram by the block, and follow // at most 16 datagram tables so that a cyclic chain cannot loop forever -void mg_usb_decode(struct mg_usb *u, const uint8_t *p, size_t len) { +static void mgi_usb_decode(const uint8_t *p, size_t len) { size_t block, ndp, end, i, ofs, n, tables = 0; - if (len < 12 || MG_LOAD_LE32(p) != 0x484d434e) return; // "NCMH" + if (s_usb.ifp == NULL || len < 12 || MG_LOAD_LE32(p) != 0x484d434e) return; block = MG_LOAD_LE16(p + 8), ndp = MG_LOAD_LE16(p + 10); if (block > len) return; while (ndp && tables++ < 16 && ndp + 16 <= block && @@ -38056,27 +38149,537 @@ void mg_usb_decode(struct mg_usb *u, const uint8_t *p, size_t len) { ofs = MG_LOAD_LE16(p + i), n = MG_LOAD_LE16(p + i + 2); if (ofs == 0 || n == 0) break; if (n >= 14 && n <= 1514 && ofs + n <= block) - mg_tcpip_qwrite((void *) (p + ofs), n, u->ifp); + mg_tcpip_qwrite((void *) (p + ofs), n, s_usb.ifp); } ndp = MG_LOAD_LE16(p + ndp + 6); } } + +// If the Ethernet IN endpoint is idle, start sending the first queued +// transfer block. It stays queued until sent. Drop blocks the host cannot +// take now: the link closed, or it lowered its block size +static void mgi_usb_tx_next(void) { + char *block; + size_t len; + while (!s_usb.in[MG_USB_EP_ETH_DATA].busy && + (len = mg_queue_next(&s_usb.txq, &block)) > 0) { + if (s_usb.alt && s_usb.filter && len <= s_usb.input_size) { + mgi_usb_in_start(MG_USB_EP_ETH_DATA, block, len, len < s_usb.input_size); + } else { + mg_queue_del(&s_usb.txq, len); + } + } +} #endif #if MG_ENABLE_USB_SERIAL -void mg_usb_log(char ch, void *arg) { - struct mg_usb *u = (struct mg_usb *) arg; - if (u->head - u->tail >= MG_USB_LOG_SIZE) u->tail++; - u->log[u->head++ % MG_USB_LOG_SIZE] = ch; +// Log output function: keep the latest MG_USB_LOG_SIZE characters +static void mgi_usb_log(char ch, void *arg) { + if (s_usb.head - s_usb.tail >= MG_USB_LOG_SIZE) s_usb.tail++; + s_usb.log[s_usb.head++ % MG_USB_LOG_SIZE] = ch; + (void) arg; +} +#endif + +// Controller events, see enum mg_usb_ev +static int mgi_usb_event(enum mg_usb_ev ev, enum mg_usb_ep ep, void *buf, + size_t len) { + const uint8_t *p = (const uint8_t *) buf; + unsigned i; + if (ev == MG_USB_EV_RESET) { + mgi_usb_unconfigure(); + for (i = 0; i < 5; i++) mgi_usb_idle(i); + } else if (ev == MG_USB_EV_SETUP) { + const void *reply; + unsigned wlen = len < 8 ? 0 : MG_LOAD_LE16(p + 6); + int n; + mgi_usb_idle(MG_USB_EP_CTL); // A SETUP ends the previous transfer + if (len < 8 || (!(p[0] & 0x80) && len < 8 + wlen)) return -1; + if ((n = mgi_usb_request(p, &reply)) < 0) return -1; + if (!(p[0] & 0x80) || wlen == 0) return 0; + mgi_usb_in_start(MG_USB_EP_CTL, reply, (size_t) n, n < (int) wlen); + return 1; + } else if (ev == MG_USB_EV_IN && s_usb.in[ep].busy) { + s_usb.in[ep].busy = mgi_usb_in_next(ep); +#if MG_ENABLE_USB_ETHERNET + if (ep == MG_USB_EP_ETH_DATA && !s_usb.in[ep].busy) { + mg_queue_del(&s_usb.txq, mg_queue_next(&s_usb.txq, NULL)); // Sent + mgi_usb_tx_next(); + } +#endif + return s_usb.in[ep].busy; +#if MG_ENABLE_USB_ETHERNET + } else if (ev == MG_USB_EV_OUT && ep == MG_USB_EP_ETH_DATA) { + // Add the packet to the transfer block. At the advertised maximum OUT + // size, the host need not send a ZLP. Other blocks end with a short + // packet, possibly empty + if (!s_usb.discard && s_usb.rxlen + len <= sizeof(s_usb.rx)) { + memcpy(s_usb.rx + s_usb.rxlen, buf, len); + s_usb.rxlen += len; + } else { + s_usb.discard = true; + } + if (len < 64 || s_usb.rxlen == sizeof(s_usb.rx)) { + if (!s_usb.discard) mgi_usb_decode(s_usb.rx, s_usb.rxlen); + s_usb.rxlen = 0, s_usb.discard = false; + } +#endif + } + return 0; } -size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len) { - size_t n = 0; - while (n < len && u->tail != u->head) { - ((char *) buf)[n++] = u->log[u->tail++ % MG_USB_LOG_SIZE]; +bool mg_usb_init(struct mg_tcpip_if *ifp, const struct mg_usb_hw *hw) { + if (s_usb.hw == NULL) { + s_usb.hw = hw; + mgi_usb_unconfigure(); +#if MG_ENABLE_USB_ETHERNET + mg_queue_init(&s_usb.txq, s_usb.txq_buf, sizeof(s_usb.txq_buf)); +#endif +#if MG_ENABLE_USB_SERIAL + mg_log_set_fn(mgi_usb_log, NULL); // Log to the USB serial port +#endif + hw->init(s_usb.serial); } - return n; +#if MG_ENABLE_USB_ETHERNET + if (ifp != NULL) s_usb.ifp = ifp; +#else + (void) ifp; +#endif + return true; } + +size_t mg_usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { +#if MG_ENABLE_USB_ETHERNET + // Queue the frame wrapped in its transfer block, ready to send + size_t n = sizeof(s_nth) + len; + char *p; + if (!s_usb.alt || !s_usb.filter || len < 14 || len > 1514) return 0; + if (mg_queue_next(&s_usb.txq, NULL) == 0) { + mg_queue_init(&s_usb.txq, s_usb.txq.buf, s_usb.txq.size); // Unwrap + } + if (mg_queue_book(&s_usb.txq, &p, n) < n) { + ifp->nerr++; // Queue full: the host is not reading + return 0; + } + memcpy(p, s_nth, sizeof(s_nth)); + MG_STORE_LE16(p + 6, s_usb.sequence); + s_usb.sequence++; + MG_STORE_LE16(p + 8, n); + MG_STORE_LE16(p + 22, len); + memcpy(p + sizeof(s_nth), buf, len); + mg_queue_add(&s_usb.txq, n); + mgi_usb_tx_next(); + return len; +#else + (void) ifp, (void) buf, (void) len; + return 0; +#endif +} + +bool mg_usb_poll(struct mg_tcpip_if *ifp, bool s1) { + (void) ifp; + if (s_usb.hw == NULL) return false; // mg_usb_init() not called yet + s_usb.hw->poll(mgi_usb_event); +#if MG_ENABLE_USB_SERIAL + if (s_usb.reboot && mg_millis() > s_usb.reboot) { + s_usb.reboot = 0; + MG_USB_REBOOT(); + } + if (s_usb.configured && s_usb.dtr && !s_usb.in[MG_USB_EP_SER_DATA].busy) { + size_t n = 0; + while (n < sizeof(s_usb.out) && s_usb.tail != s_usb.head) { + s_usb.out[n++] = s_usb.log[s_usb.tail++ % MG_USB_LOG_SIZE]; + } + if (n > 0) mgi_usb_in_start(MG_USB_EP_SER_DATA, s_usb.out, n, true); + } +#endif +#if MG_ENABLE_USB_ETHERNET + if (s_usb.notify && !s_usb.in[MG_USB_EP_ETH_EV].busy) { + // Link notifications: the speed first if the link is up, then the state + if (s_usb.notify == 1 && s_usb.alt) { + s_usb.notify = 2; + mgi_usb_in_start(MG_USB_EP_ETH_EV, s_speed, sizeof(s_speed), false); + } else { + s_usb.notify = 0; + mgi_usb_in_start(MG_USB_EP_ETH_EV, s_usb.alt ? s_up : s_down, + sizeof(s_up), false); + } + } + mgi_usb_tx_next(); + return s1 && s_usb.alt && s_usb.filter; +#else + (void) s1; + return false; +#endif +} + +#endif + +#ifdef MG_ENABLE_LINES +#line 1 "src/drivers/usb_dwc2.c" +#endif + + + + + + +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_DWC2 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// DWC2 device controller, polled: no interrupt handler, no DMA. Received +// packets come through one shared RX FIFO, each IN endpoint has a TX FIFO of +// its own. Register layout: STM32 reference manuals, OTG chapter. + +#ifndef MG_USB_DWC2_BASE +#error "MG_ENABLE_DRIVER_USB_DWC2 needs MG_USB_DWC2_BASE, the core's address" +#endif +#ifndef MG_USB_DWC2_ULPI +#define MG_USB_DWC2_ULPI 0 +#endif +#ifndef MG_USB_DWC2_UTMI +#define MG_USB_DWC2_UTMI 0 +#endif +#if MG_USB_DWC2_ULPI && MG_USB_DWC2_UTMI +#error "MG_USB_DWC2_ULPI and MG_USB_DWC2_UTMI: choose one PHY" +#endif +#define MGI_DWC2_HS_PHY (MG_USB_DWC2_ULPI || MG_USB_DWC2_UTMI) // At full speed + +// Register at offset off +#define MGI_DWC2(off) \ + (*(volatile uint32_t *) ((uintptr_t) (MG_USB_DWC2_BASE) + (off))) +#define MGI_DWC2_GOTGCTL MGI_DWC2(0x000) +#define MGI_DWC2_GUSBCFG MGI_DWC2(0x00c) +#define MGI_DWC2_GRSTCTL MGI_DWC2(0x010) +#define MGI_DWC2_GINTSTS MGI_DWC2(0x014) +#define MGI_DWC2_GRXSTSP MGI_DWC2(0x020) +#define MGI_DWC2_GRXFSIZ MGI_DWC2(0x024) +#define MGI_DWC2_DIEPTXF0 MGI_DWC2(0x028) +#define MGI_DWC2_GCCFG MGI_DWC2(0x038) +#define MGI_DWC2_GSNPSID MGI_DWC2(0x040) +#define MGI_DWC2_DIEPTXF(n) MGI_DWC2(0x100 + 4 * (n)) // n: 1.. +#define MGI_DWC2_DCFG MGI_DWC2(0x800) +#define MGI_DWC2_DCTL MGI_DWC2(0x804) +#define MGI_DWC2_DIEPMSK MGI_DWC2(0x810) +#define MGI_DWC2_DOEPMSK MGI_DWC2(0x814) +#define MGI_DWC2_DAINT MGI_DWC2(0x818) +#define MGI_DWC2_DAINTMSK MGI_DWC2(0x81c) +#define MGI_DWC2_DIEPCTL(n) MGI_DWC2(0x900 + 0x20 * (n)) +#define MGI_DWC2_DIEPINT(n) MGI_DWC2(0x908 + 0x20 * (n)) +#define MGI_DWC2_DIEPTSIZ(n) MGI_DWC2(0x910 + 0x20 * (n)) +#define MGI_DWC2_DOEPCTL(n) MGI_DWC2(0xb00 + 0x20 * (n)) +#define MGI_DWC2_DOEPINT(n) MGI_DWC2(0xb08 + 0x20 * (n)) +#define MGI_DWC2_DOEPTSIZ(n) MGI_DWC2(0xb10 + 0x20 * (n)) +#define MGI_DWC2_PCGCCTL MGI_DWC2(0xe00) +#define MGI_DWC2_FIFO(n) MGI_DWC2(0x1000 * ((n) + 1)) + +// Endpoint control bits, DIEPCTL and DOEPCTL +#define MGI_DWC2_USBAEP MG_BIT(15) // Active +#define MGI_DWC2_STALL MG_BIT(21) +#define MGI_DWC2_CNAK MG_BIT(26) +#define MGI_DWC2_SNAK MG_BIT(27) +#define MGI_DWC2_SD0PID MG_BIT(28) // Next packet is DATA0 +#define MGI_DWC2_EPDIS MG_BIT(30) +#define MGI_DWC2_EPENA MG_BIT(31) + +// FIFOs, in 32-bit words: RX first, then a packet's room per IN endpoint. +// 208 words in all, so it fits a full-speed core's 320 +#define MGI_DWC2_RX_WORDS 128 + +// usb.c's event handler, see mg_usb_hw::poll() +#define MGI_DWC2_FN int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t) + +static uint32_t s_mgi_dwc2_pkt[64 / 4]; // A received packet +static uint8_t s_mgi_dwc2_req[16]; // SETUP packet, then its OUT data +static size_t s_mgi_dwc2_req_len; // OUT data received so far +static bool s_mgi_dwc2_req_out; // Waiting for that OUT data stage + +// Wait until the mask bits of reg are set, or clear. Bounded +static void mgi_dwc2_wait(volatile uint32_t *reg, uint32_t mask, bool set) { + unsigned i; + for (i = 0; ((*reg & mask) != 0) != set && i < 1000000; i++) (void) 0; +} + +// Flush the TX FIFO of endpoint n, 0x10: all of them +static void mgi_dwc2_flush_tx(unsigned n) { + MGI_DWC2_GRSTCTL = MG_BIT(5) | (n << 6); // TXFFLSH, TXFNUM + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(5), false); +} + +// mg_usb_hw::in(): load one packet, then let the endpoint send it +static void mgi_dwc2_in(enum mg_usb_ep ep, const void *buf, size_t len) { + const uint8_t *p = (const uint8_t *) buf; + size_t i, k; + MGI_DWC2_DIEPTSIZ(ep) = MG_BIT(19) | (uint32_t) len; // One packet + MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_CNAK | MGI_DWC2_EPENA; + for (i = 0; i < len; i += 4) { + uint32_t w = 0; + for (k = 0; k < 4 && i + k < len; k++) w |= (uint32_t) p[i + k] << (8 * k); + MGI_DWC2_FIFO(ep) = w; + } +} + +// Stop an IN transfer on endpoint ep, and empty its TX FIFO +static void mgi_dwc2_in_stop(unsigned ep) { + if (MGI_DWC2_DIEPCTL(ep) & MGI_DWC2_EPENA) { + MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_SNAK; + mgi_dwc2_wait(&MGI_DWC2_DIEPINT(ep), MG_BIT(6), true); // INEPNE + MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_EPDIS; + mgi_dwc2_wait(&MGI_DWC2_DIEPINT(ep), MG_BIT(1), true); // EPDISD + MGI_DWC2_DIEPINT(ep) = MG_BIT(1); + } + mgi_dwc2_flush_tx(ep); +} + +// Let OUT endpoint ep take one packet. Endpoint 0 also takes SETUPs +static void mgi_dwc2_arm(unsigned ep) { + MGI_DWC2_DOEPTSIZ(ep) = (ep == 0 ? 3UL << 29 : 0) | MG_BIT(19) | 64; + MGI_DWC2_DOEPCTL(ep) |= MGI_DWC2_CNAK | MGI_DWC2_EPENA; +} + +// Endpoint ep active, idle, DATA0 next. type: 2 bulk, 3 interrupt. out: +// also its OUT direction, ready to receive +static void mgi_dwc2_open(unsigned ep, uint32_t type, bool out) { + uint32_t ctl = 64 | MGI_DWC2_USBAEP | (type << 18) | MGI_DWC2_SD0PID; + mgi_dwc2_in_stop(ep); + MGI_DWC2_DIEPCTL(ep) = ctl | (ep << 22) | MGI_DWC2_SNAK; // Own TX FIFO + if (out) { + MGI_DWC2_DOEPCTL(ep) = ctl; + mgi_dwc2_arm(ep); + } +} + +// Stall endpoint 0, until the next SETUP +static void mgi_dwc2_stall(void) { + MGI_DWC2_DIEPCTL(0) |= MGI_DWC2_STALL; + MGI_DWC2_DOEPCTL(0) |= MGI_DWC2_STALL; +} + +// USB reset: address 0, endpoints off, FIFOs laid out again +static void mgi_dwc2_bus_reset(void) { + unsigned ep; + for (ep = 0; ep < 5; ep++) { + MGI_DWC2_DOEPCTL(ep) |= MGI_DWC2_SNAK; + if (ep > 0) MGI_DWC2_DOEPCTL(ep) &= ~MGI_DWC2_USBAEP; + if (ep > 0) MGI_DWC2_DIEPCTL(ep) &= ~MGI_DWC2_USBAEP; + mgi_dwc2_in_stop(ep); + } + MGI_DWC2_DAINTMSK = 0x1f; // IN endpoints 0-4: transfer complete + MGI_DWC2_DIEPMSK = MG_BIT(0); // XFRC + MGI_DWC2_DOEPMSK = MG_BIT(3) | 1U; // STUP, XFRC + MGI_DWC2_GRSTCTL = MG_BIT(4); // RXFFLSH + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(4), false); + MGI_DWC2_GRXFSIZ = MGI_DWC2_RX_WORDS; + MGI_DWC2_DIEPTXF0 = (16UL << 16) | MGI_DWC2_RX_WORDS; + for (ep = 1; ep < 5; ep++) { + MGI_DWC2_DIEPTXF(ep) = (16UL << 16) | (MGI_DWC2_RX_WORDS + 16 * ep); + } + MGI_DWC2_DCFG &= ~(0x7fUL << 4); // Address 0 + MGI_DWC2_DIEPCTL(0) &= ~3UL; // Endpoint 0: 64-byte packets + MGI_DWC2_DOEPCTL(0) &= ~3UL; + MGI_DWC2_DOEPTSIZ(0) = 3UL << 29; // Up to 3 SETUPs in a row + s_mgi_dwc2_req_out = false; +} + +// A complete control request: usb.c answers it, then the controller follows +static void mgi_dwc2_request(MGI_DWC2_FN) { + uint8_t *r = s_mgi_dwc2_req; + size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage + int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out); + if (res < 0) { + mgi_dwc2_stall(); + return; + } + switch ((r[0] << 8) | r[1]) { + case 0x0005: // SET_ADDRESS: the new address goes before the status stage + MGI_DWC2_DCFG = + (MGI_DWC2_DCFG & ~(0x7fUL << 4)) | ((uint32_t) (r[2] & 0x7f) << 4); + break; + case 0x0009: // SET_CONFIGURATION + if (r[2] != 1) break; +#if MG_ENABLE_USB_ETHERNET + mgi_dwc2_open(MG_USB_EP_ETH_EV, 3, false); + mgi_dwc2_open(MG_USB_EP_ETH_DATA, 2, true); +#endif +#if MG_ENABLE_USB_SERIAL + mgi_dwc2_open(MG_USB_EP_SER_EV, 3, false); + mgi_dwc2_open(MG_USB_EP_SER_DATA, 2, true); +#endif + break; +#if MG_ENABLE_USB_ETHERNET + case 0x010b: // SET_INTERFACE: Ethernet data endpoints back to DATA0 + if (r[4] == MG_USB_IF_ETH_DATA) { + mgi_dwc2_open(MG_USB_EP_ETH_DATA, 2, r[2] == 1); + } + break; +#endif + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT) + if (r[4] & 0x80) { + MGI_DWC2_DIEPCTL(r[4] & 15) = + (MGI_DWC2_DIEPCTL(r[4] & 15) & ~MGI_DWC2_STALL) | MGI_DWC2_SD0PID; + } else { + MGI_DWC2_DOEPCTL(r[4] & 15) = + (MGI_DWC2_DOEPCTL(r[4] & 15) & ~MGI_DWC2_STALL) | MGI_DWC2_SD0PID; + } + break; + } + if (res == 0) mgi_dwc2_in(MG_USB_EP_CTL, NULL, 0); // Status stage +} + +// A SETUP packet: run it, or first receive its OUT data stage +static void mgi_dwc2_setup(MGI_DWC2_FN) { + uint8_t *r = s_mgi_dwc2_req; + unsigned wlen = MG_LOAD_LE16(r + 6); + mgi_dwc2_in_stop(0); // A SETUP ends the previous control transfer + s_mgi_dwc2_req_out = false; + if ((r[0] & 0x80) || wlen == 0) { + mgi_dwc2_request(fn); + } else if (wlen > sizeof(s_mgi_dwc2_req) - 8) { + mgi_dwc2_stall(); + } else { + s_mgi_dwc2_req_out = true, s_mgi_dwc2_req_len = 0; + mgi_dwc2_arm(0); + } +} + +// One entry of the RX FIFO: a SETUP, OUT data, or the end of either +static void mgi_dwc2_rx(MGI_DWC2_FN) { + uint32_t st = MGI_DWC2_GRXSTSP, i; + unsigned ep = st & 15, kind = (st >> 17) & 15; + size_t n = (st >> 4) & 0x7ff; + uint8_t *r = s_mgi_dwc2_req; + for (i = 0; i < (n + 3) / 4; i++) { // Take the packet off the FIFO + uint32_t w = MGI_DWC2_FIFO(0); + if (i < sizeof(s_mgi_dwc2_pkt) / 4) s_mgi_dwc2_pkt[i] = w; + } + if (n > sizeof(s_mgi_dwc2_pkt)) n = sizeof(s_mgi_dwc2_pkt); + if (kind == 6) { // SETUP packet + memcpy(r, s_mgi_dwc2_pkt, 8); + } else if (kind == 4) { // SETUP stage done + MGI_DWC2_DOEPTSIZ(0) |= 3UL << 29; + MGI_DWC2_DOEPINT(0) = MG_BIT(3); // STUP + mgi_dwc2_setup(fn); + } else if (kind == 2 && ep == 0 && s_mgi_dwc2_req_out) { // Control OUT + size_t room = sizeof(s_mgi_dwc2_req) - 8 - s_mgi_dwc2_req_len; + memcpy(r + 8 + s_mgi_dwc2_req_len, s_mgi_dwc2_pkt, n < room ? n : room); + s_mgi_dwc2_req_len += n; +#if MG_ENABLE_USB_ETHERNET + } else if (kind == 2 && ep == MG_USB_EP_ETH_DATA) { + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, s_mgi_dwc2_pkt, n); +#endif + } else if (kind == 3 && ep == 0 && s_mgi_dwc2_req_out) { // OUT stage done + s_mgi_dwc2_req_out = false; + if (s_mgi_dwc2_req_len != MG_LOAD_LE16(r + 6)) { + mgi_dwc2_stall(); + } else { + mgi_dwc2_request(fn); + } + } else if (kind == 3 && ep != 0) { // An OUT packet taken: take the next + mgi_dwc2_arm(ep); // Serial input is dropped + } +} + +// mg_usb_hw::poll() +static void mgi_dwc2_poll(MGI_DWC2_FN) { + uint32_t sts = MGI_DWC2_GINTSTS; + if (sts & MG_BIT(12)) { // USBRST + MGI_DWC2_GINTSTS = MG_BIT(12); + mgi_dwc2_bus_reset(); + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); + } + if (sts & MG_BIT(13)) MGI_DWC2_GINTSTS = MG_BIT(13); // ENUMDNE + while (MGI_DWC2_GINTSTS & MG_BIT(4)) mgi_dwc2_rx(fn); // RXFLVL + if (sts & MG_BIT(18)) { // IEPINT + uint32_t daint = MGI_DWC2_DAINT; + unsigned ep; + for (ep = 0; ep < 5; ep++) { + uint32_t ints; + if (!(daint & MG_BIT(ep))) continue; + ints = MGI_DWC2_DIEPINT(ep); + MGI_DWC2_DIEPINT(ep) = ints; + if (!(ints & 1U)) continue; // XFRC: the packet went out + if (!fn(MG_USB_EV_IN, (enum mg_usb_ep) ep, NULL, 0) && ep == 0 && + (s_mgi_dwc2_req[0] & 0x80) && MG_LOAD_LE16(s_mgi_dwc2_req + 6)) { + mgi_dwc2_arm(0); // IN data stage over: the host's OUT status stage + } + } + } +} + +// Core soft reset. From core v4.20a, the reset done bit says when it is over +static void mgi_dwc2_core_reset(void) { + bool done_bit = (MGI_DWC2_GSNPSID & 0xffff) >= 0x420a; + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(31), true); // AHBIDL + MGI_DWC2_GRSTCTL |= 1U; // CSRST + if (done_bit) { + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(29), true); + MGI_DWC2_GRSTCTL = (MGI_DWC2_GRSTCTL & ~1U) | MG_BIT(29); + } else { + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, 1U, false); + } + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(31), true); +} + +// mg_usb_hw::init(): the serial number, the core as a full-speed device, +// then attach +static void mgi_dwc2_start(char serial[17]) { +#if defined(UID_BASE) // STM32: from the 96-bit unique ID + const volatile uint32_t *uid = (const volatile uint32_t *) UID_BASE; + uint32_t id[2] = {uid[0] ^ uid[2], uid[1]}; + mg_snprintf(serial, 17, "%M", mg_print_hex, (int) sizeof(id), (uint8_t *) id); +#else + mg_snprintf(serial, 17, "%s", "0000000000000000"); +#endif +#if MG_USB_DWC2_ULPI // 8-bit single data rate, internal VBUS indicator + MGI_DWC2_GUSBCFG = + (MGI_DWC2_GUSBCFG & ~(MG_BIT(3) | MG_BIT(6) | MG_BIT(7) | MG_BIT(17) | + MG_BIT(19) | MG_BIT(20) | MG_BIT(21))) | + MG_BIT(4); // ULPI +#elif MG_USB_DWC2_UTMI + // The core's own high-speed PHY: UTMI, not ULPI or full-speed; no TSDPS + MGI_DWC2_GUSBCFG &= ~(MG_BIT(4) | MG_BIT(6) | MG_BIT(22)); +#else + MGI_DWC2_GUSBCFG |= MG_BIT(6); // The core's own full-speed PHY +#endif +#ifdef MG_USB_DWC2_GCCFG + MGI_DWC2_GCCFG = MG_USB_DWC2_GCCFG; +#endif + mgi_dwc2_core_reset(); +#ifdef MG_USB_DWC2_GCCFG + MGI_DWC2_GCCFG = MG_USB_DWC2_GCCFG; +#endif + // Turnaround time: 9 for a high-speed PHY, 6 for a fast AHB otherwise. + // Timeout calibration: the maximum. Then device mode, which takes a while + MGI_DWC2_GUSBCFG = (MGI_DWC2_GUSBCFG & ~((0xfUL << 10) | 7U | MG_BIT(29))) | + ((MGI_DWC2_HS_PHY ? 9UL : 6UL) << 10) | 7U | MG_BIT(30); + mgi_dwc2_wait(&MGI_DWC2_GINTSTS, 1U, false); // CMOD: device mode + MGI_DWC2_PCGCCTL = 0; // PHY clock on + // Full speed, on a high-speed PHY (DSPD 1) or the core's own full-speed + // one (DSPD 3). Stall a non-empty status stage. XCVRDLY: some ULPI PHYs + // need it to chirp + MGI_DWC2_DCFG = (MGI_DWC2_DCFG & ~3U) | MG_BIT(2) | + (MGI_DWC2_HS_PHY ? 1U : 3U) | + (MG_USB_DWC2_ULPI ? MG_BIT(14) : 0U); + MGI_DWC2_DCTL |= MG_BIT(1); // SDIS: detached while setting up + // No VBUS sensing: B-session valid, always + MGI_DWC2_GOTGCTL = (MGI_DWC2_GOTGCTL & ~MG_BIT(4)) | MG_BIT(6) | MG_BIT(7); + MGI_DWC2_GINTSTS = 0xffffffff; + mgi_dwc2_flush_tx(0x10); + mgi_dwc2_bus_reset(); + MGI_DWC2_DCTL &= ~MG_BIT(1); // Attach +} + +const struct mg_usb_hw mg_usb_hw_dwc2 = {mgi_dwc2_start, mgi_dwc2_poll, + mgi_dwc2_in}; + +#if MG_ENABLE_USB_ETHERNET +static bool mgi_dwc2_init(struct mg_tcpip_if *ifp) { + return mg_usb_init(ifp, &mg_usb_hw_dwc2); +} + +struct mg_tcpip_driver mg_tcpip_driver_usb_dwc2 = {mgi_dwc2_init, mg_usb_tx, + NULL, mg_usb_poll}; #endif #endif @@ -38088,42 +38691,30 @@ size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len) { -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 + + +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_NRF52 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) #include // nRF52840 USB device controller, polled, full speed. Endpoint buffers are // inside the controller: EasyDMA moves each packet between them and RAM, -// one transfer at a time, so longer IN transfers go out 64 bytes at a time. -// EasyDMA reads RAM only, thus constant data is copied to RAM first. The +// and reads RAM only, so every packet goes through s_mgi_usb_nrf52_pkt. The // controller handles SET_ADDRESS by itself. Errata workarounds follow // Nordic's nrfx_usbd.c: 171, 187 when enabling, 199 around each DMA -#define ERRATA_199 (*(volatile uint32_t *) 0x40027c1c) +#define MGI_USB_NRF52_ERRATA_199 (*(volatile uint32_t *) 0x40027c1c) -struct nrf_in { // IN transfer on an endpoint - const uint8_t *data; // Bytes still to send, in RAM - size_t left; // How many - unsigned packets; // Packets still to send - bool busy; // A packet is waiting for the host -}; +// usb.c's event handler, see mg_usb_hw::poll() +#define MGI_USB_NRF52_FN \ + int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t) -static struct nrf_in s_in[5]; // Index: endpoint number -static struct mg_usb s_usb; -static uint8_t s_req[16]; // SETUP packet, then its OUT data stage -static uint32_t s_ep0[256 / 4]; // Control IN reply, OUT data stage -static char s_serial[17]; // Serial number: device ID in hex -#if MG_ENABLE_USB_ETHERNET -static uint32_t s_note[16 / 4]; // Link notification -static uint32_t s_rx[MG_USB_NTB_SIZE / 4], s_tx[MG_USB_NTB_SIZE / 4]; -static size_t s_rxlen; // Received part of the OUT transfer block -static bool s_discard; // OUT transfer block too long: drop it -#endif -#if MG_ENABLE_USB_SERIAL -static uint32_t s_log[64 / 4]; // Log output in flight -#endif +static uint32_t s_mgi_usb_nrf52_pkt[64 / 4]; // One packet in RAM +static uint8_t s_mgi_usb_nrf52_req[16]; // SETUP packet, then its OUT data // Write an undocumented register the way Nordic's errata workarounds do -static void errata(uint32_t addr, uint32_t value) { +static void mgi_usb_nrf52_errata(uint32_t addr, uint32_t value) { volatile uint32_t *unlock = (volatile uint32_t *) 0x4006ec00; bool locked = *unlock == 0; if (locked) *unlock = 0x9375; @@ -38132,136 +38723,110 @@ static void errata(uint32_t addr, uint32_t value) { } // Run one EasyDMA transfer and wait for its end event -static void dma(volatile uint32_t *task, volatile uint32_t *end) { +static void mgi_usb_nrf52_dma(volatile uint32_t *task, volatile uint32_t *end) { unsigned i; *end = 0; - ERRATA_199 = 0x82; + MGI_USB_NRF52_ERRATA_199 = 0x82; *task = 1; for (i = 0; *end == 0 && i < 100000; i++) (void) 0; // Microseconds *end = 0; - ERRATA_199 = 0; -} - -// Send the next packet of the IN transfer on ep. False if it is over -static bool in_next(unsigned ep) { - struct nrf_in *e = &s_in[ep]; - size_t n = e->left > 64 ? 64 : e->left; - if (e->packets == 0) return false; - NRF_USBD->EPIN[ep].PTR = (uint32_t) (uintptr_t) e->data; - NRF_USBD->EPIN[ep].MAXCNT = (uint32_t) n; - dma(&NRF_USBD->TASKS_STARTEPIN[ep], &NRF_USBD->EVENTS_ENDEPIN[ep]); - e->data += n, e->left -= n, e->packets--; - return true; -} - -// Start an IN transfer from RAM. zlp: end a multiple of 64 bytes with an -// empty packet -static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { - struct nrf_in *e = &s_in[ep]; - e->data = (const uint8_t *) data, e->left = len; - e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); - e->busy = in_next(ep); + MGI_USB_NRF52_ERRATA_199 = 0; } // Data toggle of endpoint address ep back to DATA0 -static void dtoggle(unsigned ep) { +static void mgi_usb_nrf52_dtoggle(unsigned ep) { NRF_USBD->DTOGGLE = ep; // Select the endpoint, then set its toggle NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep; } -#if MG_ENABLE_USB_ETHERNET -// Ethernet data endpoints idle, ready to receive -static void data_reset(void) { - dtoggle(0x02), dtoggle(0x82); - memset(&s_in[2], 0, sizeof(s_in[2])); - s_rxlen = 0, s_discard = false; - NRF_USBD->SIZE.EPOUT[2] = 0; // Drop any received packet, accept the next +// mg_usb_hw::in(): copy the packet to RAM, then into the endpoint +static void mgi_usb_nrf52_in(enum mg_usb_ep ep, const void *buf, size_t len) { + if (len > 0) memcpy(s_mgi_usb_nrf52_pkt, buf, len); + NRF_USBD->EPIN[ep].PTR = (uint32_t) (uintptr_t) s_mgi_usb_nrf52_pkt; + NRF_USBD->EPIN[ep].MAXCNT = (uint32_t) len; + mgi_usb_nrf52_dma(&NRF_USBD->TASKS_STARTEPIN[ep], + &NRF_USBD->EVENTS_ENDEPIN[ep]); } -// A packet on the Ethernet OUT endpoint: add it to the transfer block. The -// endpoint accepts the next packet once this one is moved or dropped -static void rx(void) { - size_t n = NRF_USBD->SIZE.EPOUT[2]; - if (n > 0 && !s_discard && s_rxlen + n <= sizeof(s_rx)) { - uint8_t *p = (uint8_t *) s_rx + s_rxlen; - NRF_USBD->EPOUT[2].PTR = (uint32_t) (uintptr_t) p; - NRF_USBD->EPOUT[2].MAXCNT = (uint32_t) n; - dma(&NRF_USBD->TASKS_STARTEPOUT[2], &NRF_USBD->EVENTS_ENDEPOUT[2]); - s_rxlen += n; +// Move the packet on OUT endpoint ep to RAM, which also lets the endpoint +// accept the next one. Returns its length +static size_t mgi_usb_nrf52_out(unsigned ep) { + size_t n = NRF_USBD->SIZE.EPOUT[ep]; + if (n == 0) { + NRF_USBD->SIZE.EPOUT[ep] = 0; // Nothing to move: accept the next } else { - s_discard = s_discard || n > 0; // An empty packet only ends the block - NRF_USBD->SIZE.EPOUT[2] = 0; - } - // At the advertised maximum OUT size, the host need not send a ZLP. - // Other transfers end with a short packet (including a ZLP) - if (n < 64 || s_rxlen == sizeof(s_rx)) { - if (!s_discard) mg_usb_decode(&s_usb, (uint8_t *) s_rx, s_rxlen); - s_rxlen = 0, s_discard = false; + NRF_USBD->EPOUT[ep].PTR = (uint32_t) (uintptr_t) s_mgi_usb_nrf52_pkt; + NRF_USBD->EPOUT[ep].MAXCNT = (uint32_t) n; + mgi_usb_nrf52_dma(&NRF_USBD->TASKS_STARTEPOUT[ep], + &NRF_USBD->EVENTS_ENDEPOUT[ep]); } + return n; +} + +#if MG_ENABLE_USB_ETHERNET +// Ethernet data endpoints back to DATA0, OUT ready to receive +static void mgi_usb_nrf52_data_reset(void) { + mgi_usb_nrf52_dtoggle(0x02), mgi_usb_nrf52_dtoggle(0x82); + NRF_USBD->SIZE.EPOUT[2] = 0; } #endif // Endpoints 1-4 on and idle if configured, else off -static void endpoints_reset(void) { - memset(s_in, 0, sizeof(s_in)); +static void mgi_usb_nrf52_endpoints(bool on) { NRF_USBD->EPINEN = 1, NRF_USBD->EPOUTEN = 1; - if (!s_usb.configured) return; + if (!on) return; #if MG_ENABLE_USB_ETHERNET NRF_USBD->EPINEN |= MG_BIT(1) | MG_BIT(2), NRF_USBD->EPOUTEN |= MG_BIT(2); - dtoggle(0x81); - data_reset(); + mgi_usb_nrf52_dtoggle(0x81); + mgi_usb_nrf52_data_reset(); #endif #if MG_ENABLE_USB_SERIAL NRF_USBD->EPINEN |= MG_BIT(3) | MG_BIT(4), NRF_USBD->EPOUTEN |= MG_BIT(4); - dtoggle(0x83), dtoggle(0x04), dtoggle(0x84); + mgi_usb_nrf52_dtoggle(0x83), mgi_usb_nrf52_dtoggle(0x04); + mgi_usb_nrf52_dtoggle(0x84); NRF_USBD->SIZE.EPOUT[4] = 0; #endif } -// Run a complete control request: SETUP in s_req, then any OUT data -static void request(void) { - const void *reply; - unsigned wlen = MG_LOAD_LE16(s_req + 6); - int n = mg_usb_setup(&s_usb, s_req, &reply); - if (n < 0) { +// A complete control request: usb.c answers it, then the controller follows +static void mgi_usb_nrf52_request(MGI_USB_NRF52_FN) { + uint8_t *r = s_mgi_usb_nrf52_req; + size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage + int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out); + if (res < 0) { NRF_USBD->TASKS_EP0STALL = 1; return; } - switch ((s_req[0] << 8) | s_req[1]) { + switch ((r[0] << 8) | r[1]) { case 0x0009: // SET_CONFIGURATION - endpoints_reset(); + mgi_usb_nrf52_endpoints(r[2] == 1); break; #if MG_ENABLE_USB_ETHERNET case 0x010b: // SET_INTERFACE - if (s_req[4] == 1) data_reset(); + if (r[4] == MG_USB_IF_ETH_DATA) mgi_usb_nrf52_data_reset(); break; #endif case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT) - dtoggle(s_req[4]); + mgi_usb_nrf52_dtoggle(r[4]); NRF_USBD->EPSTALL = - (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | s_req[4]; - if (!(s_req[4] & 0x80)) NRF_USBD->SIZE.EPOUT[s_req[4] & 15] = 0; + (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | r[4]; + if (!(r[4] & 0x80)) NRF_USBD->SIZE.EPOUT[r[4] & 15] = 0; break; } - if ((s_req[0] & 0x80) && wlen) { // IN data stage. Largest reply: 160 - memcpy(s_ep0, reply, (size_t) n); - in_start(0, s_ep0, (size_t) n, n < (int) wlen); - } else { - NRF_USBD->TASKS_EP0STATUS = 1; - } + if (res == 0) NRF_USBD->TASKS_EP0STATUS = 1; // No IN data stage } // A SETUP packet: run it, or first receive its OUT data stage -static void setup(void) { +static void mgi_usb_nrf52_setup(MGI_USB_NRF52_FN) { const volatile uint32_t *regs = &NRF_USBD->BMREQUESTTYPE; + uint8_t *r = s_mgi_usb_nrf52_req; unsigned i, wlen; - for (i = 0; i < 8; i++) s_req[i] = (uint8_t) regs[i]; - wlen = MG_LOAD_LE16(s_req + 6); - memset(&s_in[0], 0, sizeof(s_in[0])); // Cancels the previous transfer - if (s_req[0] == 0 && s_req[1] == 5) return; // SET_ADDRESS: hardware's - if ((s_req[0] & 0x80) || wlen == 0) { - request(); - } else if (wlen > sizeof(s_req) - 8) { + for (i = 0; i < 8; i++) r[i] = (uint8_t) regs[i]; + wlen = MG_LOAD_LE16(r + 6); + if (r[0] == 0 && r[1] == 5) return; // SET_ADDRESS: the controller's + if ((r[0] & 0x80) || wlen == 0) { + mgi_usb_nrf52_request(fn); + } else if (wlen > sizeof(s_mgi_usb_nrf52_req) - 8) { NRF_USBD->TASKS_EP0STALL = 1; } else { NRF_USBD->TASKS_EP0RCVOUT = 1; // Accept the OUT data stage @@ -38269,35 +38834,36 @@ static void setup(void) { } // A control data stage packet: an IN one acknowledged, or an OUT one arrived -static void ep0_data(void) { +static void mgi_usb_nrf52_ep0_data(MGI_USB_NRF52_FN) { + uint8_t *r = s_mgi_usb_nrf52_req; size_t n = NRF_USBD->SIZE.EPOUT[0]; - if (s_req[0] & 0x80) { - if (!in_next(0)) NRF_USBD->TASKS_EP0STATUS = 1; - } else if (n != MG_LOAD_LE16(s_req + 6)) { + if (r[0] & 0x80) { + if (!fn(MG_USB_EV_IN, MG_USB_EP_CTL, NULL, 0)) { + NRF_USBD->TASKS_EP0STATUS = 1; + } + } else if (n != MG_LOAD_LE16(r + 6)) { NRF_USBD->TASKS_EP0STALL = 1; } else { - NRF_USBD->EPOUT[0].PTR = (uint32_t) (uintptr_t) s_ep0; - NRF_USBD->EPOUT[0].MAXCNT = (uint32_t) n; - dma(&NRF_USBD->TASKS_STARTEPOUT[0], &NRF_USBD->EVENTS_ENDEPOUT[0]); - memcpy(s_req + 8, s_ep0, n); - request(); + mgi_usb_nrf52_out(0); + memcpy(r + 8, s_mgi_usb_nrf52_pkt, n); + mgi_usb_nrf52_request(fn); } } // Follow USB power: enable the controller when VBUS appears, attach to the // bus once both are ready, and detach when VBUS goes. True while attached -static bool attach(void) { +static bool mgi_usb_nrf52_attach(MGI_USB_NRF52_FN) { uint32_t power = NRF_POWER->USBREGSTATUS; if (!(power & POWER_USBREGSTATUS_VBUSDETECT_Msk)) { if (NRF_USBD->ENABLE) { NRF_USBD->USBPULLUP = 0, NRF_USBD->ENABLE = 0; - mg_usb_reset(&s_usb); + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); } return false; } if (!NRF_USBD->ENABLE) { - errata(0x4006ed14, 3); // Errata 187 - errata(0x4006ec14, 0xc0); // Errata 171 + mgi_usb_nrf52_errata(0x4006ed14, 3); // Errata 187 + mgi_usb_nrf52_errata(0x4006ec14, 0xc0); // Errata 171 NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; NRF_USBD->ENABLE = 1; } @@ -38306,56 +38872,30 @@ static bool attach(void) { !(power & POWER_USBREGSTATUS_OUTPUTRDY_Msk)) return false; NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; - errata(0x4006ec14, 0); - errata(0x4006ed14, 0); + mgi_usb_nrf52_errata(0x4006ec14, 0); + mgi_usb_nrf52_errata(0x4006ed14, 0); NRF_USBD->USBPULLUP = 1; return true; } -void mg_usb_init(void) { - static bool started; - uint32_t id[2], xtal = CLOCK_HFCLKSTAT_SRC_Msk | CLOCK_HFCLKSTAT_STATE_Msk; - if (started) return; - started = true; - id[0] = NRF_FICR->DEVICEID[0], id[1] = NRF_FICR->DEVICEID[1]; - mg_snprintf(s_serial, sizeof(s_serial), "%M", mg_print_hex, (int) sizeof(id), - (uint8_t *) id); - s_usb.serial = s_serial; - mg_usb_reset(&s_usb); -#if MG_ENABLE_USB_SERIAL - mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port -#endif - if ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) { // USB needs the crystal - NRF_CLOCK->TASKS_HFCLKSTART = 1; - while ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) (void) 0; - } - // The controller itself starts in mg_usb_poll(), once USB power is there -} - -void mg_usb_poll(void) { - mg_usb_init(); -#if MG_ENABLE_USB_SERIAL - if (s_usb.reboot && mg_millis() > s_usb.reboot) { - NRF_POWER->GPREGRET = 0x57; // Adafruit bootloader: stay in DFU mode - NVIC_SystemReset(); - } -#endif - if (!attach()) return; +// mg_usb_hw::poll() +static void mgi_usb_nrf52_poll(MGI_USB_NRF52_FN) { + if (!mgi_usb_nrf52_attach(fn)) return; if (NRF_USBD->EVENTS_USBRESET) { NRF_USBD->EVENTS_USBRESET = 0; NRF_USBD->EVENTS_EP0DATADONE = NRF_USBD->EVENTS_EPDATA = 0; NRF_USBD->EPDATASTATUS = NRF_USBD->EPDATASTATUS; - mg_usb_reset(&s_usb); - endpoints_reset(); + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); + mgi_usb_nrf52_endpoints(false); return; } - if (NRF_USBD->EVENTS_EP0DATADONE) { // Before a new SETUP replaces s_req + if (NRF_USBD->EVENTS_EP0DATADONE) { // Before a new SETUP replaces req NRF_USBD->EVENTS_EP0DATADONE = 0; - ep0_data(); + mgi_usb_nrf52_ep0_data(fn); } if (NRF_USBD->EVENTS_EP0SETUP) { NRF_USBD->EVENTS_EP0SETUP = 0; - setup(); + mgi_usb_nrf52_setup(fn); } if (NRF_USBD->EVENTS_EPDATA) { // Bit n: IN n acknowledged, 16+n: OUT n uint32_t done = NRF_USBD->EPDATASTATUS; @@ -38363,61 +38903,44 @@ void mg_usb_poll(void) { NRF_USBD->EVENTS_EPDATA = 0; NRF_USBD->EPDATASTATUS = done; for (i = 1; i < 5; i++) { - if (done & MG_BIT(i)) s_in[i].busy = in_next(i); + if (done & MG_BIT(i)) fn(MG_USB_EV_IN, (enum mg_usb_ep) i, NULL, 0); } #if MG_ENABLE_USB_ETHERNET - if (done & MG_BIT(18)) rx(); -#endif -#if MG_ENABLE_USB_SERIAL - if (done & MG_BIT(20)) NRF_USBD->SIZE.EPOUT[4] = 0; // Serial: ignored -#endif - } -#if MG_ENABLE_USB_ETHERNET - { - const void *msg; - size_t n; - if (!s_in[1].busy && (n = mg_usb_notify(&s_usb, &msg)) > 0) { - memcpy(s_note, msg, n); - in_start(1, s_note, n, false); + if (done & MG_BIT(16 + MG_USB_EP_ETH_DATA)) { + size_t n = mgi_usb_nrf52_out(MG_USB_EP_ETH_DATA); + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, s_mgi_usb_nrf52_pkt, n); } - } #endif #if MG_ENABLE_USB_SERIAL - if (s_usb.configured && s_usb.dtr && !s_in[4].busy) { - size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); - if (n > 0) in_start(4, s_log, n, true); - } + if (done & MG_BIT(16 + MG_USB_EP_SER_DATA)) { + NRF_USBD->SIZE.EPOUT[MG_USB_EP_SER_DATA] = 0; // Serial input: dropped + } #endif + } } +// mg_usb_hw::init(): the serial number, and the crystal that USB needs. The +// controller itself starts in poll, once USB power is there +static void mgi_usb_nrf52_start(char serial[17]) { + uint32_t id[2], xtal = CLOCK_HFCLKSTAT_SRC_Msk | CLOCK_HFCLKSTAT_STATE_Msk; + id[0] = NRF_FICR->DEVICEID[0], id[1] = NRF_FICR->DEVICEID[1]; + mg_snprintf(serial, 17, "%M", mg_print_hex, (int) sizeof(id), (uint8_t *) id); + if ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) { + NRF_CLOCK->TASKS_HFCLKSTART = 1; + while ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) (void) 0; + } +} + +const struct mg_usb_hw mg_usb_hw_nrf52 = { + mgi_usb_nrf52_start, mgi_usb_nrf52_poll, mgi_usb_nrf52_in}; + #if MG_ENABLE_USB_ETHERNET -static bool mg_tcpip_driver_usb_nrf52_init(struct mg_tcpip_if *ifp) { - s_usb.ifp = ifp; // mg_tcpip_init() has started USB already - return true; -} - -static size_t mg_tcpip_driver_usb_nrf52_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - // One frame can be in flight. Keep USB moving while waiting, but bound - // the wait if the host stops reading or the cable is gone - uint64_t until = mg_millis() + 20; - size_t n = 0; - while (s_in[2].busy && mg_millis() < until) mg_usb_poll(); - if (!s_in[2].busy) n = mg_usb_encode(&s_usb, (uint8_t *) s_tx, buf, len); - if (n) in_start(2, s_tx, n, n < s_usb.input_size); - (void) ifp; - return n ? len : 0; -} - -// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open -static bool mg_tcpip_driver_usb_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { - (void) ifp; - return s1 && s_usb.alt && s_usb.filter; +static bool mgi_usb_nrf52_init(struct mg_tcpip_if *ifp) { + return mg_usb_init(ifp, &mg_usb_hw_nrf52); } struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52 = { - mg_tcpip_driver_usb_nrf52_init, mg_tcpip_driver_usb_nrf52_tx, NULL, - mg_tcpip_driver_usb_nrf52_poll}; + mgi_usb_nrf52_init, mg_usb_tx, NULL, mg_usb_poll}; #endif #endif @@ -38429,45 +38952,35 @@ struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52 = { -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP + +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && MG_ENABLE_DRIVER_USB_RP && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) // RP2040 / RP2350 USB device controller: single core, polled, full speed, -// 64-byte single-buffered endpoints in USB DPRAM. Longer IN transfers go -// out one packet at a time, the next one when the previous completes +// 64-byte single-buffered endpoints in USB DPRAM -struct rp_ep { - uint8_t *buf; // Endpoint buffer in USB DPRAM - io_rw_32 *ctrl; // Buffer control register - const uint8_t *data; // IN transfer: bytes still to send - size_t left; // IN transfer: how many - unsigned packets; // IN transfer: packets still to send - uint8_t pid; // Next DATA PID, 0 or 1 - bool busy; // Buffer handed to the controller +// usb.c's event handler, see mg_usb_hw::poll() +#define MGI_USB_RP_FN int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t) + +struct mgi_usb_rp_ep { + uint8_t *buf; // Endpoint buffer in USB DPRAM + io_rw_32 *ctrl; // Buffer control register + uint8_t pid; // Next DATA PID, 0 or 1 }; -static struct rp_ep s_ep[5][2]; // Index: endpoint number, OUT=0 IN=1 -static struct mg_usb s_usb; -static uint8_t s_req[16]; // SETUP packet, then its OUT data stage -static bool s_req_out; // Waiting for that OUT data stage -static uint8_t s_address; // Address to apply after the status stage -static char s_serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1]; -#if MG_ENABLE_USB_ETHERNET -static uint8_t s_rx[MG_USB_NTB_SIZE], s_tx[MG_USB_NTB_SIZE]; -static size_t s_rxlen; // Received part of the OUT transfer block -static bool s_discard; // OUT transfer block too long: drop it -#endif -#if MG_ENABLE_USB_SERIAL -static char s_log[64]; // Log output in flight -#endif +static struct mgi_usb_rp_ep s_mgi_usb_rp_ep[5][2]; // Endpoint, OUT=0 IN=1 +static uint8_t s_mgi_usb_rp_req[16]; // SETUP packet, then its OUT data +static bool s_mgi_usb_rp_req_out; // Waiting for that OUT data stage +static uint8_t s_mgi_usb_rp_address; // Address to set after the status stage // Hand one packet buffer to the controller. OUT: accept up to len bytes -static void packet(unsigned ep, bool in, const void *data, unsigned len) { - struct rp_ep *e = &s_ep[ep][in]; +static void mgi_usb_rp_packet(unsigned ep, bool in, const void *data, + unsigned len) { + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; uint32_t v = len | (e->pid ? USB_BUF_CTRL_DATA1_PID : 0) | (in ? USB_BUF_CTRL_FULL : 0); if (in && len) memcpy(e->buf, data, len); e->pid ^= 1; - e->busy = true; *e->ctrl = v; // RP2040 datasheet: allow at least 12 cycles between writing buffer // metadata and handing ownership to the controller through AVAIL @@ -38475,36 +38988,23 @@ static void packet(unsigned ep, bool in, const void *data, unsigned len) { *e->ctrl = v | USB_BUF_CTRL_AVAIL; } -// Send the next packet of the IN transfer on ep. False if it is over -static bool in_next(unsigned ep) { - struct rp_ep *e = &s_ep[ep][1]; - unsigned n = e->left > 64 ? 64 : (unsigned) e->left; - if (e->packets == 0) return false; - packet(ep, true, e->data, n); - e->data += n, e->left -= n, e->packets--; - return true; -} - -// Start an IN transfer. zlp: end a multiple of 64 bytes with an empty packet -static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { - struct rp_ep *e = &s_ep[ep][1]; - e->data = (const uint8_t *) data, e->left = len; - e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); - in_next(ep); +// mg_usb_hw::in() +static void mgi_usb_rp_in(enum mg_usb_ep ep, const void *buf, size_t len) { + mgi_usb_rp_packet(ep, true, buf, (unsigned) len); } // Set up endpoint ep, direction in, idle. Endpoints 1 and 3 are interrupt, // 2 and 4 bulk, each with a 64-byte DPRAM buffer of its own -static void ep_init(unsigned ep, bool in) { - struct rp_ep *e = &s_ep[ep][in]; - e->ctrl = in ? &usb_dpram->ep_buf_ctrl[ep].in - : &usb_dpram->ep_buf_ctrl[ep].out; +static void mgi_usb_rp_ep_init(unsigned ep, bool in) { + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; + e->ctrl = + in ? &usb_dpram->ep_buf_ctrl[ep].in : &usb_dpram->ep_buf_ctrl[ep].out; e->buf = ep ? &usb_dpram->epx_data[(ep * 2 + in) * 64] : usb_dpram->ep0_buf_a; - e->pid = 0, e->busy = false, e->packets = 0; + e->pid = 0; *e->ctrl = 0; if (ep) { - io_rw_32 *ctrl = in ? &usb_dpram->ep_ctrl[ep - 1].in - : &usb_dpram->ep_ctrl[ep - 1].out; + io_rw_32 *ctrl = + in ? &usb_dpram->ep_ctrl[ep - 1].in : &usb_dpram->ep_ctrl[ep - 1].out; *ctrl = EP_CTRL_ENABLE_BITS | EP_CTRL_INTERRUPT_PER_BUFFER | ((ep & 1 ? 3U : 2U) << EP_CTRL_BUFFER_TYPE_LSB) | (uint32_t) ((uintptr_t) e->buf - (uintptr_t) usb_dpram); @@ -38512,152 +39012,150 @@ static void ep_init(unsigned ep, bool in) { } #if MG_ENABLE_USB_ETHERNET -// Ethernet data endpoints idle, then armed to receive if Ethernet is open -static void data_reset(void) { - ep_init(2, false), ep_init(2, true); - s_rxlen = 0, s_discard = false; - if (s_usb.alt) packet(2, false, NULL, 64); -} - -// A packet on the Ethernet OUT endpoint: add it to the transfer block -static void rx(const uint8_t *buf, unsigned n) { - if (s_rxlen + n <= sizeof(s_rx) && !s_discard) { - memcpy(s_rx + s_rxlen, buf, n); - s_rxlen += n; - } else { - s_discard = true; - } - // At the advertised maximum OUT size, the host need not send a ZLP. - // Other transfers end with a short packet (including a ZLP) - if (n < 64 || s_rxlen == sizeof(s_rx)) { - if (!s_discard) mg_usb_decode(&s_usb, s_rx, s_rxlen); - s_rxlen = 0; - s_discard = false; - } - if (s_usb.alt) packet(2, false, NULL, 64); +// Ethernet data endpoints idle, OUT armed to receive if Ethernet is open +static void mgi_usb_rp_data_reset(bool open) { + mgi_usb_rp_ep_init(2, false), mgi_usb_rp_ep_init(2, true); + if (open) mgi_usb_rp_packet(2, false, NULL, 64); } #endif -// All endpoints idle, then the serial port armed to receive if configured -static void endpoints_reset(void) { - static const uint8_t eps[] = { - 0x00, 0x80, +// Endpoints 1-4 idle. If configured, the serial port armed to receive +static void mgi_usb_rp_endpoints(bool on) { #if MG_ENABLE_USB_ETHERNET - 0x81, + mgi_usb_rp_ep_init(1, true); + mgi_usb_rp_data_reset(false); #endif #if MG_ENABLE_USB_SERIAL - 0x83, 0x04, 0x84, -#endif - }; - size_t i; - for (i = 0; i < sizeof(eps); i++) ep_init(eps[i] & 15U, eps[i] >> 7); -#if MG_ENABLE_USB_ETHERNET - data_reset(); -#endif -#if MG_ENABLE_USB_SERIAL - if (s_usb.configured) packet(4, false, NULL, 64); + mgi_usb_rp_ep_init(3, true); + mgi_usb_rp_ep_init(4, false), mgi_usb_rp_ep_init(4, true); + if (on) mgi_usb_rp_packet(4, false, NULL, 64); #endif + (void) on; } // Stall endpoint 0 until the next SETUP -static void stall(void) { +static void mgi_usb_rp_stall(void) { usb_hw->ep_stall_arm = USB_EP_STALL_ARM_EP0_IN_BITS | USB_EP_STALL_ARM_EP0_OUT_BITS; - *s_ep[0][1].ctrl = USB_BUF_CTRL_STALL; - *s_ep[0][0].ctrl = USB_BUF_CTRL_STALL; + *s_mgi_usb_rp_ep[0][1].ctrl = USB_BUF_CTRL_STALL; + *s_mgi_usb_rp_ep[0][0].ctrl = USB_BUF_CTRL_STALL; } -// Run a complete control request: SETUP in s_req, then any OUT data -static void request(void) { - const void *reply; - int n = mg_usb_setup(&s_usb, s_req, &reply); - if (n < 0) { - stall(); +// A complete control request: usb.c answers it, then the controller follows +static void mgi_usb_rp_request(MGI_USB_RP_FN) { + uint8_t *r = s_mgi_usb_rp_req; + size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage + int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out); + if (res < 0) { + mgi_usb_rp_stall(); return; } - switch ((s_req[0] << 8) | s_req[1]) { - case 0x0005: // SET_ADDRESS, applied after the status stage - s_address = s_req[2]; + switch ((r[0] << 8) | r[1]) { + case 0x0005: // SET_ADDRESS, set after the status stage + s_mgi_usb_rp_address = r[2]; break; case 0x0009: // SET_CONFIGURATION - endpoints_reset(); + mgi_usb_rp_endpoints(r[2] == 1); break; #if MG_ENABLE_USB_ETHERNET case 0x010b: // SET_INTERFACE - if (s_req[4] == 1) data_reset(); + if (r[4] == MG_USB_IF_ETH_DATA) mgi_usb_rp_data_reset(r[2] == 1); break; #endif case 0x0201: { // CLEAR_FEATURE(ENDPOINT_HALT) - struct rp_ep *e = &s_ep[s_req[4] & 15][s_req[4] >> 7]; + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[r[4] & 15][r[4] >> 7]; *e->ctrl &= ~USB_BUF_CTRL_STALL, e->pid = 0; break; } } - // IN data stage, or the status stage, both starting with DATA1 - s_ep[0][1].pid = 1; - in_start(0, reply, (size_t) n, n < (int) MG_LOAD_LE16(s_req + 6)); + if (res == 0) mgi_usb_rp_packet(0, true, NULL, 0); // Status stage, DATA1 } // A SETUP packet: run it, or first receive its OUT data stage -static void setup(void) { +static void mgi_usb_rp_setup(MGI_USB_RP_FN) { + uint8_t *r = s_mgi_usb_rp_req; unsigned wlen; - memcpy(s_req, (const void *) usb_dpram->setup_packet, 8); - wlen = MG_LOAD_LE16(s_req + 6); - // A SETUP cancels the preceding control transfer. OUT stages use DATA1 - ep_init(0, false), ep_init(0, true); - s_ep[0][0].pid = 1; - s_address = 0, s_req_out = false; - if ((s_req[0] & 0x80) || wlen == 0) { - request(); - } else if (wlen > sizeof(s_req) - 8) { - stall(); + memcpy(r, (const void *) usb_dpram->setup_packet, 8); + wlen = MG_LOAD_LE16(r + 6); + // A SETUP cancels the preceding control transfer. Both its data and + // status stages start with DATA1 + mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true); + s_mgi_usb_rp_ep[0][0].pid = s_mgi_usb_rp_ep[0][1].pid = 1; + s_mgi_usb_rp_address = 0, s_mgi_usb_rp_req_out = false; + if ((r[0] & 0x80) || wlen == 0) { + mgi_usb_rp_request(fn); + } else if (wlen > sizeof(s_mgi_usb_rp_req) - 8) { + mgi_usb_rp_stall(); } else { - s_req_out = true; - packet(0, false, NULL, 64); + s_mgi_usb_rp_req_out = true; + mgi_usb_rp_packet(0, false, NULL, 64); } } // A buffer the controller has finished with -static void complete(unsigned ep, bool in) { - struct rp_ep *e = &s_ep[ep][in]; +static void mgi_usb_rp_complete(unsigned ep, bool in, MGI_USB_RP_FN) { + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; + uint8_t *r = s_mgi_usb_rp_req; unsigned n = *e->ctrl & USB_BUF_CTRL_LEN_MASK; - e->busy = false; - if (in && in_next(ep)) return; + if (in && fn(MG_USB_EV_IN, (enum mg_usb_ep) ep, NULL, 0)) return; if (ep == 0 && in) { // Control IN data or status stage sent - if (s_address) { - usb_hw->dev_addr_ctrl = s_address, s_address = 0; - } else if ((s_req[0] & 0x80) && MG_LOAD_LE16(s_req + 6)) { - packet(0, false, NULL, 64); // Host's OUT status stage + if (s_mgi_usb_rp_address) { + usb_hw->dev_addr_ctrl = s_mgi_usb_rp_address, s_mgi_usb_rp_address = 0; + } else if ((r[0] & 0x80) && MG_LOAD_LE16(r + 6)) { + mgi_usb_rp_packet(0, false, NULL, 64); // Host's OUT status stage } - } else if (ep == 0 && !in && s_req_out) { // Control OUT data stage - s_req_out = false; - if (n != MG_LOAD_LE16(s_req + 6)) { - stall(); + } else if (ep == 0 && !in && s_mgi_usb_rp_req_out) { // OUT data stage + s_mgi_usb_rp_req_out = false; + if (n != MG_LOAD_LE16(r + 6)) { + mgi_usb_rp_stall(); } else { - memcpy(s_req + 8, e->buf, n); - request(); + memcpy(r + 8, e->buf, n); + mgi_usb_rp_request(fn); } #if MG_ENABLE_USB_ETHERNET - } else if (ep == 2 && !in) { - rx(e->buf, n); + } else if (ep == MG_USB_EP_ETH_DATA && !in) { + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, e->buf, n); + mgi_usb_rp_packet(ep, false, NULL, 64); #endif #if MG_ENABLE_USB_SERIAL - } else if (ep == 4 && !in) { - packet(4, false, NULL, 64); // Serial input is discarded: log console + } else if (ep == MG_USB_EP_SER_DATA && !in) { + mgi_usb_rp_packet(ep, false, NULL, 64); // Serial input: dropped #endif } } -void mg_usb_init(void) { - static bool started; - if (started) return; - started = true; - pico_get_unique_board_id_string(s_serial, sizeof(s_serial)); - s_usb.serial = s_serial; - mg_usb_reset(&s_usb); -#if MG_ENABLE_USB_SERIAL - mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port -#endif +// mg_usb_hw::poll() +static void mgi_usb_rp_poll(MGI_USB_RP_FN) { + uint32_t status = usb_hw->intr, done; + unsigned i; + if (status & USB_INTR_BUS_RESET_BITS) { + usb_hw->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; + usb_hw->dev_addr_ctrl = 0; + usb_hw->buf_status = 0xffffffff; + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); + mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true); + mgi_usb_rp_endpoints(false); + return; + } + if (status & USB_INTR_SETUP_REQ_BITS) { + // Discard stale EP0 completions from an interrupted control transfer + usb_hw->buf_status = 3; + usb_hw->sie_status = USB_SIE_STATUS_SETUP_REC_BITS; + mgi_usb_rp_setup(fn); + } + done = usb_hw->buf_status; + for (i = 0; i < 10; i++) { // Bits: EP0 IN, EP0 OUT, EP1 IN, ... + if (!(done & (1U << i))) continue; + usb_hw->buf_status = 1U << i; + if (s_mgi_usb_rp_ep[i / 2][!(i & 1)].ctrl) { + mgi_usb_rp_complete(i / 2, !(i & 1), fn); + } + } +} + +// mg_usb_hw::init(): the serial number, then the controller, attached +static void mgi_usb_rp_start(char serial[17]) { + pico_get_unique_board_id_string(serial, 17); reset_block(RESETS_RESET_USBCTRL_BITS); unreset_block_wait(RESETS_RESET_USBCTRL_BITS); memset(usb_dpram, 0, sizeof(*usb_dpram)); @@ -38667,81 +39165,21 @@ void mg_usb_init(void) { usb_hw->main_ctrl = USB_MAIN_CTRL_CONTROLLER_EN_BITS; usb_hw->sie_ctrl = USB_SIE_CTRL_EP0_INT_1BUF_BITS; usb_hw->inte = 0; // Poll raw status instead of an interrupt handler - endpoints_reset(); + mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true); + mgi_usb_rp_endpoints(false); hw_set_bits(&usb_hw->sie_ctrl, USB_SIE_CTRL_PULLUP_EN_BITS); } -void mg_usb_poll(void) { - uint32_t status, done; - unsigned i; - mg_usb_init(); - status = usb_hw->intr; -#if MG_ENABLE_USB_SERIAL - if (s_usb.reboot && mg_millis() > s_usb.reboot) reset_usb_boot(0, 0); -#endif - if (status & USB_INTR_BUS_RESET_BITS) { - usb_hw->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; - usb_hw->dev_addr_ctrl = 0; - usb_hw->buf_status = 0xffffffff; - mg_usb_reset(&s_usb); - endpoints_reset(); - return; - } - if (status & USB_INTR_SETUP_REQ_BITS) { - // Discard stale EP0 completions from an interrupted control transfer - usb_hw->buf_status = 3; - usb_hw->sie_status = USB_SIE_STATUS_SETUP_REC_BITS; - setup(); - } - done = usb_hw->buf_status; - for (i = 0; i < 10; i++) { // Bits: EP0 IN, EP0 OUT, EP1 IN, ... - if (!(done & (1U << i))) continue; - usb_hw->buf_status = 1U << i; - if (s_ep[i / 2][!(i & 1)].ctrl) complete(i / 2, !(i & 1)); - } -#if MG_ENABLE_USB_ETHERNET - if (!s_ep[1][1].busy) { - const void *msg; - size_t n = mg_usb_notify(&s_usb, &msg); - if (n) in_start(1, msg, n, false); - } -#endif -#if MG_ENABLE_USB_SERIAL - if (s_usb.configured && s_usb.dtr && !s_ep[4][1].busy) { - size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); - if (n) in_start(4, s_log, n, true); - } -#endif -} +const struct mg_usb_hw mg_usb_hw_rp = {mgi_usb_rp_start, mgi_usb_rp_poll, + mgi_usb_rp_in}; #if MG_ENABLE_USB_ETHERNET -static bool mg_tcpip_driver_usb_rp_init(struct mg_tcpip_if *ifp) { - s_usb.ifp = ifp; // mg_tcpip_init() has started USB already - return true; +static bool mgi_usb_rp_init(struct mg_tcpip_if *ifp) { + return mg_usb_init(ifp, &mg_usb_hw_rp); } -static size_t mg_tcpip_driver_usb_rp_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - // One frame can be in flight. Keep USB moving while waiting, but bound - // the wait if the host stops reading or the cable is gone - uint64_t until = mg_millis() + 20; - size_t n = 0; - while (s_ep[2][1].busy && mg_millis() < until) mg_usb_poll(); - if (!s_ep[2][1].busy) n = mg_usb_encode(&s_usb, s_tx, buf, len); - if (n) in_start(2, s_tx, n, n < s_usb.input_size); - (void) ifp; - return n ? len : 0; -} - -// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open -static bool mg_tcpip_driver_usb_rp_poll(struct mg_tcpip_if *ifp, bool s1) { - (void) ifp; - return s1 && s_usb.alt && s_usb.filter; -} - -struct mg_tcpip_driver mg_tcpip_driver_usb_rp = { - mg_tcpip_driver_usb_rp_init, mg_tcpip_driver_usb_rp_tx, NULL, - mg_tcpip_driver_usb_rp_poll}; +struct mg_tcpip_driver mg_tcpip_driver_usb_rp = {mgi_usb_rp_init, mg_usb_tx, + NULL, mg_usb_poll}; #endif #endif diff --git a/mongoose.h b/mongoose.h index 450e24f5..952fe498 100644 --- a/mongoose.h +++ b/mongoose.h @@ -1324,14 +1324,14 @@ struct timeval { #define MG_ENABLE_DRIVER_USB_RP 0 // USB device, RP2040 / RP2350 #endif -#ifndef MG_ENABLE_DRIVER_USB_SAMD21 -#define MG_ENABLE_DRIVER_USB_SAMD21 0 // USB device, SAMD21 -#endif - #ifndef MG_ENABLE_DRIVER_USB_NRF52 #define MG_ENABLE_DRIVER_USB_NRF52 0 // USB device, nRF52840 #endif +#ifndef MG_ENABLE_DRIVER_USB_DWC2 +#define MG_ENABLE_DRIVER_USB_DWC2 0 // USB device, Synopsys DWC2: STM32 OTG +#endif + #ifndef MG_ENABLE_USB_ETHERNET #define MG_ENABLE_USB_ETHERNET 0 // USB driver: CDC-NCM Ethernet interface #endif @@ -4797,6 +4797,8 @@ enum { MG_TCPIP_EV_WIFI_CONNECT_ERR, // Wi-Fi connection failed driver and chip specific MG_TCPIP_EV_DRIVER, // Driver-defined event driver specific MG_TCPIP_EV_STATE6_CHANGE, // IPv6 link state changed uint8_t *(&ifp->state6) + MG_TCPIP_EV_PHY_RX, // Radio frame received struct mg_str * + MG_TCPIP_EV_PHY_TX, // Radio frame about to be sent struct mg_str * MG_TCPIP_EV_USER // Starting ID for user-defined events }; // clang-format on @@ -4978,117 +4980,6 @@ extern struct mg_tcpip_spi mg_spi; #endif #endif -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved -// -// Ethernet over radio, through a mesh. Mongoose sees an Ethernet interface, -// the mesh splits Ethernet frames into radio frames. Two parts plug in: -// - struct mg_radio: a radio standard, e.g. mg_radio_802154 -// - struct mg_mesh: how the mesh is built and routed - - - - - -#if MG_ENABLE_TCPIP - -// A radio standard -struct mg_radio { - const char *name; // For logs - size_t max_frame_size; // Largest radio frame, bytes - uint32_t bitrate; // Bits per second on air - size_t overhead; // Bytes on air besides the frame: preamble, FCS - uint32_t slot_us; // Random backoff slot duration, us - uint32_t cca_us; // Channel sensing duration, us - uint32_t turnaround_us; // Idle check to transmission start, us - uint32_t ifs_us; // Inter-frame spacing in us: gap between transmits - uint8_t backoff_min; // Initial backoff exponent - uint8_t backoff_max; // Maximum backoff exponent - bool csma; // Use channel sensing and backoff before TX - size_t header_len; // Radio hardware header length - // Write the radio header, with 0xffff as the broadcast address. - void (*print_hdr)(const struct mg_radio *radio, uint8_t *buf, uint16_t dst, - uint16_t src); - // Return the parsed header length, or zero for an invalid header. - size_t (*parse_hdr)(const struct mg_radio *radio, const uint8_t *buf, - size_t len, uint16_t *dst, uint16_t *src); -}; - -#define MG_802154_HEADER_LEN 9 // MAC header, short addresses -#define MG_802154_PAN_ID 0xabcd // Our network's PAN ID - -#ifndef MG_802154_CHANNEL -#define MG_802154_CHANNEL 15 -#endif - -// A turn's answer must arrive this soon after the turn's last frame ends on -// air, or the turn ends. A node that would answer later stays silent and keeps -// its frame for the next turn. Covers the node's poll latency, the radio -// turnaround and one full fragment's airtime, 4.3 ms on 802.15.4 -#ifndef MG_MESH_ANSWER_TIMEOUT_US -#define MG_MESH_ANSWER_TIMEOUT_US 8000 -#endif - -// A radio driver aborts a transmission that has not finished this soon, and -// lets the mesh go on as if the frame was sent -#ifndef MG_MESH_TX_TIMEOUT_US -#define MG_MESH_TX_TIMEOUT_US 60000 -#endif - -// Misses in a row before giving up, 1 to 127. The bridge removes a member -// that did not answer this many turns. A node leaves the mesh after this -// many rounds without a turn -#ifndef MG_MESH_MAX_MISSES -#define MG_MESH_MAX_MISSES 10 -#endif - -extern const struct mg_radio mg_radio_802154; - -struct mg_mesh_node { - struct mg_tcpip_if *radio; // Owning radio driver interface - struct mg_tcpip_if *lan; // Bridge LAN interface, NULL for a client - const struct mg_mesh *strategy; // Selected strategy - size_t (*tx)(struct mg_tcpip_if *, const void *, size_t); // Radio frame TX - size_t rx_len; // Complete Ethernet frame in the interface RX buffer - uint64_t now; // Current driver poll time, us - uint64_t rx_at; // Arrival time of the radio frame being handled, us - uint64_t tx_at; // Earliest next transmission, us - void *data; // Private state owned by the strategy - size_t ram_used; // Live mesh state bytes - size_t ram_peak; // Peak live mesh state bytes - uint64_t next_tick; // Next deadline in us, or UINT64_MAX - uint16_t radio_address; // Local address supplied by the radio - bool joined; // Client is a member of the mesh -}; - -struct mg_mesh { - const char *name; - bool (*init)(struct mg_mesh_node *node, struct mg_tcpip_if *radio, - struct mg_tcpip_if *lan, uint16_t radio_address); - void (*tick)(struct mg_mesh_node *node, uint64_t now_microseconds); - void (*free)(struct mg_mesh_node *node); - size_t (*tx)(struct mg_mesh_node *, const void *, size_t); // ETH frame TX - void (*rx)(struct mg_mesh_node *, void *, size_t); // Radio frame RX - bool single_bridge; // Require exactly one bridge - bool scheduled_tx; // The mesh schedules transmission turns - const struct mg_radio *radio; // Radio configuration for this strategy -}; - -extern const struct mg_mesh mg_mesh_default; - -// Put a received radio frame into the driver's receive queue, together with -// its arrival time from mg_micros(). Call it when the frame arrives, from the -// radio interrupt if the driver has one. If the queue is full, the frame is -// dropped and counted in ifp->ndrop -void mg_mesh_rx_queue(struct mg_queue *q, struct mg_tcpip_if *ifp, - const void *frame, size_t len); - -// Pass queued radio frames to the mesh, oldest first. Before each frame, -// node->rx_at is set to its arrival time. Stops while the node holds a -// received Ethernet frame the TCP/IP stack has not taken yet -void mg_mesh_rx_drain(struct mg_mesh_node *node, struct mg_queue *q); - -#endif @@ -5454,36 +5345,28 @@ extern struct mg_tcpip_driver mg_tcpip_driver_cyw; -#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32_802154) && \ - MG_ENABLE_DRIVER_ESP32_802154 +#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32) && MG_ENABLE_DRIVER_ESP32 // ESP32-C6 IEEE 802.15.4 radio, as an Ethernet interface through the mesh. // Needs MG_ARCH_ESP32 and CONFIG_IEEE802154_ENABLED. // See tutorials/esp32/minimal-802.15.4 -struct mg_tcpip_driver_esp32_802154_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; +extern struct mg_tcpip_driver mg_tcpip_driver_esp32; -extern struct mg_tcpip_driver mg_tcpip_driver_esp32_802154; - -#define MG_TCPIP_DRIVER_ESP32_802154_INIT(manager) \ - do { \ - static struct mg_tcpip_driver_esp32_802154_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.mgr = (manager); \ - mif_.driver = &mg_tcpip_driver_esp32_802154; \ - mif_.driver_data = &driver_data_; \ - mg_tcpip_init((manager), &mif_); \ - MG_INFO(("Driver: esp32_802154, MAC: %M", mg_print_mac, mif_.mac)); \ +#define MG_TCPIP_DRIVER_ESP32_INIT(manager) \ + do { \ + static struct mg_tcpip_if mif_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.mgr = (manager); \ + mif_.driver = &mg_tcpip_driver_esp32; \ + mg_tcpip_init((manager), &mif_); \ + MG_INFO(("Driver: esp32, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) #ifndef MG_TCPIP_DRIVER_INIT -#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ESP32_802154_INIT(x) +#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ESP32_INIT(x) #endif #endif @@ -5550,23 +5433,16 @@ extern struct mg_tcpip_driver mg_tcpip_driver_imxrt; #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MCXW71) && \ MG_ENABLE_DRIVER_MCXW71 -struct mg_tcpip_driver_mcxw71_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71; #define MG_TCPIP_DRIVER_MCXW71_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_mcxw71_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_mcxw71; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) @@ -5583,23 +5459,16 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71; #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MG24) && MG_ENABLE_DRIVER_MG24 -struct mg_tcpip_driver_mg24_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_mg24; #define MG_TCPIP_DRIVER_MG24_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_mg24_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_mg24; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) @@ -5668,23 +5537,16 @@ extern struct mg_tcpip_driver mg_tcpip_driver_netc; #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NRF52) && MG_ENABLE_DRIVER_NRF52 -struct mg_tcpip_driver_nrf52_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_nrf52; #define MG_TCPIP_DRIVER_NRF52_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_nrf52_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_nrf52; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) @@ -5838,6 +5700,80 @@ extern struct mg_tcpip_driver mg_tcpip_driver_ra; #define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_RA_INIT(x) #endif +#endif +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved +// +// Ethernet over radio: shared framing, scheduling and bridge forwarding. +// Hardware drivers pass their functions to mg_radio_init(). + + + + + +#define MG_RADIO_802154 1 // IEEE 802.15.4, 250 kbit/s +#define MG_RADIO_BLE 2 // Bluetooth LE 2 Mbit/s PHY, raw: no BLE link layer + +#ifndef MG_RADIO +#define MG_RADIO MG_RADIO_802154 +#endif + +// The radio network: a channel, and an id that keeps other networks out. +// A bridge and its nodes must use the same values +#if MG_RADIO == MG_RADIO_BLE +#ifndef MG_RADIO_CHANNEL +#define MG_RADIO_CHANNEL 36 // Data channel 0-36. 36: 2478 MHz, clear of Wi-Fi +#endif +#ifndef MG_RADIO_NETWORK +#define MG_RADIO_NETWORK 0x71764129 // Access address +#endif +#else +#ifndef MG_RADIO_CHANNEL +#define MG_RADIO_CHANNEL 15 // Channel 11-26 +#endif +#ifndef MG_RADIO_NETWORK +#define MG_RADIO_NETWORK 0xabcd // PAN ID +#endif +#endif + +// A turn's answer must arrive this soon after the turn's last frame ends on +// air, or the turn ends. A node that would answer later stays silent and keeps +// its frame for the next turn. Covers the node's poll latency, the radio +// turnaround and one full fragment's airtime, 4.3 ms on 802.15.4 +#ifndef MG_RADIO_ANSWER_TIMEOUT_US +#define MG_RADIO_ANSWER_TIMEOUT_US 8000 +#endif + +// A radio driver aborts a transmission that has not finished this soon, and +// reports it done to mg_radio_poll() +#ifndef MG_RADIO_TX_TIMEOUT_US +#define MG_RADIO_TX_TIMEOUT_US 60000 +#endif + +// Membership timeout. The bridge removes a member that has not answered its +// turns for this long, counted from the first missed turn. A node leaves the +// mesh when it has had no turn for this long +#ifndef MG_RADIO_TIMEOUT_MS +#define MG_RADIO_TIMEOUT_MS 1000 +#endif + +#if MG_ENABLE_TCPIP + +bool mg_radio_init(struct mg_tcpip_if *ifp, + bool (*hw_init)(struct mg_tcpip_if *, uint16_t addr), + bool (*hw_poll)(struct mg_tcpip_if *), + size_t (*hw_tx)(struct mg_tcpip_if *, const void *, size_t)); +bool mg_radio_poll(struct mg_tcpip_if *, bool s1); // Run it. true: joined +size_t mg_radio_tx(const void *, size_t, struct mg_tcpip_if *); // Queue +size_t mg_radio_rx(void *, size_t, struct mg_tcpip_if *); // Received frame + +// Bridge LAN and radio Ethernet frames. Call after both interfaces initialize. +void mg_radio_bridge(struct mg_tcpip_if *, struct mg_tcpip_if *lan); + +// Queue a received radio frame with its arrival time. Call it from the +// receive interrupt. Frames for other radios are skipped +void mg_radio_rx_queue(struct mg_tcpip_if *, const void *, size_t); + #endif @@ -5899,23 +5835,16 @@ extern struct mg_tcpip_driver mg_tcpip_driver_rw612; #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612W) && \ MG_ENABLE_DRIVER_RW612W -struct mg_tcpip_driver_rw612w_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_rw612w; #define MG_TCPIP_DRIVER_RW612W_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_rw612w_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_rw612w; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) @@ -6290,107 +6219,146 @@ extern struct mg_tcpip_driver mg_tcpip_driver_tms570; -// USB device, independent of the controller: CDC-NCM Ethernet, enabled by -// MG_ENABLE_USB_ETHERNET, and a CDC-ACM serial port that carries the -// Mongoose log, enabled by MG_ENABLE_USB_SERIAL. The controller drivers -// are usb_rp.c, usb_samd21.c and usb_nrf52.c, enabled by -// MG_ENABLE_DRIVER_USB_*. Mongoose runs USB from mg_tcpip_init() and -// mg_mgr_poll(), so user code needs no USB calls +// USB device: a CDC-NCM Ethernet interface, enabled by MG_ENABLE_USB_ETHERNET, +// and a CDC-ACM serial port for logs, enabled by MG_ENABLE_USB_SERIAL. -#if MG_ENABLE_TCPIP && \ - (MG_ENABLE_DRIVER_USB_RP || MG_ENABLE_DRIVER_USB_SAMD21 || \ - MG_ENABLE_DRIVER_USB_NRF52) && \ - (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) -#define MG_ENABLE_USB 1 - -// #if defined(MG_ENABLE_DRIVER_USB_SAMD21) && MG_ENABLE_DRIVER_USB_SAMD21 -// #define MG_USB_DEFAULT_SIZE 2048 // SAMD21: 32k RAM -// #else -// #define MG_USB_DEFAULT_SIZE 4096 -// #endif -#define MG_USB_DEFAULT_SIZE 2048 -#ifndef MG_USB_NTB_SIZE // Transfer block buffer, each direction, >= 2048 -#define MG_USB_NTB_SIZE MG_USB_DEFAULT_SIZE +#ifndef MG_USB_NTB_SIZE +#define MG_USB_NTB_SIZE 2048 // Transfer block, each direction, >= 2048 #endif -#ifndef MG_USB_LOG_SIZE // Serial log ring buffer -#define MG_USB_LOG_SIZE (MG_USB_DEFAULT_SIZE / 2) +#ifndef MG_USB_TX_SIZE +#define MG_USB_TX_SIZE 4096 // Ethernet frames waiting to go to the host #endif -#ifndef MG_USB_QUEUE_SIZE // TCP/IP stack receive queue -#define MG_USB_QUEUE_SIZE (MG_USB_DEFAULT_SIZE * 2) +#ifndef MG_USB_QUEUE_SIZE +#define MG_USB_QUEUE_SIZE 4096 // Ethernet frames from the host +#endif +#ifndef MG_USB_LOG_SIZE +#define MG_USB_LOG_SIZE 1024 // Serial log ring #endif -// Endpoints: 1 interrupt IN, link notifications. 2 bulk IN/OUT, Ethernet. -// 3 interrupt IN, serial notifications (unused). 4 bulk IN/OUT, serial +// Restart into the board's bootloader when the host opens the serial port at +// 1200 baud and closes it, the "1200 baud touch" that flashing tools use +#ifndef MG_USB_REBOOT +#define MG_USB_REBOOT() (void) 0 +#endif -struct mg_usb { - const char *serial; // USB serial number, set by the driver - bool configured; // Host has set the configuration - uint8_t buf[66]; // Generated replies -#if MG_ENABLE_USB_ETHERNET - struct mg_tcpip_if *ifp; // TCP/IP interface, set by the driver - bool alt; // Ethernet open: data interface setting 1 - uint16_t filter, sequence; // Host packet filter, next IN block number - uint32_t input_size; // Largest IN block the host accepts - uint8_t notify; // Pending link notifications -#endif -#if MG_ENABLE_USB_SERIAL - bool dtr; // Terminal open - uint64_t reboot; // mg_millis() to enter the bootloader, or 0 - uint8_t line[7]; // Serial line coding - char log[MG_USB_LOG_SIZE]; // Serial log ring buffer - unsigned head, tail; // Log ring write and read counters -#endif +// Endpoints, numbered as in the configuration descriptor +enum mg_usb_ep { + MG_USB_EP_CTL, // control + MG_USB_EP_ETH_EV, // Ethernet link notifications, IN + MG_USB_EP_ETH_DATA, // Ethernet data, IN and OUT + MG_USB_EP_SER_EV, // serial notifications, IN, unused + MG_USB_EP_SER_DATA, // serial data, IN and OUT }; -// Implemented by the enabled controller driver. Start the controller, once, -// and send the log to the serial port -void mg_usb_init(void); +// Interfaces: the serial port's control and data first, then Ethernet's. The +// Ethernet data interface has setting 1: Ethernet open +#define MG_USB_IF_ETH_DATA (2 * MG_ENABLE_USB_SERIAL + 1) -// Implemented by the enabled controller driver. Run the controller. Calls -// mg_usb_init() first, so it works without a TCP/IP interface too -void mg_usb_poll(void); +// Controller events, reported by mg_usb_hw::poll() to its fn. What fn returns +enum mg_usb_ev { + MG_USB_EV_RESET, // Bus reset or detach. Returns 0 + MG_USB_EV_SETUP, // Control request, buf: the SETUP packet, then its OUT + // data. Returns -1: stall, 0: no IN data stage, send + // the status stage, 1: IN data stage started on ep 0 + MG_USB_EV_IN, // An IN packet on ep went out. Returns 1: next packet + // sent, 0: transfer done + MG_USB_EV_OUT // An OUT packet arrived on ep, buf and len. Returns 0 +}; -// Unconfigured state, on start and after a bus reset. Keeps the log -void mg_usb_reset(struct mg_usb *u); +// A USB device controller, implemented by its driver. Packets: up to 64 bytes +struct mg_usb_hw { + void (*init)(char serial[17]); // Start, write the serial number + void (*poll)(int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *buf, size_t)); + void (*in)(enum mg_usb_ep, const void *buf, size_t len); // Write IN packet +}; -// Handle an 8-byte SETUP packet, followed by its OUT data stage if it has -// one. Returns -1 to stall, else the IN reply length, 0 for status only -int mg_usb_setup(struct mg_usb *u, const uint8_t *req, const void **reply); +struct mg_tcpip_if; // Without MG_ENABLE_TCPIP: serial console only -#if MG_ENABLE_USB_ETHERNET -// Next link notification for endpoint 1. Returns its length, 0 if none -size_t mg_usb_notify(struct mg_usb *u, const void **msg); +// Start the controller hw, and attach ifp: NULL for the serial console only. +// Call again to attach ifp later; the first call's hw stays in use +bool mg_usb_init(struct mg_tcpip_if *ifp, const struct mg_usb_hw *hw); -// Wrap an Ethernet frame into a transfer block at ntb. Returns the block -// length, 0 if the link is down or the frame does not fit -size_t mg_usb_encode(struct mg_usb *u, uint8_t *ntb, const void *buf, - size_t len); +// Queue an Ethernet frame for the host. The controller driver's tx +size_t mg_usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp); + +// Run the controller. The controller driver's poll; returns true when the +// host has the Ethernet interface open and s1 is true. Serial only: ifp NULL +bool mg_usb_poll(struct mg_tcpip_if *ifp, bool s1); + + +// Synopsys DesignWare USB 2.0 OTG controller, "DWC2", as a device, see usb.h: +// CDC-NCM Ethernet and a CDC-ACM serial log console. Polled, no DMA, full +// speed. STM32 OTG_FS and OTG_HS (F2, F4, F7, H7, L4+, U5) are DWC2. Set in +// mongoose_config.h: +// - MG_USB_DWC2_BASE: the core's address, e.g. USB1_OTG_HS_PERIPH_BASE. The +// application enables its clocks, power and pins +// - MG_USB_DWC2_ULPI 1: an external ULPI PHY, run at full speed. Default: the +// core's own full-speed PHY +// - MG_USB_DWC2_UTMI 1: the core's own high-speed PHY (UTMI), run at full +// speed, e.g. STM32U59x/U5Ax OTG_HS. The application powers and clocks it +// - MG_USB_DWC2_GCCFG: optional, written to the STM32 GCCFG register, e.g. +// its PWRDWN bit to power the core's own full-speed PHY +// On STM32, include the device header in mongoose_config.h: the USB serial +// number is then the chip's unique ID. Examples: +// tutorials/stm32/portenta-h7/minimal-usb (ULPI), +// tutorials/stm32/nucleo-u5a5zj-q/minimal-usb (UTMI) + +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_DWC2 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// The controller. Without USB Ethernet, run the serial console from main(): +// mg_usb_init(NULL, &mg_usb_hw_dwc2) once, mg_usb_poll(NULL, false) in +// the main loop +extern const struct mg_usb_hw mg_usb_hw_dwc2; -// Queue the Ethernet frames of a received transfer block to the TCP/IP stack -void mg_usb_decode(struct mg_usb *u, const uint8_t *ntb, size_t len); #endif -#if MG_ENABLE_USB_SERIAL -// Log output function for mg_log_set_fn(mg_usb_log, u). Keeps the latest -// MG_USB_LOG_SIZE characters -void mg_usb_log(char ch, void *u); +#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_DWC2 && MG_ENABLE_USB_ETHERNET -// Take up to len logged characters into buf. Returns how many -size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len); +extern struct mg_tcpip_driver mg_tcpip_driver_usb_dwc2; + +// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the +// USB host. Leave it unset to get an address over DHCP, e.g. from macOS +// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if +// it is not set; the host end of the link gets a MAC derived from it +#define MG_TCPIP_DRIVER_USB_DWC2_INIT(mgr) \ + do { \ + static struct mg_tcpip_if mif_; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.enable_dhcp_server = mif_.ip != 0; \ + mif_.driver = &mg_tcpip_driver_usb_dwc2; \ + mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: usb_dwc2, MAC: %M", mg_print_mac, mif_.mac)); \ + } while (0) + +#ifndef MG_TCPIP_DRIVER_INIT +#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_DWC2_INIT(mgr) #endif -#else -#define MG_ENABLE_USB 0 -#define mg_usb_init() -#define mg_usb_poll() #endif // nRF52840 USB device controller, see usb.h: CDC-NCM Ethernet and a CDC-ACM // serial log console. No TinyUSB, polled. Needs the nRF52840 device headers -// from nrfx/mdk on the include path. Example: tutorials/nordic/xiao-52840 +// from nrfx/mdk on the include path. Example: tutorials/nordic/xiao-nrf52840 -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 && MG_ENABLE_USB_ETHERNET +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_NRF52 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// The controller. Without USB Ethernet, run the serial console from main(): +// mg_usb_init(NULL, &mg_usb_hw_nrf52) once, mg_usb_poll(NULL, false) in +// the main loop +extern const struct mg_usb_hw mg_usb_hw_nrf52; + +#endif + +#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_NRF52 && MG_ENABLE_USB_ETHERNET extern struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52; @@ -6423,7 +6391,17 @@ extern struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52; // RP2040 / RP2350 native USB controller, see usb.h: CDC-NCM Ethernet and // a CDC-ACM serial log console. No TinyUSB, polled. Example: tutorials/rp/usb -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP && MG_ENABLE_USB_ETHERNET +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && MG_ENABLE_DRIVER_USB_RP && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// The controller. Without USB Ethernet, run the serial console from main(): +// mg_usb_init(NULL, &mg_usb_hw_rp) once, mg_usb_poll(NULL, false) in +// the main loop +extern const struct mg_usb_hw mg_usb_hw_rp; + +#endif + +#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_RP && MG_ENABLE_USB_ETHERNET extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; @@ -6431,7 +6409,7 @@ extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; // USB host. Leave it unset to get an address over DHCP, e.g. from macOS // Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if // it is not set; the host end of the link gets a MAC derived from it -#define MG_TCPIP_DRIVER_INIT(mgr) \ +#define MG_TCPIP_DRIVER_USB_RP_INIT(mgr) \ do { \ static struct mg_tcpip_if mif_; \ mif_.ip = MG_TCPIP_IP; \ @@ -6445,6 +6423,10 @@ extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; MG_INFO(("Driver: usb_rp, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) +#ifndef MG_TCPIP_DRIVER_INIT +#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_RP_INIT(mgr) +#endif + #endif diff --git a/src/config.h b/src/config.h index d8913264..74640853 100644 --- a/src/config.h +++ b/src/config.h @@ -187,14 +187,14 @@ #define MG_ENABLE_DRIVER_USB_RP 0 // USB device, RP2040 / RP2350 #endif -#ifndef MG_ENABLE_DRIVER_USB_SAMD21 -#define MG_ENABLE_DRIVER_USB_SAMD21 0 // USB device, SAMD21 -#endif - #ifndef MG_ENABLE_DRIVER_USB_NRF52 #define MG_ENABLE_DRIVER_USB_NRF52 0 // USB device, nRF52840 #endif +#ifndef MG_ENABLE_DRIVER_USB_DWC2 +#define MG_ENABLE_DRIVER_USB_DWC2 0 // USB device, Synopsys DWC2: STM32 OTG +#endif + #ifndef MG_ENABLE_USB_ETHERNET #define MG_ENABLE_USB_ETHERNET 0 // USB driver: CDC-NCM Ethernet interface #endif diff --git a/src/drivers/esp32.c b/src/drivers/esp32.c new file mode 100644 index 00000000..57b71fe1 --- /dev/null +++ b/src/drivers/esp32.c @@ -0,0 +1,147 @@ +#include "log.h" +#include "net_builtin.h" +#include "radio.h" +#include "util.h" + +#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32) && MG_ENABLE_DRIVER_ESP32 + +#if MG_RADIO != MG_RADIO_802154 +#error "MG_ENABLE_DRIVER_ESP32 supports MG_RADIO_802154 only" +#endif + +#if MG_ARCH != MG_ARCH_ESP32 +#error "MG_ENABLE_DRIVER_ESP32 needs MG_ARCH_ESP32 (ESP-IDF)" +#endif + +// ESP-IDF owns the PHY, coexistence and interrupts. Its callbacks run in +// interrupt context and pass radio frames through a lock-free queue, read by +// mgi_esp32_poll(). In both directions frame[0] is the PHR, the length +// including FCS +#include +#include +#include + +static struct mg_tcpip_if *s_esp32_ifp; +static volatile bool s_esp32_txing, s_esp32_tx_done; +static uint64_t s_esp32_txstart; // Send start, us +// Frame for the radio: PHR, the length including FCS, then the PSDU +static uint8_t s_esp32_txframe[128] __attribute__((aligned(4))); + +// ESP-IDF only: it accepts a frame and may refuse it later, because of Wi-Fi +// coexistence, a busy channel or an abort. Such a frame is sent again after +// this pause, until MG_RADIO_TX_TIMEOUT_US. Without it, the mesh would count +// the refused frame as sent +#define MGI_ESP32_RETRY_US 200 + +static volatile bool s_esp32_retry; // A resend is pending +static volatile uint32_t s_esp32_retry_at; // When to resend, us + +// ESP-IDF's esp_ieee802154 driver calls the three functions below by name, +// from interrupt context. They are global only for that reason, and IRAM_ATTR +// keeps them in IRAM +void IRAM_ATTR esp_ieee802154_receive_done(uint8_t *frame, + esp_ieee802154_frame_info_t *info) { + (void) info; + if (frame[0] > 2) mg_radio_rx_queue(s_esp32_ifp, frame + 1, frame[0] - 2U); + esp_ieee802154_receive_handle_done(frame); +} + +void IRAM_ATTR esp_ieee802154_transmit_done(const uint8_t *frame, + const uint8_t *ack, + esp_ieee802154_frame_info_t *info) { + (void) frame, (void) info; + if (ack != NULL) esp_ieee802154_receive_handle_done(ack); + s_esp32_tx_done = true; +} + +void IRAM_ATTR esp_ieee802154_transmit_failed(const uint8_t *frame, + esp_ieee802154_tx_error_t err) { + (void) frame; + if (err == ESP_IEEE802154_TX_ERR_COEXIST || + err == ESP_IEEE802154_TX_ERR_CCA_BUSY || + err == ESP_IEEE802154_TX_ERR_ABORT) { + s_esp32_retry_at = (uint32_t) esp_timer_get_time() + MGI_ESP32_RETRY_US; + s_esp32_retry = true; // Set last: the poll reads it first + } else { + s_esp32_tx_done = true; + } +} + +// rx_when_idle: the driver returns to receive after each transmission +static bool mgi_esp32_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + s_esp32_ifp = ifp; + if (esp_ieee802154_enable() == ESP_OK && + esp_ieee802154_set_promiscuous(false) == ESP_OK && + esp_ieee802154_set_coordinator(false) == ESP_OK && + esp_ieee802154_set_rx_when_idle(true) == ESP_OK && + esp_ieee802154_set_panid(MG_RADIO_NETWORK) == ESP_OK && + esp_ieee802154_set_short_address(addr) == ESP_OK && + esp_ieee802154_set_channel(MG_RADIO_CHANNEL) == ESP_OK && + esp_ieee802154_set_txpower(0) == ESP_OK && + esp_ieee802154_receive() == ESP_OK) { + return true; + } + MG_ERROR(("802.15.4 radio init failed")); + return false; +} + +static bool mg_esp32_hw_tx(void) { + s_esp32_retry = false; + return esp_ieee802154_transmit(s_esp32_txframe, false) == ESP_OK; +} + +static void mg_esp32_hw_abort(void) { + s_esp32_retry = false; + esp_ieee802154_receive(); // Stops the current operation +} + +// Resend a refused frame when its pause is over. If the radio does not take +// it, give up: the frame counts as done +static void mg_esp32_hw_poll(void) { + uint32_t now; + if (!s_esp32_retry) return; + now = (uint32_t) esp_timer_get_time(); + if ((int32_t) (now - s_esp32_retry_at) < 0) return; + s_esp32_retry = false; + if (esp_ieee802154_transmit(s_esp32_txframe, false) != ESP_OK) { + s_esp32_tx_done = true; + } +} + +// Mesh radio transmit. The hardware adds the FCS +static size_t mgi_esp32_radio_tx(struct mg_tcpip_if *ifp, const void *buf, + size_t len) { + (void) ifp; + if (len > 125 || s_esp32_txing) return 0; + s_esp32_txframe[0] = (uint8_t) (len + 2); + memcpy(s_esp32_txframe + 1, buf, len); + s_esp32_tx_done = false; + s_esp32_txing = true, s_esp32_txstart = mg_micros(); + if (!mg_esp32_hw_tx()) { + s_esp32_txing = false; + return 0; + } + return len; +} + +static bool mgi_esp32_radio_poll(struct mg_tcpip_if *ifp) { + bool done = false; + (void) ifp; + mg_esp32_hw_poll(); + if (s_esp32_txing && (s_esp32_tx_done || mg_micros() - s_esp32_txstart > + MG_RADIO_TX_TIMEOUT_US)) { + if (!s_esp32_tx_done) mg_esp32_hw_abort(); + s_esp32_txing = false; + done = true; + } + return done; +} + +static bool mgi_esp32_init(struct mg_tcpip_if *ifp) { + return mg_radio_init(ifp, mgi_esp32_radio_init, mgi_esp32_radio_poll, + mgi_esp32_radio_tx); +} + +struct mg_tcpip_driver mg_tcpip_driver_esp32 = {mgi_esp32_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; +#endif diff --git a/src/drivers/esp32.h b/src/drivers/esp32.h new file mode 100644 index 00000000..188864c6 --- /dev/null +++ b/src/drivers/esp32.h @@ -0,0 +1,30 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#pragma once + +#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32) && MG_ENABLE_DRIVER_ESP32 + +// ESP32-C6 IEEE 802.15.4 radio, as an Ethernet interface through the mesh. +// Needs MG_ARCH_ESP32 and CONFIG_IEEE802154_ENABLED. +// See tutorials/esp32/minimal-802.15.4 +extern struct mg_tcpip_driver mg_tcpip_driver_esp32; + +#define MG_TCPIP_DRIVER_ESP32_INIT(manager) \ + do { \ + static struct mg_tcpip_if mif_; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.mgr = (manager); \ + mif_.driver = &mg_tcpip_driver_esp32; \ + mg_tcpip_init((manager), &mif_); \ + MG_INFO(("Driver: esp32, MAC: %M", mg_print_mac, mif_.mac)); \ + } while (0) + +#ifndef MG_TCPIP_DRIVER_INIT +#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ESP32_INIT(x) +#endif + +#endif diff --git a/src/drivers/esp32_802154.c b/src/drivers/esp32_802154.c deleted file mode 100644 index 79d89a91..00000000 --- a/src/drivers/esp32_802154.c +++ /dev/null @@ -1,192 +0,0 @@ -#include "l2_mesh.h" -#include "log.h" -#include "util.h" -#include "net_builtin.h" - -#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32_802154) && \ - MG_ENABLE_DRIVER_ESP32_802154 - -#if MG_ARCH != MG_ARCH_ESP32 -#error "MG_ENABLE_DRIVER_ESP32_802154 needs MG_ARCH_ESP32 (ESP-IDF)" -#endif - -// ESP-IDF owns the PHY, coexistence and interrupts. Its callbacks run in -// interrupt context and pass radio frames through a lock-free queue, read by -// mgi_esp32_802154_poll(). In both directions frame[0] is the PHR, the length -// including FCS -#include -#include -#include - -static struct mg_tcpip_if *s_esp32_802154_ifp; -static struct mg_queue s_esp32_802154_rx; -static char s_esp32_802154_rxbuf[2048]; -static volatile bool s_esp32_802154_txing, s_esp32_802154_tx_done; -static uint64_t s_esp32_802154_txstart; // Send start, us -// Frame for the radio: PHR, the length including FCS, then the PSDU -static uint8_t s_esp32_802154_txframe[128] __attribute__((aligned(4))); - -// Queue a received PSDU without its FCS -static void mg_esp32_802154_rx_frame(const uint8_t *psdu, size_t len) { - mg_mesh_rx_queue(&s_esp32_802154_rx, s_esp32_802154_ifp, psdu, len); -} - -// ESP-IDF only: it accepts a frame and may refuse it later, because of Wi-Fi -// coexistence, a busy channel or an abort. Such a frame is sent again after -// this pause, until MG_MESH_TX_TIMEOUT_US. Without it, the mesh would count -// the refused frame as sent -#define MGI_ESP32_802154_RETRY_US 200 - -static volatile bool s_esp32_802154_retry; // A resend is pending -static volatile uint32_t s_esp32_802154_retry_at; // When to resend, us - -// ESP-IDF's esp_ieee802154 driver calls the three functions below by name, -// from interrupt context. They are global only for that reason, and IRAM_ATTR -// keeps them in IRAM -void IRAM_ATTR esp_ieee802154_receive_done(uint8_t *frame, - esp_ieee802154_frame_info_t *info) { - (void) info; - if (frame[0] > 2) mg_esp32_802154_rx_frame(frame + 1, frame[0] - 2U); - esp_ieee802154_receive_handle_done(frame); -} - -void IRAM_ATTR esp_ieee802154_transmit_done(const uint8_t *frame, - const uint8_t *ack, - esp_ieee802154_frame_info_t *info) { - (void) frame, (void) info; - if (ack != NULL) esp_ieee802154_receive_handle_done(ack); - s_esp32_802154_tx_done = true; -} - -void IRAM_ATTR esp_ieee802154_transmit_failed(const uint8_t *frame, - esp_ieee802154_tx_error_t err) { - (void) frame; - if (err == ESP_IEEE802154_TX_ERR_COEXIST || - err == ESP_IEEE802154_TX_ERR_CCA_BUSY || - err == ESP_IEEE802154_TX_ERR_ABORT) { - s_esp32_802154_retry_at = - (uint32_t) esp_timer_get_time() + MGI_ESP32_802154_RETRY_US; - s_esp32_802154_retry = true; // Set last: the poll reads it first - } else { - s_esp32_802154_tx_done = true; - } -} - -static bool mg_esp32_802154_hw_init(uint16_t address) { - // rx_when_idle: the driver returns to receive after each transmission - return esp_ieee802154_enable() == ESP_OK && - esp_ieee802154_set_promiscuous(false) == ESP_OK && - esp_ieee802154_set_coordinator(false) == ESP_OK && - esp_ieee802154_set_rx_when_idle(true) == ESP_OK && - esp_ieee802154_set_panid(MG_802154_PAN_ID) == ESP_OK && - esp_ieee802154_set_short_address(address) == ESP_OK && - esp_ieee802154_set_channel(MG_802154_CHANNEL) == ESP_OK && - esp_ieee802154_set_txpower(0) == ESP_OK && - esp_ieee802154_receive() == ESP_OK; -} - -static bool mg_esp32_802154_hw_tx(void) { - s_esp32_802154_retry = false; - return esp_ieee802154_transmit(s_esp32_802154_txframe, false) == ESP_OK; -} - -static void mg_esp32_802154_hw_abort(void) { - s_esp32_802154_retry = false; - esp_ieee802154_receive(); // Stops the current operation -} - -// Resend a refused frame when its pause is over. If the radio does not take -// it, give up: the frame counts as done -static void mg_esp32_802154_hw_poll(void) { - uint32_t now; - if (!s_esp32_802154_retry) return; - now = (uint32_t) esp_timer_get_time(); - if ((int32_t) (now - s_esp32_802154_retry_at) < 0) return; - s_esp32_802154_retry = false; - if (esp_ieee802154_transmit(s_esp32_802154_txframe, false) != ESP_OK) { - s_esp32_802154_tx_done = true; - } -} - -// Mesh radio transmit. The hardware adds the FCS -static size_t mgi_esp32_802154_radio_tx(struct mg_tcpip_if *ifp, - const void *buf, size_t len) { - (void) ifp; - if (len > 125 || s_esp32_802154_txing) return 0; - s_esp32_802154_txframe[0] = (uint8_t) (len + 2); - memcpy(s_esp32_802154_txframe + 1, buf, len); - s_esp32_802154_tx_done = false; - s_esp32_802154_txing = true, s_esp32_802154_txstart = mg_micros(); - if (!mg_esp32_802154_hw_tx()) { - s_esp32_802154_txing = false; - return 0; - } - return len; -} - -static size_t mgi_esp32_802154_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_esp32_802154_rx(void *buf, size_t cap, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_esp32_802154_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; - node->now = now; - mg_esp32_802154_hw_poll(); - if (s_esp32_802154_txing && - (s_esp32_802154_tx_done || - now - s_esp32_802154_txstart > MG_MESH_TX_TIMEOUT_US)) { - if (!s_esp32_802154_tx_done) mg_esp32_802154_hw_abort(); - s_esp32_802154_txing = false; - node->tx_at = now + node->strategy->radio->ifs_us; - } - mg_mesh_rx_drain(node, &s_esp32_802154_rx); - node->strategy->tick(node, now); - return node->joined; -} - -static bool mgi_esp32_802154_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_esp32_802154_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_esp32_802154_radio_tx; - mg_queue_init(&s_esp32_802154_rx, s_esp32_802154_rxbuf, - sizeof(s_esp32_802154_rxbuf)); - s_esp32_802154_ifp = ifp; - if (mg_esp32_802154_hw_init(address)) return true; - MG_ERROR(("802.15.4 radio init failed")); - data->mesh->strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; -} - -struct mg_tcpip_driver mg_tcpip_driver_esp32_802154 = { - mgi_esp32_802154_init, mgi_esp32_802154_tx, mgi_esp32_802154_rx, - mgi_esp32_802154_poll}; -#endif diff --git a/src/drivers/esp32_802154.h b/src/drivers/esp32_802154.h deleted file mode 100644 index e8e03781..00000000 --- a/src/drivers/esp32_802154.h +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved - -#pragma once - -#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32_802154) && \ - MG_ENABLE_DRIVER_ESP32_802154 - -// ESP32-C6 IEEE 802.15.4 radio, as an Ethernet interface through the mesh. -// Needs MG_ARCH_ESP32 and CONFIG_IEEE802154_ENABLED. -// See tutorials/esp32/minimal-802.15.4 -struct mg_tcpip_driver_esp32_802154_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - -extern struct mg_tcpip_driver mg_tcpip_driver_esp32_802154; - -#define MG_TCPIP_DRIVER_ESP32_802154_INIT(manager) \ - do { \ - static struct mg_tcpip_driver_esp32_802154_data driver_data_; \ - static struct mg_tcpip_if mif_; \ - MG_SET_MAC_ADDRESS(mif_.mac); \ - mif_.ip = MG_TCPIP_IP; \ - mif_.mask = MG_TCPIP_MASK; \ - mif_.gw = MG_TCPIP_GW; \ - mif_.mgr = (manager); \ - mif_.driver = &mg_tcpip_driver_esp32_802154; \ - mif_.driver_data = &driver_data_; \ - mg_tcpip_init((manager), &mif_); \ - MG_INFO(("Driver: esp32_802154, MAC: %M", mg_print_mac, mif_.mac)); \ - } while (0) - -#ifndef MG_TCPIP_DRIVER_INIT -#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ESP32_802154_INIT(x) -#endif - -#endif diff --git a/src/drivers/mcxw71.c b/src/drivers/mcxw71.c index cc116aa7..2fb086bd 100644 --- a/src/drivers/mcxw71.c +++ b/src/drivers/mcxw71.c @@ -1,11 +1,131 @@ -#include "l2_mesh.h" #include "log.h" -#include "util.h" #include "net_builtin.h" +#include "radio.h" +#include "util.h" #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MCXW71) && \ MG_ENABLE_DRIVER_MCXW71 +// TrustZone: code built for the secure state (-mcmse) uses the secure alias +// of the radio registers, 0x5xxxxxxx. Otherwise, the non-secure alias +#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE & 2) +#define MGI_RF_BASE 0x58A00000U +#define MGI_PKT_RAM ((volatile uint8_t *) 0x58A08000) +#else +#define MGI_RF_BASE 0x48A00000U +#define MGI_PKT_RAM ((volatile uint8_t *) 0x48A08000) +#endif + +#define MGI_NVIC_ISER ((volatile uint32_t *) 0xE000E100) // Enable IRQ +#define MGI_NVIC_ICER ((volatile uint32_t *) 0xE000E180) // Disable IRQ +#if MG_RADIO == MG_RADIO_BLE +#define MGI_IRQN 54 // RF_Generic_IRQn +#else +#define MGI_IRQN 53 // RF_802_15_4_IRQn +#endif + +// Keep the IRQ handler out while we change the radio. The NVIC disable is +// atomic, so register updates here and there do not race +static void mg_mcxw71_lock(void) { + MGI_NVIC_ICER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); + __asm volatile("dsb; isb" ::: "memory"); +} + +static struct mg_tcpip_if *s_mcxw71_ifp; +static volatile bool s_mcxw71_txing, s_mcxw71_done; +static uint64_t s_mcxw71_sendstart; + +#if MG_RADIO == MG_RADIO_BLE + +// GENFSK Bluetooth LE uncoded mode, RM Table 489. S0 + 8-bit length, then +// our frame. The PHY supplies the preamble, whitening and 24-bit CRC. +struct mg_genfsk { + volatile uint32_t IRQ_CTRL, EVENT_TMR, T1_CMP, T2_CMP, TIMESTAMP, XCVR_CTRL, + XCVR_STS, XCVR_CFG, CHANNEL_NUM0, TX_POWER, NTW_ADR_CTRL, NTW_ADR[4], + RX_WATERMARK, DSM_CTRL, PART_ID, SLOT_PRELOAD, SLOT_TIME, TURNAROUND_TIME, + ACKDELAY, RXDELAY, TXDELAY, PACKET_CFG, H0_CFG, H1_CFG, CRC_CFG, + LENGTH_ADJ, TIMESTAMP_RX_DONE, TIMESTAMP_TX_DONE, MULT_PKT_CTRL, + RPA_WL_STATUS, LENGTH_MAX, EVENT_TMR_LD, EVENT_TMR_ADD, ENH_FEATURE; + uint32_t reserved[21]; + volatile uint32_t SEQ_STS; +}; +#define MGI_GFSK ((struct mg_genfsk *) (MGI_RF_BASE + 0x2000)) +#define MGI_TX_PB MGI_PKT_RAM // Access address, S0, length, frame; no CRC +#define MGI_RX_PB (MGI_PKT_RAM + 0x1000) // S0, length, frame, CRC; no AA +#define MGI_RADIO_MAX 251 +#define MGI_GFSK_IRQ_EN (MG_BIT(26) | MG_BIT(16)) // Master + sequence end +// BLE preamble starts with the access address's first bit; transmit LSBit +// first. +#define MGI_GFSK_CFG \ + (MG_BIT(24) | (((MG_RADIO_NETWORK & 1U) ? 0x55U : 0xaaU) << 16) | (1U << 4)) + +static void mg_mcxw71_abort(void) { + // NXP CONNRF-767: do not abort during TX warmup. + while (MGI_GFSK->SEQ_STS & MG_BIT(2)) (void) 0; + MGI_GFSK->XCVR_CTRL = 11; // ABORT_ALL + while (MGI_GFSK->XCVR_CTRL & MG_BIT(31)) (void) 0; + MGI_GFSK->IRQ_CTRL = MGI_GFSK_IRQ_EN | 0xffffU; // W1C status +} + +static void mg_mcxw71_listen(void) { + MGI_GFSK->IRQ_CTRL = MGI_GFSK_IRQ_EN | 0xffffU; + MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG; + MGI_GFSK->XCVR_CTRL = 5; // RX_START_NOW + MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); +} + +static void mg_mcxw71_go(void) { + mg_mcxw71_abort(); + MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG; // ABORT disables packet processing + MGI_GFSK->XCVR_CTRL = 1; // TX_START_NOW +} + +void RF_Generic_IRQHandler(void); +void RF_Generic_IRQHandler(void) { + uint32_t status = MGI_GFSK->IRQ_CTRL; + if (!(status & MG_BIT(0))) return; + mg_mcxw71_abort(); + if (s_mcxw71_txing) { + s_mcxw71_txing = false; + s_mcxw71_done = true; + } else if ((status & (MG_BIT(2) | MG_BIT(10))) == + (MG_BIT(2) | MG_BIT(10))) { // RX and CRC valid + uint8_t frame[MGI_RADIO_MAX]; + size_t i, n = MGI_RX_PB[1]; + if (n > 0 && n <= sizeof(frame)) { + for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i + 2]; + mg_radio_rx_queue(s_mcxw71_ifp, frame, n); + } + } + mg_mcxw71_listen(); +} + +static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + s_mcxw71_ifp = ifp; + (void) addr; // Frames are filtered by mg_radio_rx_queue() + MGI_GFSK->IRQ_CTRL = 0xffffU; + mg_mcxw71_abort(); + // GENFSK channels are MHz above 2360; MG_RADIO_CHANNEL is a BLE data index. + MGI_GFSK->CHANNEL_NUM0 = MG_RADIO_CHANNEL < 11 ? 44 + 2 * MG_RADIO_CHANNEL + : 46 + 2 * MG_RADIO_CHANNEL; + MGI_GFSK->TX_POWER = 0x3f; + MGI_GFSK->NTW_ADR_CTRL = 0x301; // 32-bit access address, match address 0 + MGI_GFSK->NTW_ADR[0] = MG_RADIO_NETWORK; + MGI_GFSK->PACKET_CFG = 0x000800c8; // H0=8 bits, length=8, AA=4 bytes + MGI_GFSK->H0_CFG = MGI_GFSK->H1_CFG = 0; // No header filtering + MGI_GFSK->LENGTH_ADJ = 3; // Length excludes the three CRC bytes + MGI_GFSK->MULT_PKT_CTRL = 0; + MGI_GFSK->LENGTH_MAX = 16U << 16; // 256 bytes; software caps at 251 + MGI_GFSK->ENH_FEATURE = 9 | MG_BIT(6); // BLE uncoded, alternate rate: 2M + MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG; + mg_mcxw71_listen(); + return true; +} + +#else +#define MGI_ZLL ((struct mg_zll *) (MGI_RF_BASE + 0x1000)) +#define MGI_RADIO_MAX 125 + // ZLL, 802.15.4 link layer. See MCXW71 reference manual and NXP // ieee_802_15_4 PHY sources: PhyPacketProcessor.c, PhyPlmeData.c, PhyISR.c struct mg_zll { @@ -20,16 +140,6 @@ struct mg_zll { COEX_PRIORITY, ENHACK_CTRL0; }; -// TrustZone: code built for the secure state (-mcmse) uses the secure alias -// of the radio registers, 0x5xxxxxxx. Otherwise, the non-secure alias -#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE & 2) -#define MGI_ZLL ((struct mg_zll *) 0x58A01000) -#define MGI_PKT_RAM ((volatile uint8_t *) 0x58A08000) -#else -#define MGI_ZLL ((struct mg_zll *) 0x48A01000) -#define MGI_PKT_RAM ((volatile uint8_t *) 0x48A08000) -#endif - #define MGI_TX_PB MGI_PKT_RAM // Length byte (incl. FCS), then frame #define MGI_RX_PB (MGI_PKT_RAM + 0x80) // Received frame, no length byte @@ -42,9 +152,6 @@ struct mg_zll { #define MGI_PHY_CTRL_ALL_IRQ_MASKS 0x8007ff00U // Bits 8..18, 31: mask all IRQs #define MGI_PHY_CTRL_SEQMSK MG_BIT(8) // Mask the sequence end IRQ #define MGI_PHY_CTRL_TRCV_MSK MG_BIT(31) // Mask all transceiver IRQs -#define MGI_IRQN 53 // RF_802_15_4_IRQn -#define MGI_NVIC_ISER ((volatile uint32_t *) 0xE000E100) // Enable IRQ -#define MGI_NVIC_ICER ((volatile uint32_t *) 0xE000E180) // Disable IRQ #define MGI_SEQ_STATE_MASK 0x1fU #define MGI_SEQ_STATE_RX_WU 0x10U // RX warm up #define MGI_SEQ_CTRL_NO_RX_RECYCLE MG_BIT(5) @@ -53,12 +160,6 @@ struct mg_zll { // PHY_CTRL[XCVSEQ] enum { MGI_SEQ_IDLE = 0, MGI_SEQ_RX = 1, MGI_SEQ_TX = 2 }; -static struct mg_tcpip_if *s_mcxw71_ifp; -static struct mg_queue s_mcxw71_rx; -static char s_mcxw71_queue[2048]; -static volatile bool s_mcxw71_txing, s_mcxw71_done; -static uint64_t s_mcxw71_sendstart; - // Stop the current sequence, wait for the sequencer to go idle. See PhyAbort() static void mg_mcxw71_abort(void) { if (MGI_ZLL->PHY_CTRL & MGI_PHY_CTRL_XCVSEQ) { @@ -78,13 +179,6 @@ static void mg_mcxw71_listen(void) { MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); } -// Keep the IRQ handler out while we change the radio. The NVIC disable is -// atomic, so PHY_CTRL updates here and there do not race -static void mg_mcxw71_lock(void) { - MGI_NVIC_ICER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); - __asm volatile("dsb; isb" ::: "memory"); -} - // Start the TX sequence for the loaded frame. Its end: see the IRQ handler static void mg_mcxw71_go(void) { MGI_ZLL->PHY_CTRL |= MGI_PHY_CTRL_TRCV_MSK | MGI_PHY_CTRL_SEQMSK; @@ -110,22 +204,49 @@ void RF_802_15_4_IRQHandler(void) { n = n >= 2 ? n - 2 : 0; if (n > 0 && n <= sizeof(frame)) { for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i]; - mg_mesh_rx_queue(&s_mcxw71_rx, s_mcxw71_ifp, frame, n); + mg_radio_rx_queue(s_mcxw71_ifp, frame, n); } } mg_mcxw71_listen(); } } +static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + s_mcxw71_ifp = ifp; + MGI_ZLL->SEQ_CTRL_STS |= MGI_SEQ_CTRL_NO_RX_RECYCLE; + MGI_ZLL->PHY_CTRL = MGI_PHY_CTRL_ALL_IRQ_MASKS; + MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS; + MGI_ZLL->SAM_CTRL = 0; + MGI_ZLL->RX_FRAME_FILTER = MGI_FRAME_FILTER; + MGI_ZLL->CHANNEL_NUM0 = MG_RADIO_CHANNEL; + MGI_ZLL->MACSHORTADDRS0 = ((uint32_t) addr << 16) | MG_RADIO_NETWORK; + MGI_ZLL->PA_PWR = 0x3f; + mg_mcxw71_listen(); + return true; +} + +#endif + static size_t mgi_mcxw71_radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) { size_t i; (void) ifp; - if (len > 125 || s_mcxw71_txing) return 0; + if (len > MGI_RADIO_MAX || s_mcxw71_txing) return 0; mg_mcxw71_lock(); +#if MG_RADIO == MG_RADIO_BLE + if (MGI_GFSK->SEQ_STS & MG_BIT(11)) { // Do not interrupt a received frame + MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); + return 0; + } + for (i = 0; i < 4; i++) + MGI_TX_PB[i] = (uint8_t) (MG_RADIO_NETWORK >> (8 * i)); + MGI_TX_PB[4] = 0, MGI_TX_PB[5] = (uint8_t) len; + for (i = 0; i < len; i++) MGI_TX_PB[i + 6] = ((const uint8_t *) buf)[i]; +#else MGI_TX_PB[0] = (uint8_t) (len + 2); // FCS is added by hardware for (i = 0; i < len; i++) MGI_TX_PB[i + 1] = ((const uint8_t *) buf)[i]; // 8-bit access only +#endif s_mcxw71_done = false; s_mcxw71_txing = true; s_mcxw71_sendstart = mg_millis(); @@ -134,46 +255,11 @@ static size_t mgi_mcxw71_radio_tx(struct mg_tcpip_if *ifp, const void *buf, return len; } -static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - s_mcxw71_ifp = ifp; - MGI_ZLL->SEQ_CTRL_STS |= MGI_SEQ_CTRL_NO_RX_RECYCLE; - MGI_ZLL->PHY_CTRL = MGI_PHY_CTRL_ALL_IRQ_MASKS; - MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS; - MGI_ZLL->SAM_CTRL = 0; - MGI_ZLL->RX_FRAME_FILTER = MGI_FRAME_FILTER; - MGI_ZLL->CHANNEL_NUM0 = MG_802154_CHANNEL; - MGI_ZLL->MACSHORTADDRS0 = - ((uint32_t) node->radio_address << 16) | MG_802154_PAN_ID; - MGI_ZLL->PA_PWR = 0x3f; - mg_mcxw71_listen(); - return true; -} - -static size_t mgi_mcxw71_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_mcxw71_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_mcxw71_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; +static bool mgi_mcxw71_radio_poll(struct mg_tcpip_if *ifp) { + bool done; + (void) ifp; if (s_mcxw71_txing && - mg_millis() > s_mcxw71_sendstart + MG_MESH_TX_TIMEOUT_US / 1000) { + mg_millis() > s_mcxw71_sendstart + MG_RADIO_TX_TIMEOUT_US / 1000) { mg_mcxw71_lock(); if (s_mcxw71_txing) { mg_mcxw71_abort(); @@ -184,40 +270,16 @@ static bool mgi_mcxw71_poll(struct mg_tcpip_if *ifp, bool s1) { MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32); } } - if (s_mcxw71_done) { - s_mcxw71_done = false; - node->tx_at = now + node->strategy->radio->ifs_us; - } - node->now = now; - mg_mesh_rx_drain(node, &s_mcxw71_rx); - node->strategy->tick(node, now); - return node->joined; + done = s_mcxw71_done; + s_mcxw71_done = false; + return done; } static bool mgi_mcxw71_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address; - address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_mcxw71_radio_tx; - mg_queue_init(&s_mcxw71_rx, s_mcxw71_queue, sizeof(s_mcxw71_queue)); - if (mgi_mcxw71_radio_init(ifp)) return true; - strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_mcxw71_radio_init, mgi_mcxw71_radio_poll, + mgi_mcxw71_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_mcxw71 = { - mgi_mcxw71_init, mgi_mcxw71_tx, mgi_mcxw71_rx, mgi_mcxw71_poll}; +struct mg_tcpip_driver mg_tcpip_driver_mcxw71 = {mgi_mcxw71_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif diff --git a/src/drivers/mcxw71.h b/src/drivers/mcxw71.h index 8dc65179..5248a632 100644 --- a/src/drivers/mcxw71.h +++ b/src/drivers/mcxw71.h @@ -6,23 +6,16 @@ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MCXW71) && \ MG_ENABLE_DRIVER_MCXW71 -struct mg_tcpip_driver_mcxw71_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71; #define MG_TCPIP_DRIVER_MCXW71_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_mcxw71_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_mcxw71; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) diff --git a/src/drivers/mg24.c b/src/drivers/mg24.c index 7090ebe5..1955be82 100644 --- a/src/drivers/mg24.c +++ b/src/drivers/mg24.c @@ -1,38 +1,56 @@ -#include "net_builtin.h" -#include "l2_mesh.h" #include "log.h" +#include "net_builtin.h" +#include "radio.h" #include "util.h" #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MG24) && MG_ENABLE_DRIVER_MG24 #include + +// A packet in the RAIL FIFOs: the radio header, then the frame +#if MG_RADIO == MG_RADIO_BLE +#include +#define MGI_MG24_HDR 2 // S0 byte, unused, then the frame length +#define MGI_MG24_MAX 251 // Largest frame. RAIL adds and strips the CRC +// RAIL channel: the RF channel, 2402 MHz + 2 MHz steps. Data channels 0-10 +// are RF channels 1-11, data channels 11-36 are RF channels 13-38 +#define MGI_MG24_CHANNEL \ + (MG_RADIO_CHANNEL < 11 ? MG_RADIO_CHANNEL + 1 : MG_RADIO_CHANNEL + 2) +#else #include +#define MGI_MG24_HDR 1 // PHR: the frame length, FCS included +#define MGI_MG24_MAX 125 // Largest frame, without the 2 byte FCS +#define MGI_MG24_CHANNEL MG_RADIO_CHANNEL +#endif // RAIL delivers raw frames and transmit completion from interrupt context. static struct mg_tcpip_if *s_mg24_ifp; static RAIL_Handle_t s_mg24_rail; -static struct mg_queue s_mg24_rx; -static char s_mg24_rxbuf[2048]; static volatile bool s_mg24_txing, s_mg24_tx_done; static RAIL_Time_t s_mg24_txstart; // Send start, us static uint8_t s_mg24_txfifo[256] __attribute__((aligned(4))); // Power of 2 -// Copy a received PSDU, stripping the PHR and any stored FCS. +// Copy a received frame, stripping the radio header and any stored CRC static void mg_mg24_rx_frame(RAIL_Handle_t h) { + static uint8_t f[MGI_MG24_HDR + MGI_MG24_MAX + 2]; // Interrupt use only RAIL_RxPacketInfo_t info; - uint8_t f[128]; size_t n; if (RAIL_GetRxPacketInfo(h, RAIL_RX_PACKET_HANDLE_NEWEST, &info) == RAIL_RX_PACKET_HANDLE_INVALID || info.packetStatus != RAIL_RX_PACKET_READY_SUCCESS || - info.packetBytes <= 1 || info.packetBytes > sizeof(f)) { + info.packetBytes <= MGI_MG24_HDR || info.packetBytes > sizeof(f)) { return; } RAIL_CopyRxPacket(f, &info); +#if MG_RADIO == MG_RADIO_BLE + n = f[1]; + if (n + MGI_MG24_HDR > (size_t) info.packetBytes) return; +#else n = info.packetBytes - 1U; // Strip PHR if (n == f[0]) n -= 2; // FCS stored, strip it - mg_mesh_rx_queue(&s_mg24_rx, s_mg24_ifp, f + 1, n); +#endif + mg_radio_rx_queue(s_mg24_ifp, f + MGI_MG24_HDR, n); } // RAIL event callback, runs in interrupt context @@ -44,17 +62,21 @@ static void mg_mg24_events(RAIL_Handle_t h, RAIL_Events_t events) { if (events & RAIL_EVENTS_TX_COMPLETION) s_mg24_tx_done = true; } -// RAIL adds the FCS. +// RAIL adds the CRC or FCS static size_t mgi_mg24_radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) { - uint8_t phr = (uint8_t) (len + 2); // FCS is added by hardware +#if MG_RADIO == MG_RADIO_BLE + uint8_t hdr[MGI_MG24_HDR] = {0, (uint8_t) len}; +#else + uint8_t hdr[MGI_MG24_HDR] = {(uint8_t) (len + 2)}; // FCS added by hardware +#endif (void) ifp; - if (len > 125 || s_mg24_txing) return 0; - RAIL_WriteTxFifo(s_mg24_rail, &phr, 1, true); // Reset FIFO, write PHR + if (len > MGI_MG24_MAX || s_mg24_txing) return 0; + RAIL_WriteTxFifo(s_mg24_rail, hdr, sizeof(hdr), true); // Reset, write hdr RAIL_WriteTxFifo(s_mg24_rail, (const uint8_t *) buf, (uint16_t) len, false); s_mg24_tx_done = false; s_mg24_txing = true, s_mg24_txstart = RAIL_GetTime(); - if (RAIL_StartTx(s_mg24_rail, MG_802154_CHANNEL, RAIL_TX_OPTIONS_DEFAULT, + if (RAIL_StartTx(s_mg24_rail, MGI_MG24_CHANNEL, RAIL_TX_OPTIONS_DEFAULT, NULL) != RAIL_STATUS_NO_ERROR) { s_mg24_txing = false; return 0; @@ -62,11 +84,46 @@ static size_t mgi_mg24_radio_tx(struct mg_tcpip_if *ifp, const void *buf, return len; } -static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - RAIL_Config_t cfg = {0}; +#if MG_RADIO == MG_RADIO_BLE +// Raw BLE 2 Mbit/s PHY, standard packet as in nrf52.c. The 100 us state +// transitions fit within the mesh's 300 us gap between frames +static bool mgi_mg24_protocol_init(uint16_t addr) { + RAIL_StateTiming_t timing = {0}; + (void) addr; + timing.idleToRx = 100, timing.idleToTx = 100; + timing.rxToTx = 100, timing.txToRx = 100; + return RAIL_BLE_Init(s_mg24_rail) == RAIL_STATUS_NO_ERROR && + RAIL_BLE_ConfigPhy2MbpsViterbi(s_mg24_rail) == RAIL_STATUS_NO_ERROR && + RAIL_BLE_ConfigChannelRadioParams(s_mg24_rail, 0x555555, + MG_RADIO_NETWORK, MG_RADIO_CHANNEL, + false) == RAIL_STATUS_NO_ERROR && + RAIL_SetStateTiming(s_mg24_rail, &timing) == RAIL_STATUS_NO_ERROR; +} +#else +// IEEE 802.15.4 with hardware filtering by PAN ID and our short address +static bool mgi_mg24_protocol_init(uint16_t addr) { RAIL_IEEE802154_Config_t cfg154 = {0}; + RAIL_StateTransitions_t to_rx = {RAIL_RF_STATE_RX, RAIL_RF_STATE_RX}; + cfg154.ackConfig.enable = false; + cfg154.ackConfig.ackTimeout = 864; + cfg154.ackConfig.rxTransitions = to_rx; + cfg154.ackConfig.txTransitions = to_rx; + cfg154.timings.idleToRx = 100, cfg154.timings.idleToTx = 100; + cfg154.timings.rxToTx = 192, cfg154.timings.txToRx = 182; + cfg154.framesMask = RAIL_IEEE802154_ACCEPT_STANDARD_FRAMES; + cfg154.promiscuousMode = false; + return RAIL_IEEE802154_Config2p4GHzRadio(s_mg24_rail) == + RAIL_STATUS_NO_ERROR && + RAIL_IEEE802154_Init(s_mg24_rail, &cfg154) == RAIL_STATUS_NO_ERROR && + RAIL_IEEE802154_SetPanId(s_mg24_rail, MG_RADIO_NETWORK, 0) == + RAIL_STATUS_NO_ERROR && + RAIL_IEEE802154_SetShortAddress(s_mg24_rail, addr, 0) == + RAIL_STATUS_NO_ERROR; +} +#endif + +static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { + RAIL_Config_t cfg = {0}; RAIL_TxPowerConfig_t pwr; RAIL_StateTransitions_t to_rx = {RAIL_RF_STATE_RX, RAIL_RF_STATE_RX}; RAIL_Events_t events = RAIL_EVENT_CAL_NEEDED | RAIL_EVENT_RX_PACKET_RECEIVED | @@ -76,25 +133,12 @@ static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp) { MG_ERROR(("RAIL_Init failed")); return false; } - cfg154.ackConfig.enable = false; - cfg154.ackConfig.ackTimeout = 864; - cfg154.ackConfig.rxTransitions = to_rx; - cfg154.ackConfig.txTransitions = to_rx; - cfg154.timings.idleToRx = 100, cfg154.timings.idleToTx = 100; - cfg154.timings.rxToTx = 192, cfg154.timings.txToRx = 182; - cfg154.framesMask = RAIL_IEEE802154_ACCEPT_STANDARD_FRAMES; - cfg154.promiscuousMode = false; // Filter by PAN ID and our short address pwr.mode = RAIL_TX_POWER_MODE_2P4GIG_HP, pwr.voltage = 3300; pwr.rampTime = 10; if (RAIL_ConfigCal(s_mg24_rail, RAIL_CAL_ALL) != RAIL_STATUS_NO_ERROR || RAIL_ConfigEvents(s_mg24_rail, RAIL_EVENTS_ALL, events) != RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_Config2p4GHzRadio(s_mg24_rail) != RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_Init(s_mg24_rail, &cfg154) != RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_SetPanId(s_mg24_rail, MG_802154_PAN_ID, 0) != - RAIL_STATUS_NO_ERROR || - RAIL_IEEE802154_SetShortAddress(s_mg24_rail, node->radio_address, 0) != - RAIL_STATUS_NO_ERROR || + !mgi_mg24_protocol_init(addr) || RAIL_SetTxTransitions(s_mg24_rail, &to_rx) != RAIL_STATUS_NO_ERROR || RAIL_SetRxTransitions(s_mg24_rail, &to_rx) != RAIL_STATUS_NO_ERROR || RAIL_ConfigTxPower(s_mg24_rail, &pwr) != RAIL_STATUS_NO_ERROR || @@ -106,67 +150,30 @@ static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp) { return false; } s_mg24_ifp = ifp; - return RAIL_StartRx(s_mg24_rail, MG_802154_CHANNEL, NULL) == + return RAIL_StartRx(s_mg24_rail, MGI_MG24_CHANNEL, NULL) == RAIL_STATUS_NO_ERROR; } -static size_t mgi_mg24_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_mg24_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_mg24_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; - node->now = now; +static bool mgi_mg24_radio_poll(struct mg_tcpip_if *ifp) { + bool done = false; + (void) ifp; if (s_mg24_txing && (s_mg24_tx_done || RAIL_GetTime() - s_mg24_txstart > - MG_MESH_TX_TIMEOUT_US)) { + MG_RADIO_TX_TIMEOUT_US)) { if (!s_mg24_tx_done) { RAIL_Idle(s_mg24_rail, RAIL_IDLE_ABORT, true); - RAIL_StartRx(s_mg24_rail, MG_802154_CHANNEL, NULL); + RAIL_StartRx(s_mg24_rail, MGI_MG24_CHANNEL, NULL); } s_mg24_txing = false; - node->tx_at = now + node->strategy->radio->ifs_us; + done = true; } - mg_mesh_rx_drain(node, &s_mg24_rx); - node->strategy->tick(node, now); - return node->joined; + return done; } + static bool mgi_mg24_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_mg24_radio_tx; - mg_queue_init(&s_mg24_rx, s_mg24_rxbuf, sizeof(s_mg24_rxbuf)); - if (mgi_mg24_radio_init(ifp)) return true; - data->mesh->strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_mg24_radio_init, mgi_mg24_radio_poll, + mgi_mg24_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_mg24 = {mgi_mg24_init, mgi_mg24_tx, - mgi_mg24_rx, mgi_mg24_poll}; + +struct mg_tcpip_driver mg_tcpip_driver_mg24 = {mgi_mg24_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif diff --git a/src/drivers/mg24.h b/src/drivers/mg24.h index cc37ca62..4f804d87 100644 --- a/src/drivers/mg24.h +++ b/src/drivers/mg24.h @@ -5,23 +5,16 @@ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MG24) && MG_ENABLE_DRIVER_MG24 -struct mg_tcpip_driver_mg24_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_mg24; #define MG_TCPIP_DRIVER_MG24_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_mg24_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_mg24; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) diff --git a/src/drivers/nrf52.c b/src/drivers/nrf52.c index ef1bff65..53323229 100644 --- a/src/drivers/nrf52.c +++ b/src/drivers/nrf52.c @@ -1,16 +1,30 @@ -#include "net_builtin.h" -#include "l2_mesh.h" #include "log.h" +#include "net_builtin.h" +#include "radio.h" #include "util.h" #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NRF52) && MG_ENABLE_DRIVER_NRF52 #include +// A packet in RAM: the radio header, then the frame +#if MG_RADIO == MG_RADIO_BLE +#define MGI_NRF52_HDR 2 // S0 byte, unused, then the frame length +#define MGI_NRF52_MAX 251 // Largest frame. The CRC is not in RAM +#define MGI_NRF52_RXSTART EVENTS_ADDRESS // A frame is being received +#define MGI_NRF52_MHZ \ + (MG_RADIO_CHANNEL < 11 ? 2404 + 2 * MG_RADIO_CHANNEL \ + : 2406 + 2 * MG_RADIO_CHANNEL) +#else +#define MGI_NRF52_HDR 1 // PHR: the frame length, FCS included +#define MGI_NRF52_MAX 125 // Largest frame, without the 2 byte FCS +#define MGI_NRF52_RXSTART EVENTS_FRAMESTART // A frame is being received +#endif + +#define MGI_NRF52_IOLEN (MGI_NRF52_HDR + MGI_NRF52_MAX + 2) + static struct mg_tcpip_if *s_nrf52_ifp; -static struct mg_queue s_nrf52_rx; -static char s_nrf52_queue[2048]; -static uint8_t s_nrf52_rxbuf[128] __attribute__((aligned(4))); -static uint8_t s_nrf52_txbuf[128] __attribute__((aligned(4))); +static uint8_t s_nrf52_rxbuf[MGI_NRF52_IOLEN] MG_8BYTE_ALIGNED; +static uint8_t s_nrf52_txbuf[MGI_NRF52_IOLEN] MG_8BYTE_ALIGNED; static volatile bool s_nrf52_txing, s_nrf52_done; static uint64_t s_nrf52_started; @@ -18,10 +32,11 @@ static void mgi_nrf52_listen(void) { NRF_RADIO->PACKETPTR = (uint32_t) s_nrf52_rxbuf; NRF_RADIO->SHORTS = RADIO_SHORTS_READY_START_Msk | RADIO_SHORTS_END_DISABLE_Msk; - NRF_RADIO->EVENTS_FRAMESTART = 0; + NRF_RADIO->MGI_NRF52_RXSTART = 0; NRF_RADIO->EVENTS_END = 0; NRF_RADIO->TASKS_RXEN = 1; } + static void mgi_nrf52_disable(void) { NRF_RADIO->SHORTS = 0; NRF_RADIO->EVENTS_DISABLED = 0; @@ -29,6 +44,7 @@ static void mgi_nrf52_disable(void) { while (!NRF_RADIO->EVENTS_DISABLED) (void) 0; NRF_RADIO->EVENTS_DISABLED = 0; } + void RADIO_IRQHandler(void); void RADIO_IRQHandler(void) { if (!NRF_RADIO->EVENTS_DISABLED) return; @@ -37,32 +53,31 @@ void RADIO_IRQHandler(void) { s_nrf52_txing = false; s_nrf52_done = true; } else if (NRF_RADIO->CRCSTATUS) { - struct mg_tcpip_driver_nrf52_data *data = s_nrf52_ifp->driver_data; - struct mg_mesh_node *node = data->mesh; +#if MG_RADIO == MG_RADIO_BLE + size_t len = s_nrf52_rxbuf[1]; +#else size_t len = s_nrf52_rxbuf[0] >= 2 ? s_nrf52_rxbuf[0] - 2U : 0; - uint8_t *frame = s_nrf52_rxbuf + 1; - uint16_t dst, src; - if (len <= 125 && - mg_radio_802154.parse_hdr(&mg_radio_802154, frame, len, &dst, &src) != - 0 && - (dst == 0xffffu || dst == node->radio_address)) { - mg_mesh_rx_queue(&s_nrf52_rx, s_nrf52_ifp, frame, len); - } +#endif + mg_radio_rx_queue(s_nrf52_ifp, s_nrf52_rxbuf + MGI_NRF52_HDR, len); } mgi_nrf52_listen(); } static size_t mgi_nrf52_radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) { (void) ifp; - if (len > 125) return 0; + if (len > MGI_NRF52_MAX) return 0; NVIC_DisableIRQ(RADIO_IRQn); - if (s_nrf52_txing || NRF_RADIO->EVENTS_FRAMESTART) { + if (s_nrf52_txing || NRF_RADIO->MGI_NRF52_RXSTART) { NVIC_EnableIRQ(RADIO_IRQn); return 0; } mgi_nrf52_disable(); +#if MG_RADIO == MG_RADIO_BLE + s_nrf52_txbuf[0] = 0, s_nrf52_txbuf[1] = (uint8_t) len; +#else s_nrf52_txbuf[0] = (uint8_t) (len + 2); - memcpy(s_nrf52_txbuf + 1, buf, len); +#endif + memcpy(s_nrf52_txbuf + MGI_NRF52_HDR, buf, len); s_nrf52_done = false; s_nrf52_txing = true; s_nrf52_started = mg_micros(); @@ -73,9 +88,33 @@ static size_t mgi_nrf52_radio_tx(struct mg_tcpip_if *ifp, const void *buf, NVIC_EnableIRQ(RADIO_IRQn); return len; } -static bool mgi_nrf52_radio_init(struct mg_tcpip_if *ifp) { +static bool mgi_nrf52_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) { s_nrf52_ifp = ifp; + (void) addr; // Frames are filtered by mg_radio_rx_queue() NRF_RADIO->POWER = 1; +#if MG_RADIO == MG_RADIO_BLE + // Standard BLE packet: 2 byte preamble, access address, S0 byte, 8 bit + // length, payload, 24 bit CRC over everything after the access address, + // initial value 0x555555. Whitening seeded by the channel index + NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_2Mbit; + NRF_RADIO->PCNF0 = (1UL << RADIO_PCNF0_S0LEN_Pos) | + (8UL << RADIO_PCNF0_LFLEN_Pos) | + (RADIO_PCNF0_PLEN_16bit << RADIO_PCNF0_PLEN_Pos); + NRF_RADIO->PCNF1 = ((uint32_t) MGI_NRF52_MAX << RADIO_PCNF1_MAXLEN_Pos) | + (3UL << RADIO_PCNF1_BALEN_Pos) | RADIO_PCNF1_WHITEEN_Msk; + NRF_RADIO->BASE0 = (uint32_t) MG_RADIO_NETWORK << 8; + NRF_RADIO->PREFIX0 = ((uint32_t) MG_RADIO_NETWORK >> 24) & 0xff; + NRF_RADIO->TXADDRESS = 0; + NRF_RADIO->RXADDRESSES = 1; + NRF_RADIO->CRCCNF = + 3 | (RADIO_CRCCNF_SKIPADDR_Skip << RADIO_CRCCNF_SKIPADDR_Pos); + NRF_RADIO->CRCPOLY = 0x65b; + NRF_RADIO->CRCINIT = 0x555555; + NRF_RADIO->DATAWHITEIV = MG_RADIO_CHANNEL; + NRF_RADIO->FREQUENCY = MGI_NRF52_MHZ - 2400; + NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_DTX_Center << RADIO_MODECNF0_DTX_Pos) | + RADIO_MODECNF0_RU_Fast; +#else NRF_RADIO->MODE = RADIO_MODE_MODE_Ieee802154_250Kbit; NRF_RADIO->PCNF0 = (8UL << RADIO_PCNF0_LFLEN_Pos) | (RADIO_PCNF0_PLEN_32bitZero << RADIO_PCNF0_PLEN_Pos) | @@ -87,42 +126,26 @@ static bool mgi_nrf52_radio_init(struct mg_tcpip_if *ifp) { NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_DTX_Center << RADIO_MODECNF0_DTX_Pos) | RADIO_MODECNF0_RU_Fast; NRF_RADIO->SFD = 0xa7; - NRF_RADIO->FREQUENCY = 5 * (MG_802154_CHANNEL - 10); - NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Pos8dBm; + NRF_RADIO->FREQUENCY = 5 * (MG_RADIO_CHANNEL - 10); // Correlator threshold 45 matches the RADIO reset value. A threshold of // 20 caused false busy detections and persistent L2 retries. NRF_RADIO->CCACTRL = (RADIO_CCACTRL_CCAMODE_CarrierMode << RADIO_CCACTRL_CCAMODE_Pos) | (2UL << RADIO_CCACTRL_CCACORRCNT_Pos) | (45UL << RADIO_CCACTRL_CCACORRTHRES_Pos); +#endif + NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Pos8dBm; NRF_RADIO->INTENSET = RADIO_INTENSET_DISABLED_Msk; NVIC_SetPriority(RADIO_IRQn, 0); NVIC_EnableIRQ(RADIO_IRQn); mgi_nrf52_listen(); return true; } -static size_t mgi_nrf52_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} -static size_t mgi_nrf52_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; - if (s_nrf52_txing && mg_micros() - s_nrf52_started > MG_MESH_TX_TIMEOUT_US) { +static bool mgi_nrf52_radio_poll(struct mg_tcpip_if *ifp) { + bool done; + (void) ifp; + if (s_nrf52_txing && mg_micros() - s_nrf52_started > MG_RADIO_TX_TIMEOUT_US) { NVIC_DisableIRQ(RADIO_IRQn); mgi_nrf52_disable(); s_nrf52_txing = false; @@ -130,40 +153,16 @@ static bool mgi_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { mgi_nrf52_listen(); NVIC_EnableIRQ(RADIO_IRQn); } - if (s_nrf52_done) { - s_nrf52_done = false; - node->tx_at = now + node->strategy->radio->ifs_us; - } - node->now = now; - mg_mesh_rx_drain(node, &s_nrf52_rx); - node->strategy->tick(node, now); - return node->joined; + done = s_nrf52_done; + s_nrf52_done = false; + return done; } static bool mgi_nrf52_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; - uint16_t address; - address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_nrf52_radio_tx; - mg_queue_init(&s_nrf52_rx, s_nrf52_queue, sizeof(s_nrf52_queue)); - if (mgi_nrf52_radio_init(ifp)) return true; - strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_nrf52_radio_init, mgi_nrf52_radio_poll, + mgi_nrf52_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_nrf52 = {mgi_nrf52_init, mgi_nrf52_tx, - mgi_nrf52_rx, mgi_nrf52_poll}; +struct mg_tcpip_driver mg_tcpip_driver_nrf52 = {mgi_nrf52_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif diff --git a/src/drivers/nrf52.h b/src/drivers/nrf52.h index f019ec89..f15c4568 100644 --- a/src/drivers/nrf52.h +++ b/src/drivers/nrf52.h @@ -5,23 +5,16 @@ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NRF52) && MG_ENABLE_DRIVER_NRF52 -struct mg_tcpip_driver_nrf52_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_nrf52; #define MG_TCPIP_DRIVER_NRF52_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_nrf52_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_nrf52; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) diff --git a/src/drivers/radio.c b/src/drivers/radio.c new file mode 100644 index 00000000..d7635425 --- /dev/null +++ b/src/drivers/radio.c @@ -0,0 +1,718 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "radio.h" +#include "log.h" +#include "printf.h" +#include "util.h" + +#if MG_ENABLE_TCPIP + +#define MGI_ETH_MAX 1514 +#define MGI_TX_DST_LEN 2 + +// The radio, chosen by MG_RADIO. A frame starts with the radio header, with +// the radio addresses, then the mesh header: type, then burst: the +// fragment's index << 4 | the last fragment's index. Then the payload +#if MG_RADIO == MG_RADIO_BLE +#define MGI_RADIO_MTU 251 // Largest frame: BLE 5 data length +#define MGI_RADIO_BITRATE 2000000 // Bits per second on air +#define MGI_RADIO_OVERHEAD 11 // Preamble, access address, length, CRC +#define MGI_RADIO_TURNAROUND_US 40 // Receive to transmit: nRF52840 fast ramp +#define MGI_RADIO_IFS_US 300 // Gap between transmissions +#define MGI_RADIO_HDR_LEN 4 // Destination, source + +// Write the radio header. Little endian +static void mgi_radio_write_hdr(uint8_t *buf, uint16_t dst, uint16_t src) { + buf[0] = (uint8_t) dst, buf[1] = (uint8_t) (dst >> 8); + buf[2] = (uint8_t) src, buf[3] = (uint8_t) (src >> 8); +} + +// Read the radio header. The access address already keeps other networks out +static bool mgi_radio_parse_hdr(const uint8_t *buf, size_t len, uint16_t *dst, + uint16_t *src) { + if (len < MGI_RADIO_HDR_LEN) return false; + *dst = (uint16_t) (buf[0] | buf[1] << 8); + *src = (uint16_t) (buf[2] | buf[3] << 8); + return true; +} +#else +#define MGI_RADIO_MTU 125 // 127 minus FCS +#define MGI_RADIO_BITRATE 250000 // Bits per second on air +#define MGI_RADIO_OVERHEAD 8 // Preamble, SFD, PHR, FCS +#define MGI_RADIO_TURNAROUND_US 100 // Receive to transmit +#define MGI_RADIO_IFS_US 640 // Gap between transmissions +#define MGI_RADIO_HDR_LEN 9 // MAC header, short addresses + +// MAC header: frame control 0x8841, a data frame, PAN ID compression, short +// destination and source addresses; sequence number, 0, as nothing uses it +// yet; PAN ID; destination; source. Little endian, as the standard says +static void mgi_radio_write_hdr(uint8_t *buf, uint16_t dst, uint16_t src) { + buf[0] = 0x41, buf[1] = 0x88, buf[2] = 0; + buf[3] = (uint8_t) MG_RADIO_NETWORK; + buf[4] = (uint8_t) (MG_RADIO_NETWORK >> 8); + buf[5] = (uint8_t) dst, buf[6] = (uint8_t) (dst >> 8); + buf[7] = (uint8_t) src, buf[8] = (uint8_t) (src >> 8); +} + +// Read the MAC header. Other networks' frames fail the check +static bool mgi_radio_parse_hdr(const uint8_t *buf, size_t len, uint16_t *dst, + uint16_t *src) { + if (len < MGI_RADIO_HDR_LEN || buf[0] != 0x41 || buf[1] != 0x88 || + buf[3] != (uint8_t) MG_RADIO_NETWORK || + buf[4] != (uint8_t) (MG_RADIO_NETWORK >> 8)) { + return false; + } + *dst = (uint16_t) (buf[5] | buf[6] << 8); + *src = (uint16_t) (buf[7] | buf[8] << 8); + return true; +} +#endif + +#define MGI_FRAME_HDR_LEN (MGI_RADIO_HDR_LEN + 2) // Radio and mesh headers +#define MGI_FRAG_CAP (MGI_RADIO_MTU - MGI_FRAME_HDR_LEN) // Payload per frame +#define MGI_TX_QUEUE_SIZE 2048 // Ethernet frames to send, as bursts +#define MGI_RX_STAMP_LEN sizeof(uint64_t) +#define MGI_RX_QUEUE_SIZE (16 * (MGI_RX_STAMP_LEN + MGI_RADIO_MTU + 8)) + +// A radio interface's state, its driver_data, allocated by mg_radio_init() +struct mg_radio_node { + bool (*hw_poll)(struct mg_tcpip_if *); // Hardware: service it + size_t (*hw_tx)(struct mg_tcpip_if *, const void *, size_t); // Start TX + struct mg_tcpip_if *ifp; // Radio interface + struct mg_tcpip_if *lan; // Bridge: LAN interface. NULL: a node + struct mg_queue frames; // Received radio frames, with arrival times + struct mg_queue tx; // Ethernet frames to send, one burst each + uint64_t now; // Current poll time, us + uint64_t tx_at; // Earliest next radio TX, us + uint64_t burst_at; // Next fragment TX, us + uint64_t deadline; // End of the current turn, us + uint64_t expire_at; // Node: no turn by then, leave. 0: had one + uint64_t answer_by; // Node: first answer frame must end by then + size_t rx_len; // Ethernet frame waiting for the stack + size_t tx_offset; // Next fragment of the queued burst + struct mgi_radio_peer *members; // Bridge: members, round-robin order + struct mgi_radio_peer *current; // Bridge: member whose turn is active/next + struct mgi_radio_peer *fanout; // Bridge: next broadcast recipient + uint32_t random; // PRNG state, for join timing + uint16_t radio_address; // Our radio address, made from the MAC + uint16_t coordinator; // Node: the bridge's radio address + uint8_t phase; // Turn: idle, join or data + uint8_t rx_expected; // Next fragment: index << 4 | last index. 0xff: idle + bool joined; // Node: member of the mesh + bool granted; // Node: had a turn this round + uint8_t rx_buf[MGI_ETH_MAX]; // Ethernet frame being reassembled + char tx_buf[MGI_TX_QUEUE_SIZE]; // Storage of the tx queue + char frames_buf[MGI_RX_QUEUE_SIZE]; // Storage of the frames queue +}; + +// Time on air of a len byte frame, us +static uint64_t mgi_radio_airtime(size_t len) { + return ((uint64_t) (len + MGI_RADIO_OVERHEAD) * 8000000 + MGI_RADIO_BITRATE - + 1) / + MGI_RADIO_BITRATE; +} + +// Each queue record holds a destination and a complete burst. +static size_t mgi_radio_queue(struct mg_radio_node *node, struct mg_queue *q, + const void *buf, size_t len, uint16_t dst, + uint8_t type) { + const uint8_t *eth = (const uint8_t *) buf; + size_t hdr = MGI_FRAME_HDR_LEN, cap = MGI_RADIO_MTU - hdr; + size_t frames, size, i; + char *record; + uint8_t *out; + if (len < 14 || len > MGI_ETH_MAX) return 0; + frames = (len + cap - 1) / cap; + size = MGI_TX_DST_LEN + len + frames * (1 + hdr); + if (mg_queue_next(q, NULL) == 0) mg_queue_init(q, q->buf, q->size); + if (mg_queue_book(q, &record, size) < size) { + MG_ERROR(("TX queue full: need %u, head %u, tail %u, size %u", + (unsigned) size, (unsigned) q->head, (unsigned) q->tail, + (unsigned) q->size)); + return 0; + } + out = (uint8_t *) record; + *out++ = (uint8_t) (dst >> 8); + *out++ = (uint8_t) dst; + for (i = 0; i < frames; i++) { + size_t chunk = len - i * cap; + if (chunk > cap) chunk = cap; + *out++ = (uint8_t) (hdr + chunk); + mgi_radio_write_hdr(out, dst, node->radio_address); + out[MGI_RADIO_HDR_LEN] = type; + out[MGI_RADIO_HDR_LEN + 1] = (uint8_t) (i << 4 | (frames - 1)); + memcpy(out + hdr, eth + i * cap, chunk); + out += hdr + chunk; + } + mg_queue_add(q, size); + return len; +} + +#define MGI_JOIN_WINDOW_US 3000 +#define MGI_JOIN_TURN_US 192 +#define MGI_JOIN_JITTER_US 640 +#define MGI_TX_RETRY_US 32 +// Node: finish the first answer frame this much before the bridge stops +// waiting +#define MGI_ANSWER_MARGIN_US 500 +#define MGI_JOIN_UP_LEN (MGI_FRAME_HDR_LEN + 6) // Payload: the MAC address +#define MGI_MAX_FRAGMENTS 14 + +enum { MGI_JOIN_DOWN = 1, MGI_JOIN_UP, MGI_DATA_DOWN, MGI_DATA_UP }; + +enum { MGI_TURN_IDLE, MGI_TURN_JOIN, MGI_TURN_DATA }; + +struct mgi_radio_peer { + struct mgi_radio_peer *next; // Next member in round-robin order + uint16_t radio_address; // Source address supplied in MGI_JOIN_UP + uint8_t mac[6]; // Ethernet MAC supplied in MGI_JOIN_UP + uint64_t expire_at; // First missed turn + MG_RADIO_TIMEOUT_MS, 0: answering +}; + +static uint32_t mgi_radio_random(struct mg_radio_node *node) { + uint32_t *random = &node->random; + if (*random == 0) { + size_t i; + *random = (uint32_t) mg_now(); + for (i = 0; i < 6; i++) *random = *random * 33u + node->ifp->mac[i]; + if (*random == 0) *random = 1; + } + *random ^= *random << 13; + *random ^= *random >> 17; + *random ^= *random << 5; + return *random; +} + +// Read a frame's radio addresses to dst and src, and return its type, from +// the mesh header. 0: not a frame of ours +static unsigned mgi_radio_frame_parse(const uint8_t *frame, size_t len, + uint16_t *dst, uint16_t *src) { + if (len < MGI_FRAME_HDR_LEN || !mgi_radio_parse_hdr(frame, len, dst, src)) { + return 0; + } + return frame[MGI_RADIO_HDR_LEN]; +} + +// Write a frame's headers: the radio's, to dst from src, then ours: type, +// and burst: high nibble is the index, low nibble is the last index +static void mgi_radio_frame_header(uint8_t *frame, uint16_t dst, uint16_t src, + uint8_t type, uint8_t burst) { + mgi_radio_write_hdr(frame, dst, src); + frame[MGI_RADIO_HDR_LEN] = type, frame[MGI_RADIO_HDR_LEN + 1] = burst; +} + +// Hand a radio frame to the hardware. The interface's fn sees it first +static bool mgi_radio_send(struct mg_radio_node *node, const void *frame, + size_t len) { + struct mg_str s = mg_str_n((const char *) frame, len); + mg_tcpip_call(node->ifp, MG_TCPIP_EV_PHY_TX, &s); + return node->hw_tx(node->ifp, frame, len) == len; +} + +static bool mgi_radio_control_send(struct mg_radio_node *node, uint16_t dst, + uint8_t command) { + uint8_t frame[MGI_JOIN_UP_LEN] = {0}; + size_t len = MGI_FRAME_HDR_LEN; + mgi_radio_frame_header(frame, dst, node->radio_address, command, 0); + if (command == MGI_JOIN_UP) { + memcpy(frame + MGI_FRAME_HDR_LEN, node->ifp->mac, 6); + len = MGI_JOIN_UP_LEN; + } + return node->now >= node->tx_at && mgi_radio_send(node, frame, len); +} + +// Time on air of a burst carrying len bytes, gaps between frames included +static uint64_t mgi_radio_burst_time(size_t len) { + size_t frames = len == 0 ? 1 : (len + MGI_FRAG_CAP - 1) / MGI_FRAG_CAP; + return (frames - 1) * (mgi_radio_airtime(MGI_RADIO_MTU) + MGI_RADIO_IFS_US) + + mgi_radio_airtime(MGI_FRAME_HDR_LEN + len - + (frames - 1) * MGI_FRAG_CAP); +} + +// End the current turn. A queued burst is used up only when done: all its +// frames went out. Otherwise it stays queued, and a later turn sends it again +static void mgi_radio_tx_finish(struct mg_radio_node *node, bool done) { + if (node->tx_offset != 0 && done) { + if (node->fanout != NULL) node->fanout = node->fanout->next; + if (node->fanout == NULL) { + size_t len = mg_queue_next(&node->tx, NULL); + mg_queue_del(&node->tx, len); + } + } + node->tx_offset = 0; + node->burst_at = (uint64_t) -1; +} + +static void mgi_radio_tx_step(struct mg_radio_node *node, uint64_t now) { + uint8_t empty[MGI_FRAME_HDR_LEN], *frame = empty; + size_t len = MGI_FRAME_HDR_LEN, record_len = 0; + uint16_t dst; + uint8_t command; + if (now < node->burst_at) return; + if (now >= node->deadline) { + mgi_radio_tx_finish(node, false); + return; + } + dst = node->lan == NULL ? node->coordinator : node->current->radio_address; + command = node->lan == NULL ? MGI_DATA_UP : MGI_DATA_DOWN; + if (node->tx_offset != 0) { + char *record; + uint8_t *part; + record_len = mg_queue_next(&node->tx, &record); + part = (uint8_t *) record + node->tx_offset; + len = part[0]; + frame = part + 1; + mgi_radio_write_hdr(frame, dst, node->radio_address); + } else { + mgi_radio_frame_header(frame, dst, node->radio_address, command, 0); + } + // A node's first answer frame: if it cannot end on air before the bridge + // stops waiting, stay silent. The queued frame waits for the next turn + if (node->lan == NULL && + (node->tx_offset == 0 || node->tx_offset == MGI_TX_DST_LEN) && + now + mgi_radio_airtime(len) > node->answer_by) { + node->tx_offset = 0; + node->burst_at = (uint64_t) -1; + return; + } + if (now < node->tx_at || !mgi_radio_send(node, frame, len)) { + node->burst_at = now + MGI_TX_RETRY_US; + return; + } + if (node->tx_offset == 0 || (node->tx_offset += len + 1) == record_len) { + // Bridge: the turn's last frame is out, wait for the answer + if (node->lan != NULL) + node->deadline = + now + mgi_radio_airtime(len) + MG_RADIO_ANSWER_TIMEOUT_US; + mgi_radio_tx_finish(node, true); + } else { + node->burst_at = now + mgi_radio_airtime(len) + MGI_RADIO_IFS_US; + } +} + +static void mgi_radio_tx_begin(struct mg_radio_node *node, bool burst, + uint64_t now, uint64_t deadline) { + node->phase = MGI_TURN_DATA; + node->answer_by = (uint64_t) -1; // Node sets it after a grant + node->tx_offset = burst ? MGI_TX_DST_LEN : 0; + node->burst_at = now; + node->deadline = deadline; +} + +// Return the assembled length, zero for an empty frame, or -1 if incomplete +// or invalid. Full non-final fragments make the write offset derivable. +static int mgi_radio_data_receive(struct mg_radio_node *node, + const uint8_t *frame, size_t len, + uint64_t now) { + unsigned burst = frame[MGI_FRAME_HDR_LEN - 1], index = burst >> 4, + last = burst & 15; + size_t chunk = len - MGI_FRAME_HDR_LEN, cap = MGI_FRAG_CAP; + size_t offset = index * cap; + if (index == 0) { + node->rx_expected = (uint8_t) burst; + if (node->lan == NULL) + node->deadline = now + mgi_radio_burst_time(MGI_ETH_MAX) + + 2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US; + } + if (last >= MGI_MAX_FRAGMENTS || index > last || burst != node->rx_expected || + chunk > cap || now > node->deadline || (index < last && chunk != cap) || + (last != 0 && chunk == 0) || offset + chunk > sizeof(node->rx_buf)) { + MG_ERROR( + ("%s: fragment %u/%u dropped, expected %u/%u, %u bytes, %lld us " + "past deadline", + node->lan == NULL ? "Node" : "Bridge", index, last, + (unsigned) node->rx_expected >> 4, node->rx_expected & 15U, + (unsigned) chunk, (long long) (now - node->deadline))); + node->rx_expected = 0xff; + return -1; + } + memcpy(node->rx_buf + offset, frame + MGI_FRAME_HDR_LEN, chunk); + if (index < last) { + node->rx_expected = (uint8_t) (burst + 0x10); + // Bridge: an answer is under way, wait for its next fragment + if (node->lan != NULL) + node->deadline = now + mgi_radio_airtime(MGI_RADIO_MTU) + + MGI_RADIO_IFS_US + MG_RADIO_ANSWER_TIMEOUT_US; + return -1; + } + node->rx_expected = 0xff; + return offset + chunk == 0 || offset + chunk >= 14 ? (int) (offset + chunk) + : -1; +} + +// Bridge scheduling and Ethernet forwarding. + +static uint16_t mgi_radio_join_field(const uint8_t *p) { + return (uint16_t) ((unsigned) p[0] * 256 + p[1]); +} + +// Return chaddr for an Ethernet DHCP server reply, even when broadcast. +static const uint8_t *mgi_radio_dhcp_client(const uint8_t *frame, size_t len) { + size_t ip_len, ihl, udp_len; + const uint8_t *udp, *dhcp; + if (len < 34 || mgi_radio_join_field(frame + 12) != 0x0800 || + (frame[14] >> 4) != 4 || frame[23] != 17 || + (mgi_radio_join_field(frame + 20) & 0x3fff) != 0) + return NULL; + ip_len = mgi_radio_join_field(frame + 16); + ihl = (size_t) (frame[14] & 15) * 4; + if (ihl < 20 || ip_len > len - 14 || ip_len < ihl + 8 + 240) return NULL; + udp = frame + 14 + ihl; + udp_len = mgi_radio_join_field(udp + 4); + if (mgi_radio_join_field(udp) != 67 || mgi_radio_join_field(udp + 2) != 68 || + udp_len < 8 + 240 || udp_len > ip_len - ihl) + return NULL; + dhcp = udp + 8; + if (dhcp[0] != 2 || dhcp[1] != 1 || dhcp[2] != 6 || + memcmp(dhcp + 236, "\x63\x82\x53\x63", 4) != 0) + return NULL; + return dhcp + 28; +} + +static size_t mgi_radio_enqueue(struct mg_radio_node *node, const void *buf, + size_t len) { + const uint8_t *frame = (const uint8_t *) buf; + if (node->lan == NULL) + return mgi_radio_queue(node, &node->tx, buf, len, node->coordinator, + MGI_DATA_UP); + if (len >= 14 && len <= MGI_ETH_MAX) { + const uint8_t *client = mgi_radio_dhcp_client(frame, len); + const uint8_t *dst = client == NULL ? frame : client; + bool multicast = client == NULL && (frame[0] & 1) != 0; + struct mgi_radio_peer *peer; + for (peer = node->members; peer != NULL; peer = peer->next) { + if (multicast || memcmp(dst, peer->mac, 6) == 0) { + uint16_t addr = multicast ? 0xffffu : peer->radio_address; + return mgi_radio_queue(node, &node->tx, buf, len, addr, MGI_DATA_DOWN); + } + } + } + return 0; +} + +static void mgi_radio_bridge_queue_lan(struct mg_radio_node *bridge) { + struct mg_queue *rx = &bridge->lan->recv_queue; + char *buf; + size_t len; + while ((len = mg_queue_next(rx, &buf)) > 0) { + bridge->ifp->driver->tx(buf, len, bridge->ifp); + mg_queue_del(rx, len); + } +} + +static void mgi_radio_bridge_rx(uint64_t now, struct mg_radio_node *b, + const uint8_t *frame, size_t len) { + struct mgi_radio_peer *peer; + uint16_t dst = 0, src = 0; + unsigned command = mgi_radio_frame_parse(frame, len, &dst, &src); + if (command == MGI_DATA_UP && dst == b->radio_address && + b->phase == MGI_TURN_DATA && b->current != NULL && + src == b->current->radio_address && now <= b->deadline) { + int received = mgi_radio_data_receive(b, frame, len, now); + if (received < 0) return; + if (received != 0) { + b->lan->driver->tx(b->rx_buf, (size_t) received, b->lan); + } + b->current->expire_at = 0; + b->current = b->current->next; + b->phase = MGI_TURN_IDLE; + b->deadline = now; + return; + } + if (command == MGI_DATA_UP && dst == b->radio_address) { + MG_ERROR( + ("Bridge: fragment %u/%u from %04x outside its turn: phase %u, " + "turn of %04x, %lld us past deadline", + frame[MGI_FRAME_HDR_LEN - 1] >> 4U, frame[MGI_FRAME_HDR_LEN - 1] & 15U, + src, b->phase, b->current == NULL ? 0 : b->current->radio_address, + (long long) (now - b->deadline))); + return; + } + if (len != MGI_JOIN_UP_LEN || command != MGI_JOIN_UP || + dst != b->radio_address || b->phase != MGI_TURN_JOIN || + now >= b->deadline) { + return; + } + if (src == 0 || src == 0xffffu) return; + for (peer = b->members; peer != NULL; peer = peer->next) { + if (peer->radio_address == src) break; + } + if (peer == NULL) { + peer = (struct mgi_radio_peer *) mg_calloc(1, sizeof(*peer)); + if (peer == NULL) return; + peer->radio_address = src; + peer->next = b->members; + b->members = peer; + MG_DEBUG(("Member %M joined, radio address %04x", mg_print_mac, + frame + MGI_FRAME_HDR_LEN, src)); + } + memcpy(peer->mac, frame + MGI_FRAME_HDR_LEN, sizeof(peer->mac)); + peer->expire_at = 0; +} + +// Member peer did not answer its turn. The first miss starts the timeout. If +// it is still silent when that ends, it is gone: remove it, and its queued +// downlink frames +static void mgi_radio_member_missed(struct mg_radio_node *node, + struct mgi_radio_peer *peer, uint64_t now) { + if (peer->expire_at == 0) peer->expire_at = now + MG_RADIO_TIMEOUT_MS * 1000; + if (now < peer->expire_at) return; + MG_DEBUG(("Member %M removed: no answer for %d ms", mg_print_mac, peer->mac, + MG_RADIO_TIMEOUT_MS)); + if (node->fanout == peer) { + node->fanout = peer->next; + if (node->fanout == NULL) { + size_t len = mg_queue_next(&node->tx, NULL); + mg_queue_del(&node->tx, len); + } + } + LIST_DELETE(struct mgi_radio_peer, &node->members, peer); + mg_free(peer); +} + +// A broadcast occupies one record and is sent once to each member in list +// order. +static size_t mgi_radio_bridge_burst(struct mg_radio_node *node, + struct mgi_radio_peer *peer) { + char *record; + size_t len; + while ((len = mg_queue_next(&node->tx, &record)) != 0) { + uint16_t dst = mgi_radio_join_field((const uint8_t *) record); + struct mgi_radio_peer *member; + if (dst == 0xffffu) { + if (node->fanout == NULL) node->fanout = node->members; + return node->fanout == peer ? len : 0; + } + if (dst == peer->radio_address) return len; + for (member = node->members; member != NULL; member = member->next) { + if (member->radio_address == dst) return 0; + } + mg_queue_del(&node->tx, len); // Its destination has left. + } + return 0; +} + +static uint64_t mgi_radio_queued_burst_time(struct mg_radio_node *node, + size_t len) { + char *record; + size_t frames; + if (len == 0) return mgi_radio_burst_time(0); + mg_queue_next(&node->tx, &record); + // Fragment zero carries the final index. Count overhead and IFS per frame. + frames = ((uint8_t) record[MGI_TX_DST_LEN + MGI_FRAME_HDR_LEN] & 15u) + 1u; + return mgi_radio_airtime(len - MGI_TX_DST_LEN - frames + + (frames - 1) * MGI_RADIO_OVERHEAD) + + (frames - 1) * MGI_RADIO_IFS_US; +} + +static void mgi_radio_bridge_io(uint64_t now, struct mg_radio_node *b) { + mgi_radio_bridge_queue_lan(b); + if (now >= b->deadline) { + if (b->burst_at != (uint64_t) -1) mgi_radio_tx_finish(b, false); + if (b->phase == MGI_TURN_DATA && b->current != NULL) { + struct mgi_radio_peer *peer = b->current; + b->current = peer->next; + mgi_radio_member_missed(b, peer, now); + } else if (b->phase == MGI_TURN_JOIN) { + b->current = b->members; + } + b->phase = MGI_TURN_IDLE; + if (b->current != NULL) { + size_t burst = mgi_radio_bridge_burst(b, b->current); + uint64_t down = mgi_radio_queued_burst_time(b, burst); + b->rx_expected = 0xff; + down += mgi_radio_burst_time(MGI_ETH_MAX); + mgi_radio_tx_begin(b, burst != 0, now, + now + down + 2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US); + } else if (mgi_radio_control_send(b, 0xffffu, MGI_JOIN_DOWN)) { + b->phase = MGI_TURN_JOIN; + b->deadline = now + MGI_JOIN_WINDOW_US; + } + if (b->deadline <= now) b->deadline = now + MGI_JOIN_TURN_US; + } +} + +static void mgi_radio_node_rx(struct mg_radio_node *n, uint64_t now, + uint8_t *frame, size_t len) { + uint16_t dst = 0, src = 0; + unsigned command = mgi_radio_frame_parse(frame, len, &dst, &src); + if (command == MGI_JOIN_DOWN && len == MGI_FRAME_HDR_LEN && dst == 0xffffu) { + // A round without our turn starts the timeout, a turn clears it + if (n->joined && src == n->coordinator && n->granted) { + n->granted = false; + } else if (n->joined && src == n->coordinator && n->expire_at == 0) { + n->expire_at = now + MG_RADIO_TIMEOUT_MS * 1000; + } else if (n->joined && src == n->coordinator && now >= n->expire_at) { + MG_INFO(("Left the mesh: no turn for %d ms", MG_RADIO_TIMEOUT_MS)); + n->joined = false; + n->phase = MGI_TURN_IDLE; + n->burst_at = (uint64_t) -1; + n->tx_offset = 0; + n->rx_expected = 0xff; + } + if (!n->joined && (mgi_radio_random(n) % 64) == 0) { + // Spread contenders across windows as well as within the reply window. + n->coordinator = src; + n->phase = MGI_TURN_JOIN; + n->burst_at = + now + MGI_JOIN_TURN_US + mgi_radio_random(n) % MGI_JOIN_JITTER_US; + } + } else if (command == MGI_DATA_DOWN && n->coordinator != 0 && + dst == n->radio_address && src == n->coordinator) { + int received = mgi_radio_data_receive(n, frame, len, now); + if (received < 0) return; + if (!n->joined) MG_INFO(("Joined the mesh, bridge address %04x", src)); + n->joined = true; + n->granted = true; + n->expire_at = 0; + if (received != 0) { + struct mg_tcpip_if *ifp = n->ifp; + if (n->rx_len != 0 || (size_t) received > ifp->recv_queue.size) { + ifp->ndrop++; + } else { + memcpy(ifp->recv_queue.buf, n->rx_buf, (size_t) received); + n->rx_len = (size_t) received; + } + } + // A grant that waited in the receive queue while the node was busy, e.g. + // computing TLS keys, is too old to answer. Leave the turn state alone: + // queued frames go out on the first grant that can still be answered + if (n->now + MGI_ANSWER_MARGIN_US >= now + MG_RADIO_ANSWER_TIMEOUT_US) { + return; + } + if (n->burst_at != (uint64_t) -1) mgi_radio_tx_finish(n, false); + mgi_radio_tx_begin(n, mg_queue_next(&n->tx, NULL) != 0, now, + now + mgi_radio_burst_time(MGI_ETH_MAX) + + 2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US); + n->answer_by = now + MG_RADIO_ANSWER_TIMEOUT_US - MGI_ANSWER_MARGIN_US; + } +} + +// Handle a received radio frame. Its timing counts from its arrival, us +static void mgi_radio_input(struct mg_radio_node *node, uint64_t arrived, + void *buf, size_t len) { + uint64_t ready = node->now + MGI_RADIO_TURNAROUND_US; + if (node->tx_at < ready) node->tx_at = ready; + if (node->lan != NULL) { + mgi_radio_bridge_rx(arrived, node, (const uint8_t *) buf, len); + } else { + mgi_radio_node_rx(node, arrived, (uint8_t *) buf, len); + } +} + +static void mgi_radio_tick(struct mg_radio_node *node, uint64_t now) { + node->now = now; + if (node->lan != NULL) { + mgi_radio_bridge_io(now, node); + mgi_radio_tx_step(node, now); + return; + } + if (node->phase == MGI_TURN_JOIN) { + if (node->burst_at <= now) { + if (now - node->burst_at <= MGI_JOIN_TURN_US && !node->joined) + mgi_radio_control_send(node, node->coordinator, MGI_JOIN_UP); + node->burst_at = (uint64_t) -1; + node->phase = MGI_TURN_IDLE; + } + } else { + mgi_radio_tx_step(node, now); + } +} + +bool mg_radio_init(struct mg_tcpip_if *ifp, + bool (*hw_init)(struct mg_tcpip_if *, uint16_t addr), + bool (*hw_poll)(struct mg_tcpip_if *), + size_t (*hw_tx)(struct mg_tcpip_if *, const void *, + size_t)) { + struct mg_radio_node *node = + (struct mg_radio_node *) mg_calloc(1, sizeof(*node)); + if (node == NULL) return false; + node->hw_poll = hw_poll, node->hw_tx = hw_tx; + node->ifp = ifp; + node->radio_address = + (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); + node->burst_at = (uint64_t) -1; + node->rx_expected = 0xff; + mg_queue_init(&node->tx, node->tx_buf, sizeof(node->tx_buf)); + mg_queue_init(&node->frames, node->frames_buf, sizeof(node->frames_buf)); + ifp->driver_data = node; + if (hw_init(ifp, node->radio_address)) return true; + ifp->driver_data = NULL; + mg_free(node); + return false; +} + +void mg_radio_bridge(struct mg_tcpip_if *ifp, struct mg_tcpip_if *lan) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + node->lan = lan; +} + +size_t mg_radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + size_t n = mgi_radio_enqueue(node, buf, len); + if (n != len) { // Mongoose ignores a failed send: count and report it + ifp->nerr++; + MG_ERROR(("Mesh refused a %u byte frame", (unsigned) len)); + } + return n; +} + +size_t mg_radio_rx(void *buf, size_t len, struct mg_tcpip_if *ifp) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + size_t n = node->rx_len; + if (n > len) return 0; + if (n != 0 && buf != ifp->recv_queue.buf) memcpy(buf, ifp->recv_queue.buf, n); + node->rx_len = 0; + return n; +} + +void mg_radio_rx_queue(struct mg_tcpip_if *ifp, const void *frame, size_t len) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + uint64_t arrived = mg_micros(); + size_t need = MGI_RX_STAMP_LEN + len; + uint16_t dst, src; + char *p; + if (len > MGI_RADIO_MTU || + !mgi_radio_parse_hdr((const uint8_t *) frame, len, &dst, &src) || + (dst != 0xffffu && dst != node->radio_address)) { + return; + } + if (mg_queue_book(&node->frames, &p, need) < need) { + ifp->ndrop++; + return; + } + memcpy(p, &arrived, MGI_RX_STAMP_LEN); + memcpy(p + MGI_RX_STAMP_LEN, frame, len); + mg_queue_add(&node->frames, need); +} + +// Process queued radio frames, oldest first, each with its arrival time. +// Stop while the node holds an Ethernet frame the TCP/IP stack has not taken +// yet +bool mg_radio_poll(struct mg_tcpip_if *ifp, bool s1) { + struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data; + bool tx_done = node->hw_poll(ifp); + uint64_t now = mg_micros(); + char *record; + size_t len; + (void) s1; + if (tx_done) node->tx_at = now + MGI_RADIO_IFS_US; + node->now = now; + while (node->rx_len == 0 && + (len = mg_queue_next(&node->frames, &record)) != 0) { + if (len > MGI_RX_STAMP_LEN) { + struct mg_str s = + mg_str_n(record + MGI_RX_STAMP_LEN, len - MGI_RX_STAMP_LEN); + uint64_t arrived; + memcpy(&arrived, record, MGI_RX_STAMP_LEN); + mg_tcpip_call(ifp, MG_TCPIP_EV_PHY_RX, &s); + mgi_radio_input(node, arrived, s.buf, s.len); + } + mg_queue_del(&node->frames, len); + } + mgi_radio_tick(node, now); + return node->joined; +} + +#endif diff --git a/src/drivers/radio.h b/src/drivers/radio.h new file mode 100644 index 00000000..4304e31c --- /dev/null +++ b/src/drivers/radio.h @@ -0,0 +1,74 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved +// +// Ethernet over radio: shared framing, scheduling and bridge forwarding. +// Hardware drivers pass their functions to mg_radio_init(). + +#pragma once + +#include "net_builtin.h" + +#define MG_RADIO_802154 1 // IEEE 802.15.4, 250 kbit/s +#define MG_RADIO_BLE 2 // Bluetooth LE 2 Mbit/s PHY, raw: no BLE link layer + +#ifndef MG_RADIO +#define MG_RADIO MG_RADIO_802154 +#endif + +// The radio network: a channel, and an id that keeps other networks out. +// A bridge and its nodes must use the same values +#if MG_RADIO == MG_RADIO_BLE +#ifndef MG_RADIO_CHANNEL +#define MG_RADIO_CHANNEL 36 // Data channel 0-36. 36: 2478 MHz, clear of Wi-Fi +#endif +#ifndef MG_RADIO_NETWORK +#define MG_RADIO_NETWORK 0x71764129 // Access address +#endif +#else +#ifndef MG_RADIO_CHANNEL +#define MG_RADIO_CHANNEL 15 // Channel 11-26 +#endif +#ifndef MG_RADIO_NETWORK +#define MG_RADIO_NETWORK 0xabcd // PAN ID +#endif +#endif + +// A turn's answer must arrive this soon after the turn's last frame ends on +// air, or the turn ends. A node that would answer later stays silent and keeps +// its frame for the next turn. Covers the node's poll latency, the radio +// turnaround and one full fragment's airtime, 4.3 ms on 802.15.4 +#ifndef MG_RADIO_ANSWER_TIMEOUT_US +#define MG_RADIO_ANSWER_TIMEOUT_US 8000 +#endif + +// A radio driver aborts a transmission that has not finished this soon, and +// reports it done to mg_radio_poll() +#ifndef MG_RADIO_TX_TIMEOUT_US +#define MG_RADIO_TX_TIMEOUT_US 60000 +#endif + +// Membership timeout. The bridge removes a member that has not answered its +// turns for this long, counted from the first missed turn. A node leaves the +// mesh when it has had no turn for this long +#ifndef MG_RADIO_TIMEOUT_MS +#define MG_RADIO_TIMEOUT_MS 1000 +#endif + +#if MG_ENABLE_TCPIP + +bool mg_radio_init(struct mg_tcpip_if *ifp, + bool (*hw_init)(struct mg_tcpip_if *, uint16_t addr), + bool (*hw_poll)(struct mg_tcpip_if *), + size_t (*hw_tx)(struct mg_tcpip_if *, const void *, size_t)); +bool mg_radio_poll(struct mg_tcpip_if *, bool s1); // Run it. true: joined +size_t mg_radio_tx(const void *, size_t, struct mg_tcpip_if *); // Queue +size_t mg_radio_rx(void *, size_t, struct mg_tcpip_if *); // Received frame + +// Bridge LAN and radio Ethernet frames. Call after both interfaces initialize. +void mg_radio_bridge(struct mg_tcpip_if *, struct mg_tcpip_if *lan); + +// Queue a received radio frame with its arrival time. Call it from the +// receive interrupt. Frames for other radios are skipped +void mg_radio_rx_queue(struct mg_tcpip_if *, const void *, size_t); + +#endif diff --git a/src/drivers/rw612w.c b/src/drivers/rw612w.c index e32e2450..bd694225 100644 --- a/src/drivers/rw612w.c +++ b/src/drivers/rw612w.c @@ -1,11 +1,15 @@ -#include "net_builtin.h" -#include "l2_mesh.h" #include "log.h" +#include "net_builtin.h" +#include "radio.h" #include "util.h" #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612W) && \ MG_ENABLE_DRIVER_RW612W +#if MG_RADIO != MG_RADIO_802154 +#error "MG_ENABLE_DRIVER_RW612W supports MG_RADIO_802154 only" +#endif + #include "sha256.h" #ifdef ENET @@ -114,8 +118,6 @@ struct mg_rw612 { struct mg_tcpip_if *ifp; // Our interface, for the L2 receive pool }; static struct mg_rw612 s_rw612; -static struct mg_queue s_rw612w_rx; -static char s_rw612w_queue[2048]; static void mg_rw612_imu_send(uint8_t type, uint8_t subtype, const uint32_t *payload, uint8_t len) { @@ -139,7 +141,7 @@ static void mg_rw612_control(uint8_t subtype, uint32_t a, uint32_t b, } static void mg_rw612_queue_rx(const uint8_t *frame, size_t len) { - mg_mesh_rx_queue(&s_rw612w_rx, s_rw612.ifp, frame, len); + mg_radio_rx_queue(s_rw612.ifp, frame, len); } // Spinel packed unsigned integer: 7 bits per byte, LSB first @@ -362,7 +364,7 @@ static size_t mgi_rw612w_radio_tx(struct mg_tcpip_if *ifp, const void *buf, memcpy(f + n, buf, len), n += len; f[n++] = 0, f[n++] = 0; // FCS, filled in by the radio (void) ifp; - f[n++] = MG_802154_CHANNEL; + f[n++] = MG_RADIO_CHANNEL; f[n++] = 0; // Max CSMA backoffs f[n++] = 0; // Max frame retries f[n++] = 0; // CSMA disabled for scheduled turns @@ -371,11 +373,9 @@ static size_t mgi_rw612w_radio_tx(struct mg_tcpip_if *ifp, const void *buf, return len; } -static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp) { +static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp, uint16_t address) { struct mg_rw612 *s = &s_rw612; - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint8_t f[8], one = 1, zero = 0, pan[2], addr[2], channel = MG_802154_CHANNEL; + uint8_t f[8], one = 1, zero = 0, pan[2], addr[2], channel = MG_RADIO_CHANNEL; uint64_t expire; if (MGI_MBOX->magic[0] != MGI_SYNC_MAGIC) { MG_ERROR(("Radio firmware is not running on CPU2")); @@ -414,10 +414,10 @@ static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp) { if (!mg_rw612_set(MGI_PROP_PHY_ENABLED, &one, 1)) { return mg_rw612_fail("PHY enable failed"); } - pan[0] = (uint8_t) MG_802154_PAN_ID; - pan[1] = (uint8_t) (MG_802154_PAN_ID >> 8); - addr[0] = (uint8_t) node->radio_address; - addr[1] = (uint8_t) (node->radio_address >> 8); + pan[0] = (uint8_t) MG_RADIO_NETWORK; + pan[1] = (uint8_t) (MG_RADIO_NETWORK >> 8); + addr[0] = (uint8_t) address; + addr[1] = (uint8_t) (address >> 8); if (!mg_rw612_set(MGI_PROP_PHY_CHAN, &channel, 1) || !mg_rw612_set(MGI_PROP_PANID, pan, 2) || !mg_rw612_set(MGI_PROP_SADDR, addr, 2) || @@ -430,72 +430,30 @@ static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp) { return true; } -static size_t mgi_rw612w_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - return data->mesh->strategy->tx(data->mesh, buf, len); -} - -static size_t mgi_rw612w_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - size_t len = data->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - data->mesh->rx_len = 0; - return len; -} - -static bool mgi_rw612w_poll(struct mg_tcpip_if *ifp, bool s1) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - struct mg_mesh_node *node = data->mesh; - uint64_t now = mg_micros(); - (void) s1; +static bool mgi_rw612w_radio_poll(struct mg_tcpip_if *ifp) { bool was_sending = s_rw612.txing; + (void) ifp; mg_rw612_poll_imu(); if (s_rw612.txing && (s_rw612.rsp || mg_millis() > s_rw612.txstart + MGI_TX_TIMEOUT_MS)) { if (!s_rw612.rsp) MG_ERROR(("TX timeout")); s_rw612.txing = false; } - if (was_sending && !s_rw612.txing) - node->tx_at = now + node->strategy->radio->ifs_us; - node->now = now; - mg_mesh_rx_drain(node, &s_rw612w_rx); - node->strategy->tick(node, now); - return node->joined; + return was_sending && !s_rw612.txing; } +// The MAC comes from the chip's unique ID static bool mgi_rw612w_init(struct mg_tcpip_if *ifp) { - struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; - const struct mg_mesh *strategy = data->strategy; uint8_t uid[FSL_OCOTP_UID_LENGTH] = {0}, digest[32]; uint32_t uid_len = sizeof(uid); - uint16_t address; OCOTP_ReadUniqueID(uid, &uid_len); mg_sha256(digest, uid, sizeof(uid)); memcpy(ifp->mac, digest, 6); ifp->mac[0] = 0x02; - address = - (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); - if (strategy == NULL) strategy = &mg_mesh_default; - data->mesh = mg_calloc(1, sizeof(*data->mesh)); - if (data->mesh == NULL) return false; - if (!strategy->init(data->mesh, ifp, NULL, address)) { - mg_free(data->mesh); - data->mesh = NULL; - return false; - } - data->mesh->strategy = strategy; - data->mesh->tx = mgi_rw612w_radio_tx; - mg_queue_init(&s_rw612w_rx, s_rw612w_queue, sizeof(s_rw612w_queue)); - if (mgi_rw612w_radio_init(ifp)) return true; - strategy->free(data->mesh); - mg_free(data->mesh); - data->mesh = NULL; - return false; + return mg_radio_init(ifp, mgi_rw612w_radio_init, mgi_rw612w_radio_poll, + mgi_rw612w_radio_tx); } -struct mg_tcpip_driver mg_tcpip_driver_rw612w = { - mgi_rw612w_init, mgi_rw612w_tx, mgi_rw612w_rx, mgi_rw612w_poll}; +struct mg_tcpip_driver mg_tcpip_driver_rw612w = {mgi_rw612w_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; #endif diff --git a/src/drivers/rw612w.h b/src/drivers/rw612w.h index 05ae30ea..b8ffe211 100644 --- a/src/drivers/rw612w.h +++ b/src/drivers/rw612w.h @@ -6,23 +6,16 @@ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612W) && \ MG_ENABLE_DRIVER_RW612W -struct mg_tcpip_driver_rw612w_data { - struct mg_mesh_node *mesh; // Driver-owned runtime state - const struct mg_mesh *strategy; // NULL selects mg_mesh_default -}; - extern struct mg_tcpip_driver mg_tcpip_driver_rw612w; #define MG_TCPIP_DRIVER_RW612W_INIT(mgr) \ do { \ - static struct mg_tcpip_driver_rw612w_data driver_data_; \ static struct mg_tcpip_if mif_; \ MG_SET_MAC_ADDRESS(mif_.mac); \ mif_.ip = MG_TCPIP_IP; \ mif_.mask = MG_TCPIP_MASK; \ mif_.gw = MG_TCPIP_GW; \ mif_.driver = &mg_tcpip_driver_rw612w; \ - mif_.driver_data = &driver_data_; \ mg_tcpip_init((mgr), &mif_); \ MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) diff --git a/src/drivers/usb.c b/src/drivers/usb.c index 9990ee2b..053b8239 100644 --- a/src/drivers/usb.c +++ b/src/drivers/usb.c @@ -1,53 +1,65 @@ -#include "drivers/usb.h" #include "net_builtin.h" +#include "drivers/usb.h" +#include "log.h" +#include "printf.h" +#include "util.h" -#if MG_ENABLE_USB +// USB Ethernet needs the TCP/IP stack, the serial console does not +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + (MG_ENABLE_DRIVER_USB_RP || MG_ENABLE_DRIVER_USB_NRF52 || \ + MG_ENABLE_DRIVER_USB_DWC2) && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) -// Interfaces: NCM control and data 0/1 if enabled, then ACM control and data -#define MG_USB_SERIAL_IF (2 * MG_ENABLE_USB_ETHERNET) -#define MG_USB_NUM_IFS (2 * MG_ENABLE_USB_ETHERNET + 2 * MG_ENABLE_USB_SERIAL) -#define MG_USB_CONFIG_LEN \ +// Interfaces: ACM control and data 0/1 if enabled, then NCM control and data. +// The serial port comes first, so that its name on macOS does not depend on +// Ethernet: /dev/cu.usbmodem...01 +#define MGI_USB_ETH_IF (MG_USB_IF_ETH_DATA - 1) +#define MGI_USB_NUM_IFS (2 * MG_ENABLE_USB_ETHERNET + 2 * MG_ENABLE_USB_SERIAL) +#define MGI_USB_CONFIG_LEN \ (9 + 85 * MG_ENABLE_USB_ETHERNET + 66 * MG_ENABLE_USB_SERIAL) #if MG_ENABLE_USB_ETHERNET -#define MG_USB_PRODUCT "MongooseUsbEthernet" +#define MGI_USB_PRODUCT "MongooseUsbEthernet" #else -#define MG_USB_PRODUCT "MongooseUsbSerial" +#define MGI_USB_PRODUCT "MongooseUsbSerial" #endif -// 0xdead is our example VID, for development only +// VID 0xadde, PID 0x40e4: an example, for development only static const uint8_t s_device_desc[] = { 18, 1, 1, 2, 0xef, 2, 1, 64, 0xde, 0xad, 0xe4, 0x40, 0, 1, 1, 2, 3, 1}; // NCM: endpoints 0x81, 0x02/0x82. ACM: endpoints 0x83, 0x04/0x84 +// clang-format off static const uint8_t s_config_desc[] = { - 9, 2, MG_USB_CONFIG_LEN, 0, MG_USB_NUM_IFS, 1, 0, 0x80, 50, // Config -#if MG_ENABLE_USB_ETHERNET - 8, 11, 0, 2, 2, 13, 0, 4, // NCM association - 9, 4, 0, 0, 1, 2, 13, 0, 4, // NCM control interface - 5, 0x24, 0, 0x20, 1, // CDC header - 5, 0x24, 6, 0, 1, // Union - 13, 0x24, 15, 5, 0, 0, 0, 0, 0xea, - 5, 0, 0, 0, // Eth, 1514 bytes - 6, 0x24, 0x1a, 0, 1, 0x21, // NCM 1.0 - 7, 5, 0x81, 3, 16, 0, 16, // Notification endpoint - 9, 4, 1, 0, 0, 10, 0, 1, 0, // Data interface, off - 9, 4, 1, 1, 2, 10, 0, 1, 0, // Data interface, on - 7, 5, 0x02, 2, 64, 0, 0, // Data OUT - 7, 5, 0x82, 2, 64, 0, 0, // Data IN -#endif + 9, 2, MGI_USB_CONFIG_LEN, 0, MGI_USB_NUM_IFS, 1, 0, 0x80, + 50, // Config #if MG_ENABLE_USB_SERIAL - 8, 11, MG_USB_SERIAL_IF, 2, 2, 2, 1, 6, // ACM association - 9, 4, MG_USB_SERIAL_IF, 0, 1, 2, 2, 1, 6, // ACM control interface - 5, 0x24, 0, 0x20, 1, // CDC header - 5, 0x24, 1, 0, MG_USB_SERIAL_IF + 1, // Call management - 4, 0x24, 2, 2, // ACM - 5, 0x24, 6, MG_USB_SERIAL_IF, MG_USB_SERIAL_IF + 1, // Union - 7, 5, 0x83, 3, 16, 0, 16, // Notification endpoint - 9, 4, MG_USB_SERIAL_IF + 1, 0, 2, 10, 0, 0, 0, // Data interface - 7, 5, 0x04, 2, 64, 0, 0, // Data OUT - 7, 5, 0x84, 2, 64, 0, 0, // Data IN + 8, 11, 0, 2, 2, 2, 1, 6, // ACM association + 9, 4, 0, 0, 1, 2, 2, 1, 6, // ACM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 1, 0, 1, // Call management + 4, 0x24, 2, 2, // ACM + 5, 0x24, 6, 0, 1, // Union + 7, 5, 0x83, 3, 16, 0, 16, // Notification endpoint + 9, 4, 1, 0, 2, 10, 0, 0, 0, // Data interface + 7, 5, 0x04, 2, 64, 0, 0, // Data OUT + 7, 5, 0x84, 2, 64, 0, 0, // Data IN +#endif +#if MG_ENABLE_USB_ETHERNET + 8, 11, MGI_USB_ETH_IF, 2, 2, 13, 0, 4, // NCM association + 9, 4, MGI_USB_ETH_IF, 0, 1, 2, 13, 0, 4, // NCM control interface + 5, 0x24, 0, 0x20, 1, // CDC header + 5, 0x24, 6, MGI_USB_ETH_IF, MGI_USB_ETH_IF + 1, // Union + 13, 0x24, 15, 5, 0, 0, 0, 0, 0xea, + 5, 0, 0, 0, // Eth, 1514 bytes + 6, 0x24, 0x1a, 0, 1, 0x21, // NCM 1.0 + 7, 5, 0x81, 3, 16, 0, 16, // Notification endpoint + 9, 4, MGI_USB_ETH_IF + 1, 0, 0, 10, 0, 1, 0, // Data interface, off + 9, 4, MGI_USB_ETH_IF + 1, 1, 2, 10, 0, 1, 0, // Data interface, on + 7, 5, 0x02, 2, 64, 0, 0, // Data OUT + 7, 5, 0x82, 2, 64, 0, 0, // Data IN #endif }; +// clang-format on // Endpoint addresses, for CLEAR_FEATURE(ENDPOINT_HALT) static const uint8_t s_endpoints[] = { @@ -61,12 +73,14 @@ static const uint8_t s_endpoints[] = { #if MG_ENABLE_USB_ETHERNET // Windows 11 binds its NCM driver through a Microsoft OS 2.0 compatible ID +// clang-format off static const uint8_t s_ms_os_desc[] = { 10, 0, 0, 0, 0, 0, 3, 6, 46, 0, // Set header, Windows 8.1+ 8, 0, 1, 0, 0, 0, 36, 0, // Configuration subset - 8, 0, 2, 0, 0, 0, 28, 0, // Function subset, NCM + 8, 0, 2, 0, MGI_USB_ETH_IF, 0, 28, 0, // Function subset, NCM 20, 0, 3, 0, 'W', 'I', 'N', 'N', 'C', 'M', // Compatible ID 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; +// clang-format on static const uint8_t s_bos_desc[] = { 5, 15, 33, 0, 1, 28, 16, 5, 0, 0xdf, 0x60, 0xdd, 0xd8, 0x89, 0x45, 0xc7, 0x4c, 0x9c, 0xd2, 0x65, @@ -93,51 +107,123 @@ static const uint8_t s_nth[30] = {'N', 'C', 'M', 'H', 12, 0, 0, 0, 0, 0, 30, 0, 0, 0, 0, 0, 0, 0, 0, 0}; #endif -// Build string descriptor i in u->buf. Returns its length, 0 if none -static int string_desc(struct mg_usb *u, unsigned i) { - static const char *strings[] = { - NULL, "Mongoose", MG_USB_PRODUCT, NULL, - "USB Ethernet", NULL, "USB Serial"}; - const char *s = i < 7 ? strings[i] : NULL; +// An IN transfer on an endpoint, sent a packet at a time +struct mgi_usb_in { + const uint8_t *data; // Bytes still to send + size_t left; // How many + unsigned packets; // Packets still to send: a short or empty one ends it + bool busy; // A packet is waiting for the host +}; + +// The USB device. There is one +static struct mgi_usb { + const struct mg_usb_hw *hw; // Controller, NULL until mg_usb_init() + struct mgi_usb_in in[5]; // IN transfers, by endpoint + char serial[17]; // Serial number, from the controller + bool configured; // Host has set the configuration + uint8_t buf[66]; // Generated control replies #if MG_ENABLE_USB_ETHERNET - char mac[13]; + struct mg_tcpip_if *ifp; // Ethernet interface, NULL: serial only + bool alt; // Ethernet open: data interface setting 1 + uint16_t filter, sequence; // Host packet filter, next IN block number + uint32_t input_size; // Largest IN block the host accepts + uint8_t notify; // Pending link notifications + struct mg_queue txq; // Transfer blocks for the host, see tx + char txq_buf[MG_USB_TX_SIZE]; // Its storage + uint8_t rx[MG_USB_NTB_SIZE]; // OUT transfer block being received + size_t rxlen; // How much of it arrived + bool discard; // It is too long: drop it #endif - size_t k, n; - if (i == 0) return u->buf[0] = 4, u->buf[1] = 3, u->buf[2] = 9, u->buf[3] = 4; - if (i == 3) s = u->serial; +#if MG_ENABLE_USB_SERIAL + bool dtr; // Terminal open + uint64_t reboot; // mg_millis() to enter the bootloader, or 0 + uint8_t line[7]; // Serial line coding + char log[MG_USB_LOG_SIZE]; // Log ring + unsigned head, tail; // Log ring write and read counters + char out[64]; // Log output being sent +#endif +} s_usb; + +// Send the next packet of the IN transfer on ep. False if it is over +static bool mgi_usb_in_next(unsigned ep) { + struct mgi_usb_in *e = &s_usb.in[ep]; + size_t n = e->left > 64 ? 64 : e->left; + if (e->packets == 0) return false; + s_usb.hw->in((enum mg_usb_ep) ep, e->data, n); + e->data += n, e->left -= n, e->packets--; + return true; +} + +// Start an IN transfer. zlp: end a multiple of 64 bytes with an empty packet +static void mgi_usb_in_start(unsigned ep, const void *data, size_t len, + bool zlp) { + struct mgi_usb_in *e = &s_usb.in[ep]; + e->data = (const uint8_t *) data, e->left = len; + e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); + e->busy = mgi_usb_in_next(ep); +} + +// Cancel the transfers on ep +static void mgi_usb_idle(unsigned ep) { + memset(&s_usb.in[ep], 0, sizeof(s_usb.in[ep])); #if MG_ENABLE_USB_ETHERNET - if (i == 5) { // Host end of the link: the device MAC, first byte changed - uint8_t *m = u->ifp->mac; - mg_snprintf(mac, sizeof(mac), "%02X%02X%02X%02X%02X%02X", + if (ep == MG_USB_EP_ETH_DATA) s_usb.rxlen = 0, s_usb.discard = false; +#endif +} + +// Unconfigured, on start, bus reset and SET_CONFIGURATION. Keeps the log +static void mgi_usb_unconfigure(void) { +#if MG_ENABLE_USB_SERIAL + static const uint8_t line[7] = {0, 0xc2, 1, 0, 0, 0, 8}; // 115200 8N1 + s_usb.dtr = false; + memcpy(s_usb.line, line, sizeof(line)); +#endif +#if MG_ENABLE_USB_ETHERNET + s_usb.alt = false, s_usb.filter = s_usb.sequence = 0, s_usb.notify = 0; + s_usb.input_size = MG_USB_NTB_SIZE; +#endif + s_usb.configured = false; +} + +// Build string descriptor i in s_usb.buf. Returns its length, 0 if none +static int mgi_usb_string(unsigned i) { + static const char *strings[] = {NULL, "Mongoose", MGI_USB_PRODUCT, + NULL, "USB Ethernet", NULL, + "USB Serial"}; + const char *s = i < 7 ? strings[i] : NULL; + char tmp[33]; // Built strings: product name, host MAC + uint8_t *b = s_usb.buf; + size_t k, n; + if (i == 0) return b[0] = 4, b[1] = 3, b[2] = 9, b[3] = 4; + if (i == 2) { // Serial's last 4 digits: tell devices apart + size_t len = strlen(s_usb.serial); + mg_snprintf(tmp, sizeof(tmp), "%s_%s", MGI_USB_PRODUCT, + s_usb.serial + (len > 4 ? len - 4 : 0)); + s = tmp; + } + if (i == 3) s = s_usb.serial; +#if MG_ENABLE_USB_ETHERNET + if (i == 5 && s_usb.ifp != NULL) { // Host end: our MAC, first byte changed + uint8_t *m = s_usb.ifp->mac; + mg_snprintf(tmp, sizeof(tmp), "%02X%02X%02X%02X%02X%02X", ((m[0] ^ 4) | 2) & ~1, m[1], m[2], m[3], m[4], m[5]); - s = mac; + s = tmp; } #endif if (s == NULL) return 0; n = strlen(s) > 32 ? 32 : strlen(s); - memset(u->buf, 0, sizeof(u->buf)); - for (k = 0; k < n; k++) u->buf[2 + k * 2] = (uint8_t) s[k]; - u->buf[0] = (uint8_t) (2 + n * 2), u->buf[1] = 3; - return u->buf[0]; + memset(b, 0, sizeof(s_usb.buf)); + for (k = 0; k < n; k++) b[2 + k * 2] = (uint8_t) s[k]; + b[0] = (uint8_t) (2 + n * 2), b[1] = 3; + return b[0]; } -void mg_usb_reset(struct mg_usb *u) { -#if MG_ENABLE_USB_SERIAL - static const uint8_t line[7] = {0, 0xc2, 1, 0, 0, 0, 8}; // 115200 8N1 - u->dtr = false; - memcpy(u->line, line, sizeof(line)); -#endif -#if MG_ENABLE_USB_ETHERNET - u->alt = false, u->filter = u->sequence = 0, u->notify = 0; - u->input_size = MG_USB_NTB_SIZE; -#endif - u->configured = false; -} - -int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { +// Answer a control request r, its OUT data at r + 8. Returns -1 to stall, +// else the IN reply length in *reply, 0 for status only +static int mgi_usb_request(const uint8_t *r, const void **reply) { unsigned value = MG_LOAD_LE16(r + 2), index = MG_LOAD_LE16(r + 4); - unsigned wlen = MG_LOAD_LE16(r + 6); - const void *d = u->buf; + unsigned wlen = MG_LOAD_LE16(r + 6), i; + const void *d = s_usb.buf; int n = 0; switch ((r[0] << 8) | r[1]) { case 0x8006: // GET_DESCRIPTOR @@ -146,32 +232,37 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { #if MG_ENABLE_USB_ETHERNET if (value >> 8 == 15) d = s_bos_desc, n = sizeof(s_bos_desc); #endif - if (value >> 8 == 3) n = string_desc(u, value & 255); + if (value >> 8 == 3) n = mgi_usb_string(value & 255); if (n == 0) return -1; break; - case 0x0005: // SET_ADDRESS, applied by the driver after the status + case 0x0005: // SET_ADDRESS, applied by the controller if (value > 127) return -1; break; case 0x0009: // SET_CONFIGURATION if (value > 1) return -1; - mg_usb_reset(u); - u->configured = value == 1; + mgi_usb_unconfigure(); + for (i = 1; i < 5; i++) mgi_usb_idle(i); + s_usb.configured = value == 1; break; case 0x8008: // GET_CONFIGURATION - u->buf[0] = u->configured, n = 1; + s_usb.buf[0] = s_usb.configured, n = 1; break; case 0x010b: // SET_INTERFACE: only the Ethernet data interface has 1 - if (index >= MG_USB_NUM_IFS || - value > (unsigned) (MG_ENABLE_USB_ETHERNET && index == 1)) + if (index >= MGI_USB_NUM_IFS || + value > (unsigned) (MG_ENABLE_USB_ETHERNET && + index == MG_USB_IF_ETH_DATA)) return -1; #if MG_ENABLE_USB_ETHERNET - if (index == 1) u->alt = value == 1, u->notify = 1; + if (index == MG_USB_IF_ETH_DATA) { + s_usb.alt = value == 1, s_usb.notify = 1; + mgi_usb_idle(MG_USB_EP_ETH_DATA); + } #endif break; case 0x810a: // GET_INTERFACE - u->buf[0] = 0, n = 1; + s_usb.buf[0] = 0, n = 1; #if MG_ENABLE_USB_ETHERNET - if (index == 1) u->buf[0] = u->alt; + if (index == MG_USB_IF_ETH_DATA) s_usb.buf[0] = s_usb.alt; #endif break; #if MG_ENABLE_USB_ETHERNET @@ -180,9 +271,9 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { case 0x8000: // GET_STATUS: device, interface, endpoint case 0x8100: case 0x8200: - u->buf[0] = u->buf[1] = 0, n = 2; + s_usb.buf[0] = s_usb.buf[1] = 0, n = 2; break; - case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT), applied by the driver + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT), applied by the controller if (value || index > 255 || !memchr(s_endpoints, (int) index, sizeof(s_endpoints))) return -1; @@ -193,7 +284,7 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { d = s_ms_os_desc, n = sizeof(s_ms_os_desc); break; case 0x2143: // SET_ETHERNET_PACKET_FILTER - u->filter = (uint16_t) value; + s_usb.filter = (uint16_t) value; break; case 0xa180: // GET_NTB_PARAMETERS d = s_ntb_params, n = sizeof(s_ntb_params); @@ -202,30 +293,31 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { if (value) return -1; break; case 0xa185: // GET_NTB_INPUT_SIZE, one datagram per block - memset(u->buf, 0, 8); - MG_STORE_LE32(u->buf, u->input_size); - u->buf[4] = 1, n = 8; + memset(s_usb.buf, 0, 8); + MG_STORE_LE32(s_usb.buf, s_usb.input_size); + s_usb.buf[4] = 1, n = 8; break; case 0x2186: // SET_NTB_INPUT_SIZE if ((wlen != 4 && wlen != 8) || MG_LOAD_LE32(r + 8) < 2048 || MG_LOAD_LE32(r + 8) > 65535) return -1; - u->input_size = MG_LOAD_LE32(r + 8); - if (u->input_size > MG_USB_NTB_SIZE) u->input_size = MG_USB_NTB_SIZE; + s_usb.input_size = MG_LOAD_LE32(r + 8); + if (s_usb.input_size > MG_USB_NTB_SIZE) + s_usb.input_size = MG_USB_NTB_SIZE; break; #endif #if MG_ENABLE_USB_SERIAL case 0xa121: // GET_LINE_CODING - d = u->line, n = sizeof(u->line); + d = s_usb.line, n = sizeof(s_usb.line); break; case 0x2120: // SET_LINE_CODING - if (wlen != sizeof(u->line)) return -1; - memcpy(u->line, r + 8, sizeof(u->line)); + if (wlen != sizeof(s_usb.line)) return -1; + memcpy(s_usb.line, r + 8, sizeof(s_usb.line)); break; case 0x2122: // SET_CONTROL_LINE_STATE. Closed at 1200 baud: bootloader, - u->dtr = value & 1; // after a delay that lets this request complete - if (!u->dtr && MG_LOAD_LE32(u->line) == 1200) - u->reboot = mg_millis() + 100; + s_usb.dtr = value & 1; // after a delay that lets this request complete + if (!s_usb.dtr && MG_LOAD_LE32(s_usb.line) == 1200) + s_usb.reboot = mg_millis() + 100; break; case 0x2123: // SEND_BREAK break; @@ -238,32 +330,12 @@ int mg_usb_setup(struct mg_usb *u, const uint8_t *r, const void **reply) { } #if MG_ENABLE_USB_ETHERNET -size_t mg_usb_notify(struct mg_usb *u, const void **msg) { - if (!u->notify) return 0; - if (u->notify == 1 && u->alt) return u->notify = 2, *msg = s_speed, 16; - u->notify = 0, *msg = u->alt ? s_up : s_down; - return 8; -} - -size_t mg_usb_encode(struct mg_usb *u, uint8_t *p, const void *buf, - size_t len) { - if (!u->alt || !u->filter || len < 14 || len > 1514 || - len + 30 > u->input_size) - return 0; - memcpy(p, s_nth, sizeof(s_nth)); - MG_STORE_LE16(p + 6, u->sequence); - MG_STORE_LE16(p + 8, len + 30); - MG_STORE_LE16(p + 22, len); - memcpy(p + 30, buf, len); - u->sequence++; - return len + 30; -} - +// Queue the frames of a received transfer block to the TCP/IP stack. // Offsets come from the host: bound every datagram by the block, and follow // at most 16 datagram tables so that a cyclic chain cannot loop forever -void mg_usb_decode(struct mg_usb *u, const uint8_t *p, size_t len) { +static void mgi_usb_decode(const uint8_t *p, size_t len) { size_t block, ndp, end, i, ofs, n, tables = 0; - if (len < 12 || MG_LOAD_LE32(p) != 0x484d434e) return; // "NCMH" + if (s_usb.ifp == NULL || len < 12 || MG_LOAD_LE32(p) != 0x484d434e) return; block = MG_LOAD_LE16(p + 8), ndp = MG_LOAD_LE16(p + 10); if (block > len) return; while (ndp && tables++ < 16 && ndp + 16 <= block && @@ -273,27 +345,168 @@ void mg_usb_decode(struct mg_usb *u, const uint8_t *p, size_t len) { ofs = MG_LOAD_LE16(p + i), n = MG_LOAD_LE16(p + i + 2); if (ofs == 0 || n == 0) break; if (n >= 14 && n <= 1514 && ofs + n <= block) - mg_tcpip_qwrite((void *) (p + ofs), n, u->ifp); + mg_tcpip_qwrite((void *) (p + ofs), n, s_usb.ifp); } ndp = MG_LOAD_LE16(p + ndp + 6); } } + +// If the Ethernet IN endpoint is idle, start sending the first queued +// transfer block. It stays queued until sent. Drop blocks the host cannot +// take now: the link closed, or it lowered its block size +static void mgi_usb_tx_next(void) { + char *block; + size_t len; + while (!s_usb.in[MG_USB_EP_ETH_DATA].busy && + (len = mg_queue_next(&s_usb.txq, &block)) > 0) { + if (s_usb.alt && s_usb.filter && len <= s_usb.input_size) { + mgi_usb_in_start(MG_USB_EP_ETH_DATA, block, len, len < s_usb.input_size); + } else { + mg_queue_del(&s_usb.txq, len); + } + } +} #endif #if MG_ENABLE_USB_SERIAL -void mg_usb_log(char ch, void *arg) { - struct mg_usb *u = (struct mg_usb *) arg; - if (u->head - u->tail >= MG_USB_LOG_SIZE) u->tail++; - u->log[u->head++ % MG_USB_LOG_SIZE] = ch; +// Log output function: keep the latest MG_USB_LOG_SIZE characters +static void mgi_usb_log(char ch, void *arg) { + if (s_usb.head - s_usb.tail >= MG_USB_LOG_SIZE) s_usb.tail++; + s_usb.log[s_usb.head++ % MG_USB_LOG_SIZE] = ch; + (void) arg; } +#endif -size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len) { - size_t n = 0; - while (n < len && u->tail != u->head) { - ((char *) buf)[n++] = u->log[u->tail++ % MG_USB_LOG_SIZE]; +// Controller events, see enum mg_usb_ev +static int mgi_usb_event(enum mg_usb_ev ev, enum mg_usb_ep ep, void *buf, + size_t len) { + const uint8_t *p = (const uint8_t *) buf; + unsigned i; + if (ev == MG_USB_EV_RESET) { + mgi_usb_unconfigure(); + for (i = 0; i < 5; i++) mgi_usb_idle(i); + } else if (ev == MG_USB_EV_SETUP) { + const void *reply; + unsigned wlen = len < 8 ? 0 : MG_LOAD_LE16(p + 6); + int n; + mgi_usb_idle(MG_USB_EP_CTL); // A SETUP ends the previous transfer + if (len < 8 || (!(p[0] & 0x80) && len < 8 + wlen)) return -1; + if ((n = mgi_usb_request(p, &reply)) < 0) return -1; + if (!(p[0] & 0x80) || wlen == 0) return 0; + mgi_usb_in_start(MG_USB_EP_CTL, reply, (size_t) n, n < (int) wlen); + return 1; + } else if (ev == MG_USB_EV_IN && s_usb.in[ep].busy) { + s_usb.in[ep].busy = mgi_usb_in_next(ep); +#if MG_ENABLE_USB_ETHERNET + if (ep == MG_USB_EP_ETH_DATA && !s_usb.in[ep].busy) { + mg_queue_del(&s_usb.txq, mg_queue_next(&s_usb.txq, NULL)); // Sent + mgi_usb_tx_next(); + } +#endif + return s_usb.in[ep].busy; +#if MG_ENABLE_USB_ETHERNET + } else if (ev == MG_USB_EV_OUT && ep == MG_USB_EP_ETH_DATA) { + // Add the packet to the transfer block. At the advertised maximum OUT + // size, the host need not send a ZLP. Other blocks end with a short + // packet, possibly empty + if (!s_usb.discard && s_usb.rxlen + len <= sizeof(s_usb.rx)) { + memcpy(s_usb.rx + s_usb.rxlen, buf, len); + s_usb.rxlen += len; + } else { + s_usb.discard = true; + } + if (len < 64 || s_usb.rxlen == sizeof(s_usb.rx)) { + if (!s_usb.discard) mgi_usb_decode(s_usb.rx, s_usb.rxlen); + s_usb.rxlen = 0, s_usb.discard = false; + } +#endif } - return n; + return 0; } + +bool mg_usb_init(struct mg_tcpip_if *ifp, const struct mg_usb_hw *hw) { + if (s_usb.hw == NULL) { + s_usb.hw = hw; + mgi_usb_unconfigure(); +#if MG_ENABLE_USB_ETHERNET + mg_queue_init(&s_usb.txq, s_usb.txq_buf, sizeof(s_usb.txq_buf)); #endif +#if MG_ENABLE_USB_SERIAL + mg_log_set_fn(mgi_usb_log, NULL); // Log to the USB serial port +#endif + hw->init(s_usb.serial); + } +#if MG_ENABLE_USB_ETHERNET + if (ifp != NULL) s_usb.ifp = ifp; +#else + (void) ifp; +#endif + return true; +} + +size_t mg_usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { +#if MG_ENABLE_USB_ETHERNET + // Queue the frame wrapped in its transfer block, ready to send + size_t n = sizeof(s_nth) + len; + char *p; + if (!s_usb.alt || !s_usb.filter || len < 14 || len > 1514) return 0; + if (mg_queue_next(&s_usb.txq, NULL) == 0) { + mg_queue_init(&s_usb.txq, s_usb.txq.buf, s_usb.txq.size); // Unwrap + } + if (mg_queue_book(&s_usb.txq, &p, n) < n) { + ifp->nerr++; // Queue full: the host is not reading + return 0; + } + memcpy(p, s_nth, sizeof(s_nth)); + MG_STORE_LE16(p + 6, s_usb.sequence); + s_usb.sequence++; + MG_STORE_LE16(p + 8, n); + MG_STORE_LE16(p + 22, len); + memcpy(p + sizeof(s_nth), buf, len); + mg_queue_add(&s_usb.txq, n); + mgi_usb_tx_next(); + return len; +#else + (void) ifp, (void) buf, (void) len; + return 0; +#endif +} + +bool mg_usb_poll(struct mg_tcpip_if *ifp, bool s1) { + (void) ifp; + if (s_usb.hw == NULL) return false; // mg_usb_init() not called yet + s_usb.hw->poll(mgi_usb_event); +#if MG_ENABLE_USB_SERIAL + if (s_usb.reboot && mg_millis() > s_usb.reboot) { + s_usb.reboot = 0; + MG_USB_REBOOT(); + } + if (s_usb.configured && s_usb.dtr && !s_usb.in[MG_USB_EP_SER_DATA].busy) { + size_t n = 0; + while (n < sizeof(s_usb.out) && s_usb.tail != s_usb.head) { + s_usb.out[n++] = s_usb.log[s_usb.tail++ % MG_USB_LOG_SIZE]; + } + if (n > 0) mgi_usb_in_start(MG_USB_EP_SER_DATA, s_usb.out, n, true); + } +#endif +#if MG_ENABLE_USB_ETHERNET + if (s_usb.notify && !s_usb.in[MG_USB_EP_ETH_EV].busy) { + // Link notifications: the speed first if the link is up, then the state + if (s_usb.notify == 1 && s_usb.alt) { + s_usb.notify = 2; + mgi_usb_in_start(MG_USB_EP_ETH_EV, s_speed, sizeof(s_speed), false); + } else { + s_usb.notify = 0; + mgi_usb_in_start(MG_USB_EP_ETH_EV, s_usb.alt ? s_up : s_down, + sizeof(s_up), false); + } + } + mgi_usb_tx_next(); + return s1 && s_usb.alt && s_usb.filter; +#else + (void) s1; + return false; +#endif +} #endif diff --git a/src/drivers/usb.h b/src/drivers/usb.h index 02879cd2..cdca7ec4 100644 --- a/src/drivers/usb.h +++ b/src/drivers/usb.h @@ -1,96 +1,67 @@ #pragma once -// USB device, independent of the controller: CDC-NCM Ethernet, enabled by -// MG_ENABLE_USB_ETHERNET, and a CDC-ACM serial port that carries the -// Mongoose log, enabled by MG_ENABLE_USB_SERIAL. The controller drivers -// are usb_rp.c, usb_samd21.c and usb_nrf52.c, enabled by -// MG_ENABLE_DRIVER_USB_*. Mongoose runs USB from mg_tcpip_init() and -// mg_mgr_poll(), so user code needs no USB calls +// USB device: a CDC-NCM Ethernet interface, enabled by MG_ENABLE_USB_ETHERNET, +// and a CDC-ACM serial port for logs, enabled by MG_ENABLE_USB_SERIAL. -#if MG_ENABLE_TCPIP && \ - (MG_ENABLE_DRIVER_USB_RP || MG_ENABLE_DRIVER_USB_SAMD21 || \ - MG_ENABLE_DRIVER_USB_NRF52) && \ - (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) -#define MG_ENABLE_USB 1 - -// #if defined(MG_ENABLE_DRIVER_USB_SAMD21) && MG_ENABLE_DRIVER_USB_SAMD21 -// #define MG_USB_DEFAULT_SIZE 2048 // SAMD21: 32k RAM -// #else -// #define MG_USB_DEFAULT_SIZE 4096 -// #endif -#define MG_USB_DEFAULT_SIZE 2048 -#ifndef MG_USB_NTB_SIZE // Transfer block buffer, each direction, >= 2048 -#define MG_USB_NTB_SIZE MG_USB_DEFAULT_SIZE +#ifndef MG_USB_NTB_SIZE +#define MG_USB_NTB_SIZE 2048 // Transfer block, each direction, >= 2048 #endif -#ifndef MG_USB_LOG_SIZE // Serial log ring buffer -#define MG_USB_LOG_SIZE (MG_USB_DEFAULT_SIZE / 2) +#ifndef MG_USB_TX_SIZE +#define MG_USB_TX_SIZE 4096 // Ethernet frames waiting to go to the host #endif -#ifndef MG_USB_QUEUE_SIZE // TCP/IP stack receive queue -#define MG_USB_QUEUE_SIZE (MG_USB_DEFAULT_SIZE * 2) +#ifndef MG_USB_QUEUE_SIZE +#define MG_USB_QUEUE_SIZE 4096 // Ethernet frames from the host +#endif +#ifndef MG_USB_LOG_SIZE +#define MG_USB_LOG_SIZE 1024 // Serial log ring #endif -// Endpoints: 1 interrupt IN, link notifications. 2 bulk IN/OUT, Ethernet. -// 3 interrupt IN, serial notifications (unused). 4 bulk IN/OUT, serial +// Restart into the board's bootloader when the host opens the serial port at +// 1200 baud and closes it, the "1200 baud touch" that flashing tools use +#ifndef MG_USB_REBOOT +#define MG_USB_REBOOT() (void) 0 +#endif -struct mg_usb { - const char *serial; // USB serial number, set by the driver - bool configured; // Host has set the configuration - uint8_t buf[66]; // Generated replies -#if MG_ENABLE_USB_ETHERNET - struct mg_tcpip_if *ifp; // TCP/IP interface, set by the driver - bool alt; // Ethernet open: data interface setting 1 - uint16_t filter, sequence; // Host packet filter, next IN block number - uint32_t input_size; // Largest IN block the host accepts - uint8_t notify; // Pending link notifications -#endif -#if MG_ENABLE_USB_SERIAL - bool dtr; // Terminal open - uint64_t reboot; // mg_millis() to enter the bootloader, or 0 - uint8_t line[7]; // Serial line coding - char log[MG_USB_LOG_SIZE]; // Serial log ring buffer - unsigned head, tail; // Log ring write and read counters -#endif +// Endpoints, numbered as in the configuration descriptor +enum mg_usb_ep { + MG_USB_EP_CTL, // control + MG_USB_EP_ETH_EV, // Ethernet link notifications, IN + MG_USB_EP_ETH_DATA, // Ethernet data, IN and OUT + MG_USB_EP_SER_EV, // serial notifications, IN, unused + MG_USB_EP_SER_DATA, // serial data, IN and OUT }; -// Implemented by the enabled controller driver. Start the controller, once, -// and send the log to the serial port -void mg_usb_init(void); +// Interfaces: the serial port's control and data first, then Ethernet's. The +// Ethernet data interface has setting 1: Ethernet open +#define MG_USB_IF_ETH_DATA (2 * MG_ENABLE_USB_SERIAL + 1) -// Implemented by the enabled controller driver. Run the controller. Calls -// mg_usb_init() first, so it works without a TCP/IP interface too -void mg_usb_poll(void); +// Controller events, reported by mg_usb_hw::poll() to its fn. What fn returns +enum mg_usb_ev { + MG_USB_EV_RESET, // Bus reset or detach. Returns 0 + MG_USB_EV_SETUP, // Control request, buf: the SETUP packet, then its OUT + // data. Returns -1: stall, 0: no IN data stage, send + // the status stage, 1: IN data stage started on ep 0 + MG_USB_EV_IN, // An IN packet on ep went out. Returns 1: next packet + // sent, 0: transfer done + MG_USB_EV_OUT // An OUT packet arrived on ep, buf and len. Returns 0 +}; -// Unconfigured state, on start and after a bus reset. Keeps the log -void mg_usb_reset(struct mg_usb *u); +// A USB device controller, implemented by its driver. Packets: up to 64 bytes +struct mg_usb_hw { + void (*init)(char serial[17]); // Start, write the serial number + void (*poll)(int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *buf, size_t)); + void (*in)(enum mg_usb_ep, const void *buf, size_t len); // Write IN packet +}; -// Handle an 8-byte SETUP packet, followed by its OUT data stage if it has -// one. Returns -1 to stall, else the IN reply length, 0 for status only -int mg_usb_setup(struct mg_usb *u, const uint8_t *req, const void **reply); +struct mg_tcpip_if; // Without MG_ENABLE_TCPIP: serial console only -#if MG_ENABLE_USB_ETHERNET -// Next link notification for endpoint 1. Returns its length, 0 if none -size_t mg_usb_notify(struct mg_usb *u, const void **msg); +// Start the controller hw, and attach ifp: NULL for the serial console only. +// Call again to attach ifp later; the first call's hw stays in use +bool mg_usb_init(struct mg_tcpip_if *ifp, const struct mg_usb_hw *hw); -// Wrap an Ethernet frame into a transfer block at ntb. Returns the block -// length, 0 if the link is down or the frame does not fit -size_t mg_usb_encode(struct mg_usb *u, uint8_t *ntb, const void *buf, - size_t len); +// Queue an Ethernet frame for the host. The controller driver's tx +size_t mg_usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp); -// Queue the Ethernet frames of a received transfer block to the TCP/IP stack -void mg_usb_decode(struct mg_usb *u, const uint8_t *ntb, size_t len); -#endif - -#if MG_ENABLE_USB_SERIAL -// Log output function for mg_log_set_fn(mg_usb_log, u). Keeps the latest -// MG_USB_LOG_SIZE characters -void mg_usb_log(char ch, void *u); - -// Take up to len logged characters into buf. Returns how many -size_t mg_usb_log_read(struct mg_usb *u, void *buf, size_t len); -#endif - -#else -#define MG_ENABLE_USB 0 -#define mg_usb_init() -#define mg_usb_poll() -#endif +// Run the controller. The controller driver's poll; returns true when the +// host has the Ethernet interface open and s1 is true. Serial only: ifp NULL +bool mg_usb_poll(struct mg_tcpip_if *ifp, bool s1); diff --git a/src/drivers/usb_dwc2.c b/src/drivers/usb_dwc2.c new file mode 100644 index 00000000..ade2285b --- /dev/null +++ b/src/drivers/usb_dwc2.c @@ -0,0 +1,365 @@ +#include "net_builtin.h" +#include "drivers/usb.h" +#include "drivers/usb_dwc2.h" +#include "printf.h" +#include "util.h" + +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_DWC2 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// DWC2 device controller, polled: no interrupt handler, no DMA. Received +// packets come through one shared RX FIFO, each IN endpoint has a TX FIFO of +// its own. Register layout: STM32 reference manuals, OTG chapter. + +#ifndef MG_USB_DWC2_BASE +#error "MG_ENABLE_DRIVER_USB_DWC2 needs MG_USB_DWC2_BASE, the core's address" +#endif +#ifndef MG_USB_DWC2_ULPI +#define MG_USB_DWC2_ULPI 0 +#endif +#ifndef MG_USB_DWC2_UTMI +#define MG_USB_DWC2_UTMI 0 +#endif +#if MG_USB_DWC2_ULPI && MG_USB_DWC2_UTMI +#error "MG_USB_DWC2_ULPI and MG_USB_DWC2_UTMI: choose one PHY" +#endif +#define MGI_DWC2_HS_PHY (MG_USB_DWC2_ULPI || MG_USB_DWC2_UTMI) // At full speed + +// Register at offset off +#define MGI_DWC2(off) \ + (*(volatile uint32_t *) ((uintptr_t) (MG_USB_DWC2_BASE) + (off))) +#define MGI_DWC2_GOTGCTL MGI_DWC2(0x000) +#define MGI_DWC2_GUSBCFG MGI_DWC2(0x00c) +#define MGI_DWC2_GRSTCTL MGI_DWC2(0x010) +#define MGI_DWC2_GINTSTS MGI_DWC2(0x014) +#define MGI_DWC2_GRXSTSP MGI_DWC2(0x020) +#define MGI_DWC2_GRXFSIZ MGI_DWC2(0x024) +#define MGI_DWC2_DIEPTXF0 MGI_DWC2(0x028) +#define MGI_DWC2_GCCFG MGI_DWC2(0x038) +#define MGI_DWC2_GSNPSID MGI_DWC2(0x040) +#define MGI_DWC2_DIEPTXF(n) MGI_DWC2(0x100 + 4 * (n)) // n: 1.. +#define MGI_DWC2_DCFG MGI_DWC2(0x800) +#define MGI_DWC2_DCTL MGI_DWC2(0x804) +#define MGI_DWC2_DIEPMSK MGI_DWC2(0x810) +#define MGI_DWC2_DOEPMSK MGI_DWC2(0x814) +#define MGI_DWC2_DAINT MGI_DWC2(0x818) +#define MGI_DWC2_DAINTMSK MGI_DWC2(0x81c) +#define MGI_DWC2_DIEPCTL(n) MGI_DWC2(0x900 + 0x20 * (n)) +#define MGI_DWC2_DIEPINT(n) MGI_DWC2(0x908 + 0x20 * (n)) +#define MGI_DWC2_DIEPTSIZ(n) MGI_DWC2(0x910 + 0x20 * (n)) +#define MGI_DWC2_DOEPCTL(n) MGI_DWC2(0xb00 + 0x20 * (n)) +#define MGI_DWC2_DOEPINT(n) MGI_DWC2(0xb08 + 0x20 * (n)) +#define MGI_DWC2_DOEPTSIZ(n) MGI_DWC2(0xb10 + 0x20 * (n)) +#define MGI_DWC2_PCGCCTL MGI_DWC2(0xe00) +#define MGI_DWC2_FIFO(n) MGI_DWC2(0x1000 * ((n) + 1)) + +// Endpoint control bits, DIEPCTL and DOEPCTL +#define MGI_DWC2_USBAEP MG_BIT(15) // Active +#define MGI_DWC2_STALL MG_BIT(21) +#define MGI_DWC2_CNAK MG_BIT(26) +#define MGI_DWC2_SNAK MG_BIT(27) +#define MGI_DWC2_SD0PID MG_BIT(28) // Next packet is DATA0 +#define MGI_DWC2_EPDIS MG_BIT(30) +#define MGI_DWC2_EPENA MG_BIT(31) + +// FIFOs, in 32-bit words: RX first, then a packet's room per IN endpoint. +// 208 words in all, so it fits a full-speed core's 320 +#define MGI_DWC2_RX_WORDS 128 + +// usb.c's event handler, see mg_usb_hw::poll() +#define MGI_DWC2_FN int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t) + +static uint32_t s_mgi_dwc2_pkt[64 / 4]; // A received packet +static uint8_t s_mgi_dwc2_req[16]; // SETUP packet, then its OUT data +static size_t s_mgi_dwc2_req_len; // OUT data received so far +static bool s_mgi_dwc2_req_out; // Waiting for that OUT data stage + +// Wait until the mask bits of reg are set, or clear. Bounded +static void mgi_dwc2_wait(volatile uint32_t *reg, uint32_t mask, bool set) { + unsigned i; + for (i = 0; ((*reg & mask) != 0) != set && i < 1000000; i++) (void) 0; +} + +// Flush the TX FIFO of endpoint n, 0x10: all of them +static void mgi_dwc2_flush_tx(unsigned n) { + MGI_DWC2_GRSTCTL = MG_BIT(5) | (n << 6); // TXFFLSH, TXFNUM + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(5), false); +} + +// mg_usb_hw::in(): load one packet, then let the endpoint send it +static void mgi_dwc2_in(enum mg_usb_ep ep, const void *buf, size_t len) { + const uint8_t *p = (const uint8_t *) buf; + size_t i, k; + MGI_DWC2_DIEPTSIZ(ep) = MG_BIT(19) | (uint32_t) len; // One packet + MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_CNAK | MGI_DWC2_EPENA; + for (i = 0; i < len; i += 4) { + uint32_t w = 0; + for (k = 0; k < 4 && i + k < len; k++) w |= (uint32_t) p[i + k] << (8 * k); + MGI_DWC2_FIFO(ep) = w; + } +} + +// Stop an IN transfer on endpoint ep, and empty its TX FIFO +static void mgi_dwc2_in_stop(unsigned ep) { + if (MGI_DWC2_DIEPCTL(ep) & MGI_DWC2_EPENA) { + MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_SNAK; + mgi_dwc2_wait(&MGI_DWC2_DIEPINT(ep), MG_BIT(6), true); // INEPNE + MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_EPDIS; + mgi_dwc2_wait(&MGI_DWC2_DIEPINT(ep), MG_BIT(1), true); // EPDISD + MGI_DWC2_DIEPINT(ep) = MG_BIT(1); + } + mgi_dwc2_flush_tx(ep); +} + +// Let OUT endpoint ep take one packet. Endpoint 0 also takes SETUPs +static void mgi_dwc2_arm(unsigned ep) { + MGI_DWC2_DOEPTSIZ(ep) = (ep == 0 ? 3UL << 29 : 0) | MG_BIT(19) | 64; + MGI_DWC2_DOEPCTL(ep) |= MGI_DWC2_CNAK | MGI_DWC2_EPENA; +} + +// Endpoint ep active, idle, DATA0 next. type: 2 bulk, 3 interrupt. out: +// also its OUT direction, ready to receive +static void mgi_dwc2_open(unsigned ep, uint32_t type, bool out) { + uint32_t ctl = 64 | MGI_DWC2_USBAEP | (type << 18) | MGI_DWC2_SD0PID; + mgi_dwc2_in_stop(ep); + MGI_DWC2_DIEPCTL(ep) = ctl | (ep << 22) | MGI_DWC2_SNAK; // Own TX FIFO + if (out) { + MGI_DWC2_DOEPCTL(ep) = ctl; + mgi_dwc2_arm(ep); + } +} + +// Stall endpoint 0, until the next SETUP +static void mgi_dwc2_stall(void) { + MGI_DWC2_DIEPCTL(0) |= MGI_DWC2_STALL; + MGI_DWC2_DOEPCTL(0) |= MGI_DWC2_STALL; +} + +// USB reset: address 0, endpoints off, FIFOs laid out again +static void mgi_dwc2_bus_reset(void) { + unsigned ep; + for (ep = 0; ep < 5; ep++) { + MGI_DWC2_DOEPCTL(ep) |= MGI_DWC2_SNAK; + if (ep > 0) MGI_DWC2_DOEPCTL(ep) &= ~MGI_DWC2_USBAEP; + if (ep > 0) MGI_DWC2_DIEPCTL(ep) &= ~MGI_DWC2_USBAEP; + mgi_dwc2_in_stop(ep); + } + MGI_DWC2_DAINTMSK = 0x1f; // IN endpoints 0-4: transfer complete + MGI_DWC2_DIEPMSK = MG_BIT(0); // XFRC + MGI_DWC2_DOEPMSK = MG_BIT(3) | 1U; // STUP, XFRC + MGI_DWC2_GRSTCTL = MG_BIT(4); // RXFFLSH + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(4), false); + MGI_DWC2_GRXFSIZ = MGI_DWC2_RX_WORDS; + MGI_DWC2_DIEPTXF0 = (16UL << 16) | MGI_DWC2_RX_WORDS; + for (ep = 1; ep < 5; ep++) { + MGI_DWC2_DIEPTXF(ep) = (16UL << 16) | (MGI_DWC2_RX_WORDS + 16 * ep); + } + MGI_DWC2_DCFG &= ~(0x7fUL << 4); // Address 0 + MGI_DWC2_DIEPCTL(0) &= ~3UL; // Endpoint 0: 64-byte packets + MGI_DWC2_DOEPCTL(0) &= ~3UL; + MGI_DWC2_DOEPTSIZ(0) = 3UL << 29; // Up to 3 SETUPs in a row + s_mgi_dwc2_req_out = false; +} + +// A complete control request: usb.c answers it, then the controller follows +static void mgi_dwc2_request(MGI_DWC2_FN) { + uint8_t *r = s_mgi_dwc2_req; + size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage + int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out); + if (res < 0) { + mgi_dwc2_stall(); + return; + } + switch ((r[0] << 8) | r[1]) { + case 0x0005: // SET_ADDRESS: the new address goes before the status stage + MGI_DWC2_DCFG = + (MGI_DWC2_DCFG & ~(0x7fUL << 4)) | ((uint32_t) (r[2] & 0x7f) << 4); + break; + case 0x0009: // SET_CONFIGURATION + if (r[2] != 1) break; +#if MG_ENABLE_USB_ETHERNET + mgi_dwc2_open(MG_USB_EP_ETH_EV, 3, false); + mgi_dwc2_open(MG_USB_EP_ETH_DATA, 2, true); +#endif +#if MG_ENABLE_USB_SERIAL + mgi_dwc2_open(MG_USB_EP_SER_EV, 3, false); + mgi_dwc2_open(MG_USB_EP_SER_DATA, 2, true); +#endif + break; +#if MG_ENABLE_USB_ETHERNET + case 0x010b: // SET_INTERFACE: Ethernet data endpoints back to DATA0 + if (r[4] == MG_USB_IF_ETH_DATA) { + mgi_dwc2_open(MG_USB_EP_ETH_DATA, 2, r[2] == 1); + } + break; +#endif + case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT) + if (r[4] & 0x80) { + MGI_DWC2_DIEPCTL(r[4] & 15) = + (MGI_DWC2_DIEPCTL(r[4] & 15) & ~MGI_DWC2_STALL) | MGI_DWC2_SD0PID; + } else { + MGI_DWC2_DOEPCTL(r[4] & 15) = + (MGI_DWC2_DOEPCTL(r[4] & 15) & ~MGI_DWC2_STALL) | MGI_DWC2_SD0PID; + } + break; + } + if (res == 0) mgi_dwc2_in(MG_USB_EP_CTL, NULL, 0); // Status stage +} + +// A SETUP packet: run it, or first receive its OUT data stage +static void mgi_dwc2_setup(MGI_DWC2_FN) { + uint8_t *r = s_mgi_dwc2_req; + unsigned wlen = MG_LOAD_LE16(r + 6); + mgi_dwc2_in_stop(0); // A SETUP ends the previous control transfer + s_mgi_dwc2_req_out = false; + if ((r[0] & 0x80) || wlen == 0) { + mgi_dwc2_request(fn); + } else if (wlen > sizeof(s_mgi_dwc2_req) - 8) { + mgi_dwc2_stall(); + } else { + s_mgi_dwc2_req_out = true, s_mgi_dwc2_req_len = 0; + mgi_dwc2_arm(0); + } +} + +// One entry of the RX FIFO: a SETUP, OUT data, or the end of either +static void mgi_dwc2_rx(MGI_DWC2_FN) { + uint32_t st = MGI_DWC2_GRXSTSP, i; + unsigned ep = st & 15, kind = (st >> 17) & 15; + size_t n = (st >> 4) & 0x7ff; + uint8_t *r = s_mgi_dwc2_req; + for (i = 0; i < (n + 3) / 4; i++) { // Take the packet off the FIFO + uint32_t w = MGI_DWC2_FIFO(0); + if (i < sizeof(s_mgi_dwc2_pkt) / 4) s_mgi_dwc2_pkt[i] = w; + } + if (n > sizeof(s_mgi_dwc2_pkt)) n = sizeof(s_mgi_dwc2_pkt); + if (kind == 6) { // SETUP packet + memcpy(r, s_mgi_dwc2_pkt, 8); + } else if (kind == 4) { // SETUP stage done + MGI_DWC2_DOEPTSIZ(0) |= 3UL << 29; + MGI_DWC2_DOEPINT(0) = MG_BIT(3); // STUP + mgi_dwc2_setup(fn); + } else if (kind == 2 && ep == 0 && s_mgi_dwc2_req_out) { // Control OUT + size_t room = sizeof(s_mgi_dwc2_req) - 8 - s_mgi_dwc2_req_len; + memcpy(r + 8 + s_mgi_dwc2_req_len, s_mgi_dwc2_pkt, n < room ? n : room); + s_mgi_dwc2_req_len += n; +#if MG_ENABLE_USB_ETHERNET + } else if (kind == 2 && ep == MG_USB_EP_ETH_DATA) { + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, s_mgi_dwc2_pkt, n); +#endif + } else if (kind == 3 && ep == 0 && s_mgi_dwc2_req_out) { // OUT stage done + s_mgi_dwc2_req_out = false; + if (s_mgi_dwc2_req_len != MG_LOAD_LE16(r + 6)) { + mgi_dwc2_stall(); + } else { + mgi_dwc2_request(fn); + } + } else if (kind == 3 && ep != 0) { // An OUT packet taken: take the next + mgi_dwc2_arm(ep); // Serial input is dropped + } +} + +// mg_usb_hw::poll() +static void mgi_dwc2_poll(MGI_DWC2_FN) { + uint32_t sts = MGI_DWC2_GINTSTS; + if (sts & MG_BIT(12)) { // USBRST + MGI_DWC2_GINTSTS = MG_BIT(12); + mgi_dwc2_bus_reset(); + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); + } + if (sts & MG_BIT(13)) MGI_DWC2_GINTSTS = MG_BIT(13); // ENUMDNE + while (MGI_DWC2_GINTSTS & MG_BIT(4)) mgi_dwc2_rx(fn); // RXFLVL + if (sts & MG_BIT(18)) { // IEPINT + uint32_t daint = MGI_DWC2_DAINT; + unsigned ep; + for (ep = 0; ep < 5; ep++) { + uint32_t ints; + if (!(daint & MG_BIT(ep))) continue; + ints = MGI_DWC2_DIEPINT(ep); + MGI_DWC2_DIEPINT(ep) = ints; + if (!(ints & 1U)) continue; // XFRC: the packet went out + if (!fn(MG_USB_EV_IN, (enum mg_usb_ep) ep, NULL, 0) && ep == 0 && + (s_mgi_dwc2_req[0] & 0x80) && MG_LOAD_LE16(s_mgi_dwc2_req + 6)) { + mgi_dwc2_arm(0); // IN data stage over: the host's OUT status stage + } + } + } +} + +// Core soft reset. From core v4.20a, the reset done bit says when it is over +static void mgi_dwc2_core_reset(void) { + bool done_bit = (MGI_DWC2_GSNPSID & 0xffff) >= 0x420a; + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(31), true); // AHBIDL + MGI_DWC2_GRSTCTL |= 1U; // CSRST + if (done_bit) { + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(29), true); + MGI_DWC2_GRSTCTL = (MGI_DWC2_GRSTCTL & ~1U) | MG_BIT(29); + } else { + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, 1U, false); + } + mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(31), true); +} + +// mg_usb_hw::init(): the serial number, the core as a full-speed device, +// then attach +static void mgi_dwc2_start(char serial[17]) { +#if defined(UID_BASE) // STM32: from the 96-bit unique ID + const volatile uint32_t *uid = (const volatile uint32_t *) UID_BASE; + uint32_t id[2] = {uid[0] ^ uid[2], uid[1]}; + mg_snprintf(serial, 17, "%M", mg_print_hex, (int) sizeof(id), (uint8_t *) id); +#else + mg_snprintf(serial, 17, "%s", "0000000000000000"); +#endif +#if MG_USB_DWC2_ULPI // 8-bit single data rate, internal VBUS indicator + MGI_DWC2_GUSBCFG = + (MGI_DWC2_GUSBCFG & ~(MG_BIT(3) | MG_BIT(6) | MG_BIT(7) | MG_BIT(17) | + MG_BIT(19) | MG_BIT(20) | MG_BIT(21))) | + MG_BIT(4); // ULPI +#elif MG_USB_DWC2_UTMI + // The core's own high-speed PHY: UTMI, not ULPI or full-speed; no TSDPS + MGI_DWC2_GUSBCFG &= ~(MG_BIT(4) | MG_BIT(6) | MG_BIT(22)); +#else + MGI_DWC2_GUSBCFG |= MG_BIT(6); // The core's own full-speed PHY +#endif +#ifdef MG_USB_DWC2_GCCFG + MGI_DWC2_GCCFG = MG_USB_DWC2_GCCFG; +#endif + mgi_dwc2_core_reset(); +#ifdef MG_USB_DWC2_GCCFG + MGI_DWC2_GCCFG = MG_USB_DWC2_GCCFG; +#endif + // Turnaround time: 9 for a high-speed PHY, 6 for a fast AHB otherwise. + // Timeout calibration: the maximum. Then device mode, which takes a while + MGI_DWC2_GUSBCFG = (MGI_DWC2_GUSBCFG & ~((0xfUL << 10) | 7U | MG_BIT(29))) | + ((MGI_DWC2_HS_PHY ? 9UL : 6UL) << 10) | 7U | MG_BIT(30); + mgi_dwc2_wait(&MGI_DWC2_GINTSTS, 1U, false); // CMOD: device mode + MGI_DWC2_PCGCCTL = 0; // PHY clock on + // Full speed, on a high-speed PHY (DSPD 1) or the core's own full-speed + // one (DSPD 3). Stall a non-empty status stage. XCVRDLY: some ULPI PHYs + // need it to chirp + MGI_DWC2_DCFG = (MGI_DWC2_DCFG & ~3U) | MG_BIT(2) | + (MGI_DWC2_HS_PHY ? 1U : 3U) | + (MG_USB_DWC2_ULPI ? MG_BIT(14) : 0U); + MGI_DWC2_DCTL |= MG_BIT(1); // SDIS: detached while setting up + // No VBUS sensing: B-session valid, always + MGI_DWC2_GOTGCTL = (MGI_DWC2_GOTGCTL & ~MG_BIT(4)) | MG_BIT(6) | MG_BIT(7); + MGI_DWC2_GINTSTS = 0xffffffff; + mgi_dwc2_flush_tx(0x10); + mgi_dwc2_bus_reset(); + MGI_DWC2_DCTL &= ~MG_BIT(1); // Attach +} + +const struct mg_usb_hw mg_usb_hw_dwc2 = {mgi_dwc2_start, mgi_dwc2_poll, + mgi_dwc2_in}; + +#if MG_ENABLE_USB_ETHERNET +static bool mgi_dwc2_init(struct mg_tcpip_if *ifp) { + return mg_usb_init(ifp, &mg_usb_hw_dwc2); +} + +struct mg_tcpip_driver mg_tcpip_driver_usb_dwc2 = {mgi_dwc2_init, mg_usb_tx, + NULL, mg_usb_poll}; +#endif + +#endif diff --git a/src/drivers/usb_dwc2.h b/src/drivers/usb_dwc2.h new file mode 100644 index 00000000..622a1e43 --- /dev/null +++ b/src/drivers/usb_dwc2.h @@ -0,0 +1,57 @@ +#pragma once + +// Synopsys DesignWare USB 2.0 OTG controller, "DWC2", as a device, see usb.h: +// CDC-NCM Ethernet and a CDC-ACM serial log console. Polled, no DMA, full +// speed. STM32 OTG_FS and OTG_HS (F2, F4, F7, H7, L4+, U5) are DWC2. Set in +// mongoose_config.h: +// - MG_USB_DWC2_BASE: the core's address, e.g. USB1_OTG_HS_PERIPH_BASE. The +// application enables its clocks, power and pins +// - MG_USB_DWC2_ULPI 1: an external ULPI PHY, run at full speed. Default: the +// core's own full-speed PHY +// - MG_USB_DWC2_UTMI 1: the core's own high-speed PHY (UTMI), run at full +// speed, e.g. STM32U59x/U5Ax OTG_HS. The application powers and clocks it +// - MG_USB_DWC2_GCCFG: optional, written to the STM32 GCCFG register, e.g. +// its PWRDWN bit to power the core's own full-speed PHY +// On STM32, include the device header in mongoose_config.h: the USB serial +// number is then the chip's unique ID. Examples: +// tutorials/stm32/portenta-h7/minimal-usb (ULPI), +// tutorials/stm32/nucleo-u5a5zj-q/minimal-usb (UTMI) + +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_DWC2 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// The controller. Without USB Ethernet, run the serial console from main(): +// mg_usb_init(NULL, &mg_usb_hw_dwc2) once, mg_usb_poll(NULL, false) in +// the main loop +extern const struct mg_usb_hw mg_usb_hw_dwc2; + +#endif + +#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_DWC2 && MG_ENABLE_USB_ETHERNET + +extern struct mg_tcpip_driver mg_tcpip_driver_usb_dwc2; + +// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the +// USB host. Leave it unset to get an address over DHCP, e.g. from macOS +// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if +// it is not set; the host end of the link gets a MAC derived from it +#define MG_TCPIP_DRIVER_USB_DWC2_INIT(mgr) \ + do { \ + static struct mg_tcpip_if mif_; \ + mif_.ip = MG_TCPIP_IP; \ + mif_.mask = MG_TCPIP_MASK; \ + mif_.gw = MG_TCPIP_GW; \ + mif_.enable_dhcp_server = mif_.ip != 0; \ + mif_.driver = &mg_tcpip_driver_usb_dwc2; \ + mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \ + MG_SET_MAC_ADDRESS(mif_.mac); \ + mg_tcpip_init(mgr, &mif_); \ + MG_INFO(("Driver: usb_dwc2, MAC: %M", mg_print_mac, mif_.mac)); \ + } while (0) + +#ifndef MG_TCPIP_DRIVER_INIT +#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_DWC2_INIT(mgr) +#endif + +#endif diff --git a/src/drivers/usb_nrf52.c b/src/drivers/usb_nrf52.c index 1b938865..410d5926 100644 --- a/src/drivers/usb_nrf52.c +++ b/src/drivers/usb_nrf52.c @@ -1,43 +1,31 @@ +#include "net_builtin.h" #include "drivers/usb.h" #include "drivers/usb_nrf52.h" -#include "net_builtin.h" +#include "printf.h" +#include "util.h" -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_NRF52 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) #include // nRF52840 USB device controller, polled, full speed. Endpoint buffers are // inside the controller: EasyDMA moves each packet between them and RAM, -// one transfer at a time, so longer IN transfers go out 64 bytes at a time. -// EasyDMA reads RAM only, thus constant data is copied to RAM first. The +// and reads RAM only, so every packet goes through s_mgi_usb_nrf52_pkt. The // controller handles SET_ADDRESS by itself. Errata workarounds follow // Nordic's nrfx_usbd.c: 171, 187 when enabling, 199 around each DMA -#define ERRATA_199 (*(volatile uint32_t *) 0x40027c1c) +#define MGI_USB_NRF52_ERRATA_199 (*(volatile uint32_t *) 0x40027c1c) -struct nrf_in { // IN transfer on an endpoint - const uint8_t *data; // Bytes still to send, in RAM - size_t left; // How many - unsigned packets; // Packets still to send - bool busy; // A packet is waiting for the host -}; +// usb.c's event handler, see mg_usb_hw::poll() +#define MGI_USB_NRF52_FN \ + int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t) -static struct nrf_in s_in[5]; // Index: endpoint number -static struct mg_usb s_usb; -static uint8_t s_req[16]; // SETUP packet, then its OUT data stage -static uint32_t s_ep0[256 / 4]; // Control IN reply, OUT data stage -static char s_serial[17]; // Serial number: device ID in hex -#if MG_ENABLE_USB_ETHERNET -static uint32_t s_note[16 / 4]; // Link notification -static uint32_t s_rx[MG_USB_NTB_SIZE / 4], s_tx[MG_USB_NTB_SIZE / 4]; -static size_t s_rxlen; // Received part of the OUT transfer block -static bool s_discard; // OUT transfer block too long: drop it -#endif -#if MG_ENABLE_USB_SERIAL -static uint32_t s_log[64 / 4]; // Log output in flight -#endif +static uint32_t s_mgi_usb_nrf52_pkt[64 / 4]; // One packet in RAM +static uint8_t s_mgi_usb_nrf52_req[16]; // SETUP packet, then its OUT data // Write an undocumented register the way Nordic's errata workarounds do -static void errata(uint32_t addr, uint32_t value) { +static void mgi_usb_nrf52_errata(uint32_t addr, uint32_t value) { volatile uint32_t *unlock = (volatile uint32_t *) 0x4006ec00; bool locked = *unlock == 0; if (locked) *unlock = 0x9375; @@ -46,136 +34,110 @@ static void errata(uint32_t addr, uint32_t value) { } // Run one EasyDMA transfer and wait for its end event -static void dma(volatile uint32_t *task, volatile uint32_t *end) { +static void mgi_usb_nrf52_dma(volatile uint32_t *task, volatile uint32_t *end) { unsigned i; *end = 0; - ERRATA_199 = 0x82; + MGI_USB_NRF52_ERRATA_199 = 0x82; *task = 1; for (i = 0; *end == 0 && i < 100000; i++) (void) 0; // Microseconds *end = 0; - ERRATA_199 = 0; -} - -// Send the next packet of the IN transfer on ep. False if it is over -static bool in_next(unsigned ep) { - struct nrf_in *e = &s_in[ep]; - size_t n = e->left > 64 ? 64 : e->left; - if (e->packets == 0) return false; - NRF_USBD->EPIN[ep].PTR = (uint32_t) (uintptr_t) e->data; - NRF_USBD->EPIN[ep].MAXCNT = (uint32_t) n; - dma(&NRF_USBD->TASKS_STARTEPIN[ep], &NRF_USBD->EVENTS_ENDEPIN[ep]); - e->data += n, e->left -= n, e->packets--; - return true; -} - -// Start an IN transfer from RAM. zlp: end a multiple of 64 bytes with an -// empty packet -static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { - struct nrf_in *e = &s_in[ep]; - e->data = (const uint8_t *) data, e->left = len; - e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); - e->busy = in_next(ep); + MGI_USB_NRF52_ERRATA_199 = 0; } // Data toggle of endpoint address ep back to DATA0 -static void dtoggle(unsigned ep) { +static void mgi_usb_nrf52_dtoggle(unsigned ep) { NRF_USBD->DTOGGLE = ep; // Select the endpoint, then set its toggle NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep; } -#if MG_ENABLE_USB_ETHERNET -// Ethernet data endpoints idle, ready to receive -static void data_reset(void) { - dtoggle(0x02), dtoggle(0x82); - memset(&s_in[2], 0, sizeof(s_in[2])); - s_rxlen = 0, s_discard = false; - NRF_USBD->SIZE.EPOUT[2] = 0; // Drop any received packet, accept the next +// mg_usb_hw::in(): copy the packet to RAM, then into the endpoint +static void mgi_usb_nrf52_in(enum mg_usb_ep ep, const void *buf, size_t len) { + if (len > 0) memcpy(s_mgi_usb_nrf52_pkt, buf, len); + NRF_USBD->EPIN[ep].PTR = (uint32_t) (uintptr_t) s_mgi_usb_nrf52_pkt; + NRF_USBD->EPIN[ep].MAXCNT = (uint32_t) len; + mgi_usb_nrf52_dma(&NRF_USBD->TASKS_STARTEPIN[ep], + &NRF_USBD->EVENTS_ENDEPIN[ep]); } -// A packet on the Ethernet OUT endpoint: add it to the transfer block. The -// endpoint accepts the next packet once this one is moved or dropped -static void rx(void) { - size_t n = NRF_USBD->SIZE.EPOUT[2]; - if (n > 0 && !s_discard && s_rxlen + n <= sizeof(s_rx)) { - uint8_t *p = (uint8_t *) s_rx + s_rxlen; - NRF_USBD->EPOUT[2].PTR = (uint32_t) (uintptr_t) p; - NRF_USBD->EPOUT[2].MAXCNT = (uint32_t) n; - dma(&NRF_USBD->TASKS_STARTEPOUT[2], &NRF_USBD->EVENTS_ENDEPOUT[2]); - s_rxlen += n; +// Move the packet on OUT endpoint ep to RAM, which also lets the endpoint +// accept the next one. Returns its length +static size_t mgi_usb_nrf52_out(unsigned ep) { + size_t n = NRF_USBD->SIZE.EPOUT[ep]; + if (n == 0) { + NRF_USBD->SIZE.EPOUT[ep] = 0; // Nothing to move: accept the next } else { - s_discard = s_discard || n > 0; // An empty packet only ends the block - NRF_USBD->SIZE.EPOUT[2] = 0; - } - // At the advertised maximum OUT size, the host need not send a ZLP. - // Other transfers end with a short packet (including a ZLP) - if (n < 64 || s_rxlen == sizeof(s_rx)) { - if (!s_discard) mg_usb_decode(&s_usb, (uint8_t *) s_rx, s_rxlen); - s_rxlen = 0, s_discard = false; + NRF_USBD->EPOUT[ep].PTR = (uint32_t) (uintptr_t) s_mgi_usb_nrf52_pkt; + NRF_USBD->EPOUT[ep].MAXCNT = (uint32_t) n; + mgi_usb_nrf52_dma(&NRF_USBD->TASKS_STARTEPOUT[ep], + &NRF_USBD->EVENTS_ENDEPOUT[ep]); } + return n; +} + +#if MG_ENABLE_USB_ETHERNET +// Ethernet data endpoints back to DATA0, OUT ready to receive +static void mgi_usb_nrf52_data_reset(void) { + mgi_usb_nrf52_dtoggle(0x02), mgi_usb_nrf52_dtoggle(0x82); + NRF_USBD->SIZE.EPOUT[2] = 0; } #endif // Endpoints 1-4 on and idle if configured, else off -static void endpoints_reset(void) { - memset(s_in, 0, sizeof(s_in)); +static void mgi_usb_nrf52_endpoints(bool on) { NRF_USBD->EPINEN = 1, NRF_USBD->EPOUTEN = 1; - if (!s_usb.configured) return; + if (!on) return; #if MG_ENABLE_USB_ETHERNET NRF_USBD->EPINEN |= MG_BIT(1) | MG_BIT(2), NRF_USBD->EPOUTEN |= MG_BIT(2); - dtoggle(0x81); - data_reset(); + mgi_usb_nrf52_dtoggle(0x81); + mgi_usb_nrf52_data_reset(); #endif #if MG_ENABLE_USB_SERIAL NRF_USBD->EPINEN |= MG_BIT(3) | MG_BIT(4), NRF_USBD->EPOUTEN |= MG_BIT(4); - dtoggle(0x83), dtoggle(0x04), dtoggle(0x84); + mgi_usb_nrf52_dtoggle(0x83), mgi_usb_nrf52_dtoggle(0x04); + mgi_usb_nrf52_dtoggle(0x84); NRF_USBD->SIZE.EPOUT[4] = 0; #endif } -// Run a complete control request: SETUP in s_req, then any OUT data -static void request(void) { - const void *reply; - unsigned wlen = MG_LOAD_LE16(s_req + 6); - int n = mg_usb_setup(&s_usb, s_req, &reply); - if (n < 0) { +// A complete control request: usb.c answers it, then the controller follows +static void mgi_usb_nrf52_request(MGI_USB_NRF52_FN) { + uint8_t *r = s_mgi_usb_nrf52_req; + size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage + int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out); + if (res < 0) { NRF_USBD->TASKS_EP0STALL = 1; return; } - switch ((s_req[0] << 8) | s_req[1]) { + switch ((r[0] << 8) | r[1]) { case 0x0009: // SET_CONFIGURATION - endpoints_reset(); + mgi_usb_nrf52_endpoints(r[2] == 1); break; #if MG_ENABLE_USB_ETHERNET case 0x010b: // SET_INTERFACE - if (s_req[4] == 1) data_reset(); + if (r[4] == MG_USB_IF_ETH_DATA) mgi_usb_nrf52_data_reset(); break; #endif case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT) - dtoggle(s_req[4]); + mgi_usb_nrf52_dtoggle(r[4]); NRF_USBD->EPSTALL = - (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | s_req[4]; - if (!(s_req[4] & 0x80)) NRF_USBD->SIZE.EPOUT[s_req[4] & 15] = 0; + (USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | r[4]; + if (!(r[4] & 0x80)) NRF_USBD->SIZE.EPOUT[r[4] & 15] = 0; break; } - if ((s_req[0] & 0x80) && wlen) { // IN data stage. Largest reply: 160 - memcpy(s_ep0, reply, (size_t) n); - in_start(0, s_ep0, (size_t) n, n < (int) wlen); - } else { - NRF_USBD->TASKS_EP0STATUS = 1; - } + if (res == 0) NRF_USBD->TASKS_EP0STATUS = 1; // No IN data stage } // A SETUP packet: run it, or first receive its OUT data stage -static void setup(void) { +static void mgi_usb_nrf52_setup(MGI_USB_NRF52_FN) { const volatile uint32_t *regs = &NRF_USBD->BMREQUESTTYPE; + uint8_t *r = s_mgi_usb_nrf52_req; unsigned i, wlen; - for (i = 0; i < 8; i++) s_req[i] = (uint8_t) regs[i]; - wlen = MG_LOAD_LE16(s_req + 6); - memset(&s_in[0], 0, sizeof(s_in[0])); // Cancels the previous transfer - if (s_req[0] == 0 && s_req[1] == 5) return; // SET_ADDRESS: hardware's - if ((s_req[0] & 0x80) || wlen == 0) { - request(); - } else if (wlen > sizeof(s_req) - 8) { + for (i = 0; i < 8; i++) r[i] = (uint8_t) regs[i]; + wlen = MG_LOAD_LE16(r + 6); + if (r[0] == 0 && r[1] == 5) return; // SET_ADDRESS: the controller's + if ((r[0] & 0x80) || wlen == 0) { + mgi_usb_nrf52_request(fn); + } else if (wlen > sizeof(s_mgi_usb_nrf52_req) - 8) { NRF_USBD->TASKS_EP0STALL = 1; } else { NRF_USBD->TASKS_EP0RCVOUT = 1; // Accept the OUT data stage @@ -183,35 +145,36 @@ static void setup(void) { } // A control data stage packet: an IN one acknowledged, or an OUT one arrived -static void ep0_data(void) { +static void mgi_usb_nrf52_ep0_data(MGI_USB_NRF52_FN) { + uint8_t *r = s_mgi_usb_nrf52_req; size_t n = NRF_USBD->SIZE.EPOUT[0]; - if (s_req[0] & 0x80) { - if (!in_next(0)) NRF_USBD->TASKS_EP0STATUS = 1; - } else if (n != MG_LOAD_LE16(s_req + 6)) { + if (r[0] & 0x80) { + if (!fn(MG_USB_EV_IN, MG_USB_EP_CTL, NULL, 0)) { + NRF_USBD->TASKS_EP0STATUS = 1; + } + } else if (n != MG_LOAD_LE16(r + 6)) { NRF_USBD->TASKS_EP0STALL = 1; } else { - NRF_USBD->EPOUT[0].PTR = (uint32_t) (uintptr_t) s_ep0; - NRF_USBD->EPOUT[0].MAXCNT = (uint32_t) n; - dma(&NRF_USBD->TASKS_STARTEPOUT[0], &NRF_USBD->EVENTS_ENDEPOUT[0]); - memcpy(s_req + 8, s_ep0, n); - request(); + mgi_usb_nrf52_out(0); + memcpy(r + 8, s_mgi_usb_nrf52_pkt, n); + mgi_usb_nrf52_request(fn); } } // Follow USB power: enable the controller when VBUS appears, attach to the // bus once both are ready, and detach when VBUS goes. True while attached -static bool attach(void) { +static bool mgi_usb_nrf52_attach(MGI_USB_NRF52_FN) { uint32_t power = NRF_POWER->USBREGSTATUS; if (!(power & POWER_USBREGSTATUS_VBUSDETECT_Msk)) { if (NRF_USBD->ENABLE) { NRF_USBD->USBPULLUP = 0, NRF_USBD->ENABLE = 0; - mg_usb_reset(&s_usb); + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); } return false; } if (!NRF_USBD->ENABLE) { - errata(0x4006ed14, 3); // Errata 187 - errata(0x4006ec14, 0xc0); // Errata 171 + mgi_usb_nrf52_errata(0x4006ed14, 3); // Errata 187 + mgi_usb_nrf52_errata(0x4006ec14, 0xc0); // Errata 171 NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; NRF_USBD->ENABLE = 1; } @@ -220,56 +183,30 @@ static bool attach(void) { !(power & POWER_USBREGSTATUS_OUTPUTRDY_Msk)) return false; NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk; - errata(0x4006ec14, 0); - errata(0x4006ed14, 0); + mgi_usb_nrf52_errata(0x4006ec14, 0); + mgi_usb_nrf52_errata(0x4006ed14, 0); NRF_USBD->USBPULLUP = 1; return true; } -void mg_usb_init(void) { - static bool started; - uint32_t id[2], xtal = CLOCK_HFCLKSTAT_SRC_Msk | CLOCK_HFCLKSTAT_STATE_Msk; - if (started) return; - started = true; - id[0] = NRF_FICR->DEVICEID[0], id[1] = NRF_FICR->DEVICEID[1]; - mg_snprintf(s_serial, sizeof(s_serial), "%M", mg_print_hex, (int) sizeof(id), - (uint8_t *) id); - s_usb.serial = s_serial; - mg_usb_reset(&s_usb); -#if MG_ENABLE_USB_SERIAL - mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port -#endif - if ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) { // USB needs the crystal - NRF_CLOCK->TASKS_HFCLKSTART = 1; - while ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) (void) 0; - } - // The controller itself starts in mg_usb_poll(), once USB power is there -} - -void mg_usb_poll(void) { - mg_usb_init(); -#if MG_ENABLE_USB_SERIAL - if (s_usb.reboot && mg_millis() > s_usb.reboot) { - NRF_POWER->GPREGRET = 0x57; // Adafruit bootloader: stay in DFU mode - NVIC_SystemReset(); - } -#endif - if (!attach()) return; +// mg_usb_hw::poll() +static void mgi_usb_nrf52_poll(MGI_USB_NRF52_FN) { + if (!mgi_usb_nrf52_attach(fn)) return; if (NRF_USBD->EVENTS_USBRESET) { NRF_USBD->EVENTS_USBRESET = 0; NRF_USBD->EVENTS_EP0DATADONE = NRF_USBD->EVENTS_EPDATA = 0; NRF_USBD->EPDATASTATUS = NRF_USBD->EPDATASTATUS; - mg_usb_reset(&s_usb); - endpoints_reset(); + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); + mgi_usb_nrf52_endpoints(false); return; } - if (NRF_USBD->EVENTS_EP0DATADONE) { // Before a new SETUP replaces s_req + if (NRF_USBD->EVENTS_EP0DATADONE) { // Before a new SETUP replaces req NRF_USBD->EVENTS_EP0DATADONE = 0; - ep0_data(); + mgi_usb_nrf52_ep0_data(fn); } if (NRF_USBD->EVENTS_EP0SETUP) { NRF_USBD->EVENTS_EP0SETUP = 0; - setup(); + mgi_usb_nrf52_setup(fn); } if (NRF_USBD->EVENTS_EPDATA) { // Bit n: IN n acknowledged, 16+n: OUT n uint32_t done = NRF_USBD->EPDATASTATUS; @@ -277,61 +214,44 @@ void mg_usb_poll(void) { NRF_USBD->EVENTS_EPDATA = 0; NRF_USBD->EPDATASTATUS = done; for (i = 1; i < 5; i++) { - if (done & MG_BIT(i)) s_in[i].busy = in_next(i); + if (done & MG_BIT(i)) fn(MG_USB_EV_IN, (enum mg_usb_ep) i, NULL, 0); } #if MG_ENABLE_USB_ETHERNET - if (done & MG_BIT(18)) rx(); -#endif -#if MG_ENABLE_USB_SERIAL - if (done & MG_BIT(20)) NRF_USBD->SIZE.EPOUT[4] = 0; // Serial: ignored -#endif - } -#if MG_ENABLE_USB_ETHERNET - { - const void *msg; - size_t n; - if (!s_in[1].busy && (n = mg_usb_notify(&s_usb, &msg)) > 0) { - memcpy(s_note, msg, n); - in_start(1, s_note, n, false); + if (done & MG_BIT(16 + MG_USB_EP_ETH_DATA)) { + size_t n = mgi_usb_nrf52_out(MG_USB_EP_ETH_DATA); + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, s_mgi_usb_nrf52_pkt, n); } - } #endif #if MG_ENABLE_USB_SERIAL - if (s_usb.configured && s_usb.dtr && !s_in[4].busy) { - size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); - if (n > 0) in_start(4, s_log, n, true); - } + if (done & MG_BIT(16 + MG_USB_EP_SER_DATA)) { + NRF_USBD->SIZE.EPOUT[MG_USB_EP_SER_DATA] = 0; // Serial input: dropped + } #endif + } } +// mg_usb_hw::init(): the serial number, and the crystal that USB needs. The +// controller itself starts in poll, once USB power is there +static void mgi_usb_nrf52_start(char serial[17]) { + uint32_t id[2], xtal = CLOCK_HFCLKSTAT_SRC_Msk | CLOCK_HFCLKSTAT_STATE_Msk; + id[0] = NRF_FICR->DEVICEID[0], id[1] = NRF_FICR->DEVICEID[1]; + mg_snprintf(serial, 17, "%M", mg_print_hex, (int) sizeof(id), (uint8_t *) id); + if ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) { + NRF_CLOCK->TASKS_HFCLKSTART = 1; + while ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) (void) 0; + } +} + +const struct mg_usb_hw mg_usb_hw_nrf52 = { + mgi_usb_nrf52_start, mgi_usb_nrf52_poll, mgi_usb_nrf52_in}; + #if MG_ENABLE_USB_ETHERNET -static bool mg_tcpip_driver_usb_nrf52_init(struct mg_tcpip_if *ifp) { - s_usb.ifp = ifp; // mg_tcpip_init() has started USB already - return true; -} - -static size_t mg_tcpip_driver_usb_nrf52_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - // One frame can be in flight. Keep USB moving while waiting, but bound - // the wait if the host stops reading or the cable is gone - uint64_t until = mg_millis() + 20; - size_t n = 0; - while (s_in[2].busy && mg_millis() < until) mg_usb_poll(); - if (!s_in[2].busy) n = mg_usb_encode(&s_usb, (uint8_t *) s_tx, buf, len); - if (n) in_start(2, s_tx, n, n < s_usb.input_size); - (void) ifp; - return n ? len : 0; -} - -// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open -static bool mg_tcpip_driver_usb_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) { - (void) ifp; - return s1 && s_usb.alt && s_usb.filter; +static bool mgi_usb_nrf52_init(struct mg_tcpip_if *ifp) { + return mg_usb_init(ifp, &mg_usb_hw_nrf52); } struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52 = { - mg_tcpip_driver_usb_nrf52_init, mg_tcpip_driver_usb_nrf52_tx, NULL, - mg_tcpip_driver_usb_nrf52_poll}; + mgi_usb_nrf52_init, mg_usb_tx, NULL, mg_usb_poll}; #endif #endif diff --git a/src/drivers/usb_nrf52.h b/src/drivers/usb_nrf52.h index 7efff6f0..d14bde3f 100644 --- a/src/drivers/usb_nrf52.h +++ b/src/drivers/usb_nrf52.h @@ -2,9 +2,20 @@ // nRF52840 USB device controller, see usb.h: CDC-NCM Ethernet and a CDC-ACM // serial log console. No TinyUSB, polled. Needs the nRF52840 device headers -// from nrfx/mdk on the include path. Example: tutorials/nordic/xiao-52840 +// from nrfx/mdk on the include path. Example: tutorials/nordic/xiao-nrf52840 -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_NRF52 && MG_ENABLE_USB_ETHERNET +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \ + MG_ENABLE_DRIVER_USB_NRF52 && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// The controller. Without USB Ethernet, run the serial console from main(): +// mg_usb_init(NULL, &mg_usb_hw_nrf52) once, mg_usb_poll(NULL, false) in +// the main loop +extern const struct mg_usb_hw mg_usb_hw_nrf52; + +#endif + +#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_NRF52 && MG_ENABLE_USB_ETHERNET extern struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52; diff --git a/src/drivers/usb_rp.c b/src/drivers/usb_rp.c index 425932b0..f1bea115 100644 --- a/src/drivers/usb_rp.c +++ b/src/drivers/usb_rp.c @@ -1,46 +1,36 @@ +#include "net_builtin.h" #include "drivers/usb.h" #include "drivers/usb_rp.h" -#include "net_builtin.h" +#include "util.h" -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && MG_ENABLE_DRIVER_USB_RP && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) // RP2040 / RP2350 USB device controller: single core, polled, full speed, -// 64-byte single-buffered endpoints in USB DPRAM. Longer IN transfers go -// out one packet at a time, the next one when the previous completes +// 64-byte single-buffered endpoints in USB DPRAM -struct rp_ep { - uint8_t *buf; // Endpoint buffer in USB DPRAM - io_rw_32 *ctrl; // Buffer control register - const uint8_t *data; // IN transfer: bytes still to send - size_t left; // IN transfer: how many - unsigned packets; // IN transfer: packets still to send - uint8_t pid; // Next DATA PID, 0 or 1 - bool busy; // Buffer handed to the controller +// usb.c's event handler, see mg_usb_hw::poll() +#define MGI_USB_RP_FN int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t) + +struct mgi_usb_rp_ep { + uint8_t *buf; // Endpoint buffer in USB DPRAM + io_rw_32 *ctrl; // Buffer control register + uint8_t pid; // Next DATA PID, 0 or 1 }; -static struct rp_ep s_ep[5][2]; // Index: endpoint number, OUT=0 IN=1 -static struct mg_usb s_usb; -static uint8_t s_req[16]; // SETUP packet, then its OUT data stage -static bool s_req_out; // Waiting for that OUT data stage -static uint8_t s_address; // Address to apply after the status stage -static char s_serial[2 * PICO_UNIQUE_BOARD_ID_SIZE_BYTES + 1]; -#if MG_ENABLE_USB_ETHERNET -static uint8_t s_rx[MG_USB_NTB_SIZE], s_tx[MG_USB_NTB_SIZE]; -static size_t s_rxlen; // Received part of the OUT transfer block -static bool s_discard; // OUT transfer block too long: drop it -#endif -#if MG_ENABLE_USB_SERIAL -static char s_log[64]; // Log output in flight -#endif +static struct mgi_usb_rp_ep s_mgi_usb_rp_ep[5][2]; // Endpoint, OUT=0 IN=1 +static uint8_t s_mgi_usb_rp_req[16]; // SETUP packet, then its OUT data +static bool s_mgi_usb_rp_req_out; // Waiting for that OUT data stage +static uint8_t s_mgi_usb_rp_address; // Address to set after the status stage // Hand one packet buffer to the controller. OUT: accept up to len bytes -static void packet(unsigned ep, bool in, const void *data, unsigned len) { - struct rp_ep *e = &s_ep[ep][in]; +static void mgi_usb_rp_packet(unsigned ep, bool in, const void *data, + unsigned len) { + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; uint32_t v = len | (e->pid ? USB_BUF_CTRL_DATA1_PID : 0) | (in ? USB_BUF_CTRL_FULL : 0); if (in && len) memcpy(e->buf, data, len); e->pid ^= 1; - e->busy = true; *e->ctrl = v; // RP2040 datasheet: allow at least 12 cycles between writing buffer // metadata and handing ownership to the controller through AVAIL @@ -48,36 +38,23 @@ static void packet(unsigned ep, bool in, const void *data, unsigned len) { *e->ctrl = v | USB_BUF_CTRL_AVAIL; } -// Send the next packet of the IN transfer on ep. False if it is over -static bool in_next(unsigned ep) { - struct rp_ep *e = &s_ep[ep][1]; - unsigned n = e->left > 64 ? 64 : (unsigned) e->left; - if (e->packets == 0) return false; - packet(ep, true, e->data, n); - e->data += n, e->left -= n, e->packets--; - return true; -} - -// Start an IN transfer. zlp: end a multiple of 64 bytes with an empty packet -static void in_start(unsigned ep, const void *data, size_t len, bool zlp) { - struct rp_ep *e = &s_ep[ep][1]; - e->data = (const uint8_t *) data, e->left = len; - e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp)); - in_next(ep); +// mg_usb_hw::in() +static void mgi_usb_rp_in(enum mg_usb_ep ep, const void *buf, size_t len) { + mgi_usb_rp_packet(ep, true, buf, (unsigned) len); } // Set up endpoint ep, direction in, idle. Endpoints 1 and 3 are interrupt, // 2 and 4 bulk, each with a 64-byte DPRAM buffer of its own -static void ep_init(unsigned ep, bool in) { - struct rp_ep *e = &s_ep[ep][in]; - e->ctrl = in ? &usb_dpram->ep_buf_ctrl[ep].in - : &usb_dpram->ep_buf_ctrl[ep].out; +static void mgi_usb_rp_ep_init(unsigned ep, bool in) { + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; + e->ctrl = + in ? &usb_dpram->ep_buf_ctrl[ep].in : &usb_dpram->ep_buf_ctrl[ep].out; e->buf = ep ? &usb_dpram->epx_data[(ep * 2 + in) * 64] : usb_dpram->ep0_buf_a; - e->pid = 0, e->busy = false, e->packets = 0; + e->pid = 0; *e->ctrl = 0; if (ep) { - io_rw_32 *ctrl = in ? &usb_dpram->ep_ctrl[ep - 1].in - : &usb_dpram->ep_ctrl[ep - 1].out; + io_rw_32 *ctrl = + in ? &usb_dpram->ep_ctrl[ep - 1].in : &usb_dpram->ep_ctrl[ep - 1].out; *ctrl = EP_CTRL_ENABLE_BITS | EP_CTRL_INTERRUPT_PER_BUFFER | ((ep & 1 ? 3U : 2U) << EP_CTRL_BUFFER_TYPE_LSB) | (uint32_t) ((uintptr_t) e->buf - (uintptr_t) usb_dpram); @@ -85,152 +62,150 @@ static void ep_init(unsigned ep, bool in) { } #if MG_ENABLE_USB_ETHERNET -// Ethernet data endpoints idle, then armed to receive if Ethernet is open -static void data_reset(void) { - ep_init(2, false), ep_init(2, true); - s_rxlen = 0, s_discard = false; - if (s_usb.alt) packet(2, false, NULL, 64); -} - -// A packet on the Ethernet OUT endpoint: add it to the transfer block -static void rx(const uint8_t *buf, unsigned n) { - if (s_rxlen + n <= sizeof(s_rx) && !s_discard) { - memcpy(s_rx + s_rxlen, buf, n); - s_rxlen += n; - } else { - s_discard = true; - } - // At the advertised maximum OUT size, the host need not send a ZLP. - // Other transfers end with a short packet (including a ZLP) - if (n < 64 || s_rxlen == sizeof(s_rx)) { - if (!s_discard) mg_usb_decode(&s_usb, s_rx, s_rxlen); - s_rxlen = 0; - s_discard = false; - } - if (s_usb.alt) packet(2, false, NULL, 64); +// Ethernet data endpoints idle, OUT armed to receive if Ethernet is open +static void mgi_usb_rp_data_reset(bool open) { + mgi_usb_rp_ep_init(2, false), mgi_usb_rp_ep_init(2, true); + if (open) mgi_usb_rp_packet(2, false, NULL, 64); } #endif -// All endpoints idle, then the serial port armed to receive if configured -static void endpoints_reset(void) { - static const uint8_t eps[] = { - 0x00, 0x80, +// Endpoints 1-4 idle. If configured, the serial port armed to receive +static void mgi_usb_rp_endpoints(bool on) { #if MG_ENABLE_USB_ETHERNET - 0x81, + mgi_usb_rp_ep_init(1, true); + mgi_usb_rp_data_reset(false); #endif #if MG_ENABLE_USB_SERIAL - 0x83, 0x04, 0x84, -#endif - }; - size_t i; - for (i = 0; i < sizeof(eps); i++) ep_init(eps[i] & 15U, eps[i] >> 7); -#if MG_ENABLE_USB_ETHERNET - data_reset(); -#endif -#if MG_ENABLE_USB_SERIAL - if (s_usb.configured) packet(4, false, NULL, 64); + mgi_usb_rp_ep_init(3, true); + mgi_usb_rp_ep_init(4, false), mgi_usb_rp_ep_init(4, true); + if (on) mgi_usb_rp_packet(4, false, NULL, 64); #endif + (void) on; } // Stall endpoint 0 until the next SETUP -static void stall(void) { +static void mgi_usb_rp_stall(void) { usb_hw->ep_stall_arm = USB_EP_STALL_ARM_EP0_IN_BITS | USB_EP_STALL_ARM_EP0_OUT_BITS; - *s_ep[0][1].ctrl = USB_BUF_CTRL_STALL; - *s_ep[0][0].ctrl = USB_BUF_CTRL_STALL; + *s_mgi_usb_rp_ep[0][1].ctrl = USB_BUF_CTRL_STALL; + *s_mgi_usb_rp_ep[0][0].ctrl = USB_BUF_CTRL_STALL; } -// Run a complete control request: SETUP in s_req, then any OUT data -static void request(void) { - const void *reply; - int n = mg_usb_setup(&s_usb, s_req, &reply); - if (n < 0) { - stall(); +// A complete control request: usb.c answers it, then the controller follows +static void mgi_usb_rp_request(MGI_USB_RP_FN) { + uint8_t *r = s_mgi_usb_rp_req; + size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage + int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out); + if (res < 0) { + mgi_usb_rp_stall(); return; } - switch ((s_req[0] << 8) | s_req[1]) { - case 0x0005: // SET_ADDRESS, applied after the status stage - s_address = s_req[2]; + switch ((r[0] << 8) | r[1]) { + case 0x0005: // SET_ADDRESS, set after the status stage + s_mgi_usb_rp_address = r[2]; break; case 0x0009: // SET_CONFIGURATION - endpoints_reset(); + mgi_usb_rp_endpoints(r[2] == 1); break; #if MG_ENABLE_USB_ETHERNET case 0x010b: // SET_INTERFACE - if (s_req[4] == 1) data_reset(); + if (r[4] == MG_USB_IF_ETH_DATA) mgi_usb_rp_data_reset(r[2] == 1); break; #endif case 0x0201: { // CLEAR_FEATURE(ENDPOINT_HALT) - struct rp_ep *e = &s_ep[s_req[4] & 15][s_req[4] >> 7]; + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[r[4] & 15][r[4] >> 7]; *e->ctrl &= ~USB_BUF_CTRL_STALL, e->pid = 0; break; } } - // IN data stage, or the status stage, both starting with DATA1 - s_ep[0][1].pid = 1; - in_start(0, reply, (size_t) n, n < (int) MG_LOAD_LE16(s_req + 6)); + if (res == 0) mgi_usb_rp_packet(0, true, NULL, 0); // Status stage, DATA1 } // A SETUP packet: run it, or first receive its OUT data stage -static void setup(void) { +static void mgi_usb_rp_setup(MGI_USB_RP_FN) { + uint8_t *r = s_mgi_usb_rp_req; unsigned wlen; - memcpy(s_req, (const void *) usb_dpram->setup_packet, 8); - wlen = MG_LOAD_LE16(s_req + 6); - // A SETUP cancels the preceding control transfer. OUT stages use DATA1 - ep_init(0, false), ep_init(0, true); - s_ep[0][0].pid = 1; - s_address = 0, s_req_out = false; - if ((s_req[0] & 0x80) || wlen == 0) { - request(); - } else if (wlen > sizeof(s_req) - 8) { - stall(); + memcpy(r, (const void *) usb_dpram->setup_packet, 8); + wlen = MG_LOAD_LE16(r + 6); + // A SETUP cancels the preceding control transfer. Both its data and + // status stages start with DATA1 + mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true); + s_mgi_usb_rp_ep[0][0].pid = s_mgi_usb_rp_ep[0][1].pid = 1; + s_mgi_usb_rp_address = 0, s_mgi_usb_rp_req_out = false; + if ((r[0] & 0x80) || wlen == 0) { + mgi_usb_rp_request(fn); + } else if (wlen > sizeof(s_mgi_usb_rp_req) - 8) { + mgi_usb_rp_stall(); } else { - s_req_out = true; - packet(0, false, NULL, 64); + s_mgi_usb_rp_req_out = true; + mgi_usb_rp_packet(0, false, NULL, 64); } } // A buffer the controller has finished with -static void complete(unsigned ep, bool in) { - struct rp_ep *e = &s_ep[ep][in]; +static void mgi_usb_rp_complete(unsigned ep, bool in, MGI_USB_RP_FN) { + struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in]; + uint8_t *r = s_mgi_usb_rp_req; unsigned n = *e->ctrl & USB_BUF_CTRL_LEN_MASK; - e->busy = false; - if (in && in_next(ep)) return; + if (in && fn(MG_USB_EV_IN, (enum mg_usb_ep) ep, NULL, 0)) return; if (ep == 0 && in) { // Control IN data or status stage sent - if (s_address) { - usb_hw->dev_addr_ctrl = s_address, s_address = 0; - } else if ((s_req[0] & 0x80) && MG_LOAD_LE16(s_req + 6)) { - packet(0, false, NULL, 64); // Host's OUT status stage + if (s_mgi_usb_rp_address) { + usb_hw->dev_addr_ctrl = s_mgi_usb_rp_address, s_mgi_usb_rp_address = 0; + } else if ((r[0] & 0x80) && MG_LOAD_LE16(r + 6)) { + mgi_usb_rp_packet(0, false, NULL, 64); // Host's OUT status stage } - } else if (ep == 0 && !in && s_req_out) { // Control OUT data stage - s_req_out = false; - if (n != MG_LOAD_LE16(s_req + 6)) { - stall(); + } else if (ep == 0 && !in && s_mgi_usb_rp_req_out) { // OUT data stage + s_mgi_usb_rp_req_out = false; + if (n != MG_LOAD_LE16(r + 6)) { + mgi_usb_rp_stall(); } else { - memcpy(s_req + 8, e->buf, n); - request(); + memcpy(r + 8, e->buf, n); + mgi_usb_rp_request(fn); } #if MG_ENABLE_USB_ETHERNET - } else if (ep == 2 && !in) { - rx(e->buf, n); + } else if (ep == MG_USB_EP_ETH_DATA && !in) { + fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, e->buf, n); + mgi_usb_rp_packet(ep, false, NULL, 64); #endif #if MG_ENABLE_USB_SERIAL - } else if (ep == 4 && !in) { - packet(4, false, NULL, 64); // Serial input is discarded: log console + } else if (ep == MG_USB_EP_SER_DATA && !in) { + mgi_usb_rp_packet(ep, false, NULL, 64); // Serial input: dropped #endif } } -void mg_usb_init(void) { - static bool started; - if (started) return; - started = true; - pico_get_unique_board_id_string(s_serial, sizeof(s_serial)); - s_usb.serial = s_serial; - mg_usb_reset(&s_usb); -#if MG_ENABLE_USB_SERIAL - mg_log_set_fn(mg_usb_log, &s_usb); // Log to the USB serial port -#endif +// mg_usb_hw::poll() +static void mgi_usb_rp_poll(MGI_USB_RP_FN) { + uint32_t status = usb_hw->intr, done; + unsigned i; + if (status & USB_INTR_BUS_RESET_BITS) { + usb_hw->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; + usb_hw->dev_addr_ctrl = 0; + usb_hw->buf_status = 0xffffffff; + fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0); + mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true); + mgi_usb_rp_endpoints(false); + return; + } + if (status & USB_INTR_SETUP_REQ_BITS) { + // Discard stale EP0 completions from an interrupted control transfer + usb_hw->buf_status = 3; + usb_hw->sie_status = USB_SIE_STATUS_SETUP_REC_BITS; + mgi_usb_rp_setup(fn); + } + done = usb_hw->buf_status; + for (i = 0; i < 10; i++) { // Bits: EP0 IN, EP0 OUT, EP1 IN, ... + if (!(done & (1U << i))) continue; + usb_hw->buf_status = 1U << i; + if (s_mgi_usb_rp_ep[i / 2][!(i & 1)].ctrl) { + mgi_usb_rp_complete(i / 2, !(i & 1), fn); + } + } +} + +// mg_usb_hw::init(): the serial number, then the controller, attached +static void mgi_usb_rp_start(char serial[17]) { + pico_get_unique_board_id_string(serial, 17); reset_block(RESETS_RESET_USBCTRL_BITS); unreset_block_wait(RESETS_RESET_USBCTRL_BITS); memset(usb_dpram, 0, sizeof(*usb_dpram)); @@ -240,81 +215,21 @@ void mg_usb_init(void) { usb_hw->main_ctrl = USB_MAIN_CTRL_CONTROLLER_EN_BITS; usb_hw->sie_ctrl = USB_SIE_CTRL_EP0_INT_1BUF_BITS; usb_hw->inte = 0; // Poll raw status instead of an interrupt handler - endpoints_reset(); + mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true); + mgi_usb_rp_endpoints(false); hw_set_bits(&usb_hw->sie_ctrl, USB_SIE_CTRL_PULLUP_EN_BITS); } -void mg_usb_poll(void) { - uint32_t status, done; - unsigned i; - mg_usb_init(); - status = usb_hw->intr; -#if MG_ENABLE_USB_SERIAL - if (s_usb.reboot && mg_millis() > s_usb.reboot) reset_usb_boot(0, 0); -#endif - if (status & USB_INTR_BUS_RESET_BITS) { - usb_hw->sie_status = USB_SIE_STATUS_BUS_RESET_BITS; - usb_hw->dev_addr_ctrl = 0; - usb_hw->buf_status = 0xffffffff; - mg_usb_reset(&s_usb); - endpoints_reset(); - return; - } - if (status & USB_INTR_SETUP_REQ_BITS) { - // Discard stale EP0 completions from an interrupted control transfer - usb_hw->buf_status = 3; - usb_hw->sie_status = USB_SIE_STATUS_SETUP_REC_BITS; - setup(); - } - done = usb_hw->buf_status; - for (i = 0; i < 10; i++) { // Bits: EP0 IN, EP0 OUT, EP1 IN, ... - if (!(done & (1U << i))) continue; - usb_hw->buf_status = 1U << i; - if (s_ep[i / 2][!(i & 1)].ctrl) complete(i / 2, !(i & 1)); - } -#if MG_ENABLE_USB_ETHERNET - if (!s_ep[1][1].busy) { - const void *msg; - size_t n = mg_usb_notify(&s_usb, &msg); - if (n) in_start(1, msg, n, false); - } -#endif -#if MG_ENABLE_USB_SERIAL - if (s_usb.configured && s_usb.dtr && !s_ep[4][1].busy) { - size_t n = mg_usb_log_read(&s_usb, s_log, sizeof(s_log)); - if (n) in_start(4, s_log, n, true); - } -#endif -} +const struct mg_usb_hw mg_usb_hw_rp = {mgi_usb_rp_start, mgi_usb_rp_poll, + mgi_usb_rp_in}; #if MG_ENABLE_USB_ETHERNET -static bool mg_tcpip_driver_usb_rp_init(struct mg_tcpip_if *ifp) { - s_usb.ifp = ifp; // mg_tcpip_init() has started USB already - return true; +static bool mgi_usb_rp_init(struct mg_tcpip_if *ifp) { + return mg_usb_init(ifp, &mg_usb_hw_rp); } -static size_t mg_tcpip_driver_usb_rp_tx(const void *buf, size_t len, - struct mg_tcpip_if *ifp) { - // One frame can be in flight. Keep USB moving while waiting, but bound - // the wait if the host stops reading or the cable is gone - uint64_t until = mg_millis() + 20; - size_t n = 0; - while (s_ep[2][1].busy && mg_millis() < until) mg_usb_poll(); - if (!s_ep[2][1].busy) n = mg_usb_encode(&s_usb, s_tx, buf, len); - if (n) in_start(2, s_tx, n, n < s_usb.input_size); - (void) ifp; - return n ? len : 0; -} - -// USB itself runs from mg_mgr_poll(). Report the link: Ethernet open -static bool mg_tcpip_driver_usb_rp_poll(struct mg_tcpip_if *ifp, bool s1) { - (void) ifp; - return s1 && s_usb.alt && s_usb.filter; -} - -struct mg_tcpip_driver mg_tcpip_driver_usb_rp = { - mg_tcpip_driver_usb_rp_init, mg_tcpip_driver_usb_rp_tx, NULL, - mg_tcpip_driver_usb_rp_poll}; +struct mg_tcpip_driver mg_tcpip_driver_usb_rp = {mgi_usb_rp_init, mg_usb_tx, + NULL, mg_usb_poll}; #endif #endif diff --git a/src/drivers/usb_rp.h b/src/drivers/usb_rp.h index 118214a4..5b8c9f55 100644 --- a/src/drivers/usb_rp.h +++ b/src/drivers/usb_rp.h @@ -3,7 +3,17 @@ // RP2040 / RP2350 native USB controller, see usb.h: CDC-NCM Ethernet and // a CDC-ACM serial log console. No TinyUSB, polled. Example: tutorials/rp/usb -#if MG_ENABLE_USB && MG_ENABLE_DRIVER_USB_RP && MG_ENABLE_USB_ETHERNET +#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && MG_ENABLE_DRIVER_USB_RP && \ + (MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL) + +// The controller. Without USB Ethernet, run the serial console from main(): +// mg_usb_init(NULL, &mg_usb_hw_rp) once, mg_usb_poll(NULL, false) in +// the main loop +extern const struct mg_usb_hw mg_usb_hw_rp; + +#endif + +#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_RP && MG_ENABLE_USB_ETHERNET extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; @@ -11,7 +21,7 @@ extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; // USB host. Leave it unset to get an address over DHCP, e.g. from macOS // Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if // it is not set; the host end of the link gets a MAC derived from it -#define MG_TCPIP_DRIVER_INIT(mgr) \ +#define MG_TCPIP_DRIVER_USB_RP_INIT(mgr) \ do { \ static struct mg_tcpip_if mif_; \ mif_.ip = MG_TCPIP_IP; \ @@ -25,4 +35,8 @@ extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp; MG_INFO(("Driver: usb_rp, MAC: %M", mg_print_mac, mif_.mac)); \ } while (0) +#ifndef MG_TCPIP_DRIVER_INIT +#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_RP_INIT(mgr) +#endif + #endif diff --git a/src/l2_mesh.c b/src/l2_mesh.c deleted file mode 100644 index 681c4f6b..00000000 --- a/src/l2_mesh.c +++ /dev/null @@ -1,677 +0,0 @@ -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved - -#include "l2_mesh.h" -#include "log.h" -#include "printf.h" -#include "util.h" - -#if MG_ENABLE_TCPIP - -#define MGI_ETH_MAX 1514 -#define MGI_TX_DST_LEN 2 - -// Mesh header, after the radio header: type, then burst: the fragment's -// index << 4 | the last fragment's index. Common to every radio -#define MG_MESH_HDR_LEN 2 - -#define MG_MESH_FRAME_HDR_LEN (MG_802154_HEADER_LEN + MG_MESH_HDR_LEN) - -// MAC header, 9 bytes: frame control 0x8841, a data frame, PAN ID -// compression, short destination and source addresses; sequence number, 0, -// as nothing uses it yet; PAN ID; destination; source. Little endian, as -// the standard says -static void mgi_802154_print_hdr(const struct mg_radio *radio, uint8_t *buf, - uint16_t dst, uint16_t src) { - buf[0] = 0x41, buf[1] = 0x88, buf[2] = 0; - buf[3] = (uint8_t) MG_802154_PAN_ID; - buf[4] = (uint8_t) (MG_802154_PAN_ID >> 8); - buf[5] = (uint8_t) dst, buf[6] = (uint8_t) (dst >> 8); - buf[7] = (uint8_t) src, buf[8] = (uint8_t) (src >> 8); - (void) radio; -} - -static size_t mgi_802154_parse_hdr(const struct mg_radio *radio, - const uint8_t *buf, size_t len, - uint16_t *dst, uint16_t *src) { - (void) radio; - if (len < MG_802154_HEADER_LEN || buf[0] != 0x41 || buf[1] != 0x88 || - buf[3] != (uint8_t) MG_802154_PAN_ID || - buf[4] != (uint8_t) (MG_802154_PAN_ID >> 8)) { - return 0; - } - *dst = (uint16_t) (buf[5] | buf[6] << 8); - *src = (uint16_t) (buf[7] | buf[8] << 8); - return MG_802154_HEADER_LEN; -} - -const struct mg_radio mg_radio_802154 = { - "802.15.4", // name - 125, // max_frame_size: 127 minus FCS - 250000, // bitrate - 8, // overhead - 320, // slot_us - 128, // cca_us - 100, // turnaround_us - 640, // ifs_us - 3, // backoff_min - 5, // backoff_max - true, // csma - MG_802154_HEADER_LEN, // header_len - mgi_802154_print_hdr, // print_hdr - mgi_802154_parse_hdr // parse_hdr -}; - -static uint64_t mgi_mesh_b_airtime(size_t len) { - const struct mg_radio *radio = &mg_radio_802154; - return ((uint64_t) (len + radio->overhead) * 8000000 + radio->bitrate - 1) / - radio->bitrate; -} - -// Each queue record holds a destination and a complete burst. -static size_t mgi_mesh_b_queue(struct mg_mesh_node *node, struct mg_queue *q, - const void *buf, size_t len, uint16_t dst, - uint8_t type) { - const struct mg_radio *radio = &mg_radio_802154; - const uint8_t *eth = (const uint8_t *) buf; - size_t hdr = MG_MESH_FRAME_HDR_LEN, cap = radio->max_frame_size - hdr; - size_t frames, size, i; - char *record; - uint8_t *out; - if (len < 14 || len > MGI_ETH_MAX) return 0; - frames = (len + cap - 1) / cap; - size = MGI_TX_DST_LEN + len + frames * (1 + hdr); - if (mg_queue_next(q, NULL) == 0) mg_queue_init(q, q->buf, q->size); - if (mg_queue_book(q, &record, size) < size) return 0; - out = (uint8_t *) record; - *out++ = (uint8_t) (dst >> 8); - *out++ = (uint8_t) dst; - for (i = 0; i < frames; i++) { - size_t chunk = len - i * cap; - if (chunk > cap) chunk = cap; - *out++ = (uint8_t) (hdr + chunk); - radio->print_hdr(radio, out, dst, node->radio_address); - out[radio->header_len] = type; - out[radio->header_len + 1] = (uint8_t) (i << 4 | (frames - 1)); - memcpy(out + hdr, eth + i * cap, chunk); - out += hdr + chunk; - } - mg_queue_add(q, size); - return len; -} - -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved - -#define MGI_JOIN_WINDOW_US 3000 -#define MGI_JOIN_TURN_US 192 -#define MGI_JOIN_JITTER_US 640 -#define MGI_DATA_QUEUE_SIZE 2048 -#define MGI_TX_RETRY_US 32 -#define MGI_ANSWER_MARGIN_US 500 // Node: finish the first answer frame this - // much before the bridge stops waiting -// Our frames: the radio header, with the radio addresses, then the mesh -// header MG_MESH_HDR_LEN, then the payload -#define MGI_JOIN_UP_LEN \ - (MG_MESH_FRAME_HDR_LEN + 6) // MGI_JOIN_UP's payload: MAC addr -#define MGI_MAX_FRAGMENTS 14 - -enum { MGI_JOIN_DOWN = 1, MGI_JOIN_UP, MGI_DATA_DOWN, MGI_DATA_UP }; - -enum { MGI_TURN_IDLE, MGI_TURN_JOIN, MGI_TURN_DATA }; - -struct mgi_mesh_b_data { - uint8_t rx_buf[MGI_ETH_MAX]; // Ethernet frame being reassembled - uint8_t rx_expected; // Expected index | last index, 0xff if idle - struct mg_mesh_node *node; // Owner of the TCP/IP interface - struct mg_queue tx; // One record per burst of RF fragments - size_t tx_offset; // Next queued fragment; zero for an empty frame - uint64_t tx_at; // Next fragment or JOIN transmission time - uint64_t deadline; // End of the current JOIN or DATA turn - struct mgi_mesh_b_peer *fanout; // Next broadcast recipient - char tx_buf[MGI_DATA_QUEUE_SIZE]; // Transmit queue storage - uint32_t random; // PRNG state for join timing - struct mgi_mesh_b_peer *members; // Bridge membership list - struct mgi_mesh_b_peer *current; // Member whose turn is active or next - int8_t missed_rounds; // -1 after a grant; otherwise completed rounds missed - uint16_t coordinator; // Coordinator radio address - uint8_t phase; // MGI_TURN_IDLE, MGI_TURN_JOIN, or MGI_TURN_DATA - uint64_t answer_by; // Node: first answer frame must end on air by then -}; - -struct mgi_mesh_b_peer { - struct mgi_mesh_b_peer *next; // Next member in round-robin order - uint16_t radio_address; // Source address supplied in MGI_JOIN_UP - uint8_t mac[6]; // Ethernet MAC supplied in MGI_JOIN_UP - uint8_t misses; // Turns in a row it did not answer -}; - -static uint32_t mgi_mesh_b_random(struct mg_mesh_node *node, - struct mgi_mesh_b_data *data) { - uint32_t *random = &data->random; - if (*random == 0) { - size_t i; - *random = (uint32_t) mg_now(); - for (i = 0; i < 6; i++) *random = *random * 33u + node->radio->mac[i]; - if (*random == 0) *random = 1; - } - *random ^= *random << 13; - *random ^= *random >> 17; - *random ^= *random << 5; - return *random; -} - -static const struct mg_radio *const s_mesh_default_radio = &mg_radio_802154; - -// Read a frame's radio addresses to dst and src, see mg_radio::parse_hdr(), and -// return its type, from the mesh header. 0: not a frame of ours -static unsigned mgi_mesh_b_frame_parse(const uint8_t *frame, size_t len, - uint16_t *dst, uint16_t *src) { - if (len < MG_MESH_FRAME_HDR_LEN || - s_mesh_default_radio->parse_hdr(s_mesh_default_radio, frame, len, dst, - src) != - s_mesh_default_radio->header_len) { - return 0; - } - return frame[s_mesh_default_radio->header_len]; -} - -// Write a frame's headers: the radio's, to dst from src, then ours: type, -// and burst: high nibble is the index, low nibble is the last index -static void mgi_mesh_b_frame_header(uint8_t *frame, uint16_t dst, uint16_t src, - uint8_t type, uint8_t burst) { - size_t h = s_mesh_default_radio->header_len; - s_mesh_default_radio->print_hdr(s_mesh_default_radio, frame, dst, src); - frame[h] = type, frame[h + 1] = burst; -} - -static bool mgi_mesh_b_control_send(struct mg_mesh_node *node, uint16_t dst, - uint8_t command) { - struct mg_tcpip_if *ifp = node->radio; - uint8_t frame[MGI_JOIN_UP_LEN] = {0}; - size_t len = MG_MESH_FRAME_HDR_LEN; - mgi_mesh_b_frame_header(frame, dst, node->radio_address, command, 0); - if (command == MGI_JOIN_UP) { - memcpy(frame + MG_MESH_FRAME_HDR_LEN, node->radio->mac, 6); - len = MGI_JOIN_UP_LEN; - } - return node->now >= node->tx_at && node->tx(ifp, frame, len) == len; -} - -static size_t mgi_mesh_b_fragment_capacity(void) { - return s_mesh_default_radio->max_frame_size - MG_MESH_FRAME_HDR_LEN; -} - -static uint64_t mgi_mesh_b_burst_time(size_t len) { - size_t cap = mgi_mesh_b_fragment_capacity(); - size_t frames = len == 0 ? 1 : (len + cap - 1) / cap; - return (frames - 1) * - (mgi_mesh_b_airtime(s_mesh_default_radio->max_frame_size) + - s_mesh_default_radio->ifs_us) + - mgi_mesh_b_airtime(MG_MESH_FRAME_HDR_LEN + len - (frames - 1) * cap); -} - -static void mgi_mesh_b_tx_finish(struct mgi_mesh_b_data *data) { - if (data->tx_offset != 0) { - if (data->fanout != NULL) data->fanout = data->fanout->next; - if (data->fanout == NULL) { - size_t len = mg_queue_next(&data->tx, NULL); - mg_queue_del(&data->tx, len); - } - } - data->tx_offset = 0; - data->tx_at = (uint64_t) -1; -} - -static void mgi_mesh_b_tx_step(struct mgi_mesh_b_data *data, uint64_t now) { - struct mg_mesh_node *node = data->node; - struct mg_tcpip_if *radio = node->radio; - uint8_t empty[MG_MESH_FRAME_HDR_LEN], *frame = empty; - size_t len = MG_MESH_FRAME_HDR_LEN, record_len = 0; - uint16_t dst; - uint8_t command; - if (now < data->tx_at) return; - if (now >= data->deadline) { - mgi_mesh_b_tx_finish(data); - return; - } - dst = node->lan == NULL ? data->coordinator : data->current->radio_address; - command = node->lan == NULL ? MGI_DATA_UP : MGI_DATA_DOWN; - if (data->tx_offset != 0) { - char *record; - uint8_t *part; - record_len = mg_queue_next(&data->tx, &record); - part = (uint8_t *) record + data->tx_offset; - len = part[0]; - frame = part + 1; - s_mesh_default_radio->print_hdr(s_mesh_default_radio, frame, dst, - node->radio_address); - } else { - mgi_mesh_b_frame_header(frame, dst, node->radio_address, command, 0); - } - // A node's first answer frame: if it cannot end on air before the bridge - // stops waiting, stay silent. The queued frame waits for the next turn - if (node->lan == NULL && - (data->tx_offset == 0 || data->tx_offset == MGI_TX_DST_LEN) && - now + mgi_mesh_b_airtime(len) > data->answer_by) { - data->tx_offset = 0; - data->tx_at = (uint64_t) -1; - return; - } - if (now < data->node->tx_at || data->node->tx(radio, frame, len) != len) { - data->tx_at = now + MGI_TX_RETRY_US; - return; - } - if (data->tx_offset == 0 || (data->tx_offset += len + 1) == record_len) { - // Bridge: the turn's last frame is out, wait for the answer - if (node->lan != NULL) - data->deadline = - now + mgi_mesh_b_airtime(len) + MG_MESH_ANSWER_TIMEOUT_US; - mgi_mesh_b_tx_finish(data); - } else { - data->tx_at = now + mgi_mesh_b_airtime(len) + s_mesh_default_radio->ifs_us; - } -} - -static void mgi_mesh_b_tx_begin(struct mgi_mesh_b_data *data, bool burst, - uint64_t now, uint64_t deadline) { - data->phase = MGI_TURN_DATA; - data->answer_by = (uint64_t) -1; // Node sets it after a grant - data->tx_offset = burst ? MGI_TX_DST_LEN : 0; - data->tx_at = now; - data->deadline = deadline; -} - -// Return the assembled length, zero for an empty frame, or -1 if incomplete -// or invalid. Full non-final fragments make the write offset derivable. -static int mgi_mesh_b_data_receive(struct mgi_mesh_b_data *data, - const uint8_t *frame, size_t len, - uint64_t now) { - unsigned burst = frame[MG_MESH_FRAME_HDR_LEN - 1], index = burst >> 4, - last = burst & 15; - size_t chunk = len - MG_MESH_FRAME_HDR_LEN, - cap = mgi_mesh_b_fragment_capacity(); - size_t offset = index * cap; - if (index == 0) { - data->rx_expected = (uint8_t) burst; - if (data->node->lan == NULL) - data->deadline = now + mgi_mesh_b_burst_time(MGI_ETH_MAX) + - 2 * s_mesh_default_radio->ifs_us + MGI_JOIN_TURN_US; - } - if (last >= MGI_MAX_FRAGMENTS || index > last || burst != data->rx_expected || - chunk > cap || now > data->deadline || (index < last && chunk != cap) || - (last != 0 && chunk == 0) || offset + chunk > sizeof(data->rx_buf)) { - data->rx_expected = 0xff; - return -1; - } - memcpy(data->rx_buf + offset, frame + MG_MESH_FRAME_HDR_LEN, chunk); - if (index < last) { - data->rx_expected = (uint8_t) (burst + 0x10); - // Bridge: an answer is under way, wait for its next fragment - if (data->node->lan != NULL) - data->deadline = - now + mgi_mesh_b_airtime(s_mesh_default_radio->max_frame_size) + - s_mesh_default_radio->ifs_us + MG_MESH_ANSWER_TIMEOUT_US; - return -1; - } - data->rx_expected = 0xff; - return offset + chunk == 0 || offset + chunk >= 14 ? (int) (offset + chunk) - : -1; -} - -// Bridge scheduling and Ethernet forwarding. - - -static uint16_t mgi_mesh_b_join_field(const uint8_t *p) { - return (uint16_t) ((unsigned) p[0] * 256 + p[1]); -} - -// Return chaddr for an Ethernet DHCP server reply, even when broadcast. -static const uint8_t *mgi_mesh_b_dhcp_client(const uint8_t *frame, size_t len) { - size_t ip_len, ihl, udp_len; - const uint8_t *udp, *dhcp; - if (len < 34 || mgi_mesh_b_join_field(frame + 12) != 0x0800 || - (frame[14] >> 4) != 4 || frame[23] != 17 || - (mgi_mesh_b_join_field(frame + 20) & 0x3fff) != 0) - return NULL; - ip_len = mgi_mesh_b_join_field(frame + 16); - ihl = (size_t) (frame[14] & 15) * 4; - if (ihl < 20 || ip_len > len - 14 || ip_len < ihl + 8 + 240) return NULL; - udp = frame + 14 + ihl; - udp_len = mgi_mesh_b_join_field(udp + 4); - if (mgi_mesh_b_join_field(udp) != 67 || - mgi_mesh_b_join_field(udp + 2) != 68 || udp_len < 8 + 240 || - udp_len > ip_len - ihl) - return NULL; - dhcp = udp + 8; - if (dhcp[0] != 2 || dhcp[1] != 1 || dhcp[2] != 6 || - memcmp(dhcp + 236, "\x63\x82\x53\x63", 4) != 0) - return NULL; - return dhcp + 28; -} - -static size_t mgi_mesh_b_enqueue(struct mg_mesh_node *node, const void *buf, - size_t len) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) node->data; - const uint8_t *frame = (const uint8_t *) buf; - if (node->lan == NULL) - return mgi_mesh_b_queue(node, &data->tx, buf, len, data->coordinator, - MGI_DATA_UP); - if (len >= 14 && len <= MGI_ETH_MAX) { - const uint8_t *client = mgi_mesh_b_dhcp_client(frame, len); - const uint8_t *dst = client == NULL ? frame : client; - bool multicast = client == NULL && (frame[0] & 1) != 0; - struct mgi_mesh_b_peer *peer; - for (peer = data->members; peer != NULL; peer = peer->next) { - if (multicast || memcmp(dst, peer->mac, 6) == 0) { - uint16_t addr = multicast ? 0xffffu : peer->radio_address; - return mgi_mesh_b_queue(node, &data->tx, buf, len, addr, MGI_DATA_DOWN); - } - } - } - return 0; -} - -static void mgi_mesh_b_bridge_queue_lan(struct mg_mesh_node *bridge) { - struct mg_queue *rx = &bridge->lan->recv_queue; - char *buf; - size_t len; - while ((len = mg_queue_next(rx, &buf)) > 0) { - bridge->strategy->tx(bridge, buf, len); - mg_queue_del(rx, len); - } -} - -static void mgi_mesh_b_bridge_rx(uint64_t now, struct mg_mesh_node *b, - const uint8_t *frame, size_t len) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) b->data; - struct mgi_mesh_b_peer *peer; - uint16_t dst = 0, src = 0; - unsigned command = mgi_mesh_b_frame_parse(frame, len, &dst, &src); - if (command == MGI_DATA_UP && dst == b->radio_address && - data->phase == MGI_TURN_DATA && data->current != NULL && - src == data->current->radio_address && now <= data->deadline) { - int received = mgi_mesh_b_data_receive(data, frame, len, now); - if (received < 0) return; - if (received != 0) { - b->lan->driver->tx(data->rx_buf, (size_t) received, b->lan); - } - data->current->misses = 0; - data->current = data->current->next; - data->phase = MGI_TURN_IDLE; - data->deadline = now; - return; - } - if (len != MGI_JOIN_UP_LEN || command != MGI_JOIN_UP || - dst != b->radio_address || data->phase != MGI_TURN_JOIN || - now >= data->deadline) { - return; - } - if (src == 0 || src == 0xffffu) return; - for (peer = data->members; peer != NULL; peer = peer->next) { - if (peer->radio_address == src) break; - } - if (peer == NULL) { - peer = (struct mgi_mesh_b_peer *) mg_calloc(1, sizeof(*peer)); - if (peer == NULL) return; - peer->radio_address = src; - peer->next = data->members; - data->members = peer; - } - memcpy(peer->mac, frame + MG_MESH_FRAME_HDR_LEN, sizeof(peer->mac)); -} - -// Member peer did not answer its turn. After MG_MESH_MAX_MISSES in a row, it -// is gone: remove it, and its queued downlink frames -static void mgi_mesh_b_member_missed(struct mgi_mesh_b_data *data, - struct mgi_mesh_b_peer *peer) { - if (++peer->misses < MG_MESH_MAX_MISSES) return; - MG_INFO(("Member %M removed: no answer %d times", mg_print_mac, peer->mac, - MG_MESH_MAX_MISSES)); - if (data->fanout == peer) { - data->fanout = peer->next; - if (data->fanout == NULL) { - size_t len = mg_queue_next(&data->tx, NULL); - mg_queue_del(&data->tx, len); - } - } - LIST_DELETE(struct mgi_mesh_b_peer, &data->members, peer); - mg_free(peer); -} - -// A broadcast occupies one record and is sent once to each member in list -// order. -static size_t mgi_mesh_b_bridge_burst(struct mgi_mesh_b_data *data, - struct mgi_mesh_b_peer *peer) { - char *record; - size_t len; - while ((len = mg_queue_next(&data->tx, &record)) != 0) { - uint16_t dst = mgi_mesh_b_join_field((const uint8_t *) record); - struct mgi_mesh_b_peer *member; - if (dst == 0xffffu) { - if (data->fanout == NULL) data->fanout = data->members; - return data->fanout == peer ? len : 0; - } - if (dst == peer->radio_address) return len; - for (member = data->members; member != NULL; member = member->next) { - if (member->radio_address == dst) return 0; - } - mg_queue_del(&data->tx, len); // Its destination has left. - } - return 0; -} - -static uint64_t mgi_mesh_b_queued_burst_time(struct mgi_mesh_b_data *data, - size_t len) { - char *record; - size_t frames; - if (len == 0) return mgi_mesh_b_burst_time(0); - mg_queue_next(&data->tx, &record); - // Fragment zero carries the final index. Count overhead and IFS per frame. - frames = - ((uint8_t) record[MGI_TX_DST_LEN + MG_MESH_FRAME_HDR_LEN] & 15u) + 1u; - return mgi_mesh_b_airtime(len - MGI_TX_DST_LEN - frames + - (frames - 1) * s_mesh_default_radio->overhead) + - (frames - 1) * s_mesh_default_radio->ifs_us; -} - -static void mgi_mesh_b_bridge_io(uint64_t now, struct mg_mesh_node *b) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) b->data; - mgi_mesh_b_bridge_queue_lan(b); - if (now >= data->deadline) { - if (data->tx_at != (uint64_t) -1) mgi_mesh_b_tx_finish(data); - if (data->phase == MGI_TURN_DATA && data->current != NULL) { - struct mgi_mesh_b_peer *peer = data->current; - data->current = peer->next; - mgi_mesh_b_member_missed(data, peer); - } else if (data->phase == MGI_TURN_JOIN) { - data->current = data->members; - } - data->phase = MGI_TURN_IDLE; - if (data->current != NULL) { - size_t burst = mgi_mesh_b_bridge_burst(data, data->current); - uint64_t down = mgi_mesh_b_queued_burst_time(data, burst); - data->rx_expected = 0xff; - mgi_mesh_b_tx_begin(data, burst != 0, now, - now + down + mgi_mesh_b_burst_time(MGI_ETH_MAX) + - 2 * s_mesh_default_radio->ifs_us + - MGI_JOIN_TURN_US); - } else if (mgi_mesh_b_control_send(b, 0xffffu, MGI_JOIN_DOWN)) { - data->phase = MGI_TURN_JOIN; - data->deadline = now + MGI_JOIN_WINDOW_US; - } - if (data->deadline <= now) data->deadline = now + MGI_JOIN_TURN_US; - } -} - -static void mgi_mesh_b_bridge_free(struct mgi_mesh_b_data *data) { - while (data->members != NULL) { - struct mgi_mesh_b_peer *peer = data->members; - data->members = peer->next; - mg_free(peer); - } -} - -static void mgi_mesh_b_node_rx(struct mg_mesh_node *n, uint64_t now, - uint8_t *frame, size_t len) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) n->data; - uint16_t dst = 0, src = 0; - unsigned command = mgi_mesh_b_frame_parse(frame, len, &dst, &src); - if (command == MGI_JOIN_DOWN && len == MG_MESH_FRAME_HDR_LEN && - dst == 0xffffu) { - if (n->joined && src == data->coordinator && - ++data->missed_rounds >= MG_MESH_MAX_MISSES) { - n->joined = false; - data->phase = MGI_TURN_IDLE; - data->tx_at = (uint64_t) -1; - data->tx_offset = 0; - data->rx_expected = 0xff; - } - if (!n->joined && (mgi_mesh_b_random(n, data) % 64) == 0) { - // Spread contenders across windows as well as within the reply window. - data->coordinator = src; - data->phase = MGI_TURN_JOIN; - data->tx_at = now + MGI_JOIN_TURN_US + - mgi_mesh_b_random(n, data) % MGI_JOIN_JITTER_US; - } - } else if (command == MGI_DATA_DOWN && data->coordinator != 0 && - dst == n->radio_address && src == data->coordinator) { - int received = mgi_mesh_b_data_receive(data, frame, len, now); - if (received < 0) return; - n->joined = true; - data->missed_rounds = - -1; // This round had a grant; do not count it as missed. - if (received != 0) { - struct mg_tcpip_if *ifp = n->radio; - if (n->rx_len != 0 || (size_t) received > ifp->recv_queue.size) { - ifp->ndrop++; - } else { - memcpy(ifp->recv_queue.buf, data->rx_buf, (size_t) received); - n->rx_len = (size_t) received; - } - } - if (data->tx_at != (uint64_t) -1) mgi_mesh_b_tx_finish(data); - mgi_mesh_b_tx_begin(data, mg_queue_next(&data->tx, NULL) != 0, now, - now + mgi_mesh_b_burst_time(MGI_ETH_MAX) + - 2 * s_mesh_default_radio->ifs_us + - MGI_JOIN_TURN_US); - data->answer_by = now + MG_MESH_ANSWER_TIMEOUT_US - MGI_ANSWER_MARGIN_US; - } -} - -// Receive timing counts from the frame's arrival, see mg_mesh_rx_drain(). -// Without an arrival time, e.g. when called directly, use the poll time -static void mgi_mesh_b_input(struct mg_mesh_node *node, void *buf, size_t len) { - uint64_t ready = node->now + node->strategy->radio->turnaround_us; - uint64_t arrived = node->rx_at != 0 ? node->rx_at : node->now; - if (node->tx_at < ready) node->tx_at = ready; - node->next_tick = node->now; - if (node->lan != NULL) { - mgi_mesh_b_bridge_rx(arrived, node, (const uint8_t *) buf, len); - } else { - mgi_mesh_b_node_rx(node, arrived, (uint8_t *) buf, len); - } -} - -static void mgi_mesh_b_tick(struct mg_mesh_node *node, uint64_t now) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) node->data; - node->now = now; - if (node->lan != NULL) { - mgi_mesh_b_bridge_io(now, node); - mgi_mesh_b_tx_step(data, now); - node->next_tick = data->deadline; - if (data->tx_at < node->next_tick) node->next_tick = data->tx_at; - return; - } - if (data->phase == MGI_TURN_JOIN) { - if (data->tx_at <= now) { - if (now - data->tx_at <= MGI_JOIN_TURN_US && !node->joined) - mgi_mesh_b_control_send(node, data->coordinator, MGI_JOIN_UP); - data->tx_at = (uint64_t) -1; - data->phase = MGI_TURN_IDLE; - } - } else { - mgi_mesh_b_tx_step(data, now); - } - node->next_tick = data->tx_at; -} - -static bool mgi_mesh_b_init(struct mg_mesh_node *node, - struct mg_tcpip_if *radio, struct mg_tcpip_if *lan, - uint16_t radio_address) { - struct mgi_mesh_b_data *data = - (struct mgi_mesh_b_data *) mg_calloc(1, sizeof(*data)); - memset(node, 0, sizeof(*node)); - node->radio = radio; - node->lan = lan; - node->radio_address = radio_address; - node->next_tick = (uint64_t) -1; - node->ram_used = node->ram_peak = sizeof(*node); - if (data == NULL) return false; - node->ram_used += sizeof(*data); - node->ram_peak = node->ram_used; - data->rx_expected = 0xff; - node->data = data; - data->node = node; - data->tx_at = (uint64_t) -1; - mg_queue_init(&data->tx, data->tx_buf, sizeof(data->tx_buf)); - if (lan != NULL) node->next_tick = 0; - return true; -} - -static void mgi_mesh_b_free(struct mg_mesh_node *node) { - struct mgi_mesh_b_data *data = (struct mgi_mesh_b_data *) node->data; - if (data == NULL) return; - mgi_mesh_b_bridge_free(data); - mg_free(data); - node->data = NULL; -} - -// Receive queue record: arrival time, then the radio frame -#define MGI_RX_STAMP_LEN sizeof(uint64_t) - -void mg_mesh_rx_queue(struct mg_queue *q, struct mg_tcpip_if *ifp, - const void *frame, size_t len) { - uint64_t arrived = mg_micros(); - size_t need = MGI_RX_STAMP_LEN + len; - char *dst; - - if (mg_queue_book(q, &dst, need) < need) { - if (ifp != NULL) ifp->ndrop++; - return; - } - memcpy(dst, &arrived, MGI_RX_STAMP_LEN); - memcpy(dst + MGI_RX_STAMP_LEN, frame, len); - mg_queue_add(q, need); -} - -void mg_mesh_rx_drain(struct mg_mesh_node *node, struct mg_queue *q) { - char *record; - size_t len; - - while (node->rx_len == 0) { - len = mg_queue_next(q, &record); - if (len == 0) break; - if (len > MGI_RX_STAMP_LEN) { - memcpy(&node->rx_at, record, MGI_RX_STAMP_LEN); - node->strategy->rx(node, record + MGI_RX_STAMP_LEN, - len - MGI_RX_STAMP_LEN); - node->rx_at = 0; - } - mg_queue_del(q, len); - } -} - -const struct mg_mesh mg_mesh_default = { - "default", - mgi_mesh_b_init, - mgi_mesh_b_tick, - mgi_mesh_b_free, - mgi_mesh_b_enqueue, - mgi_mesh_b_input, - true, - true, - &mg_radio_802154, -}; - -#endif diff --git a/src/l2_mesh.h b/src/l2_mesh.h deleted file mode 100644 index dc2f63b4..00000000 --- a/src/l2_mesh.h +++ /dev/null @@ -1,111 +0,0 @@ -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved -// -// Ethernet over radio, through a mesh. Mongoose sees an Ethernet interface, -// the mesh splits Ethernet frames into radio frames. Two parts plug in: -// - struct mg_radio: a radio standard, e.g. mg_radio_802154 -// - struct mg_mesh: how the mesh is built and routed - -#pragma once - -#include "net_builtin.h" - -#if MG_ENABLE_TCPIP - -// A radio standard -struct mg_radio { - const char *name; // For logs - size_t max_frame_size; // Largest radio frame, bytes - uint32_t bitrate; // Bits per second on air - size_t overhead; // Bytes on air besides the frame: preamble, FCS - uint32_t slot_us; // Random backoff slot duration, us - uint32_t cca_us; // Channel sensing duration, us - uint32_t turnaround_us; // Idle check to transmission start, us - uint32_t ifs_us; // Inter-frame spacing in us: gap between transmits - uint8_t backoff_min; // Initial backoff exponent - uint8_t backoff_max; // Maximum backoff exponent - bool csma; // Use channel sensing and backoff before TX - size_t header_len; // Radio hardware header length - // Write the radio header, with 0xffff as the broadcast address. - void (*print_hdr)(const struct mg_radio *radio, uint8_t *buf, uint16_t dst, - uint16_t src); - // Return the parsed header length, or zero for an invalid header. - size_t (*parse_hdr)(const struct mg_radio *radio, const uint8_t *buf, - size_t len, uint16_t *dst, uint16_t *src); -}; - -#define MG_802154_HEADER_LEN 9 // MAC header, short addresses -#define MG_802154_PAN_ID 0xabcd // Our network's PAN ID - -#ifndef MG_802154_CHANNEL -#define MG_802154_CHANNEL 15 -#endif - -// A turn's answer must arrive this soon after the turn's last frame ends on -// air, or the turn ends. A node that would answer later stays silent and keeps -// its frame for the next turn. Covers the node's poll latency, the radio -// turnaround and one full fragment's airtime, 4.3 ms on 802.15.4 -#ifndef MG_MESH_ANSWER_TIMEOUT_US -#define MG_MESH_ANSWER_TIMEOUT_US 8000 -#endif - -// A radio driver aborts a transmission that has not finished this soon, and -// lets the mesh go on as if the frame was sent -#ifndef MG_MESH_TX_TIMEOUT_US -#define MG_MESH_TX_TIMEOUT_US 60000 -#endif - -// Misses in a row before giving up, 1 to 127. The bridge removes a member -// that did not answer this many turns. A node leaves the mesh after this -// many rounds without a turn -#ifndef MG_MESH_MAX_MISSES -#define MG_MESH_MAX_MISSES 10 -#endif - -extern const struct mg_radio mg_radio_802154; - -struct mg_mesh_node { - struct mg_tcpip_if *radio; // Owning radio driver interface - struct mg_tcpip_if *lan; // Bridge LAN interface, NULL for a client - const struct mg_mesh *strategy; // Selected strategy - size_t (*tx)(struct mg_tcpip_if *, const void *, size_t); // Radio frame TX - size_t rx_len; // Complete Ethernet frame in the interface RX buffer - uint64_t now; // Current driver poll time, us - uint64_t rx_at; // Arrival time of the radio frame being handled, us - uint64_t tx_at; // Earliest next transmission, us - void *data; // Private state owned by the strategy - size_t ram_used; // Live mesh state bytes - size_t ram_peak; // Peak live mesh state bytes - uint64_t next_tick; // Next deadline in us, or UINT64_MAX - uint16_t radio_address; // Local address supplied by the radio - bool joined; // Client is a member of the mesh -}; - -struct mg_mesh { - const char *name; - bool (*init)(struct mg_mesh_node *node, struct mg_tcpip_if *radio, - struct mg_tcpip_if *lan, uint16_t radio_address); - void (*tick)(struct mg_mesh_node *node, uint64_t now_microseconds); - void (*free)(struct mg_mesh_node *node); - size_t (*tx)(struct mg_mesh_node *, const void *, size_t); // ETH frame TX - void (*rx)(struct mg_mesh_node *, void *, size_t); // Radio frame RX - bool single_bridge; // Require exactly one bridge - bool scheduled_tx; // The mesh schedules transmission turns - const struct mg_radio *radio; // Radio configuration for this strategy -}; - -extern const struct mg_mesh mg_mesh_default; - -// Put a received radio frame into the driver's receive queue, together with -// its arrival time from mg_micros(). Call it when the frame arrives, from the -// radio interrupt if the driver has one. If the queue is full, the frame is -// dropped and counted in ifp->ndrop -void mg_mesh_rx_queue(struct mg_queue *q, struct mg_tcpip_if *ifp, - const void *frame, size_t len); - -// Pass queued radio frames to the mesh, oldest first. Before each frame, -// node->rx_at is set to its arrival time. Stops while the node holds a -// received Ethernet frame the TCP/IP stack has not taken yet -void mg_mesh_rx_drain(struct mg_mesh_node *node, struct mg_queue *q); - -#endif diff --git a/src/net_builtin.c b/src/net_builtin.c index 1b2bfc04..bffb8709 100644 --- a/src/net_builtin.c +++ b/src/net_builtin.c @@ -250,6 +250,7 @@ void mg_tcpip_call(struct mg_tcpip_if *ifp, int ev, void *ev_data) { "TCPIP_EV_TIMER_1S", "TCPIP_EV_WIFI_SCAN_RESULT", "TCPIP_EV_WIFI_SCAN_END", "TCPIP_EV_WIFI_CONNECT_ERR", "TCPIP_EV_DRIVER", "TCPIP_EV_STATE6_CHANGE", + "TCPIP_EV_PHY_RX", "TCPIP_EV_PHY_TX", "TCPIP_EV_USER"}; if (ev != MG_TCPIP_EV_TIMER_1S && ev < (int) (sizeof(names) / sizeof(names[0]))) { MG_PROF_ADD(ifp, names[ev]); // TODO(): call MG_PROF_DUMP() MG_PROF_FREE() @@ -2291,7 +2292,6 @@ void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp) { } void mg_tcpip_init(struct mg_mgr *mgr, struct mg_tcpip_if *ifp) { - mg_usb_init(); // Early, so that the log reaches the USB serial port // If L2 address is not set, make a random one; fill MTU mg_l2_init(ifp); ifp->mtu = ifp->l2mtu; @@ -2458,7 +2458,6 @@ void mg_mgr_poll(struct mg_mgr *mgr, int ms) { mg_timer_poll(&mgr->timers, now); mg_ota_poll(mgr); mg_mdash_poll(mgr); - mg_usb_poll(); // Also without a TCP/IP interface: USB serial only if (mgr->ifp == NULL || mgr->ifp->driver == NULL) return; mg_tcpip_poll(mgr->ifp, now); for (c = mgr->conns; c != NULL; c = tmp) { diff --git a/src/net_builtin.h b/src/net_builtin.h index dc906e7d..f72337a1 100644 --- a/src/net_builtin.h +++ b/src/net_builtin.h @@ -40,6 +40,8 @@ enum { MG_TCPIP_EV_WIFI_CONNECT_ERR, // Wi-Fi connection failed driver and chip specific MG_TCPIP_EV_DRIVER, // Driver-defined event driver specific MG_TCPIP_EV_STATE6_CHANGE, // IPv6 link state changed uint8_t *(&ifp->state6) + MG_TCPIP_EV_PHY_RX, // Radio frame received struct mg_str * + MG_TCPIP_EV_PHY_TX, // Radio frame about to be sent struct mg_str * MG_TCPIP_EV_USER // Starting ID for user-defined events }; // clang-format on @@ -143,6 +145,7 @@ extern const uint8_t mcast_addr[6]; // Multicast MAC address programmed by driv #include "drivers/at_cmd.h" #include "drivers/cmsis.h" #include "drivers/cyw.h" +#include "drivers/esp32.h" #include "drivers/imxrt.h" #include "drivers/mcxw71.h" #include "drivers/mg24.h" @@ -163,7 +166,6 @@ extern const uint8_t mcast_addr[6]; // Multicast MAC address programmed by driv #include "drivers/w5500.h" #include "drivers/xmc.h" #include "drivers/xmc7.h" -#include "drivers/esp32_802154.h" // SPI bus abstraction for SPI-attached network chips (e.g. W5500). // Populate and assign to the driver's driver_data field. diff --git a/test/Makefile b/test/Makefile index 03f6279e..39a028aa 100644 --- a/test/Makefile +++ b/test/Makefile @@ -98,7 +98,7 @@ mongoose.c: Makefile $(wildcard ../src/*.c) $(wildcard ../src/drivers/*.c) cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#include "mongoose.h"' ; (for F in src/*.c src/drivers/*.c ; do echo; echo '#ifdef MG_ENABLE_LINES'; echo "#line 1 \"$$F\""; echo '#endif'; cat $$F | sed -e 's,#include ".*,,'; done))> $@ mongoose.h: $(HDRS) Makefile - cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; cat src/ai.h; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/lfs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_aes128.h src/tls_p256.h src/tls_p384.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/health.h src/mdash.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/l2_mesh.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@ + cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; cat src/ai.h; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/lfs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_aes128.h src/tls_p256.h src/tls_p384.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/health.h src/mdash.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@ # Check that all external (exported) symbols have "mg_" prefix mg_prefix: mongoose.c mongoose.h diff --git a/test/mesh/Makefile b/test/mesh/Makefile index cced5071..017c21b8 100644 --- a/test/mesh/Makefile +++ b/test/mesh/Makefile @@ -1,11 +1,12 @@ # Mesh simulator. `make` builds and runs an example ROOT = ../.. PROG ?= simulator -SRCS = simulator.c mesh_a.c $(ROOT)/mongoose.c -HDRS = simulator.h $(ROOT)/mongoose.h +SRCS = simulator.c # Includes mongoose.c +HDRS = simulator.h $(ROOT)/mongoose.h $(ROOT)/mongoose.c WARN = -pedantic -W -Wall -Werror -Wshadow -Wdouble-promotion -fno-common \ -Wconversion -Wundef -Wmissing-prototypes -Wstrict-prototypes DEFS = -DMG_ENABLE_TCPIP=1 -DMG_ENABLE_TCPIP_DRIVER_INIT=0 -DMG_ENABLE_IPV6=0 \ + -DMG_RADIO=MG_RADIO_802154 \ -DMG_ENABLE_CUSTOM_MICROS=1 -DMG_ENABLE_TCPIP_TCPRTX=1 \ -DMG_IO_SIZE=512 \ -DMG_TCPIP_ARP_MS=1000 -DMG_TCPIP_ACK_MS=500 # Slow radio: wait longer diff --git a/test/mesh/README.md b/test/mesh/README.md index ae083ef8..090395a0 100644 --- a/test/mesh/README.md +++ b/test/mesh/README.md @@ -1,324 +1,109 @@ -# Ethernet over a radio mesh +# Ethernet over radio simulator -## The idea +The simulator runs real Mongoose instances with a simulated 802.15.4 radio. +A bridge forwards Ethernet frames between the LAN and radio nodes. Each node +gets an address from a LAN DHCP server and answers HTTP requests from a LAN +client. The current protocol uses one bridge and direct radio hops. -Small radio devices, e.g. IEEE 802.15.4, sub-GHz or LoRa boards, should run -Mongoose as if they were on an ordinary Ethernet LAN: get an IP address over -DHCP, answer HTTP, talk MQTT. No 6LoWPAN, no Thread, no special stack. +## Shared driver -To do that, the radio mesh looks like an Ethernet switch to Mongoose. -One or more bridges connect the radio network to the wired LAN: a bridge has -an Ethernet port and a radio. A node in range of a bridge talks to it -directly; a node out of range reaches a bridge through other nodes, which -forward its frames. That makes the radio network a mesh. With several -bridges, each node uses one of them, e.g. the nearest; the mesh covers a -bigger area, and keeps working if a bridge goes down. A PC on the LAN sees -the radio nodes as regular hosts on the same LAN. +`src/drivers/radio.[ch]` implements joining, membership, turn scheduling, +Ethernet fragmentation/reassembly and bridge forwarding. `MG_RADIO` selects +raw BLE 2 Mbit/s or IEEE 802.15.4 framing and timing at compile time. -``` - PC --- LAN --- bridge ~~~ radio nodes -``` +Each hardware driver passes three functions to `mg_radio_init()`: -## Two parts plug in +- `hw_init(ifp, addr)`: initialize the radio; `addr` is the radio address. +- `hw_tx(ifp, buf, len)`: start one radio frame asynchronously; return its + length if accepted, or zero if busy. +- `hw_poll(ifp)`: service the hardware and report one TX completion or abort. -- `struct mg_radio` describes frame size, bitrate, airtime overhead, signal - parameters and channel-access timings. -- `struct mg_mesh` has `init`, `tick`, `free`, `tx` and `rx` callbacks. The most important - one is the `tick()` callback which is called with a microsecond timestamp, - obtained from `mg_micros()`, and handles routing and mesh management. - The mesh queues and fragments Ethernet frames and reassembles incoming radio - frames. Driver `tx()` queues Ethernet into the mesh; `rx()` returns a - reassembled Ethernet frame. A private callback transmits one radio frame. +Received frames go through `mg_radio_rx_queue()` at arrival time, including +when reception runs in an interrupt. PHY length bytes and CRC are excluded. +The queue preserves arrival timestamps so a delayed poll cannot answer an +expired grant. -The default slotted mesh in `../../src/l2_mesh.c` uses the bridge as a coordinator. -It opens windows for new nodes to join and gives joined nodes DATA turns -in round-robin order. +A hardware driver's init calls `mg_radio_init()` with those functions; its +`mg_tcpip_driver` uses `mg_radio_tx()`, `mg_radio_rx()` and `mg_radio_poll()` +directly. `mg_radio_init()` allocates the interface's +private state and stores it in `ifp->driver_data`. There is one built-in +scheduling protocol and no strategy callback table. -Mongoose calls driver's `poll()`. Radio driver calls `mg_micros()` to get -the current timestamp and calls `mg_mesh :: tick()`. +The interface's event handler, `ifp->fn`, gets `MG_TCPIP_EV_PHY_RX` for each +received radio frame and `MG_TCPIP_EV_PHY_TX` for each radio frame just before +it goes to the hardware. `ev_data` is a `struct mg_str *`, the frame. -The goal is to swap radios and mesh strategies without changing application -code. The slotted star deliberately omits radio ACKs to avoid -the extra airtime and radio turnaround. Other strategies may use them. +Call `mg_radio_bridge(radio, lan)` after both interfaces initialize. The bridge +reads the LAN receive queue and passes those Ethernet frames through the +radio interface's normal driver `tx()` function. Driver wrappers can therefore +count or translate Ethernet frames. Frames received from radio nodes are +forwarded through the LAN driver's `tx()` function. -## Why a simulator +The simulator embeds each radio interface as the first member of its hardware +state and calls the production API, including the timestamped receive queue. +It compiles `mongoose.c` into `simulator.c`, to read the private radio state +for its virtual clock. Radio state lives as long as the program. -Real boards are slow to test with, and you can't put 500 of them on a desk. -The simulator runs a whole network in one process: every node is a real -Mongoose instance, only the radio and the air between nodes are emulated. -That lets us try mesh strategies with many nodes, and measure how long it -takes nodes to join, get an address, and answer a request. +## Scheduling -## Virtual time +The bridge opens JOIN windows and grants DATA turns to members in round-robin +order. Nodes only send their data during grants. Joining uses randomized reply +timing. The protocol does not request radio ACKs or use CSMA. -The simulator exposes its virtual clock through `mg_micros()`. -TCP/IP reads the same clock through `mg_millis()`, rounded down to milliseconds. -Nothing waits for real time. `-t SEC` sets the duration, 10 minutes by default. - -Radio channel checks, transmission starts and ends run at their scheduled -microsecond timestamps. The clock jumps to the earliest radio event, mesh -deadline, or periodic stack poll. - -`STEP_MICROSECONDS` is 1000: periodic polling services Mongoose's internal -stack timers every millisecond. Packet delivery triggers immediate work: -the simulator repeatedly polls DHCP, the tester, bridges and nodes at the -same virtual timestamp until that work drains. Ethernet forwarding and -radio receive processing therefore do not wait for the periodic tick. -Internal timer handling can still be delayed by up to about 1 ms. - -## The setup - -``` - DHCP server ---------+ - 10.0.0.1 | - 02:01:00:00:00:00 +-- LAN ---- bridge ~~~ nodes - | - test node --------+ - 10.0.0.2 - 02:02:00:00:00:00 -``` - -The LAN is assumed infinitely fast, see "How frames move on the LAN" below. -Two nodes are on it: - -- The DHCP server, 10.0.0.1, MAC 02:01:00:00:00:00, gives each node an - address made from its MAC: 02:00:00:X:Y:Z gets 10.X+1.Y.Z, so node - addresses never clash with the LAN nodes' 10.0.0.x. It also answers - ARP requests for its advertised gateway IP, 10.0.0.1, so nodes can resolve - the gateway MAC and stop retrying. It does not implement IP routing, - and does not have a full Mongoose instance -- The test node, 10.0.0.2, MAC 02:02:00:00:00:00, is a Mongoose - instance. It waits for the mesh to settle, 60 seconds by default - (`-w SEC`), then sends `GET /` to each node in turn, one at a time, at the - node's own IP address. It wraps back to the first node and keeps querying - until five seconds before the end, when it stops starting new requests. - An in-flight request may still complete or time out during the remaining - time. Runs lasting five seconds or less start no requests. A node with - no address, a connection error, or a request exceeding 10 seconds counts - as failed. The summary reports successful and failed attempts, plus - minimum, mean and maximum response times for successful requests. A - request still pending at the end is not included in those counts. - -Bridges are on the LAN too, and get every frame, as if in promiscuous mode: -a frame for one of their radio nodes isn't addressed to the bridge itself. -A bridge forwards every frame from the LAN to the radio and every frame -from the radio to the LAN. - -Bridges and radio nodes get MACs 02:00:00:xx:xx:xx, numbered from 1 in -command-line order: 02:00:00:00:00:01, 02:00:00:00:00:02, and so on. - -### How frames move on the LAN - -Every LAN node, the DHCP server, the test node and each bridge, has a -LAN interface, `lif`: a `struct mg_tcpip_if` with a receive queue. All of -them use the same driver, `s_lan_driver`. There are no cables and no switch: - -- Sending. A node sends a frame with its driver's `tx`, which is - `lan_tx()`. It looks at the destination MAC and copies the frame into the - receive queues of the nodes it is for: - - a broadcast or multicast goes to every node but the sender; - - a unicast goes to the node with that MAC; - - bridges get every frame, as a real bridge in promiscuous mode would: - a frame for a radio node is addressed to the node, not to its bridge. -- Receiving. Each node takes the frames from its own queue when - the main loop polls it: - - the test node runs Mongoose, which reads the queue by itself, as it - would with a real Ethernet driver that queues frames from an interrupt; - - the DHCP server reads it in `dhcp_poll()`, and replies by sending - through its own `lif`; - - bridges read it in `bridges_poll()`, and forward it to the radio. - -Enqueuing marks immediate work pending. The main loop drains that work -without advancing virtual time, so the LAN has no simulated propagation, -serialization or polling delay. Sending never calls receiver code directly; -replies are processed by subsequent polls at the same timestamp. - -For example, a node asking for an address: - -1. The node's DHCP DISCOVER crosses the radio to a bridge, which sends it - out of its `lif`. It is a broadcast, so `lan_tx()` puts it into the - queues of the DHCP server, the test node and the other bridges. -2. On its next poll, the DHCP server reads it and sends an OFFER, also a - broadcast, which lands in the test node's and the bridges' queues. -3. On their next poll, the bridges read the OFFER and send it over the - radio to the node. The test node's Mongoose drops it: the test node - has a fixed address and no DHCP client. - -### How frames move on the radio - -The simulator keeps one accepted transmission per sender in a singly linked -list. A busy sender's driver returns zero, so the mesh retains the fragment -until the driver accepts it. Different senders can still overlap on air. - -1. A sender waits a random number of backoff slots, then listens for - `cca_us` to check whether the channel was idle throughout that interval. -2. If busy, it increases its backoff exponent up to `backoff_max`, waits - again, and repeats. There is no channel-access attempt limit yet. -3. If idle, it schedules transmission after `turnaround_us`. Another sender - can also pass its check before either starts: the channel check does not - reserve the air. -4. Transmission takes `(len + overhead) * 8 / bitrate` seconds, rounded up - to a microsecond. Overlapping transmissions are both marked collided. - Channel checks at the same timestamp run before transmission starts, - so list order cannot make one simultaneous check win. -5. At the end, a collided frame is dropped. Otherwise it is queued for all - other nodes for broadcast/multicast, or the matching node for unicast. - Every other bridge receives it too. Receive processing happens at the - same virtual timestamp. - -A receiver drops a frame if any part of that frame overlaps its own channel -backoff, sensing, turnaround or transmission interval, even if it is -available again when the frame ends. -The radio summary reports total sent and collided frames, and lost receptions. -Losses include range or random loss, plus missed unicast receptions when the -destination was transmitting. - -The 802.15.4 definition uses 250 kbit/s, 8 bytes overhead, 320 us backoff -slots, 128 us channel sensing and 100 us turnaround. The initial backoff -exponent is 3 (0–7 slots), increasing to 5 (0–31 slots) on busy checks. -After transmitting, a sender waits the radio's inter-frame spacing, -`mg_radio::ifs_us`, 640 us for 802.15.4, before starting its next frame's -backoff. This wait applies even if the frame collided or the sender's -queue was temporarily empty. Reception remains enabled during the -inter-frame wait. -The backoff generator is seeded from the wall clock. - -The mesh limits each transmission to 125 bytes plus the 2-byte FCS. -Overhead and inter-frame spacing apply to each fragment. -A receiver must be within `-range METRES` of the sender (default 185 m). -`-loss PERCENT` adds independent random loss for each in-range reception -(default 0%). The radio summary counts range and random losses together. -Collisions and channel sensing still apply across the whole simulated air. - -## Files - -| File | What | -|------|------| -| `../../src/l2_mesh.h`, `../../src/l2_mesh.c` | `struct mg_radio`, `struct mg_mesh`, shared node initialization, and IEEE 802.15.4 radio | -| `mesh_a.c` | Alternative unslotted star strategy | -| `simulator.h`, `simulator.c` | The simulator | -| `Makefile` | Builds and runs the simulator | - -## Where we are - -The slotted strategy uses direct radio hops between nodes and a bridge. -The simulator models airtime, half-duplex reception and collisions. - -- Frames outside reception range are not received, so nodes out of a bridge's - range never join. But collisions and channel sensing are still global: - every overlap is a collision, wherever the receiver is, and a busy - channel is busy for everyone. -- Mesh routing remains unimplemented: bridge selection, forwarding through other - nodes and recovery are not implemented. - -Next steps include distance-aware collision and channel sensing, mesh -routing and bridge filtering. - -## Strategy A — unslotted (simulator default) - -Each sender contends for the channel using CSMA. The mesh queues radio -fragments and submits them one at a time. The receiver reassembles bursts -per sender, and the bridge forwards Ethernet frames between LAN and radio. - -## Default strategy — slotted mesh - -One bridge coordinates the network and starts with an empty member list. -It broadcasts a JOIN beacon to open a 3 ms window. Unjoined nodes choose -windows at random and add up to 640 µs of jitter before sending their JOIN -request with their Ethernet MAC to the bridge. The bridge adds each new -radio address and its Ethernet MAC to the head of its member list. - -After the JOIN window, the bridge grants each member a DATA turn in list -order, then opens another JOIN window. The bridge advances as soon as it -reassembles a valid uplink. If the reply is missing, the turn times out -after allowing for the downlink and a maximum-size uplink burst, including -inter-frame spacing. A member must answer every turn, -with an empty `DATA_UP` if it has nothing to send. A member that misses 3 -turns in a row is removed. With no -members, the bridge opens JOIN windows back to back. A node recognizes its -first `DATA_DOWN` as -confirmation that it joined. - -Slotted nodes have a separate TCP/IP interface that reports link up after -the first grant. Each mesh interface has one 2 KiB TX queue of split -radio bursts. The bridge shares that queue among members and sends the -head burst in its destination's turn. It directs DHCP replies by the -client MAC in `chaddr` and keeps one copy of other multicast and broadcast -bursts until each member has had its turn. A frame that does not fit is -rejected in full. The hardware and simulator drivers accept one raw frame -at a time. JOIN messages fit in a single radio frame. A DATA -burst carries one Ethernet frame across up to 14 radio frames. Each -fragment has a 9-byte short-address MAC header, a one-byte type, and a -byte containing the fragment index and final index in the high and low -nibbles. Empty DATA messages use a single header-only frame. The node -starts its uplink after receiving the whole downlink, and the bridge -forwards only complete uplinks to the LAN. +Ethernet frames are fragmented into radio frames and reassembled at the +receiver. The bridge sends broadcasts separately to each member. A member is +removed after `MG_RADIO_TIMEOUT_MS` without an answer, counted from its first +missed turn; a node leaves after the same interval without a turn. +`MG_RADIO_ANSWER_TIMEOUT_US` bounds answers and `MG_RADIO_TX_TIMEOUT_US` bounds +hardware transmissions. All devices must share channel, network and PHY settings. ## Running ```sh -make # 100x100 m, a bridge, 11x11 nodes -make X=200 Y=50 ROWS=2 COLS=8 # Another area and grid +make -C test/mesh +# Smaller grid, 60 simulated seconds, 15 seconds to settle: +make -C test/mesh ROWS=2 COLS=2 ARGS="-t 60 -w 15" +# Explicit topology: +./test/mesh/simulator -bridge 50,50 -node 40,40 -node 60,60 -t 60 -w 15 +# Reception loss or limited range: +./test/mesh/simulator -bridge 50,50 -node 40,40 -loss 5 -t 60 -w 15 +./test/mesh/simulator -bridge 50,50 -node 99,99 -range 20 -t 60 -w 15 ``` -`make` puts a bridge in the middle of the area, and a node at every corner -of a `ROWS` x `COLS` grid over it. The simulator itself takes: +The simulator requires exactly one bridge. Positions are `X,Y` or `X,Y,Z` in +metres, within the `-area` box. Default radio range is 185 metres; `-loss` sets +independent reception loss in percent. Overlapping transmissions collide +across the simulated channel. Reception is half duplex. Nodes outside range +cannot join. There is no multi-hop forwarding. -``` -./mesh_sim -area X,Y,Z -bridge X,Y,Z -node X,Y,Z ... -t SEC -w SEC -m A|default -range METRES -loss PERCENT -``` +Time is virtual: the clock jumps between radio events, protocol deadlines and +periodic stack polls. `mg_micros()` exposes that clock; periodic stack polls +occur every millisecond. The LAN is infinitely fast. A LAN DHCP server uses +10.0.0.1 and the HTTP tester uses 10.0.0.2. After `-w` seconds the tester cycles +through nodes until five seconds before the end of `-t`. The summary reports +successful/failed requests, latency, radio transmissions, collisions, reception +loss and how many nodes joined and acquired addresses. -Positions are in metres; `X,Y` means `Z` is 0. Repeat `-bridge` and `-node` -for more. +## Hardware examples -## Hardware +- `tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge`: USB Ethernet to BLE bridge. +- `tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge`: Ethernet to radio bridge. +- `tutorials/nordic/xiao-nrf52840/minimal`: radio node. +- `tutorials/silabs/xiao-mg24/minimal`: radio node. +- `tutorials/nxp/frdm-mcxw71/minimal`: radio node. -The FRDM-RW612 example is the Ethernet bridge. The XIAO MG24 and -FRDM-MCXW71 examples are radio clients. All three use the slotted mesh. +Hardware backends are `nrf52`, `mg24`, `mcxw71`, `rw612w`, and `esp32` in +`src/drivers`. Board HALs provide the microsecond clock. The bridge owns LAN +initialization, its receive queue and any promiscuous-mode configuration. + +MCXW71 supports raw BLE 2 Mbit/s through GENFSK, without a Bluetooth stack, +and 802.15.4 through ZLL. Its minimal example defaults to BLE: ```sh -make -C tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge -make -C tutorials/silabs/xiao-mg24/minimal -make -C tutorials/nxp/frdm-mcxw71/minimal +make -C tutorials/nxp/frdm-mcxw71/minimal build +make -C tutorials/nxp/frdm-mcxw71/minimal build CFLAGS_EXTRA=-DMG_RADIO=MG_RADIO_802154 ``` -Use each tutorial's `flash` target. Connect the -bridge to an Ethernet LAN with a DHCP server. Find the client's assigned -IP in its serial log, then send an HTTP GET to that IP from the LAN. - -All three boards use channel 15 and PAN `0xabcd` by default. Each board derives its radio address from its Ethernet MAC. -MG24 is a node only; its radio address is derived from its MAC. - -The drivers in `src/drivers` send and receive raw 802.15.4 frames. -They use the same slotted mesh implementation as the simulator. -The board driver is initialized by `mg_mgr_init()`. The RW612 bridge -has its own `ethernet-to-802.15.4-bridge/main.c`, which initializes and polls the two drivers -directly, without an event manager or local IP stack. - -## Hardware integration - -The default mesh and radio drivers are included in `mongoose.c` and `mongoose.h`. -Radio drivers live in `src/drivers/`: `mg24`, `mcxw71`, `rw612w`, -and `nrf52`. MG24 driver data contains its mesh state and `strategy`; it has -no bridge LAN interface. -A NULL strategy selects `mg_mesh_default`, named `"default"`; assigning another -`const struct mg_mesh *` overrides it. Hardware callbacks transmit and receive -raw radio frames; the selected strategy owns joining, scheduling and Ethernet -fragmentation. Driver initialization goes through `mg_tcpip_init()`. - -Board examples are under `tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge`, -`tutorials/nxp/frdm-mcxw71/minimal`, `tutorials/silabs/xiao-mg24/minimal`, and -`tutorials/nordic/xiao-52840/minimal`. Their HALs supply `mg_micros()`. - -The simulator and all radio drivers keep the hardware driver installed throughout the -interface lifetime. Mesh state belongs to `driver_data`. Driver `tx()` queues -Ethernet frames; `poll()` feeds raw received frames to the mesh and calls -strategy `tick()`. The strategy sends scheduled fragments through the driver's -private `radio_tx` callback. Driver `rx()` returns a reassembled Ethernet frame -using the stack's existing receive buffer. There is no mesh polling timer, -copied radio interface, or mesh-specific change in `net_builtin.*`. -The simulator explicitly frees its mesh state after `mg_mgr_free()`; board -drivers keep their state for the firmware lifetime. MG24, MCXW71 and nRF52 are -radio nodes. The RW612 bridge application owns Ethernet initialization, its RX -queue, promiscuous mode and link polling, and attaches the LAN to the mesh. -The RW612W driver owns only the radio interface. +The HAL initializes the selected PHY and BLE whitening seed. Other boards +using this driver must provide equivalent transceiver setup. All communicating +nodes must use the same PHY, channel and network/access address. diff --git a/test/mesh/mesh_a.c b/test/mesh/mesh_a.c deleted file mode 100644 index e901d8d4..00000000 --- a/test/mesh/mesh_a.c +++ /dev/null @@ -1,261 +0,0 @@ -// Copyright (c) 2026 Cesanta Software Limited -// All rights reserved - -#include "mongoose.h" - -// Radio header followed by type and fragment index/last index. -#define MGI_FRAME_HDR_LEN (MG_802154_HEADER_LEN + 2) - -#define MGI_ETH_MAX 1514 -#define MGI_TX_DST_LEN 2 - -#define MGI_RX_TIMEOUT_US 1000000 -#define MGI_TX_QUEUE_SIZE 4096 -#define MGI_DATA_TAG \ - 0x80u // High bit identifies DATA, low seven bits tag a burst - -struct mgi_mesh_a_rx { - struct mgi_mesh_a_rx *next; - uint64_t expires; - uint16_t src; - uint8_t tag, index, last; - size_t len; - uint8_t buf[MGI_ETH_MAX]; -}; - -struct mgi_mesh_a_data { - struct mg_mesh_node *node; - struct mg_tcpip_if *ethernet; - struct mgi_mesh_a_rx *rx; - uint8_t tag; - struct mg_queue tx; - char tx_buf[MGI_TX_QUEUE_SIZE]; - size_t tx_offset; - uint64_t tx_at; -}; - -static const struct mg_radio *const s_radio = &mg_radio_802154; - -static uint64_t mgi_mesh_a_airtime(size_t len) { - const struct mg_radio *radio = &mg_radio_802154; - return ((uint64_t) (len + radio->overhead) * 8000000 + radio->bitrate - 1) / - radio->bitrate; -} - -// Each queue record holds a destination and a complete burst. -static size_t mgi_mesh_a_queue(struct mg_mesh_node *node, struct mg_queue *q, - const void *buf, size_t len, uint16_t dst, uint8_t type) { - const struct mg_radio *radio = &mg_radio_802154; - const uint8_t *eth = (const uint8_t *) buf; - size_t hdr = MGI_FRAME_HDR_LEN, cap = radio->max_frame_size - hdr; - size_t frames, size, i; - char *record; - uint8_t *out; - if (len < 14 || len > MGI_ETH_MAX) return 0; - frames = (len + cap - 1) / cap; - size = MGI_TX_DST_LEN + len + frames * (1 + hdr); - if (mg_queue_next(q, NULL) == 0) mg_queue_init(q, q->buf, q->size); - if (mg_queue_book(q, &record, size) < size) return 0; - out = (uint8_t *) record; - *out++ = (uint8_t) (dst >> 8); - *out++ = (uint8_t) dst; - for (i = 0; i < frames; i++) { - size_t chunk = len - i * cap; - if (chunk > cap) chunk = cap; - *out++ = (uint8_t) (hdr + chunk); - radio->print_hdr(radio, out, dst, node->radio_address); - out[radio->header_len] = type; - out[radio->header_len + 1] = (uint8_t) (i << 4 | (frames - 1)); - memcpy(out + hdr, eth + i * cap, chunk); - out += hdr + chunk; - } - mg_queue_add(q, size); - return len; -} - -static size_t mgi_mesh_a_send(struct mgi_mesh_a_data *data, const void *buf, - size_t len) { - uint8_t tag = (uint8_t) ((data->tag + 1) & 0x7f); - size_t queued = mgi_mesh_a_queue(data->node, &data->tx, buf, len, 0xffffu, - (uint8_t) (MGI_DATA_TAG | tag)); - if (queued != 0) data->tag = tag; - return queued; -} - -static void mgi_mesh_a_tx(struct mgi_mesh_a_data *data, uint64_t now) { - struct mg_tcpip_if *radio = data->node->radio; - char *record; - size_t size = mg_queue_next(&data->tx, &record); - if (size == 0) return; - if (now >= data->tx_at) { - const uint8_t *part = (const uint8_t *) record + data->tx_offset; - size_t len = part[0]; - if (now >= data->node->tx_at && - data->node->tx(radio, part + 1, len) == len) { - data->tx_offset += len + 1; - if (data->tx_offset == size) { - mg_queue_del(&data->tx, size); - data->tx_offset = MGI_TX_DST_LEN; - } - data->tx_at = now + mgi_mesh_a_airtime(len) + s_radio->ifs_us; - } else { - data->tx_at = now + s_radio->slot_us; - } - } - if (mg_queue_next(&data->tx, NULL) != 0) data->node->next_tick = data->tx_at; -} - -static size_t mgi_mesh_a_enqueue(struct mg_mesh_node *node, const void *buf, - size_t len) { - return mgi_mesh_a_send(node->data, buf, len); -} - -static void mgi_mesh_a_deliver(struct mgi_mesh_a_data *data, uint8_t *buf, - size_t len) { - struct mg_tcpip_if *lan = data->node->lan; - if (len < 14) return; - if (lan != NULL) { - lan->driver->tx(buf, len, lan); - } else { - struct mg_tcpip_if *ifp = data->node->radio; - if (data->node->rx_len != 0 || len > ifp->recv_queue.size) { - ifp->ndrop++; - } else { - memcpy(ifp->recv_queue.buf, buf, len); - data->node->rx_len = len; - } - } -} - -static void mgi_mesh_a_rx_free(struct mgi_mesh_a_data *data, - struct mgi_mesh_a_rx **p) { - struct mgi_mesh_a_rx *r = *p; - *p = r->next; - data->node->ram_used -= sizeof(*r); - free(r); -} - -static void mgi_mesh_a_receive(struct mgi_mesh_a_data *data, uint8_t *frame, - size_t len, uint64_t now) { - struct mgi_mesh_a_rx **p = &data->rx, *r; - size_t cap = s_radio->max_frame_size - MGI_FRAME_HDR_LEN, chunk; - uint16_t dst, src; - uint8_t tag, index, last; - if (len <= MGI_FRAME_HDR_LEN || len > s_radio->max_frame_size || - s_radio->parse_hdr(s_radio, frame, len, &dst, &src) != - s_radio->header_len || - (dst != 0xffffu && dst != data->node->radio_address)) - return; - tag = frame[MGI_FRAME_HDR_LEN - 2]; - index = frame[MGI_FRAME_HDR_LEN - 1] >> 4; - last = frame[MGI_FRAME_HDR_LEN - 1] & 15; - chunk = len - MGI_FRAME_HDR_LEN; - if ((tag & MGI_DATA_TAG) == 0 || index > last || - last > (MGI_ETH_MAX - 1) / cap || (index < last && chunk != cap)) - return; - if (index == 0 && - (chunk < 14 || - (data->node->lan == NULL && (frame[MGI_FRAME_HDR_LEN] & 1) == 0 && - memcmp(frame + MGI_FRAME_HDR_LEN, data->ethernet->mac, 6) != 0))) - return; - while (*p != NULL && (*p)->src != src) p = &(*p)->next; - if (index == 0) { - if (*p != NULL) mgi_mesh_a_rx_free(data, p); - if (last == 0) { - mgi_mesh_a_deliver(data, frame + MGI_FRAME_HDR_LEN, chunk); - return; - } - r = calloc(1, sizeof(*r)); - if (r == NULL) return; - data->node->ram_used += sizeof(*r); - if (data->node->ram_peak < data->node->ram_used) - data->node->ram_peak = data->node->ram_used; - r->next = *p; - *p = r; - r->src = src; - r->tag = tag; - r->last = last; - } - r = *p; - if (r == NULL || r->tag != tag) return; - if (r->index != index || r->last != last || chunk > sizeof(r->buf) - r->len) { - mgi_mesh_a_rx_free(data, p); - return; - } - memcpy(r->buf + r->len, frame + MGI_FRAME_HDR_LEN, chunk); - r->len += chunk; - r->index++; - r->expires = now + MGI_RX_TIMEOUT_US; - if (index == last) { - mgi_mesh_a_deliver(data, r->buf, r->len); - mgi_mesh_a_rx_free(data, p); - } -} - -static void mgi_mesh_a_input(struct mg_mesh_node *node, void *buf, size_t len) { - uint64_t ready = node->now + node->strategy->radio->turnaround_us; - if (node->tx_at < ready) node->tx_at = ready; - node->next_tick = node->now; - mgi_mesh_a_receive(node->data, buf, len, node->now); -} - -static void mgi_mesh_a_tick(struct mg_mesh_node *node, uint64_t now) { - struct mgi_mesh_a_data *data = node->data; - struct mgi_mesh_a_rx **p = &data->rx; - size_t len; - node->now = now; - node->next_tick = (uint64_t) -1; - while (*p != NULL) { - if ((*p)->expires <= now) - mgi_mesh_a_rx_free(data, p); - else - p = &(*p)->next; - } - if (node->lan != NULL) { - struct mg_queue *q = &node->lan->recv_queue; - char *buf; - while ((len = mg_queue_next(q, &buf)) > 0) { - mgi_mesh_a_send(data, buf, len); - mg_queue_del(q, len); - } - } - mgi_mesh_a_tx(data, now); - for (p = &data->rx; *p != NULL; p = &(*p)->next) { - if ((*p)->expires < node->next_tick) node->next_tick = (*p)->expires; - } -} - -static void mgi_mesh_a_free(struct mg_mesh_node *node) { - struct mgi_mesh_a_data *data = node->data; - if (data == NULL) return; - while (data->rx != NULL) mgi_mesh_a_rx_free(data, &data->rx); - free(data); - node->data = NULL; -} - -static bool mgi_mesh_a_init(struct mg_mesh_node *node, - struct mg_tcpip_if *radio, struct mg_tcpip_if *lan, - uint16_t radio_address) { - struct mgi_mesh_a_data *data = calloc(1, sizeof(*data)); - memset(node, 0, sizeof(*node)); - node->radio = radio; - node->lan = lan; - node->radio_address = radio_address; - node->next_tick = (uint64_t) -1; - node->ram_used = node->ram_peak = sizeof(*node); - if (data == NULL) return false; - node->ram_used += sizeof(*data); - node->ram_peak = node->ram_used; - data->node = node; - data->tx_offset = MGI_TX_DST_LEN; - node->data = data; - mg_queue_init(&data->tx, data->tx_buf, sizeof(data->tx_buf)); - data->ethernet = radio; - node->joined = lan == NULL; - return true; -} - -const struct mg_mesh mg_mesh_a = { - "A", mgi_mesh_a_init, mgi_mesh_a_tick, mgi_mesh_a_free, - mgi_mesh_a_enqueue, mgi_mesh_a_input, false, false, &mg_radio_802154, -}; diff --git a/test/mesh/simulator.c b/test/mesh/simulator.c index 6c6822e4..408b7462 100644 --- a/test/mesh/simulator.c +++ b/test/mesh/simulator.c @@ -6,10 +6,25 @@ // sends HTTP requests to the nodes #include "simulator.h" +#include "mongoose.c" // One unit: the simulator reads the private radio state + +// The radio state of an interface +static struct mg_radio_node *sim_node(struct mg_tcpip_if *ifp) { + return (struct mg_radio_node *) ifp->driver_data; +} + +// When the radio state needs its next poll, us: its next fragment, or for a +// bridge, the end of the current turn if sooner +static uint64_t sim_next_tick(struct mg_tcpip_if *ifp) { + struct mg_radio_node *node = sim_node(ifp); + if (node->lan != NULL && node->deadline < node->burst_at) { + return node->deadline; + } + return node->burst_at; +} #define STEP_MICROSECONDS 1000 // Periodic stack timer polling only -static const struct mg_mesh *s_mesh = &mg_mesh_default; static struct simulator s_sim; // The simulator // Mongoose's clock: virtual time. A minute of network traffic takes far less @@ -43,8 +58,7 @@ static void usage(const struct simulator *sim, const char *prog) { " -t SEC - simulated time, seconds, default: %g\n" " -w SEC - mesh settle time before requests, default: %g\n" " -range METRES - radio range, default: %g\n" - " -loss PERCENT - random reception loss, default: %g\n" - " -m A|default - mesh strategy, default: default\n", + " -loss PERCENT - random reception loss, default: %g\n", prog, sim->area.x, sim->area.y, sim->area.z, (double) (int64_t) sim->duration / 1e6, (double) (int64_t) sim->tester.wait / 1e6, sim->radio_range, @@ -64,8 +78,7 @@ static bool add_bridge(struct simulator *sim, const char *s) { struct bridge *b = (struct bridge *) calloc(1, sizeof(*b)); if (b == NULL || !parse_pos(s, &b->pos)) return free(b), false; if (sim->last_mac >= 0xffffu - 1u) return free(b), false; - next_mac(sim, b->rif.mac); - b->radio.address = (uint16_t) sim->last_mac; + next_mac(sim, b->radio.ifp.mac); LIST_ADD_TAIL(struct bridge, &sim->bridges, b); sim->num_bridges++; return true; @@ -76,8 +89,7 @@ static bool add_node(struct simulator *sim, const char *s) { struct radio_node *n = (struct radio_node *) calloc(1, sizeof(*n)); if (n == NULL || !parse_pos(s, &n->pos)) return free(n), false; if (sim->last_mac >= 0xffffu - 1u) return free(n), false; - next_mac(sim, n->rif.mac); - n->radio.address = (uint16_t) sim->last_mac; + next_mac(sim, n->radio.ifp.mac); LIST_ADD_TAIL(struct radio_node, &sim->nodes, n); sim->num_nodes++; return true; @@ -323,50 +335,17 @@ static void init(struct simulator *sim) { // two idle checks can succeed before either node starts transmitting. // Inter-frame spacing is per sender, not a reservation of the shared air. uint64_t radio_airtime(size_t len) { - const struct mg_radio *radio = s_mesh->radio; - return ((uint64_t) (len + radio->overhead) * 8000000 + radio->bitrate - 1) / - radio->bitrate; -} - -static void radio_schedule(struct simulator *sim, struct radio_frame *f, - bool busy) { - struct radio_port *port = (struct radio_port *) f->from->driver_data; - const struct mg_radio *radio = s_mesh->radio; - bool checked = f->state == RADIO_CCA; - if (s_mesh->scheduled_tx || !radio->csma || (checked && !busy)) { - f->state = RADIO_START; - f->due = sim->now + (checked ? radio->turnaround_us : 0); - return; - } - if (!checked) { - f->backoff = radio->backoff_min; - } else if (f->backoff < radio->backoff_max) { - f->backoff++; - } - if (port->random == 0) { - size_t i; - port->random = (uint32_t) mg_now(); - for (i = 0; i < 6; i++) { - port->random = port->random * 33u + f->from->mac[i]; - } - if (port->random == 0) port->random = 1; - } - port->random ^= port->random << 13; - port->random ^= port->random >> 17; - port->random ^= port->random << 5; - f->state = RADIO_BACKOFF; - f->due = sim->now + (port->random % (1U << f->backoff)) * radio->slot_us; - if (f->due > sim->now) port->rx_off_until = f->due; + return ((uint64_t) (len + SIM_RADIO_OVERHEAD) * 8000000 + SIM_RADIO_BITRATE - + 1) / + SIM_RADIO_BITRATE; } static size_t radio_send(struct mg_tcpip_if *ifp, const void *buf, size_t len) { - struct radio_port *port = (struct radio_port *) ifp->driver_data; + struct radio_port *port = (struct radio_port *) ifp; struct simulator *sim = port->sim; struct radio_frame *f, **p = &sim->air_head; - const struct mg_radio *radio = s_mesh->radio; - if (len < radio->header_len || len > sizeof(f->buf) || - len > radio->max_frame_size || port->tx_ready_at > sim->now || - radio->bitrate == 0) + if (len < SIM_RADIO_HDR_LEN || len > SIM_RADIO_MTU || + port->tx_ready_at > sim->now) return 0; while (*p != NULL) { if ((*p)->from == ifp) return 0; @@ -377,18 +356,15 @@ static size_t radio_send(struct mg_tcpip_if *ifp, const void *buf, size_t len) { memcpy(f->buf, buf, len); *p = f; sim->work_pending = true; - radio_schedule(sim, f, false); + f->state = RADIO_START; + f->due = sim->now; return len; } static void radio_receive(struct radio_port *port, const struct radio_frame *f) { - char *buf; - if (mg_queue_book(&port->rx, &buf, f->len) >= f->len) { - memcpy(buf, f->buf, f->len); - mg_queue_add(&port->rx, f->len); - port->sim->work_pending = true; - } + mg_radio_rx_queue(&port->ifp, f->buf, f->len); + port->sim->work_pending = true; } // Test range and sample independent interference loss for this reception. @@ -408,7 +384,8 @@ static void radio_deliver_to(struct radio_port *port, const struct radio_port *from, const struct radio_frame *f, uint16_t dst) { bool all = dst == 0xffffu; - if (port == from || (!all && port->address != dst)) return; + if (port == from || (!all && sim_node(&port->ifp)->radio_address != dst)) + return; if (!visible(port->sim, from->pos, port->pos)) { port->sim->air_lost++; } else if (port->tx_until > f->start) { @@ -419,12 +396,11 @@ static void radio_deliver_to(struct radio_port *port, } static void radio_deliver(struct simulator *sim, const struct radio_frame *f) { - const struct mg_radio *radio = s_mesh->radio; - const struct radio_port *from = f->from->driver_data; + const struct radio_port *from = (const struct radio_port *) f->from; uint16_t dst, src; struct bridge *b; struct radio_node *n; - if (radio->parse_hdr(radio, f->buf, f->len, &dst, &src) == 0) return; + if (!sim_parse_hdr(f->buf, f->len, &dst, &src)) return; for (b = sim->bridges; b != NULL; b = b->next) radio_deliver_to(&b->radio, from, f, dst); for (n = sim->nodes; n != NULL; n = n->next) @@ -443,33 +419,19 @@ static void radio_poll(struct simulator *sim) { if (f->collided) { sim->air_collisions++; } + ((struct radio_port *) f->from)->tx_done = true; radio_deliver(sim, f); *p = f->next; free(f); } for (f = sim->air_head; f != NULL; f = f->next) { - if (f->state == RADIO_BACKOFF && f->due <= sim->now) { - f->state = RADIO_CCA; - f->due = sim->now + s_mesh->radio->cca_us; - ((struct radio_port *) f->from->driver_data)->rx_off_until = f->due; - } - } - for (f = sim->air_head; f != NULL; f = f->next) { - if (f->state != RADIO_CCA || f->due > sim->now) continue; - radio_schedule(sim, f, - sim->air_busy_until > sim->now - s_mesh->radio->cca_us); - if (f->state == RADIO_START) { - ((struct radio_port *) f->from->driver_data)->rx_off_until = f->due; - } - } - for (f = sim->air_head; f != NULL; f = f->next) { - struct radio_port *port = f->from->driver_data; + struct radio_port *port = (struct radio_port *) f->from; if (f->state != RADIO_START || f->due > sim->now) continue; f->state = RADIO_END; f->start = sim->now; f->due = sim->now + radio_airtime(f->len); port->rx_off_until = port->tx_until = f->due; - port->tx_ready_at = f->due + s_mesh->radio->ifs_us; + port->tx_ready_at = f->due + SIM_RADIO_IFS_US; for (g = sim->air_head; g != NULL; g = g->next) { if (g != f && g->state == RADIO_END && g->due > sim->now) { f->collided = g->collided = true; @@ -489,83 +451,41 @@ static uint64_t radio_next(const struct simulator *sim, uint64_t next) { return next; } -static size_t radio_receive_frame(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct radio_port *port = (struct radio_port *) ifp->driver_data; - char *src; - size_t len; - while ((len = mg_queue_next(&port->rx, &src)) > 0) { - if (len <= cap) memcpy(buf, src, len); - mg_queue_del(&port->rx, len); - if (len <= cap) { - if (mg_queue_next(&port->rx, &src) > 0) port->sim->work_pending = true; - return len; - } - } - return 0; +static bool radio_hw_poll(struct mg_tcpip_if *ifp) { + struct radio_port *port = (struct radio_port *) ifp; + bool done = port->tx_done; + port->tx_done = false; + return done; } -static size_t radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { - struct radio_port *port = ifp->driver_data; - return port->mesh->strategy->tx(port->mesh, buf, len); -} - -static size_t radio_rx(void *buf, size_t cap, struct mg_tcpip_if *ifp) { - struct radio_port *port = ifp->driver_data; - size_t len = port->mesh->rx_len; - if (len > cap) return 0; - if (len != 0 && buf != ifp->recv_queue.buf) - memcpy(buf, ifp->recv_queue.buf, len); - port->mesh->rx_len = 0; - return len; -} - -static bool radio_driver_poll(struct mg_tcpip_if *ifp, bool s1) { - struct radio_port *port = ifp->driver_data; - uint8_t frame[128]; - size_t len; - (void) s1; - port->mesh->now = mg_micros(); - while (port->mesh->rx_len == 0 && - (len = radio_receive_frame(frame, sizeof(frame), ifp)) != 0) - port->mesh->strategy->rx(port->mesh, frame, len); - s_mesh->tick(port->mesh, mg_micros()); - return port->mesh->joined; -} - -static bool radio_init(struct mg_tcpip_if *ifp) { - struct radio_port *port = ifp->driver_data; - char *buf = malloc(LAN_QUEUE_SIZE); - if (buf == NULL) return false; - mg_queue_init(&port->rx, buf, LAN_QUEUE_SIZE); - port->mesh = calloc(1, sizeof(*port->mesh)); - if (port->mesh == NULL || - !s_mesh->init(port->mesh, ifp, port->lan, port->address)) { - free(port->mesh); - port->mesh = NULL; - free(buf); - port->rx.buf = NULL; - return false; - } - port->mesh->strategy = s_mesh; - port->mesh->tx = radio_send; +static bool radio_hw_init(struct mg_tcpip_if *ifp, uint16_t addr) { + (void) ifp, (void) addr; return true; } -static struct mg_tcpip_driver s_radio_driver = { - radio_init, radio_tx, radio_rx, radio_driver_poll}; +static bool radio_init(struct mg_tcpip_if *ifp) { + struct radio_port *port = (struct radio_port *) ifp; + if (!mg_radio_init(ifp, radio_hw_init, radio_hw_poll, radio_send)) + return false; + if (port->lan != NULL) mg_radio_bridge(ifp, port->lan); + return true; +} -#define MG_TCPIP_DRIVER_SIM_RADIO_INIT(manager, interface) \ - do { \ - struct mg_tcpip_if *mif_ = (interface); \ - mif_->mgr = (manager); \ - mg_tcpip_init((manager), mif_); \ +static struct mg_tcpip_driver s_radio_driver = {radio_init, mg_radio_tx, + mg_radio_rx, mg_radio_poll}; + +#define MG_TCPIP_DRIVER_SIM_RADIO_INIT(manager, interface) \ + do { \ + struct mg_tcpip_if *mif_ = (interface); \ + mif_->mgr = (manager); \ + mg_tcpip_init((manager), mif_); \ MG_INFO(("Driver: sim_radio, MAC: %M", mg_print_mac, mif_->mac)); \ } while (0) -#define MG_TCPIP_DRIVER_SIM_LAN_INIT(manager, interface) \ - do { \ - struct mg_tcpip_if *mif_ = (interface); \ - mg_tcpip_init((manager), mif_); \ +#define MG_TCPIP_DRIVER_SIM_LAN_INIT(manager, interface) \ + do { \ + struct mg_tcpip_if *mif_ = (interface); \ + mg_tcpip_init((manager), mif_); \ MG_INFO(("Driver: sim_lan, MAC: %M", mg_print_mac, mif_->mac)); \ } while (0) @@ -584,12 +504,11 @@ static void node_http_ev_handler(struct mg_connection *c, int ev, static void nodes_init(struct simulator *sim) { struct radio_node *n; for (n = sim->nodes; n != NULL; n = n->next) { - n->rif.driver = &s_radio_driver; - n->rif.driver_data = &n->radio; + n->radio.ifp.driver = &s_radio_driver; n->radio.sim = sim; n->radio.pos = &n->pos; mg_mgr_init(&n->mgr); - MG_TCPIP_DRIVER_SIM_RADIO_INIT(&n->mgr, &n->rif); + MG_TCPIP_DRIVER_SIM_RADIO_INIT(&n->mgr, &n->radio.ifp); if (n->mgr.ifp != NULL) { mg_http_listen(&n->mgr, "http://0.0.0.0:80", node_http_ev_handler, n->mgr.ifp->mac); @@ -601,13 +520,12 @@ static void nodes_init(struct simulator *sim) { static void bridges_init(struct simulator *sim) { struct bridge *b; for (b = sim->bridges; b != NULL; b = b->next) { - b->lif.driver = &s_lan_driver, b->rif.driver = &s_radio_driver; - b->rif.driver_data = &b->radio; + b->lif.driver = &s_lan_driver, b->radio.ifp.driver = &s_radio_driver; b->radio.sim = sim; b->radio.pos = &b->pos; mg_mgr_init(&b->mgr); b->radio.lan = &b->lif; - MG_TCPIP_DRIVER_SIM_RADIO_INIT(&b->mgr, &b->rif); + MG_TCPIP_DRIVER_SIM_RADIO_INIT(&b->mgr, &b->radio.ifp); mg_queue_init(&b->lif.recv_queue, (char *) calloc(1, LAN_QUEUE_SIZE), LAN_QUEUE_SIZE); b->lif.driver->init(&b->lif); @@ -647,25 +565,17 @@ int main(int argc, char *argv[]) { s_sim.radio_loss = value; else s_sim.radio_range = value; - } else if (strcmp(argv[i], "-m") == 0) { - const char *name = argv[++i]; - if (strcmp(name, mg_mesh_a.name) == 0) - s_mesh = &mg_mesh_a; - else if (strcmp(name, mg_mesh_default.name) == 0) - s_mesh = &mg_mesh_default; - else - usage(&s_sim, argv[0]); } else { usage(&s_sim, argv[0]); } } printf("Area %gx%gx%g m, radio %s, mesh %s, bridges: %d, nodes: %d\n", - s_sim.area.x, s_sim.area.y, s_sim.area.z, s_mesh->radio->name, - s_mesh->name, s_sim.num_bridges, s_sim.num_nodes); + s_sim.area.x, s_sim.area.y, s_sim.area.z, "802.15.4", "default", + s_sim.num_bridges, s_sim.num_nodes); check_area(&s_sim); - if (s_mesh->single_bridge && s_sim.num_bridges != 1) { - fprintf(stderr, "%s requires exactly one bridge\n", s_mesh->name); + if (s_sim.num_bridges != 1) { + fprintf(stderr, "%s requires exactly one bridge\n", "default"); return EXIT_FAILURE; } @@ -693,13 +603,13 @@ int main(int argc, char *argv[]) { mesh_at = (uint64_t) -1; for (b = s_sim.bridges; b != NULL; b = b->next) { mg_mgr_poll(&b->mgr, 0); - if (b->radio.mesh->next_tick < mesh_at) - mesh_at = b->radio.mesh->next_tick; + if (sim_next_tick(&b->radio.ifp) < mesh_at) + mesh_at = sim_next_tick(&b->radio.ifp); } for (n = s_sim.nodes; n != NULL; n = n->next) { mg_mgr_poll(&n->mgr, 0); - if (n->radio.mesh->next_tick < mesh_at) - mesh_at = n->radio.mesh->next_tick; + if (sim_next_tick(&n->radio.ifp) < mesh_at) + mesh_at = sim_next_tick(&n->radio.ifp); } } if (mg_queue_next(&s_sim.tester.lif.recv_queue, &pending) > 0) { @@ -719,19 +629,6 @@ int main(int argc, char *argv[]) { } printf("\nSimulated %g s in %.3f s", (double) (int64_t) s_sim.now / 1e6, (double) (clock() - started) / CLOCKS_PER_SEC); - if (s_sim.nodes != NULL) { - const struct radio_node *n; - size_t min = (size_t) -1, max = 0; - double total = 0; - for (n = s_sim.nodes; n != NULL; n = n->next) { - size_t peak = n->radio.mesh->ram_peak; - if (peak < min) min = peak; - if (peak > max) max = peak; - total += (double) peak; - } - printf("; peak mesh RAM per node (bytes): min %zu, max %zu, avg %.1f", min, - max, total / s_sim.num_nodes); - } putchar('\n'); while (s_sim.air_head != NULL) { @@ -739,14 +636,14 @@ int main(int argc, char *argv[]) { s_sim.air_head = f->next; free(f); } - printf("Radio: %lu sent, %lu collided, %lu lost\n", - s_sim.air_sent, s_sim.air_collisions, s_sim.air_lost); + printf("Radio: %lu sent, %lu collided, %lu lost\n", s_sim.air_sent, + s_sim.air_collisions, s_sim.air_lost); { struct radio_node *n; int count = 0, joined = 0; for (n = s_sim.nodes; n != NULL; n = n->next) { if (n->mgr.ifp != NULL && n->mgr.ifp->ip != 0) count++; - if (n->radio.mesh->joined) joined++; + if (sim_node(&n->radio.ifp)->joined) joined++; } printf("Nodes with IP: %d of %d, joined: %d of %d\n", count, s_sim.num_nodes, joined, s_sim.num_nodes); @@ -755,18 +652,8 @@ int main(int argc, char *argv[]) { struct bridge *b; struct radio_node *n; mg_log_set(MG_LL_NONE); - for (b = s_sim.bridges; b != NULL; b = b->next) { - mg_mgr_free(&b->mgr); - s_mesh->free(b->radio.mesh); - free(b->radio.mesh); - free(b->radio.rx.buf); - } - for (n = s_sim.nodes; n != NULL; n = n->next) { - mg_mgr_free(&n->mgr); - s_mesh->free(n->radio.mesh); - free(n->radio.mesh); - free(n->radio.rx.buf); - } + for (b = s_sim.bridges; b != NULL; b = b->next) mg_mgr_free(&b->mgr); + for (n = s_sim.nodes; n != NULL; n = n->next) mg_mgr_free(&n->mgr); } return 0; } diff --git a/test/mesh/simulator.h b/test/mesh/simulator.h index 2f83cb81..f4fc858b 100644 --- a/test/mesh/simulator.h +++ b/test/mesh/simulator.h @@ -7,7 +7,26 @@ #include "mongoose.h" -extern const struct mg_mesh mg_mesh_a; +// The simulated radio: 802.15.4, as radio.c sees it with MG_RADIO_802154 +#define SIM_RADIO_MTU 125 // Largest frame, without the FCS +#define SIM_RADIO_BITRATE 250000 // Bits per second on air +#define SIM_RADIO_OVERHEAD 8 // Preamble, SFD, PHR, FCS +#define SIM_RADIO_TURNAROUND_US 100 // Receive to transmit +#define SIM_RADIO_IFS_US 640 // Gap between transmissions +#define SIM_RADIO_HDR_LEN 9 // MAC header, short addresses + +// Read the addresses from an 802.15.4 MAC header +static inline bool sim_parse_hdr(const uint8_t *buf, size_t len, uint16_t *dst, + uint16_t *src) { + if (len < SIM_RADIO_HDR_LEN || buf[0] != 0x41 || buf[1] != 0x88 || + buf[3] != (uint8_t) MG_RADIO_NETWORK || + buf[4] != (uint8_t) (MG_RADIO_NETWORK >> 8)) { + return false; + } + *dst = (uint16_t) (buf[5] | buf[6] << 8); + *src = (uint16_t) (buf[7] | buf[8] << 8); + return true; +} // A position in metres struct pos { @@ -16,28 +35,25 @@ struct pos { struct simulator; -// Private state of the simulated radio driver. +// A simulated radio: its interface, and the simulated hardware's state struct radio_port { - struct simulator *sim; + struct mg_tcpip_if ifp; // First: driver functions cast ifp to the port + struct simulator *sim; // Where it is simulated struct mg_tcpip_if *lan; // Bridge LAN interface, NULL for a node - const struct pos *pos; // Location of the radio - uint64_t tx_until; // Latest transmission end, us - uint64_t tx_ready_at; // Inter-frame wait ends, us - uint64_t rx_off_until; // Latest backoff/sensing/turnaround/TX end, us - struct mg_mesh_node *mesh; // Mesh state owned by the driver - struct mg_queue rx; - uint32_t random; // Driver backoff PRNG - uint16_t address; // Preassigned radio address + const struct pos *pos; // Location of the radio + uint64_t tx_until; // Latest transmission end, us + uint64_t tx_ready_at; // Inter-frame wait ends, us + uint64_t rx_off_until; // Latest TX end, us + bool tx_done; // Completion consumed by the generic driver }; // A bridge: forwards frames between the LAN and the radio, no IP stack struct bridge { - struct bridge *next; // Next in simulator::bridges - struct pos pos; // Where it is - struct mg_mgr mgr; // Polls the raw radio driver - struct mg_tcpip_if lif; // LAN side: LAN driver, gets every LAN frame - struct mg_tcpip_if rif; // Radio side: radio driver, gets every frame - struct radio_port radio; + struct bridge *next; // Next in simulator::bridges + struct pos pos; // Where it is + struct mg_mgr mgr; // Polls the raw radio driver + struct mg_tcpip_if lif; // LAN side: LAN driver, gets every LAN frame + struct radio_port radio; // Radio side: radio driver, gets every frame }; // A radio node: Mongoose on a radio interface @@ -45,8 +61,7 @@ struct radio_node { struct radio_node *next; // Next in simulator::nodes struct pos pos; // Where it is struct mg_mgr mgr; // Mongoose event manager - struct mg_tcpip_if rif; // Radio interface. rif.ip from DHCP, 0: none yet - struct radio_port radio; + struct radio_port radio; // Radio interface. radio.ifp.ip from DHCP }; struct simulator; @@ -70,7 +85,7 @@ struct lan_tester { double min, max, sum; // Times of successful requests, ms }; -enum { RADIO_BACKOFF, RADIO_CCA, RADIO_START, RADIO_END }; +enum { RADIO_START, RADIO_END }; // One radio frame waiting on the simulated radio channel struct radio_frame { @@ -78,7 +93,7 @@ struct radio_frame { struct mg_tcpip_if *from; uint64_t due; // Next radio event, us uint64_t start; // Transmission start, for receive overlap checks - uint8_t state, backoff; + uint8_t state; bool collided; size_t len; uint8_t buf[1540]; @@ -91,12 +106,13 @@ struct simulator { struct radio_frame *air_head; // Pending and active frames, singly linked uint64_t air_busy_until; // Last transmission end, for channel sensing unsigned long air_sent, air_collisions; - unsigned long air_lost; // Receptions lost to range, random loss or TX overlap - double radio_range; // Maximum reception distance, metres - double radio_loss; // In-range reception loss probability, percent - uint32_t loss_random; // Reception-loss PRNG state - bool work_pending; // Drain immediate work before advancing time - struct pos area; // A box: all positions inside + unsigned long + air_lost; // Receptions lost to range, random loss or TX overlap + double radio_range; // Maximum reception distance, metres + double radio_loss; // In-range reception loss probability, percent + uint32_t loss_random; // Reception-loss PRNG state + bool work_pending; // Drain immediate work before advancing time + struct pos area; // A box: all positions inside struct bridge *bridges; // Bridges, a list struct radio_node *nodes; // Radio nodes, a list int num_bridges, num_nodes; // How many diff --git a/tutorials/esp32/minimal-802.15.4/main/mongoose_config.h b/tutorials/esp32/minimal-802.15.4/main/mongoose_config.h index 77764911..676b99c3 100644 --- a/tutorials/esp32/minimal-802.15.4/main/mongoose_config.h +++ b/tutorials/esp32/minimal-802.15.4/main/mongoose_config.h @@ -8,7 +8,8 @@ #define MQTT_CLIENT_ID "esp32c6" // For tutorials/mqtt/mqtt-client #define MG_ENABLE_TCPIP 1 // Built-in TCP/IP stack, not lwIP -#define MG_ENABLE_DRIVER_ESP32_802154 1 // ESP32-C6 802.15.4 radio +#define MG_ENABLE_DRIVER_ESP32 1 // ESP32-C6 802.15.4 radio +#define MG_RADIO MG_RADIO_802154 // The driver supports 802.15.4 only #define MG_ENABLE_TCPIP_TCPRTX 1 // Link can be lossy, enable retransmit // Stable MAC, so the DHCP address stays the same across reboots: the factory diff --git a/tutorials/esp32/wifi-to-802.15.4-bridge/CMakeLists.txt b/tutorials/esp32/wifi-to-802.15.4-bridge/CMakeLists.txt new file mode 100644 index 00000000..d69f3a72 --- /dev/null +++ b/tutorials/esp32/wifi-to-802.15.4-bridge/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 3.16) +set(IDF_TARGET esp32c6) +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(mongoose-wifi-to-802154-bridge) diff --git a/tutorials/esp32/wifi-to-802.15.4-bridge/Makefile b/tutorials/esp32/wifi-to-802.15.4-bridge/Makefile new file mode 100644 index 00000000..f05efa5d --- /dev/null +++ b/tutorials/esp32/wifi-to-802.15.4-bridge/Makefile @@ -0,0 +1,22 @@ +# Build: ESP-IDF from the espressif/idf Docker image. Flash: esptool +# Wi-Fi credentials: make WIFI_NAME=... WIFI_PASS=... build, or set them in +# the environment. Unset, the defaults in main/main.c apply + +THISDIR = $(realpath $(CURDIR)) +ROOTDIR = $(realpath $(CURDIR)/../../..) +DOCKER ?= docker run --rm -e WIFI_NAME -e WIFI_PASS -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf +PORT ?= /dev/cu.usbmodem101 + +all build: + $(DOCKER) idf.py reconfigure build # reconfigure picks up WIFI_* changes + +flash: build + cd build && esptool --chip esp32c6 -p $(PORT) -b 460800 write-flash @flash_args + +menuconfig: + docker run --rm -it -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf idf.py menuconfig + +clean: + test -d build && rm -rf build sdkconfig || true + +.PHONY: all build flash menuconfig clean diff --git a/tutorials/esp32/wifi-to-802.15.4-bridge/main/CMakeLists.txt b/tutorials/esp32/wifi-to-802.15.4-bridge/main/CMakeLists.txt new file mode 100644 index 00000000..fd5a842b --- /dev/null +++ b/tutorials/esp32/wifi-to-802.15.4-bridge/main/CMakeLists.txt @@ -0,0 +1,12 @@ +idf_component_register(SRCS "main.c" "../../../../mongoose.c" + INCLUDE_DIRS "." "../../../.." + REQUIRES esp_wifi esp_netif esp_event esp_timer esp_coex + ieee802154 nvs_flash lwip app_update esp_driver_gpio) +# WIFI_NAME and WIFI_PASS environment variables override the defaults in +# main.c. They are read when CMake configures: run "idf.py reconfigure" after +# changing them +foreach(var WIFI_NAME WIFI_PASS) + if(NOT "$ENV{${var}}" STREQUAL "") + target_compile_definitions(${COMPONENT_LIB} PRIVATE ${var}="$ENV{${var}}") + endif() +endforeach() diff --git a/tutorials/esp32/wifi-to-802.15.4-bridge/main/Kconfig.projbuild b/tutorials/esp32/wifi-to-802.15.4-bridge/main/Kconfig.projbuild new file mode 100644 index 00000000..8a1b4fbb --- /dev/null +++ b/tutorials/esp32/wifi-to-802.15.4-bridge/main/Kconfig.projbuild @@ -0,0 +1,16 @@ +menu "Wi-Fi to 802.15.4 bridge" + config BRIDGE_XIAO_ESP32C6 + bool "Seeed XIAO ESP32-C6 antenna switch" + default y + help + Power the RF switch through GPIO3 and select the antenna on GPIO14. + Disable on boards without this switch. + config BRIDGE_XIAO_EXTERNAL_ANTENNA + bool "Use the XIAO's external antenna" + depends on BRIDGE_XIAO_ESP32C6 + default n + config BRIDGE_RADIO_CHANNEL + int "802.15.4 channel, must match the radio nodes" + range 11 26 + default 15 +endmenu diff --git a/tutorials/esp32/wifi-to-802.15.4-bridge/main/main.c b/tutorials/esp32/wifi-to-802.15.4-bridge/main/main.c new file mode 100644 index 00000000..ce6938f1 --- /dev/null +++ b/tutorials/esp32/wifi-to-802.15.4-bridge/main/main.c @@ -0,0 +1,476 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved +// IPv4 Wi-Fi station <-> Mongoose Ethernet-over-802.15.4 radio bridge. +// +// LAN / DHCP server <-- Wi-Fi --> ESP32-C6 <-- 802.15.4 --> radio nodes +// +// The radio side is Mongoose's esp32 driver acting as the bridge for the +// radio nodes, like tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge. +// The radio driver reads LAN frames from the Wi-Fi interface's recv_queue and +// sends frames to the LAN with that interface's driver tx(). Here the LAN +// interface is a thin wrapper around the Wi-Fi station. +// +// A Wi-Fi station can only send with its own MAC address, so unlike Ethernet +// the frames are translated, see translate(): upstream, node MACs are replaced +// with the station MAC; downstream, the node MAC is restored by IP address. +// Each node gets its own LAN IP from DHCP. The bridge gets one too, for its +// own Mongoose: GET / on port 80 returns the bridge's status as JSON. +// +// Threads: wifi_input() runs in the Wi-Fi task and only queues a copy. All +// the rest, radio, translation and Wi-Fi transmit, runs in app_main's loop. +#include "driver/gpio.h" +#include "esp_coexist.h" +#include "esp_event.h" +#include "esp_ieee802154.h" +#include "esp_log.h" +#include "esp_netif.h" +#include "esp_netif_net_stack.h" +#include "esp_system.h" +#include "esp_wifi.h" +#include "esp_wifi_default.h" +#include "freertos/FreeRTOS.h" +#include "lwip/esp_netif_net_stack.h" +#include "mongoose.h" +#include "nvs_flash.h" + +#if !CONFIG_IDF_TARGET_ESP32C6 +#error This tutorial requires ESP32-C6 +#endif + +// Override with WIFI_NAME and WIFI_PASS environment variables at build time +#ifndef WIFI_NAME +#define WIFI_NAME "WIFI_NAME" +#endif +#ifndef WIFI_PASS +#define WIFI_PASS "WIFI_PASS" +#endif + +#define FRAME_SIZE 1514 // Ethernet header + 1500, no FCS +#define NODE_COUNT 16 // Radio nodes the bridge tracks +#define NODE_TIMEOUT_MS (30UL * 60 * 1000) // Forget a node idle this long + +// A radio node, learned from its frames to Wi-Fi +struct node { + uint64_t expires; // Expiry, milliseconds since boot; zero: unused + uint8_t mac[6], ip[4]; // The node's own MAC, and its LAN IPv4 address +}; + +static uint8_t s_mac[6]; // Wi-Fi station MAC, used by all nodes +static struct node s_nodes[NODE_COUNT]; // Radio nodes, see translate() +static esp_netif_t *s_netif; // Wi-Fi station, raw Ethernet I/O +static volatile bool s_wifi_up; // Associated with the access point +static struct mg_tcpip_if s_wifi; // The radio's LAN interface +static struct mg_tcpip_if s_radio; // 802.15.4 radio interface +static struct mg_tcpip_if s_local; // The bridge's own IP, for the status + +// Cumulative totals. Up: radio -> Wi-Fi; down: Wi-Fi -> radio; bridge: Wi-Fi +// -> the bridge's own IP +static unsigned s_frames_up, s_frames_down, s_frames_local, s_wifi_drops; +static unsigned s_frames_bridge, s_radio_sent, s_radio_received; + +// Is a an IPv4 address worth learning: not 0.x, loopback or multicast +static bool is_host_ip(const uint8_t *a) { + return a[0] != 0 && a[0] != 127 && a[0] < 224; +} + +// Translate an Ethernet frame in place and update s_nodes. Returns false if +// the frame must be dropped. IPv4 and ARP only; IPs and ports stay intact. +// To Wi-Fi: learn the sending node and replace its MAC with the station MAC. +// DHCP keeps the node's chaddr, so each node gets its own LAN IP. +// To radio: find the node by destination IP, or by DHCP chaddr, and restore +// its MAC. Broadcasts pass, unknown unicasts drop +static bool translate(uint8_t *f, size_t len, bool to_radio, uint64_t now) { + uint8_t *ip = NULL, *a = NULL, *bootp = NULL, *udp = NULL; + struct node *n = NULL, *free_node = NULL; + const uint8_t *addr; + bool by_mac; + size_t i; + if (len < 14 || len > FRAME_SIZE || memcmp(f + 6, s_mac, 6) == 0) { + return false; + } + if (!to_radio && ((f[6] & 1) || memcmp(f + 6, "\0\0\0\0\0\0", 6) == 0)) { + return false; + } + if (f[12] == 8 && f[13] == 6) { // ARP for Ethernet/IPv4, request or reply + a = f + 14; + if (len < 42 || memcmp(a, "\x00\x01\x08\x00\x06\x04", 6) != 0 || + a[6] != 0 || (a[7] != 1 && a[7] != 2) || + (!to_radio && memcmp(a + 8, f + 6, 6) != 0)) { + return false; + } + } else if (f[12] == 8 && f[13] == 0 && len >= 34) { // IPv4, with options + size_t hlen, total; + ip = f + 14; + hlen = (ip[0] & 15) * 4U, total = ip[2] * 256U + ip[3]; + if ((ip[0] >> 4) != 4 || hlen < 20 || total < hlen || total > len - 14) { + return false; + } + // DHCP: UDP ports 67/68, BOOTP and the magic cookie. Only complete, + // unfragmented packets + udp = ip + hlen; + if (ip[9] == 17 && !(ip[6] & 0x3f) && ip[7] == 0 && total >= hlen + 248) { + uint8_t *p = udp + 8; + size_t ulen = udp[4] * 256U + udp[5]; + if (udp[0] == 0 && udp[1] == (to_radio ? 67 : 68) && udp[2] == 0 && + udp[3] == (to_radio ? 68 : 67) && ulen >= 248 && + ulen <= total - hlen && p[0] == (to_radio ? 2 : 1) && p[1] == 1 && + p[2] == 6 && memcmp(p + 236, "\x63\x82\x53\x63", 4) == 0) { + bootp = p; + } + } + } else { + return false; + } + + // The node: to Wi-Fi, by source MAC; to radio, by DHCP chaddr, else by + // destination IP. Expire old nodes and find a free slot in the same pass + by_mac = !to_radio || bootp != NULL; + addr = !to_radio ? f + 6 + : bootp != NULL ? bootp + 28 + : ip != NULL ? ip + 16 + : a + 24; + for (i = 0; i < NODE_COUNT; i++) { + struct node *p = &s_nodes[i]; + if (p->expires != 0 && now > p->expires) p->expires = 0; + if (p->expires == 0) { + if (free_node == NULL) free_node = p; + } else if (n == NULL && (by_mac || is_host_ip(addr)) && + memcmp(by_mac ? p->mac : p->ip, addr, by_mac ? 6 : 4) == 0) { + n = p; + } + } + + if (!to_radio) { + if (bootp != NULL && memcmp(bootp + 28, f + 6, 6) != 0) return false; + if (n == NULL) { + if ((n = free_node) == NULL) return false; // Table full + memset(n, 0, sizeof(*n)); + memcpy(n->mac, f + 6, 6); + } + n->expires = now + NODE_TIMEOUT_MS; + addr = ip != NULL ? ip + 12 : a + 14; // Sender IP + if (is_host_ip(addr)) memcpy(n->ip, addr, 4); + if (a != NULL) memcpy(a + 8, s_mac, 6); // ARP sender MAC + if (bootp != NULL) { + bootp[10] |= 0x80; // Ask for broadcast replies: no node IP yet + udp[6] = udp[7] = 0; // No UDP checksum, IPv4 allows that + } + memcpy(f + 6, s_mac, 6); + return true; + } + + if (bootp != NULL) { + if (n == NULL) return false; // Another LAN client's DHCP reply + if (is_host_ip(bootp + 16)) memcpy(n->ip, bootp + 16, 4); // yiaddr + } + if (n == NULL) return (f[0] & 1) != 0; // Broadcast passes, unicast drops + memcpy(f, n->mac, 6); + if (a != NULL && a[7] == 2) memcpy(a + 18, n->mac, 6); // ARP reply target + return true; +} + +// Is mac a radio node, learned by translate() +static bool is_node(const uint8_t *mac, uint64_t now) { + size_t i; + for (i = 0; i < NODE_COUNT; i++) { + if (s_nodes[i].expires > now && memcmp(s_nodes[i].mac, mac, 6) == 0) { + return true; + } + } + return false; +} + +// Radio events: count radio frames, and give each its Wi-Fi coexistence +// priority before it goes out. Wi-Fi and 802.15.4 share one antenna. The +// bridge's unicast frames give a node its turn, and the node answers right +// after: send those at high priority, so the radio keeps the antenna until +// the answer is in. The broadcast beacons go at low priority, and Wi-Fi gets +// the antenna between turns. ESP-IDF applies the priority when the next +// transmission or reception starts +static void radio_fn(struct mg_tcpip_if *ifp, int ev, void *ev_data) { + if (ev == MG_TCPIP_EV_PHY_RX) s_radio_received++; + if (ev == MG_TCPIP_EV_PHY_TX) { + struct mg_str *f = (struct mg_str *) ev_data; // MAC header: dst at 5..6 + const uint8_t *frame = (const uint8_t *) f->buf; + bool bcast = f->len < 7 || (frame[5] == 0xff && frame[6] == 0xff); + ieee802154_coex_event_t want = bcast ? IEEE802154_LOW : IEEE802154_HIGH; + esp_ieee802154_coex_config_t coex = esp_ieee802154_get_coex_config(); + s_radio_sent++; + if (coex.txrx != want) { + coex.txrx = want; + esp_ieee802154_set_coex_config(coex); + } + } + (void) ifp; +} + +// ESP-NETIF custom stack input: Ethernet frames from Wi-Fi, before lwIP. +// Runs in the Wi-Fi task. The queue has one producer, this function, and +// one consumer, the radio driver in app_main, so it needs no lock +static esp_err_t wifi_input(void *netif, void *buf, size_t len, void *eb) { + char *dst; + if (s_wifi_up && len >= 14 && len <= FRAME_SIZE && + mg_queue_book(&s_wifi.recv_queue, &dst, len) >= len) { + memcpy(dst, buf, len); + mg_queue_add(&s_wifi.recv_queue, len); + } else { + s_wifi_drops++; + } + esp_netif_free_rx_buffer(esp_netif_get_handle_from_netif_impl(netif), eb); + return ESP_OK; +} + +// Send an Ethernet frame over Wi-Fi. Returns len, or 0 on failure +static size_t wifi_send(void *buf, size_t len) { + return s_wifi_up && esp_netif_transmit(s_netif, buf, len) == ESP_OK ? len : 0; +} + +// LAN driver tx: the radio driver hands over an Ethernet frame from a radio +// node. A unicast to another node goes back to the radio, untranslated. +// Anything else is translated and sent over Wi-Fi +static size_t wifi_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + uint8_t *frame = (uint8_t *) buf; // The radio's receive buffer, writable + uint64_t now = mg_millis(); + (void) ifp; + if (len >= 14 && (frame[0] & 1) == 0 && is_node(frame, now)) { + if (mg_tcpip_driver_esp32.tx(buf, len, &s_radio) == 0) return 0; + s_frames_local++; + return len; + } + if (!translate(frame, len, false, now) || wifi_send(frame, len) == 0) { + return 0; + } + s_frames_up++; + return len; +} + +// Is a Wi-Fi frame for the bridge itself: an ARP or IPv4 packet to its IP, or +// a DHCP reply to its MAC, before it has an IP +static bool for_bridge(const uint8_t *f, size_t len) { + uint32_t ip = s_local.ip; + size_t hlen = len > 14 ? (size_t) (f[14] & 15) * 4 : 0; + const uint8_t *udp = f + 14 + hlen; + if (len >= 42 && f[12] == 8 && f[13] == 6) { // ARP: target IP at 38 + return ip != 0 && memcmp(f + 38, &ip, 4) == 0; + } + if (len < 34 || f[12] != 8 || f[13] != 0) return false; // IPv4 only + if (ip != 0 && memcmp(f + 30, &ip, 4) == 0) return true; // Destination + return hlen >= 20 && len >= 14 + hlen + 8 + 34 && f[23] == 17 && + udp[0] == 0 && udp[1] == 67 && udp[2] == 0 && udp[3] == 68 && + memcmp(udp + 8 + 28, s_local.mac, 6) == 0; // DHCP chaddr +} + +// Hand a Wi-Fi frame to the bridge's own TCP/IP stack +static void to_bridge(const void *buf, size_t len) { + char *p; + if (mg_queue_book(&s_local.recv_queue, &p, len) >= len) { + memcpy(p, buf, len); + mg_queue_add(&s_local.recv_queue, len); + s_frames_bridge++; + } +} + +// Radio driver tx, called with frames from the Wi-Fi interface's recv_queue: +// restore the node's MAC, then queue the frame for the radio. Frames for the +// bridge itself go to its own stack; broadcasts go to both +static size_t radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + uint8_t *frame = (uint8_t *) buf; // Points into the recv_queue, writable + bool bcast = len >= 14 && (frame[0] & 1); + if (bcast || for_bridge(frame, len)) { + to_bridge(buf, len); + if (!bcast) return len; + } + if (!translate(frame, len, true, mg_millis())) return 0; + len = mg_tcpip_driver_esp32.tx(buf, len, ifp); + if (len != 0) s_frames_down++; + return len; +} + +// The bridge's own interface sends straight to Wi-Fi, under the station MAC +static size_t local_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + (void) ifp; + return wifi_send((void *) buf, len); +} + +// The bridge's own interface is up while Wi-Fi is associated +static bool local_poll(struct mg_tcpip_if *ifp, bool s1) { + (void) ifp, (void) s1; + return s_wifi_up; +} + +// Print the node table as a JSON array, for %M +static size_t print_nodes(mg_pfn_t out, void *arg, va_list *ap) { + uint64_t now = mg_millis(); + size_t i, n = mg_xprintf(out, arg, "["); + const char *comma = ""; + (void) ap; + for (i = 0; i < NODE_COUNT; i++) { + const struct node *p = &s_nodes[i]; + uint32_t ip; + if (p->expires <= now) continue; + memcpy(&ip, p->ip, sizeof(ip)); + n += mg_xprintf(out, arg, "%s{\"mac\":\"%M\",\"ip\":\"%M\",\"idle_ms\":%llu}", + comma, mg_print_mac, p->mac, mg_print_ip4, &ip, + (unsigned long long) (now + NODE_TIMEOUT_MS - p->expires)); + comma = ","; + } + return n + mg_xprintf(out, arg, "]"); +} + +// GET /: the bridge's status, as JSON +static void http_ev(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_HTTP_MSG) { + wifi_ap_record_t ap = {0}; + bool assoc = esp_wifi_sta_get_ap_info(&ap) == ESP_OK; + mg_http_reply( + c, 200, "Content-Type: application/json\r\n", + "{\"uptime_ms\":%llu,\"free_heap\":%lu,\"ip\":\"%M\"," + "\"wifi\":{\"up\":%s,\"ssid\":%m,\"rssi\":%d,\"channel\":%u," + "\"rx_drops\":%u}," + "\"radio\":{\"channel\":%d,\"frames_sent\":%u,\"frames_received\":%u," + "\"rx_drops\":%u,\"tx_errors\":%u}," + "\"frames\":{\"up\":%u,\"down\":%u,\"node_to_node\":%u,\"bridge\":%u}," + "\"nodes\":%M}\n", + (unsigned long long) mg_millis(), + (unsigned long) esp_get_free_heap_size(), mg_print_ip4, &s_local.ip, + s_wifi_up ? "true" : "false", + MG_ESC(assoc ? (const char *) ap.ssid : ""), assoc ? ap.rssi : 0, + assoc ? ap.primary : 0, s_wifi_drops, MG_RADIO_CHANNEL, + s_radio_sent, s_radio_received, (unsigned) s_radio.ndrop, + (unsigned) s_radio.nerr, s_frames_up, s_frames_down, s_frames_local, + s_frames_bridge, print_nodes); + } + (void) ev_data; +} + +// Wi-Fi association state; the bridge's own IP comes from Mongoose's DHCP. +// app_main retries the connection, so this handler only tracks state +static void wifi_event(void *arg, esp_event_base_t base, int32_t id, + void *data) { + if (id == WIFI_EVENT_STA_CONNECTED) { + s_wifi_up = true; + MG_INFO(("Wi-Fi connected")); + } else if (id == WIFI_EVENT_STA_DISCONNECTED) { + const wifi_event_sta_disconnected_t *e = data; + s_wifi_up = false; + MG_INFO(("Wi-Fi disconnected, reason %u", e->reason)); + } + (void) arg, (void) base; +} + +// XIAO RF switch: GPIO3 low powers it, GPIO14 selects the antenna +static void antenna_init(void) { +#ifdef CONFIG_BRIDGE_XIAO_ESP32C6 + ESP_ERROR_CHECK(gpio_set_direction(GPIO_NUM_3, GPIO_MODE_OUTPUT)); + ESP_ERROR_CHECK(gpio_set_level(GPIO_NUM_3, 0)); + vTaskDelay(pdMS_TO_TICKS(100)); + ESP_ERROR_CHECK(gpio_set_direction(GPIO_NUM_14, GPIO_MODE_OUTPUT)); +#ifdef CONFIG_BRIDGE_XIAO_EXTERNAL_ANTENNA + ESP_ERROR_CHECK(gpio_set_level(GPIO_NUM_14, 1)); +#else + ESP_ERROR_CHECK(gpio_set_level(GPIO_NUM_14, 0)); +#endif +#endif +} + +// Wi-Fi station whose received frames go to wifi_input(), not to lwIP. The +// bridge's own IP is Mongoose's, see s_local +static void wifi_init(void) { + esp_netif_inherent_config_t base = ESP_NETIF_INHERENT_DEFAULT_WIFI_STA(); + const esp_netif_netstack_config_t stack = { + .lwip = {.init_fn = wlanif_init_sta, .input_fn = wifi_input}}; + const esp_netif_config_t cfg = {.base = &base, .stack = &stack}; + wifi_init_config_t init = WIFI_INIT_CONFIG_DEFAULT(); + wifi_config_t wifi = { + .sta = {.ssid = WIFI_NAME, + .password = WIFI_PASS, + .scan_method = WIFI_ALL_CHANNEL_SCAN, + .sort_method = WIFI_CONNECT_AP_BY_SIGNAL, + .threshold = {.rssi = -127, .authmode = WIFI_AUTH_OPEN}}}; + esp_err_t err = nvs_flash_init(); // Wi-Fi needs NVS, even with RAM storage + if (err == ESP_ERR_NVS_NO_FREE_PAGES || + err == ESP_ERR_NVS_NEW_VERSION_FOUND) { + ESP_ERROR_CHECK(nvs_flash_erase()); + err = nvs_flash_init(); + } + ESP_ERROR_CHECK(err); + ESP_ERROR_CHECK(esp_netif_init()); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + base.flags = ESP_NETIF_FLAG_AUTOUP; // No IP, DHCP, GARP or IPv6 + s_netif = esp_netif_new(&cfg); + if (s_netif == NULL) ESP_ERROR_CHECK(ESP_ERR_NO_MEM); + ESP_ERROR_CHECK(esp_netif_attach_wifi_station(s_netif)); + ESP_ERROR_CHECK(esp_wifi_set_default_wifi_sta_handlers()); + ESP_ERROR_CHECK(esp_wifi_init(&init)); + ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); + ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, + wifi_event, NULL)); + ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA)); + ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_STA, &wifi)); + ESP_ERROR_CHECK(esp_wifi_get_mac(WIFI_IF_STA, s_mac)); +} + +void app_main(void) { + static struct mg_tcpip_driver wifi_driver; + static struct mg_tcpip_driver radio_driver; + static struct mg_tcpip_driver local_driver; + static struct mg_mgr mgr; + static char wifi_queue[8192]; + uint64_t retry_timer = 0, stats_timer = 0; + + antenna_init(); + wifi_init(); + + // The radio uses a locally administered variant of the station MAC + memcpy(s_radio.mac, s_mac, 6); + s_radio.mac[0] = (uint8_t) ((s_radio.mac[0] | 2) & 0xfe); + s_radio.mac[5] ^= 0x80; + radio_driver = mg_tcpip_driver_esp32; + radio_driver.tx = radio_tx; + s_radio.driver = &radio_driver; + s_radio.fn = radio_fn; // Send at coexistence priority + if (!s_radio.driver->init(&s_radio)) ESP_ERROR_CHECK(ESP_FAIL); + + // The LAN interface: the radio driver only uses its recv_queue and tx + wifi_driver.tx = wifi_tx; + s_wifi.driver = &wifi_driver; + memcpy(s_wifi.mac, s_mac, 6); + mg_queue_init(&s_wifi.recv_queue, wifi_queue, sizeof(wifi_queue)); + mg_radio_bridge(&s_radio, &s_wifi); + + // The bridge's own interface, under the station MAC, with an IP from DHCP: + // GET / on port 80 returns the bridge's status + local_driver.tx = local_tx; + local_driver.poll = local_poll; + s_local.driver = &local_driver; + memcpy(s_local.mac, s_mac, 6); + mg_snprintf(s_local.dhcp_name, sizeof(s_local.dhcp_name), "radio-bridge"); + mg_mgr_init(&mgr); + mg_tcpip_init(&mgr, &s_local); + mg_http_listen(&mgr, "http://0.0.0.0:80", http_ev, NULL); + + // Start the radio before Wi-Fi, then enable coexistence. Wi-Fi power + // saving gives the arbiter time slots for 802.15.4 + ESP_ERROR_CHECK(esp_wifi_start()); + ESP_ERROR_CHECK(esp_coex_wifi_i154_enable()); + ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_MAX_MODEM)); + ESP_ERROR_CHECK(esp_wifi_connect()); + MG_INFO( + ("Wi-Fi/radio bridge, SSID %s, channel %u", WIFI_NAME, MG_RADIO_CHANNEL)); + + // Busy loop: radio turns are timed in microseconds, a FreeRTOS tick is much + // longer. Wi-Fi tasks have higher priority and preempt it. The idle task + // starves, so sdkconfig.defaults turns off the idle task watchdog check + for (;;) { + uint64_t now = mg_millis(); + s_radio.driver->poll(&s_radio, false); + mg_mgr_poll(&mgr, 0); + if (!s_wifi_up && mg_timer_expired(&retry_timer, 5000, now)) { + (void) esp_wifi_connect(); + } + if (mg_timer_expired(&stats_timer, 5000, now)) { + MG_INFO(("Frames up/down/node-to-node %u/%u/%u, Wi-Fi RX drops %u", + s_frames_up, s_frames_down, s_frames_local, s_wifi_drops)); + } + } +} diff --git a/tutorials/esp32/wifi-to-802.15.4-bridge/main/mongoose_config.h b/tutorials/esp32/wifi-to-802.15.4-bridge/main/mongoose_config.h new file mode 100644 index 00000000..122ffe36 --- /dev/null +++ b/tutorials/esp32/wifi-to-802.15.4-bridge/main/mongoose_config.h @@ -0,0 +1,9 @@ +#pragma once +#include "sdkconfig.h" +#define MG_ARCH MG_ARCH_ESP32 +#define MG_ENABLE_TCPIP 1 +#define MG_ENABLE_TCPIP_DRIVER_INIT 0 +#define MG_ENABLE_DRIVER_ESP32 1 +#define MG_RADIO MG_RADIO_802154 // The driver supports 802.15.4 only +#define MG_TLS MG_TLS_NONE +#define MG_RADIO_CHANNEL CONFIG_BRIDGE_RADIO_CHANNEL diff --git a/tutorials/esp32/wifi-to-802.15.4-bridge/sdkconfig.defaults b/tutorials/esp32/wifi-to-802.15.4-bridge/sdkconfig.defaults new file mode 100644 index 00000000..ea77cb64 --- /dev/null +++ b/tutorials/esp32/wifi-to-802.15.4-bridge/sdkconfig.defaults @@ -0,0 +1,10 @@ +CONFIG_IDF_TARGET="esp32c6" +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y +CONFIG_ESP_COEX_SW_COEXIST_ENABLE=y +CONFIG_IEEE802154_ENABLED=y +CONFIG_ESP_MAIN_TASK_STACK_SIZE=6144 +# The main task busy-loops the radio, so the idle task does not run +CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=n +# The netif is used for raw Wi-Fi I/O, not for an IPv6 stack +CONFIG_LWIP_IPV6=n diff --git a/tutorials/nordic/xiao-52840/usb/README.md b/tutorials/nordic/xiao-52840/usb/README.md deleted file mode 100644 index feb23fbf..00000000 --- a/tutorials/nordic/xiao-52840/usb/README.md +++ /dev/null @@ -1,67 +0,0 @@ -# XIAO nRF52840: USB Ethernet and serial with Mongoose - -One USB cable gives the board a CDC-NCM Ethernet interface and a CDC-ACM -serial port that carries the Mongoose log. The nRF52840 USB device controller -is driven directly: no TinyUSB, SoftDevice, Ethernet PHY, or lwIP. Mongoose -provides TCP/IP, a DHCP server, and HTTP/HTTPS servers. - -The USB code is a Mongoose driver, `src/drivers/usb_nrf52.c`. In -`mongoose_config.h`, `MG_ENABLE_DRIVER_USB_NRF52` selects it, and -`MG_ENABLE_USB_ETHERNET` and `MG_ENABLE_USB_SERIAL` turn on its two -functions. Mongoose runs it from `mg_mgr_init()` and `mg_mgr_poll()`, so -`main.c` only sets up the clock, the LED, and the HTTP listeners. - -## Build and flash - -Install the Arm GNU toolchain and `adafruit-nrfutil` -(`pip install adafruit-nrfutil`). The first build fetches CMSIS and Nordic's -nrfx, for the device headers and the startup code. - -```sh -make -make flash PORT=/dev/cu.usbmodemXXXX -``` - -The board keeps its Adafruit bootloader. The application starts at 0x27000, -above the area reserved for the SoftDevice, which is not used. `make flash` -opens the serial port at 1200 baud, which reboots the firmware into the -bootloader, then uploads over serial DFU. If no firmware with a USB serial -port is running, double-tap RESET to enter the bootloader first. - -## Use on macOS - -Connect with a USB data cable. macOS creates an Ethernet service and a -`/dev/cu.usbmodem*` serial port with built-in drivers. Allow the USB accessory -if prompted, and leave the network service set to DHCP. - -`mongoose_config.h` gives the device a static address, and the driver serves -DHCP to the host: - -* Device: `192.168.7.1/24` -* HTTP: -* HTTPS: (self-signed demonstration certificate) -* JSON tick: - -Change `MG_TCPIP_IP` and `MG_TCPIP_MASK` if the subnet conflicts with another -network. Remove them to make the board a DHCP client instead, for example -behind macOS Internet Sharing. - -```sh -curl --noproxy '*' http://192.168.7.1/api/tick -curl --noproxy '*' -k https://192.168.7.1/api/tick -screen /dev/cu.usbmodemXXXX 115200 -``` - -The baud rate is ignored, except that 1200 baud followed by DTR dropping -reboots into the bootloader. The serial port is an output console; received -bytes are discarded. - -## Implementation - -* `main.c`: LED blink task and the HTTP/HTTPS handler. -* `hal.h`, `hal.c`: clock, SysTick, RNG, LED, newlib stubs. -* `../../../../src/drivers/usb_nrf52.c`: nRF52840 USB device controller, - polled. EasyDMA moves each 64-byte packet, one transfer at a time. - Applies Nordic's errata 171, 187 and 199 workarounds. -* `../../../../src/drivers/usb.c`: controller independent NCM + ACM, shared - with the RP2040/RP2350 and SAMD21 drivers. diff --git a/tutorials/nordic/xiao-52840/minimal/Makefile b/tutorials/nordic/xiao-nrf52840/minimal/Makefile similarity index 100% rename from tutorials/nordic/xiao-52840/minimal/Makefile rename to tutorials/nordic/xiao-nrf52840/minimal/Makefile diff --git a/tutorials/nordic/xiao-52840/minimal/hal.c b/tutorials/nordic/xiao-nrf52840/minimal/hal.c similarity index 100% rename from tutorials/nordic/xiao-52840/minimal/hal.c rename to tutorials/nordic/xiao-nrf52840/minimal/hal.c diff --git a/tutorials/nordic/xiao-52840/minimal/hal.h b/tutorials/nordic/xiao-nrf52840/minimal/hal.h similarity index 100% rename from tutorials/nordic/xiao-52840/minimal/hal.h rename to tutorials/nordic/xiao-nrf52840/minimal/hal.h diff --git a/tutorials/nordic/xiao-52840/minimal/link.ld b/tutorials/nordic/xiao-nrf52840/minimal/link.ld similarity index 100% rename from tutorials/nordic/xiao-52840/minimal/link.ld rename to tutorials/nordic/xiao-nrf52840/minimal/link.ld diff --git a/tutorials/nordic/xiao-52840/minimal/main.c b/tutorials/nordic/xiao-nrf52840/minimal/main.c similarity index 96% rename from tutorials/nordic/xiao-52840/minimal/main.c rename to tutorials/nordic/xiao-nrf52840/minimal/main.c index 34cee6b4..a38f6436 100644 --- a/tutorials/nordic/xiao-52840/minimal/main.c +++ b/tutorials/nordic/xiao-nrf52840/minimal/main.c @@ -74,9 +74,10 @@ int main(void) { hal_rng_init(); hal_gpio_write(LED1, true); hal_gpio_output(LED1); + mg_usb_init(NULL, &mg_usb_hw_nrf52); // USB serial log console struct mg_mgr mgr; - mg_mgr_init(&mgr); // Also starts the radio and the USB log console + mg_mgr_init(&mgr); // Also starts the radio mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL); mg_mqtt_init(&mgr); @@ -87,6 +88,7 @@ int main(void) { for (;;) { mg_mgr_poll(&mgr, 0); + mg_usb_poll(NULL, false); mg_mqtt_poll(&mgr); blink_task(); } diff --git a/tutorials/nordic/xiao-52840/minimal/mongoose_config.h b/tutorials/nordic/xiao-nrf52840/minimal/mongoose_config.h similarity index 76% rename from tutorials/nordic/xiao-52840/minimal/mongoose_config.h rename to tutorials/nordic/xiao-nrf52840/minimal/mongoose_config.h index eb6dedb9..f9c238f4 100644 --- a/tutorials/nordic/xiao-52840/minimal/mongoose_config.h +++ b/tutorials/nordic/xiao-nrf52840/minimal/mongoose_config.h @@ -2,19 +2,21 @@ #include "nrf.h" #define MG_ARCH MG_ARCH_ARMGCC #define MG_ENABLE_TCPIP 1 -#define MG_ENABLE_DRIVER_NRF52 1 // 802.15.4 radio: the network interface +#define MG_ENABLE_DRIVER_NRF52 1 // Radio: the network interface #define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller #define MG_ENABLE_USB_SERIAL 1 // USB serial log console +// 1200 baud touch: restart into the Adafruit bootloader, staying in DFU mode +#define MG_USB_REBOOT() \ + do { \ + NRF_POWER->GPREGRET = 0x57; \ + NVIC_SystemReset(); \ + } while (0) #define MG_ENABLE_TCPIP_TCPRTX 1 #define MG_ENABLE_CUSTOM_MICROS 1 #define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_TLS MG_TLS_BUILTIN #define MQTT_CLIENT_ID "xiao-nrf52840" -#ifndef MQTT_SERVER_URL -#define MQTT_SERVER_URL "mqtt://broker.emqx.io:1883" -#endif - // Stable, locally administered MAC derived from the factory device ID. #define MG_SET_MAC_ADDRESS(mac) \ do { \ diff --git a/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/Makefile b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/Makefile new file mode 100644 index 00000000..55c2ee94 --- /dev/null +++ b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/Makefile @@ -0,0 +1,51 @@ +# Seeed XIAO nRF52840: USB Ethernet to BLE mesh bridge, no TinyUSB. +# Environment setup: https://mongoose.ws/documentation/tutorials/tools/ + +MGDIR = ../../../.. + +# Flash over USB: the board's Adafruit bootloader does serial DFU. The +# firmware reboots into it on a 1200 baud touch. PORT: the board's USB serial +# port. adafruit-nrfutil: pip install adafruit-nrfutil +PORT ?= /dev/cu.usbmodem11301 +NRFUTIL ?= adafruit-nrfutil + +CFLAGS = -W -Wall -Wextra -Werror -Wshadow -Wdouble-promotion +CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion +CFLAGS += -g3 -Os -ffunction-sections -fdata-sections +CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Inrfx/mdk +CFLAGS += -DNRF52840_XXAA -D__STARTUP_CLEAR_BSS -D__START=main -D__HEAP_SIZE=0 +CFLAGS += -mcpu=cortex-m4 -mthumb -mfloat-abi=hard -mfpu=fpv4-sp-d16 +CFLAGS += $(CFLAGS_EXTRA) + +LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lm -lgcc +LDFLAGS += -Wl,--gc-sections -Wl,-Map=$@.map + +SOURCES = hal.c main.c $(MGDIR)/mongoose.c +SOURCES += nrfx/mdk/system_nrf52840.c nrfx/mdk/gcc_startup_nrf52840.S + +all build: firmware.hex + +firmware.elf: cmsis_core nrfx $(SOURCES) $(wildcard *.h) link.ld Makefile + arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@ + arm-none-eabi-size --format=berkeley $@ + +firmware.hex: firmware.elf + arm-none-eabi-objcopy -O ihex $< $@ + +firmware.zip: firmware.hex + $(NRFUTIL) dfu genpkg --dev-type 0x0052 --sd-req 0xFFFE --application $< $@ + +flash: firmware.zip + $(NRFUTIL) dfu serial --package $< -p $(PORT) -b 115200 --singlebank --touch 1200 + +cmsis_core: + git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@ + +# nRF52840 device headers, SystemInit() and the startup code +nrfx: + git clone -q -c advice.detachedHead=false --depth 1 -b v2.11.0 https://github.com/NordicSemiconductor/nrfx $@ + +clean: + rm -rf firmware.* cmsis_core nrfx + +.PHONY: all build flash clean diff --git a/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/hal.c b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/hal.c new file mode 100644 index 00000000..ddf47a55 --- /dev/null +++ b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/hal.c @@ -0,0 +1,129 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "hal.h" +#include + +static volatile uint64_t s_ticks; // Milliseconds since boot +void SysTick_Handler(void) { // SysTick IRQ handler, triggered every 1ms + s_ticks++; +} + +uint64_t hal_get_tick(void) { + return s_ticks; +} + +// Mongoose time source, see MG_ENABLE_CUSTOM_MILLIS +uint64_t mg_millis(void) { + return s_ticks; +} + +// Mongoose microsecond time source for the mesh, see MG_ENABLE_CUSTOM_MICROS. +// SysTick runs at the core clock and reloads every millisecond. Sample the +// tick counter and the sub-millisecond counter in one critical section +uint64_t mg_micros(void) { + uint32_t primask = __get_PRIMASK(), val, pending; + uint64_t ms; + __disable_irq(); + ms = s_ticks; + pending = SCB->ICSR & SCB_ICSR_PENDSTSET_Msk; + val = SysTick->VAL; + if (pending != (SCB->ICSR & SCB_ICSR_PENDSTSET_Msk)) { + pending = SCB_ICSR_PENDSTSET_Msk; + val = SysTick->VAL; + } + __set_PRIMASK(primask); + if (pending != 0 && val != 0) ms++; + return ms * 1000 + ((uint64_t) (SysTick->LOAD - val) * 1000) / + (SysTick->LOAD + 1); +} + +// Mongoose random source, see MG_ENABLE_CUSTOM_RANDOM +bool mg_random(void *buf, size_t len) { + for (size_t n = 0; n < len; n += sizeof(uint32_t)) { + uint32_t r = hal_rng_read(); + memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r)); + } + return true; +} + +// Avoid pulling printf and friends in through assert() +void __assert_func(const char *s, int line, const char *fn, const char *expr) { + (void) s, (void) line, (void) fn, (void) expr; + for (;;) (void) 0; +} + +extern unsigned char _end[]; // End of data section, start of heap. See link.ld +static unsigned char *s_current_heap_end = _end; + +size_t hal_ram_used(void) { + return (size_t) (s_current_heap_end - _end); +} + +size_t hal_ram_free(void) { + unsigned char endofstack; + return (size_t) (&endofstack - s_current_heap_end); +} + +void *_sbrk(int incr) { + unsigned char *prev_heap; + unsigned char *heap_end = (unsigned char *) ((size_t) &heap_end - 256); + prev_heap = s_current_heap_end; + // Check how much space we got from the heap end to the stack end + if (s_current_heap_end + incr > heap_end) return (void *) -1; + s_current_heap_end += incr; + return prev_heap; +} + +// Newlib stubs +struct stat; +int _fstat(int fd, struct stat *st) { + (void) fd, (void) st; + return -1; +} + +int _open(const char *path) { + (void) path; + return -1; +} + +int _close(int fd) { + (void) fd; + return -1; +} + +int _isatty(int fd) { + (void) fd; + return 1; +} + +int _lseek(int fd, int ptr, int dir) { + (void) fd, (void) ptr, (void) dir; + return 0; +} + +void _exit(int status) { + (void) status; + for (;;) asm volatile("BKPT #0"); +} + +void _kill(int pid, int sig) { + (void) pid, (void) sig; +} + +int _getpid(void) { + return -1; +} + +int _write(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +int _read(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +void _init(void) { +} diff --git a/tutorials/nordic/xiao-52840/usb/hal.h b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/hal.h similarity index 100% rename from tutorials/nordic/xiao-52840/usb/hal.h rename to tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/hal.h diff --git a/tutorials/nordic/xiao-52840/usb/link.ld b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/link.ld similarity index 100% rename from tutorials/nordic/xiao-52840/usb/link.ld rename to tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/link.ld diff --git a/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/main.c b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/main.c new file mode 100644 index 00000000..11e0dc60 --- /dev/null +++ b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/main.c @@ -0,0 +1,70 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved +// +// USB to BLE bridge. The USB Ethernet interface is the LAN, the radio +// carries the mesh over BLE 2 Mbit/s frames. The bridge runs the mesh: it +// admits nodes and gives each one a turn to send + +#include "hal.h" +#include "mongoose.h" + +static uint64_t s_frames_up, s_frames_down; // Up: radio to USB + +// LAN side: count Ethernet frames forwarded from the radio to the USB host +static size_t usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + size_t sent = mg_tcpip_driver_usb_nrf52.tx(buf, len, ifp); + if (sent != 0) s_frames_up++; + return sent; +} + +// Mesh side: count Ethernet frames from the USB host queued for the radio +static size_t radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + size_t queued = mg_tcpip_driver_nrf52.tx(buf, len, ifp); + if (queued != 0) s_frames_down++; + return queued; +} + +int main(void) { + static struct mg_tcpip_if usb, radio; + static struct mg_tcpip_driver usb_driver; + static char usb_queue[8192]; + static struct mg_tcpip_driver radio_driver; + uint64_t blink_timer = 0, stats_timer = 0; + + hal_system_init(); + hal_rng_init(); + hal_gpio_write(LED, true); // Off + hal_gpio_output(LED); + mg_usb_init(NULL, &mg_usb_hw_nrf52); // USB first: the log goes there + + radio_driver = mg_tcpip_driver_nrf52; + radio_driver.tx = radio_tx; + radio.driver = &radio_driver; + MG_SET_MAC_ADDRESS(radio.mac); + if (!radio.driver->init(&radio)) return 1; + + usb_driver = mg_tcpip_driver_usb_nrf52; + usb_driver.tx = usb_tx; + usb.driver = &usb_driver; + memcpy(usb.mac, radio.mac, sizeof(usb.mac)); + mg_queue_init(&usb.recv_queue, usb_queue, sizeof(usb_queue)); + if (!usb.driver->init(&usb)) return 1; + + mg_radio_bridge(&radio, &usb); // Forward between radio and USB + + MG_INFO(("USB to BLE bridge, channel %d, MAC %M", MG_RADIO_CHANNEL, + mg_print_mac, radio.mac)); + for (;;) { + uint64_t now = mg_millis(); + usb.driver->poll(&usb, false); + radio.driver->poll(&radio, false); + if (mg_timer_expired(&blink_timer, 500, now)) hal_gpio_toggle(LED); + if (mg_timer_expired(&stats_timer, 5000, now)) { + MG_INFO(("Ethernet frames up/down: %llu/%llu, dropped USB/radio: %u/%u", + s_frames_up, s_frames_down, (unsigned) usb.ndrop, + (unsigned) radio.ndrop)); + } + } + + return 0; +} diff --git a/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/mongoose_config.h b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/mongoose_config.h new file mode 100644 index 00000000..5feee7b0 --- /dev/null +++ b/tutorials/nordic/xiao-nrf52840/usb-to-ble-bridge/mongoose_config.h @@ -0,0 +1,29 @@ +#pragma once +#include "nrf.h" +#define MG_ARCH MG_ARCH_ARMGCC +#define MG_ENABLE_TCPIP 1 +#define MG_ENABLE_TCPIP_DRIVER_INIT 0 // main.c sets up both interfaces +#define MG_ENABLE_IPV6 0 +#define MG_ENABLE_CUSTOM_MILLIS 1 +#define MG_ENABLE_CUSTOM_MICROS 1 +#define MG_ENABLE_CUSTOM_RANDOM 1 +#define MG_ENABLE_DRIVER_NRF52 1 // Radio: the mesh side +#define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller: the LAN side +#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface +#define MG_ENABLE_USB_SERIAL 1 // USB serial log console +// 1200 baud touch: restart into the Adafruit bootloader, staying in DFU mode +#define MG_USB_REBOOT() \ + do { \ + NRF_POWER->GPREGRET = 0x57; \ + NVIC_SystemReset(); \ + } while (0) + +// Stable, locally administered MAC derived from the factory device ID +#define MG_SET_MAC_ADDRESS(mac) \ + do { \ + uint32_t id_[2] = {NRF_FICR->DEVICEID[0], NRF_FICR->DEVICEID[1]}; \ + uint8_t hash_[32]; \ + mg_sha256(hash_, (uint8_t *) id_, sizeof(id_)); \ + memcpy(mac, hash_, 6); \ + (mac)[0] = ((mac)[0] & 0xfc) | 2; \ + } while (0) diff --git a/tutorials/nordic/xiao-52840/usb/Makefile b/tutorials/nordic/xiao-nrf52840/usb/Makefile similarity index 100% rename from tutorials/nordic/xiao-52840/usb/Makefile rename to tutorials/nordic/xiao-nrf52840/usb/Makefile diff --git a/tutorials/nordic/xiao-52840/usb/hal.c b/tutorials/nordic/xiao-nrf52840/usb/hal.c similarity index 100% rename from tutorials/nordic/xiao-52840/usb/hal.c rename to tutorials/nordic/xiao-nrf52840/usb/hal.c diff --git a/tutorials/nordic/xiao-nrf52840/usb/hal.h b/tutorials/nordic/xiao-nrf52840/usb/hal.h new file mode 100644 index 00000000..8a827a1b --- /dev/null +++ b/tutorials/nordic/xiao-nrf52840/usb/hal.h @@ -0,0 +1,67 @@ +#pragma once +#include +#include +#include +#include "nrf.h" + +#define BIT(x) (1UL << (x)) +#define PIN(port, num) (((port) << 5) | (num)) +#define PINNO(pin) ((pin) & 31) +#define PINPORT(pin) ((pin) >> 5) +#define LED PIN(0, 26) // P0.26, red user LED, active low + +uint64_t hal_get_tick(void); +size_t hal_ram_used(void); +size_t hal_ram_free(void); + +static inline NRF_GPIO_Type *hal_gpio_bank(uint16_t pin) { + return PINPORT(pin) == 0 ? NRF_P0 : NRF_P1; +} + +static inline void hal_gpio_write(uint16_t pin, bool val) { + NRF_GPIO_Type *gpio = hal_gpio_bank(pin); + if (val) { + gpio->OUTSET = BIT(PINNO(pin)); + } else { + gpio->OUTCLR = BIT(PINNO(pin)); + } +} + +static inline void hal_gpio_toggle(uint16_t pin) { + hal_gpio_write(pin, (hal_gpio_bank(pin)->OUT & BIT(PINNO(pin))) == 0); +} + +static inline void hal_gpio_output(uint16_t pin) { + hal_gpio_bank(pin)->PIN_CNF[PINNO(pin)] = + (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) | + (GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos); +} + +// Vectors above the bootloader, 64 MHz crystal clock, 1 ms SysTick +static inline void hal_system_init(void) { + extern uint32_t __isr_vector[]; + SCB->VTOR = (uint32_t) __isr_vector; + __DSB(); + __ISB(); + __enable_irq(); + NRF_CLOCK->EVENTS_HFCLKSTARTED = 0; + NRF_CLOCK->TASKS_HFCLKSTART = 1; + while (!NRF_CLOCK->EVENTS_HFCLKSTARTED) (void) 0; + SystemCoreClockUpdate(); + SysTick_Config(SystemCoreClock / 1000); +} + +static inline void hal_rng_init(void) { + NRF_RNG->CONFIG = 1; // Bias correction + NRF_RNG->TASKS_START = 1; +} + +static inline uint32_t hal_rng_read(void) { + uint32_t value = 0; + for (unsigned i = 0; i < 4; i++) { + while (!NRF_RNG->EVENTS_VALRDY) (void) 0; + value |= (uint32_t) NRF_RNG->VALUE << (i * 8); + NRF_RNG->EVENTS_VALRDY = 0; + } + return value; +} diff --git a/tutorials/nordic/xiao-nrf52840/usb/link.ld b/tutorials/nordic/xiao-nrf52840/usb/link.ld new file mode 100644 index 00000000..4c9448a2 --- /dev/null +++ b/tutorials/nordic/xiao-nrf52840/usb/link.ld @@ -0,0 +1,62 @@ +/* nRF52840 on the XIAO nRF52840, with the Adafruit UF2 bootloader. Flash: + * MBR and SoftDevice S140 below 0x27000, the bootloader from 0xED000 up: the + * application in between. The SoftDevice is not enabled, so all RAM is ours, + * except the first 24k it would take: kept free, as the Arduino core does */ +ENTRY(Reset_Handler); +MEMORY { + flash(rx) : ORIGIN = 0x00027000, LENGTH = 0xC6000 + sram(rwx) : ORIGIN = 0x20006000, LENGTH = 0x3A000 +} + +SECTIONS { + .vectors : { KEEP(*(.isr_vector)) . = ALIGN(4); } > flash + .text : { *(.text* .text.*) } > flash + .rodata : { *(.rodata*) . = ALIGN(4); } > flash + + .data : { + _sdata = .; + *(.first_data) + *(.iram .iram.*) /* Mongoose MG_IRAM functions */ + *(.data SORT(.data.*)) + . = ALIGN(4); + _edata = .; + } > sram AT > flash + __data_start = _sdata; + __data_end = _edata; + __data_load_start = LOADADDR(.data); + /* Unused data regions expected by Nordic's standard startup. */ + __sdata_start = _edata; + __sdata_end = _edata; + __sdata_load_start = _edata; + __tdata_start = _edata; + __tdata_end = _edata; + __tdata_load_start = _edata; + __fast_start = _edata; + __fast_end = _edata; + __fast_load_start = _edata; + + .bss : { + _sbss = .; + *(.bss SORT(.bss.*) COMMON) + . = ALIGN(4); + _ebss = .; + } > sram + __bss_start__ = _sbss; + __bss_end__ = _ebss; + __tbss_start__ = _ebss; + __tbss_end__ = _ebss; + __sbss_start__ = _ebss; + __sbss_end__ = _ebss; + + /* Health record, see MG_HEALTH_RAM: not cleared, survives a warm reset */ + .mg_health (NOLOAD) : { KEEP(*(.mg_health .mg_health*)) } > sram + + . = ALIGN(8); + _end = .; /* Start of heap, see _sbrk() in hal.c */ + + /* Nordic startup reserves its default 16 KiB stack at the top of RAM. */ + .stack ORIGIN(sram) + LENGTH(sram) - 0x4000 (NOLOAD) : { + KEEP(*(.stack)) + } > sram + ASSERT(_end <= __StackLimit, "RAM sections overlap the stack") +} diff --git a/tutorials/nordic/xiao-52840/usb/main.c b/tutorials/nordic/xiao-nrf52840/usb/main.c similarity index 100% rename from tutorials/nordic/xiao-52840/usb/main.c rename to tutorials/nordic/xiao-nrf52840/usb/main.c diff --git a/tutorials/nordic/xiao-52840/usb/mongoose_config.h b/tutorials/nordic/xiao-nrf52840/usb/mongoose_config.h similarity index 75% rename from tutorials/nordic/xiao-52840/usb/mongoose_config.h rename to tutorials/nordic/xiao-nrf52840/usb/mongoose_config.h index bc9921b8..3baeef77 100644 --- a/tutorials/nordic/xiao-52840/usb/mongoose_config.h +++ b/tutorials/nordic/xiao-nrf52840/usb/mongoose_config.h @@ -1,4 +1,5 @@ #pragma once + #define MG_ARCH MG_ARCH_ARMGCC #define MG_TLS MG_TLS_BUILTIN #define MG_ENABLE_TCPIP 1 @@ -8,6 +9,15 @@ #define MG_ENABLE_DRIVER_USB_NRF52 1 // nRF52840 USB controller #define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface #define MG_ENABLE_USB_SERIAL 1 // USB serial log console + +// 1200 baud touch: restart into the Adafruit bootloader, staying in DFU mode +#include "nrf.h" +#define MG_USB_REBOOT() \ + do { \ + NRF_POWER->GPREGRET = 0x57; \ + NVIC_SystemReset(); \ + } while (0) + // Static device address; the driver serves DHCP to the USB host. Remove // these to get an address over DHCP instead, e.g. from Internet Sharing #define MG_TCPIP_IP MG_IPV4(192, 168, 7, 1) diff --git a/tutorials/nxp/frdm-mcxw71/minimal/hal.c b/tutorials/nxp/frdm-mcxw71/minimal/hal.c index 3d59098d..298d61f6 100644 --- a/tutorials/nxp/frdm-mcxw71/minimal/hal.c +++ b/tutorials/nxp/frdm-mcxw71/minimal/hal.c @@ -4,14 +4,60 @@ #include "hal.h" #include "mongoose.h" +#if MG_RADIO == MG_RADIO_BLE +// NXP release/25.06.00, gen45: gfsk_bt_0p5_h_0p5_1mbps_full_config. +// The alternate data-rate bank is 2 Mbit/s, selected by GENFSK ENH_FEATURE. +// Copyright 2016 Freescale Semiconductor, Inc.; 2018-2023 NXP. +// SPDX-License-Identifier: BSD-3-Clause +// These are the differences from the 802.15.4 setup in hal.h. Both use +// xcvr_ble_uncoded_config for RBME (CRC and whitening). +static const struct w71_radio_reg s_ble_regs[] = { + {&XCVR_MISC->IPS_FO_ADDR[0], 0x0000332c}, + {&XCVR_MISC->IPS_FO_ADDR[1], 0x00000034}, + {&XCVR_MISC->IPS_FO_DRS0_DATA[0], 0x20ff0000}, + {&XCVR_MISC->IPS_FO_DRS1_DATA[0], 0x10ff0000}, + {&XCVR_MISC->XCVR_CTRL, 0x00030140}, + {&XCVR_PLL_DIG->CHAN_MAP, 0x00000000}, + {&XCVR_PLL_DIG->DELAY_MATCH, 0x00040103}, + {&XCVR_PLL_DIG->HPMCAL_CTRL, 0x00000000}, + {&XCVR_PLL_DIG->HPM_BUMP, 0x00440122}, + {&XCVR_PLL_DIG->HPM_SDM_RES, 0x20ff0000}, + {&XCVR_RX_DIG->ACQ_FILT_0_3, 0x757a0202}, + {&XCVR_RX_DIG->ACQ_FILT_0_3_DRS, 0x09023e3e}, + {&XCVR_RX_DIG->ACQ_FILT_10_11, 0x00de0068}, + {&XCVR_RX_DIG->ACQ_FILT_10_11_DRS, 0x00a1006e}, + {&XCVR_RX_DIG->ACQ_FILT_4_7, 0xeb171801}, + {&XCVR_RX_DIG->ACQ_FILT_4_7_DRS, 0xdeeb000b}, + {&XCVR_RX_DIG->ACQ_FILT_8_9, 0x01e901c2}, + {&XCVR_RX_DIG->ACQ_FILT_8_9_DRS, 0x002601f0}, + {&XCVR_RX_DIG->AGC_IDX11_GAIN_CFG, 0x02047e03}, + {&XCVR_RX_DIG->AGC_IDX11_GAIN_VAL, 0x006014fa}, + {&XCVR_RX_DIG->CTRL0, 0x60063083}, + {&XCVR_RX_DIG->CTRL0_DRS, 0x000020c0}, + {&XCVR_RX_DIG->DEMOD_FILT_0_1_DRS, 0x01fe01fd}, + {&XCVR_RX_DIG->DEMOD_FILT_2_4, 0x0bc20c24}, + {&XCVR_RX_DIG->DEMOD_FILT_2_4_DRS, 0x0bc20c23}, + {&XCVR_RX_DIG->RCCAL_CTRL0, 0x0000001a}, + {&XCVR_RX_DIG->RSSI_GLOBAL_CTRL, 0x80008310}, + {&XCVR_TX_DIG->DATARATE_CONFIG_FSK_CTRL, 0x00000000}, + {&XCVR_TX_DIG->DATARATE_CONFIG_GFSK_CTRL, 0x00000830}, + {&XCVR_TX_DIG->DATA_PADDING_CTRL, 0x00001010}, + {&XCVR_TX_DIG->DATA_PADDING_CTRL_1, 0x00001404}, + {&XCVR_TX_DIG->DATA_PADDING_CTRL_2, 0x04001c00}, + {&XCVR_TX_DIG->GFSK_CTRL, 0x00000400}, + {&XCVR_TX_DIG->PA_CTRL, 0x00010126}, + {&XCVR_TX_DIG->TXDIG_CTRL, 0x00000000}, +}; +#endif + // Initialise the transceiver the way NXP XCVR_Init() does it: start the RF // oscillator, wait for the radio to wake up, enable its clocks and load the -// 802.15.4 register setup. Then select the legacy 802.15.4 demodulator and -// CCA from RX digital. See PhyHwInit() in NXP ieee_802_15_4 PHY sources, -// PhyPacketProcessor.c +// register setup for the selected PHY. For 802.15.4, select the legacy +// demodulator and CCA from RX digital. See PhyHwInit() in NXP ieee_802_15_4 PHY +// sources, PhyPacketProcessor.c void hal_radio_init(void) { - uint32_t stat = RFMC_RF2P4GHZ_STAT_RST_STAT_MASK | - RFMC_RF2P4GHZ_STAT_LP_ACK_STAT_MASK; + uint32_t stat = + RFMC_RF2P4GHZ_STAT_RST_STAT_MASK | RFMC_RF2P4GHZ_STAT_LP_ACK_STAT_MASK; size_t i, n = 1000000; RFMC->CTRL &= ~RFMC_CTRL_RFMC_RST_MASK; // RFMC out of reset RFMC->RF2P4GHZ_CTRL |= RFMC_RF2P4GHZ_CTRL_XO_EN_MASK; // Start RF oscillator @@ -31,9 +77,19 @@ void hal_radio_init(void) { for (i = 0; i < sizeof(s_radio_regs) / sizeof(s_radio_regs[0]); i++) { *s_radio_regs[i].reg = s_radio_regs[i].val; } +#if MG_RADIO == MG_RADIO_BLE + for (i = 0; i < sizeof(s_ble_regs) / sizeof(s_ble_regs[0]); i++) { + *s_ble_regs[i].reg = s_ble_regs[i].val; + } + RADIO_CTRL->LL_CTRL = RADIO_CTRL_LL_CTRL_ACTIVE_LL(2); // GENFSK engine + // NXP GENFSK_SetBleWhitenInit(): BLE channel index with bit 6 set. + RBME->WHITEN_CFG = (RBME->WHITEN_CFG & ~RBME_WHITEN_CFG_WHITEN_INIT_MASK) | + RBME_WHITEN_CFG_WHITEN_INIT(MG_RADIO_CHANNEL | 0x40); +#else XCVR_MISC->XCVR_CTRL &= ~XCVR_MISC_XCVR_CTRL_DEMOD_SEL_MASK; XCVR_MISC->XCVR_CTRL |= XCVR_MISC_XCVR_CTRL_DEMOD_SEL(2); XCVR_ZBDEMOD->CCA_LQI_SRC |= XCVR_ZBDEMOD_CCA_LQI_SRC_CCA1_FROM_RX_DIG(1); +#endif } // Random 32 bits, for mg_random(). Entropy is radio noise: receiver RSSI, @@ -99,8 +155,8 @@ uint64_t mg_micros(void) { } __set_PRIMASK(primask); if (pending != 0 && val != 0) ms++; - return ms * 1000 + ((uint64_t) (SysTick->LOAD - val) * 1000) / - (SysTick->LOAD + 1); + return ms * 1000 + + ((uint64_t) (SysTick->LOAD - val) * 1000) / (SysTick->LOAD + 1); } uint32_t SystemCoreClock; diff --git a/tutorials/nxp/frdm-mcxw71/minimal/hal.h b/tutorials/nxp/frdm-mcxw71/minimal/hal.h index d9b0d494..fe0239bb 100644 --- a/tutorials/nxp/frdm-mcxw71/minimal/hal.h +++ b/tutorials/nxp/frdm-mcxw71/minimal/hal.h @@ -17,7 +17,7 @@ uint64_t hal_get_tick(void); bool hal_timer_expired(volatile uint64_t *t, uint64_t period, uint64_t now); size_t hal_ram_used(void); size_t hal_ram_free(void); -void hal_radio_init(void); // Set up the 2.4 GHz transceiver for 802.15.4 +void hal_radio_init(void); // Set up the 2.4 GHz transceiver for MG_RADIO uint32_t hal_rng_read(void); // Random 32 bits, radio noise. See hal.c extern uint32_t SystemCoreClock; // CPU clock, Hz. Set by hal_clock_init() diff --git a/tutorials/nxp/frdm-mcxw71/minimal/mongoose_config.h b/tutorials/nxp/frdm-mcxw71/minimal/mongoose_config.h index 8f8f8b6f..6116a936 100644 --- a/tutorials/nxp/frdm-mcxw71/minimal/mongoose_config.h +++ b/tutorials/nxp/frdm-mcxw71/minimal/mongoose_config.h @@ -9,6 +9,9 @@ #define MG_ENABLE_TCPIP 1 #define MG_ENABLE_DRIVER_MCXW71 1 +#ifndef MG_RADIO +#define MG_RADIO MG_RADIO_BLE // Raw BLE 2M; or MG_RADIO_802154 +#endif #define MG_ENABLE_CUSTOM_MICROS 1 #define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_ENABLE_TCPIP_TCPRTX 1 // Link can be lossy, enable retransmit diff --git a/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/main.c b/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/main.c index 631e5a0f..02aa779f 100644 --- a/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/main.c +++ b/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/main.c @@ -13,12 +13,15 @@ static uint64_t s_radio_led_until; // Cumulative totals. Up: radio -> LAN; down: LAN -> radio queue. static uint64_t s_frames_up, s_frames_down, s_bytes_up, s_bytes_down; static uint64_t s_radio_sent, s_radio_received; -static size_t (*s_radio_tx)(struct mg_tcpip_if *, const void *, size_t); -static size_t radio_tx(struct mg_tcpip_if *ifp, const void *buf, size_t len) { - size_t sent = s_radio_tx(ifp, buf, len); - if (sent != 0) s_radio_sent++; - return sent; +// Radio interface events: count radio frames, blink on reception +static void radio_fn(struct mg_tcpip_if *ifp, int ev, void *ev_data) { + if (ev == MG_TCPIP_EV_PHY_TX) s_radio_sent++; + if (ev == MG_TCPIP_EV_PHY_RX) { + s_radio_received++; + s_radio_led_until = mg_millis() + 2; + } + (void) ifp, (void) ev_data; } static size_t eth_up(const void *buf, size_t len, struct mg_tcpip_if *ifp) { @@ -27,31 +30,23 @@ static size_t eth_up(const void *buf, size_t len, struct mg_tcpip_if *ifp) { return sent; } -static size_t eth_down(struct mg_mesh_node *node, const void *buf, size_t len) { - size_t queued = mg_mesh_default.tx(node, buf, len); +static size_t eth_down(const void *buf, size_t len, struct mg_tcpip_if *ifp) { + size_t queued = mg_tcpip_driver_rw612w.tx(buf, len, ifp); if (queued != 0) s_frames_down++, s_bytes_down += queued; return queued; } -static void radio_rx(struct mg_mesh_node *node, void *buf, size_t len) { - s_radio_received++; - s_radio_led_until = mg_millis() + 2; - mg_mesh_default.rx(node, buf, len); -} - static void log_fn(char ch, void *arg) { hal_uart_write_buf(arg, &ch, 1); } - int main(void) { static struct mg_tcpip_driver_rw612_data eth_data; static struct mg_tcpip_if eth; static struct mg_tcpip_driver eth_driver; static char eth_queue[8192]; - static struct mg_tcpip_driver_rw612w_data radio_data; static struct mg_tcpip_if radio; - static struct mg_mesh mesh; + static struct mg_tcpip_driver radio_driver; uint32_t lan_received = 0; uint64_t lan_led_until = 0; uint64_t link_timer = 0, stats_timer = 0; @@ -68,15 +63,11 @@ int main(void) { mg_log_set_fn(log_fn, USART3); hal_ethernet_init(); - mesh = mg_mesh_default; - mesh.tx = eth_down; - mesh.rx = radio_rx; // Observe radio reception without modifying the driver. - radio_data.strategy = &mesh; - radio.driver = &mg_tcpip_driver_rw612w; - radio.driver_data = &radio_data; + radio_driver = mg_tcpip_driver_rw612w; + radio_driver.tx = eth_down; + radio.driver = &radio_driver; + radio.fn = radio_fn; if (!radio.driver->init(&radio)) return 1; - s_radio_tx = radio_data.mesh->tx; - radio_data.mesh->tx = radio_tx; eth_data.mdc_cr = MG_DRIVER_MDC_CR; eth_data.mdc_holdtime = MG_DRIVER_MDC_HOLDTIME; @@ -90,10 +81,9 @@ int main(void) { if (!eth.driver->init(ð)) return 1; ENET->RCR |= ENET_RCR_PROM_MASK; // Receive frames addressed to radio nodes. - radio_data.mesh->lan = ð - radio_data.mesh->next_tick = 0; + mg_radio_bridge(&radio, ð); - MG_INFO(("Ethernet/radio bridge, channel %u", MG_802154_CHANNEL)); + MG_INFO(("Ethernet/radio bridge, channel %u", MG_RADIO_CHANNEL)); stats_timer = mg_millis() + 5000; for (;;) { uint64_t now = mg_millis(); diff --git a/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/mongoose_config.h b/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/mongoose_config.h index ae2cca87..0003b965 100644 --- a/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/mongoose_config.h +++ b/tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge/mongoose_config.h @@ -6,6 +6,7 @@ #define MG_ENABLE_TCPIP 1 #define MG_ENABLE_DRIVER_RW612 1 // Ethernet #define MG_ENABLE_DRIVER_RW612W 1 // Mesh bridge over raw 802.15.4 +#define MG_RADIO MG_RADIO_802154 // The driver supports 802.15.4 only #define MG_ENABLE_CUSTOM_MICROS 1 diff --git a/tutorials/rp/usb/README.md b/tutorials/rp/usb/README.md deleted file mode 100644 index b6162e14..00000000 --- a/tutorials/rp/usb/README.md +++ /dev/null @@ -1,99 +0,0 @@ -# Pico 2 / XIAO RP2040: USB Ethernet and serial with Mongoose - -One USB cable gives the board a CDC-NCM Ethernet interface and a CDC-ACM -serial port that carries the Mongoose log. The native RP2040/RP2350 USB -controller is driven directly: no PIO, Ethernet PHY, TinyUSB, or lwIP. -Mongoose provides TCP/IP, a DHCP server, and HTTP/HTTPS servers. - -The USB code is a Mongoose driver, `src/drivers/usb_rp.c`, enabled by -`MG_ENABLE_DRIVER_USB_RP` in `mongoose_config.h`. `mg_mgr_init()` starts it, -so `main.c` only sets up the LED and the HTTP listeners. - -## Build and flash - -Install the Pico SDK, CMake, Arm GNU toolchain, and picotool. The Makefile -uses `~/src/pico-sdk`; override `PICO_SDK_PATH` if necessary. -The default target is `PICO_BOARD=pico2` (RP2350, Arm Cortex-M33). - -```sh -make # Pico 2 -make PICO_BOARD=seeed_xiao_rp2040 # XIAO RP2040 -``` - -Each board has its own build directory, `build/pico2/firmware.uf2` or -`build/seeed_xiao_rp2040/firmware.uf2`, so RP2040 and RP2350 CMake settings -never mix. - -On Pico 2, hold BOOTSEL while connecting the USB cable. On XIAO, hold BOOT -while pressing and releasing RESET, then release BOOT. Flash: - -```sh -make flash -``` - -The firmware also enters BOOTSEL when its serial port is opened at 1200 baud -and DTR drops. `picotool -f` alone cannot reboot it: the driver does not -implement the Pico SDK vendor reset interface. - -## Use on macOS - -Connect with a USB data cable. macOS creates an Ethernet service and a -`/dev/cu.usbmodem*` serial port with built-in drivers. Allow the USB accessory -if prompted, and leave the network service set to DHCP. - -`mongoose_config.h` gives the device a static address, and the driver serves -DHCP to the host: - -* Device: `192.168.7.1/24` -* HTTP: -* HTTPS: (self-signed demonstration certificate) -* JSON tick: - -Change `MG_TCPIP_IP` and `MG_TCPIP_MASK` if the subnet conflicts with another -network. Remove them to make the board a DHCP client instead, for example -behind macOS Internet Sharing. - -```sh -curl --noproxy '*' http://192.168.7.1/api/tick -curl --noproxy '*' -k https://192.168.7.1/api/tick -screen /dev/cu.usbmodemXXXX 115200 -``` - -Use the actual serial device path. The baud rate is ignored, except that -1200 baud followed by DTR dropping requests BOOTSEL. To exit screen, press -Ctrl-A, then backslash, and confirm. The serial port is an output console; -received bytes are discarded. - -Linux normally provides NCM and ACM drivers. Windows 11 provides NCM and ACM; -the driver includes Microsoft OS 2.0 compatible ID descriptors for driver -binding. Linux and Windows have not been tested here. Windows 10 has no -built-in NCM driver. - -## Implementation - -* `main.c`: LED blink task and the HTTP/HTTPS handler. -* `../../../src/drivers/usb_rp.c`: RP2040/RP2350 USB device controller. -* `../../../src/drivers/usb.c`: controller independent NCM + ACM: - descriptors, control requests, NTB16 negotiation, framing, parser, and the - serial log buffer. Shared with the SAMD21 driver, `usb_samd21.c`. -* Network control/data interfaces 0/1; ACM control/data interfaces 2/3. -* Network endpoints: interrupt IN 0x81, bulk OUT/IN 0x02/0x82. -* Serial endpoints: interrupt IN 0x83, bulk OUT/IN 0x04/0x84. -* Full-speed USB, 64-byte packets. Transfers span multiple packets and end - with short packets or ZLPs. Ethernet FCS is not sent on USB. -* NTB16 with no CRC, 4 KiB maximum IN/OUT blocks, and up to 16 incoming - datagrams per block, including chained NDPs. The whole block is validated - before any frame is delivered. NTB32 and CRC mode are not advertised. -* One Ethernet frame per outgoing block, within the host's negotiated input - size. Outgoing frames are not aggregated. -* Host and device MAC addresses and the USB serial number come from the - board's flash ID. One outgoing block can be in flight; incoming frames go - to Mongoose's 8 KiB queue. The serial log is a nonblocking 2 KiB ring; old - logs are overwritten when the host is not reading. -* Buffer sizes can be changed with `MG_USB_NCM_NTB_SIZE`, - `MG_USB_NCM_LOG_SIZE` and `MG_USB_NCM_QUEUE_SIZE`. -* Single core, polled from `mg_mgr_poll()`. No host mode, RNDIS, suspend, - remote wake, or Ethernet bridging. - -The development VID/PID is `CAFE:40E4`, not an allocation for shipped -products. Get a legitimate VID/PID before distributing hardware. diff --git a/tutorials/rp/usb/mongoose_config.h b/tutorials/rp/usb/mongoose_config.h index c70add6a..ceada8b5 100644 --- a/tutorials/rp/usb/mongoose_config.h +++ b/tutorials/rp/usb/mongoose_config.h @@ -5,6 +5,7 @@ #define MG_ENABLE_DRIVER_USB_RP 1 // RP2040 / RP2350 USB controller #define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface #define MG_ENABLE_USB_SERIAL 1 // USB serial log console +#define MG_USB_REBOOT() reset_usb_boot(0, 0) // 1200 baud touch: BOOTSEL // Static device address; the driver serves DHCP to the USB host. Remove // these to get an address over DHCP instead, e.g. from Internet Sharing diff --git a/tutorials/silabs/xiao-mg24/minimal/Makefile b/tutorials/silabs/xiao-mg24/minimal/Makefile index 1a5bc635..19089143 100644 --- a/tutorials/silabs/xiao-mg24/minimal/Makefile +++ b/tutorials/silabs/xiao-mg24/minimal/Makefile @@ -1,16 +1,17 @@ # Environment setup: https://mongoose.ws/documentation/tutorials/tools/ MGDIR = ../../../.. -SDK = silabs_sdk/platform -RAIL = $(SDK)/radio/rail_lib CFLAGS = -W -Wall -Wextra -Werror -Wshadow # No -Wundef: RAIL headers CFLAGS += -Wformat-truncation -fno-common -Wno-conversion -Wno-sign-conversion CFLAGS += -g3 -Os -ffunction-sections -fdata-sections CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -CFLAGS += -I$(SDK)/Device/SiliconLabs/EFR32MG24/Include -I$(SDK)/common/inc -CFLAGS += -I$(RAIL)/common -I$(RAIL)/protocol/ieee802154 -CFLAGS += -I$(RAIL)/chip/efr32/efr32xg2x +CFLAGS += -Isilabs_sdk/platform/Device/SiliconLabs/EFR32MG24/Include +CFLAGS += -Isilabs_sdk/platform/common/inc +CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/common +CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/protocol/ieee802154 +CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/protocol/ble +CFLAGS += -Isilabs_sdk/platform/radio/rail_lib/chip/efr32/efr32xg2x CFLAGS += -DEFR32MG24B220F1536IM48 CFLAGS += -D__START=main # For startup_efr32mg24.c CFLAGS += -mcpu=cortex-m33 -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16 -mcmse @@ -21,8 +22,8 @@ LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lm -lgcc -W SOURCES = main.c hal.c $(MGDIR)/mongoose.c SOURCES += $(MGDIR)/tutorials/mqtt/mqtt-client/mongoose_mqtt.c -SOURCES += $(SDK)/Device/SiliconLabs/EFR32MG24/Source/startup_efr32mg24.c -SOURCES += $(SDK)/Device/SiliconLabs/EFR32MG24/Source/system_efr32mg24.c +SOURCES += silabs_sdk/platform/Device/SiliconLabs/EFR32MG24/Source/startup_efr32mg24.c +SOURCES += silabs_sdk/platform/Device/SiliconLabs/EFR32MG24/Source/system_efr32mg24.c # RAIL radio library, a binary blob. Simplicity SDK keeps it in Git LFS, # served by Silicon Labs. The oid is the file's sha256, see the LFS pointer @@ -51,7 +52,7 @@ cmsis_core: # Device headers, startup code and RAIL headers from Simplicity SDK silabs_sdk: GIT_LFS_SKIP_SMUDGE=1 git clone -q -c advice.detachedHead=false --depth 1 -b $(SDK_VERSION) --filter=blob:none --no-checkout https://github.com/SiliconLabs/simplicity_sdk $@ - cd $@ && git sparse-checkout set --no-cone /platform/Device/SiliconLabs/EFR32MG24/ /platform/common/inc/ /platform/radio/rail_lib/common/ /platform/radio/rail_lib/protocol/ieee802154/ /platform/radio/rail_lib/chip/efr32/efr32xg2x/ + cd $@ && git sparse-checkout set --no-cone /platform/Device/SiliconLabs/EFR32MG24/ /platform/common/inc/ /platform/radio/rail_lib/common/ /platform/radio/rail_lib/protocol/ieee802154/ /platform/radio/rail_lib/protocol/ble/ /platform/radio/rail_lib/chip/efr32/efr32xg2x/ cd $@ && GIT_LFS_SKIP_SMUDGE=1 git checkout -q $(LIBRAIL): diff --git a/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/Makefile b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/Makefile new file mode 100644 index 00000000..e043cdbf --- /dev/null +++ b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/Makefile @@ -0,0 +1,37 @@ +# Environment setup: https://mongoose.ws/documentation/tutorials/tools/ +# Nucleo-U5A5ZJ-Q: Mongoose over the USB-C port CN15, OTG_HS with its embedded +# PHY, no TinyUSB. Flash over the ST-LINK USB port + +MGDIR = ../../../.. + +CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion +CFLAGS += -Wformat-truncation -fno-common -Wconversion -Wno-sign-conversion +CFLAGS += -g3 -Os -ffunction-sections -fdata-sections +CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Icmsis_u5/Include +CFLAGS += -mcpu=cortex-m33 -mthumb -mfpu=fpv5-sp-d16 -mfloat-abi=hard +CFLAGS += $(CFLAGS_EXTRA) +LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs nano.specs -lc -lgcc -Wl,--gc-sections + +SOURCES = main.c hal.c $(MGDIR)/mongoose.c +SOURCES += cmsis_u5/Source/Templates/gcc/startup_stm32u5a5xx.s + +all build: firmware.bin + +firmware.bin: firmware.elf + arm-none-eabi-objcopy -O binary $< $@ + arm-none-eabi-size --format=berkeley $< + +firmware.elf: cmsis_core cmsis_u5 $(SOURCES) $(wildcard *.h) $(MGDIR)/mongoose.h link.ld Makefile + arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@ + +flash: firmware.elf + STM32_Programmer_CLI -c port=swd -e all -w $< -hardRst + +cmsis_core: + git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@ + +cmsis_u5: + git clone -q -c advice.detachedHead=false --depth 1 -b v1.4.2 https://github.com/STMicroelectronics/cmsis_device_u5 $@ + +clean: + rm -rf firmware.* cmsis_* diff --git a/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.c b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.c new file mode 100644 index 00000000..a7f8ecca --- /dev/null +++ b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.c @@ -0,0 +1,131 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "hal.h" + +// Added to minimise the bin size: avoid pulling printf and friends +void __assert_func(const char *s, int line, const char *fn, const char *expr) { + (void) s, (void) line, (void) fn, (void) expr; + for (;;) (void) 0; // or trigger the fault handler +} + +bool hal_timer_expired(volatile uint64_t *t, uint64_t period, uint64_t now) { + uint64_t diff = now - *t; // Wrap-safe elapsed time since last expiry + if (period == 0) return false; // Avoid division by zero + if (diff < period) return false; // Period has not elapsed yet + *t += (diff / period) * period; // Preserve cadence, skip missed periods + return true; +} + +static volatile uint64_t s_ticks; // Milliseconds since boot +void SysTick_Handler(void) { // SyStick IRQ handler, triggered every 1ms + s_ticks++; +} + +uint64_t hal_get_tick(void) { + return s_ticks; +}; + +uint32_t SystemCoreClock = SYS_FREQUENCY; +void SystemInit(void) { // Called automatically by startup code + hal_system_init(); // Enable FPU + hal_clock_init(); + SysTick_Config(SystemCoreClock / 1000); // Sys tick every 1ms +} + +void ExitRun0Mode(void) { +} + +struct stat; +__attribute__((weak)) int _fstat(int fd, struct stat *st) { + (void) fd, (void) st; + return -1; +} + +extern unsigned char _end[]; // End of data section, start of heap. See link.ld +static unsigned char *s_current_heap_end = _end; + +size_t hal_ram_used(void) { + return (size_t) (s_current_heap_end - _end); +} + +size_t hal_ram_free(void) { + unsigned char endofstack; + return (size_t) (&endofstack - s_current_heap_end); +} + +void *_sbrk(int incr) { + unsigned char *prev_heap; + unsigned char *heap_end = (unsigned char *) ((size_t) &heap_end - 256); + prev_heap = s_current_heap_end; + // Check how much space we got from the heap end to the stack end + if (s_current_heap_end + incr > heap_end) return (void *) -1; + s_current_heap_end += incr; + return prev_heap; +} + +__attribute__((weak)) int _open(const char *path) { + (void) path; + return -1; +} + +__attribute__((weak)) int _close(int fd) { + (void) fd; + return -1; +} + +__attribute__((weak)) int _isatty(int fd) { + (void) fd; + return 1; +} + +__attribute__((weak)) int _lseek(int fd, int ptr, int dir) { + (void) fd, (void) ptr, (void) dir; + return 0; +} + +__attribute__((weak)) void _exit(int status) { + (void) status; + for (;;) asm volatile("BKPT #0"); +} + +__attribute__((weak)) void _kill(int pid, int sig) { + (void) pid, (void) sig; +} + +__attribute__((weak)) int _getpid(void) { + return -1; +} + +__attribute__((weak)) int _write(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +__attribute__((weak)) int _read(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +__attribute__((weak)) int _link(const char *a, const char *b) { + (void) a, (void) b; + return -1; +} + +__attribute__((weak)) int _unlink(const char *a) { + (void) a; + return -1; +} + +__attribute__((weak)) int _stat(const char *path, struct stat *st) { + (void) path, (void) st; + return -1; +} + +__attribute__((weak)) int mkdir(const char *path, int mode) { + (void) path, (void) mode; + return -1; +} + +__attribute__((weak)) void _init(void) { +} diff --git a/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.h b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.h new file mode 100644 index 00000000..edfb1eb3 --- /dev/null +++ b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/hal.h @@ -0,0 +1,184 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved +// +// RM0456 +// https://www.st.com/resource/en/reference_manual/rm0456-stm32u5-series-armbased-32bit-mcus-stmicroelectronics.pdf +// https://www.st.com/resource/en/user_manual/um2861-stm32u5-nucleo144-board-mb1549-stmicroelectronics.pdf + +#pragma once + +#define LED_1 PIN('C', 7) // On-board LED pin (green) +#define LED_2 PIN('B', 7) // On-board LED pin (blue) +#define LED_3 PIN('G', 2) // On-board LED pin (red) +#define LED LED_1 // Use green LED for blinking + +#include + +#include +#include +#include +#include + +extern bool hal_timer_expired(volatile uint64_t *t, uint64_t prd, uint64_t now); +extern uint64_t hal_get_tick(void); +extern size_t hal_ram_free(void); +extern size_t hal_ram_used(void); +extern uint32_t SystemCoreClock; + +#define BIT(x) (1UL << (x)) +#define CLRSET(reg, clear, set) ((reg) = ((reg) & ~(clear)) | (set)) +#define PIN(bank, num) ((((bank) - 'A') << 8) | (num)) +#define PINNO(pin) (pin & 255) +#define PINBANK(pin) (pin >> 8) + +enum { + HAL_D1PRE = 1, // actual divisor value + HAL_HPRE = 1, // actual divisor value + HAL_D2PRE = 1, + HAL_D3PRE = 1, +}; +enum { PLL1_M = 1, PLL1_N = 80, PLL1_P = 2, PLL1_Q = 2, PLL1_R = 2 }; +#define MSIS_FREQUENCY (4 * 1024 * 1024) // 4 Mhz +#define SYS_FREQUENCY \ + (MSIS_FREQUENCY * PLL1_N / PLL1_M / PLL1_P / HAL_D1PRE) // 160MHz +#define AHB_FREQUENCY (SYS_FREQUENCY / HAL_HPRE) +#define APB2_FREQUENCY (AHB_FREQUENCY / HAL_D2PRE) +#define APB1_FREQUENCY (AHB_FREQUENCY / HAL_D1PRE) + +static inline void spin(volatile uint32_t n) { + while (n--) (void) 0; +} + +enum { + HAL_GPIO_MODE_INPUT, + HAL_GPIO_MODE_OUTPUT, + HAL_GPIO_MODE_AF, + HAL_GPIO_MODE_ANALOG +}; +enum { HAL_GPIO_OTYPE_PUSH_PULL, HAL_GPIO_OTYPE_OPEN_DRAIN }; +enum { + HAL_GPIO_SPEED_LOW, + HAL_GPIO_SPEED_MEDIUM, + HAL_GPIO_SPEED_HIGH, + HAL_GPIO_SPEED_INSANE +}; +enum { HAL_GPIO_PULL_NONE, HAL_GPIO_PULL_UP, HAL_GPIO_PULL_DOWN }; + +#define HAL_GPIO(N) ((GPIO_TypeDef *) (GPIOA_BASE_NS + 0x400 * (N))) + +static GPIO_TypeDef *hal_gpio_bank(uint16_t pin) { + return HAL_GPIO(PINBANK(pin)); +} +static inline void hal_gpio_toggle(uint16_t pin) { + GPIO_TypeDef *gpio = hal_gpio_bank(pin); + uint32_t mask = BIT(PINNO(pin)); + gpio->BSRR = mask << (gpio->ODR & mask ? 16 : 0); +} +static inline void hal_gpio_write(uint16_t pin, bool val) { + GPIO_TypeDef *gpio = hal_gpio_bank(pin); + gpio->BSRR = BIT(PINNO(pin)) << (val ? 0 : 16); +} +static inline void hal_gpio_init(uint16_t pin, uint8_t mode, uint8_t type, + uint8_t speed, uint8_t pull, uint8_t af) { + GPIO_TypeDef *gpio = hal_gpio_bank(pin); + uint8_t n = (uint8_t) (PINNO(pin)); + RCC->AHB2ENR1 |= BIT(PINBANK(pin)); // Enable GPIO clock + CLRSET(gpio->OTYPER, 1UL << n, ((uint32_t) type) << n); + CLRSET(gpio->OSPEEDR, 3UL << (n * 2), ((uint32_t) speed) << (n * 2)); + CLRSET(gpio->PUPDR, 3UL << (n * 2), ((uint32_t) pull) << (n * 2)); + CLRSET(gpio->AFR[n >> 3], 15UL << ((n & 7) * 4), + ((uint32_t) af) << ((n & 7) * 4)); + CLRSET(gpio->MODER, 3UL << (n * 2), ((uint32_t) mode) << (n * 2)); +} +static inline void hal_gpio_output(uint16_t pin) { + hal_gpio_init(pin, HAL_GPIO_MODE_OUTPUT, HAL_GPIO_OTYPE_PUSH_PULL, + HAL_GPIO_SPEED_HIGH, HAL_GPIO_PULL_NONE, 0); +} + +static inline void hal_rng_init(void) { + RCC->CCIPR2 |= RCC_CCIPR2_RNGSEL_0; // RNG clock source pll1_q_ck + RCC->AHB2ENR1 |= RCC_AHB2ENR1_RNGEN; // Enable RNG clock + RNG->CR = RNG_CR_RNGEN; // Enable RNG +} + +static inline uint32_t hal_rng_read(void) { + while ((RNG->SR & RNG_SR_DRDY) == 0) (void) 0; + return RNG->DR; +} + +// OTG_HS and its embedded high-speed PHY, as ST's CubeU5 USBX examples for +// this board set them up. The PHY's reference clock is the board's 16 MHz +// HSE. PA11 and PA12 are the PHY's own pins: no GPIO setup. The Mongoose +// driver, usb_dwc2, then runs the core at full speed +static inline void hal_usb_init(void) { + RCC->CR |= RCC_CR_HSEON; // 16 MHz HSE: the PHY's reference clock + while ((RCC->CR & RCC_CR_HSERDY) == 0) spin(1); + RCC->CCIPR2 &= ~RCC_CCIPR2_USBPHYCSEL; // USB PHY clock: HSE + RCC->APB3ENR |= RCC_APB3ENR_SYSCFGEN; + CLRSET(SYSCFG->OTGHSPHYCR, SYSCFG_OTGHSPHYCR_CLKSEL, + SYSCFG_OTGHSPHYCR_CLKSEL_0 | SYSCFG_OTGHSPHYCR_CLKSEL_1); // 16 MHz + RCC->AHB2ENR1 |= RCC_AHB2ENR1_OTGEN | RCC_AHB2ENR1_USBPHYCEN; + PWR->SVMCR |= PWR_SVMCR_USV; // VDDUSB valid + PWR->VOSR |= PWR_VOSR_USBPWREN | PWR_VOSR_USBBOOSTEN; // PHY supply + SYSCFG->OTGHSPHYCR |= SYSCFG_OTGHSPHYCR_EN; // PHY on +} + +static inline unsigned int hal_ahb_div2prescval(unsigned int div) { + if (div == 1) return 0; + unsigned int val = 7; + while (div >>= 1) ++val; + return val; +} + +static inline unsigned int hal_apb_div2prescval(unsigned int div) { + if (div <= 1) return 0; + unsigned int val = 0; + while (div >>= 1) ++val; + return val + 2; +} + +static inline void hal_clock_init(void) { + FLASH->ACR |= BIT(8); // prefetch + RCC->AHB3ENR |= RCC_AHB3ENR_PWREN; + PWR->SVMCR |= PWR_SVMCR_IO2SV; // Enable VDDIO2 supply + PWR->UCPDR |= PWR_UCPDR_UCPD_DBDIS; // Disable the internal Pull-Up in Dead + // Battery pins of UCPD peripheral + PWR->CR3 |= PWR_CR3_REGSEL; // enable SMPS + while ((PWR->SVMSR & BIT(1)) == 0) spin(1); + if ((PWR->SVMSR & PWR_SVMSR_ACTVOS) != (PWR_VOSR_VOS_0 | PWR_VOSR_VOS_1)) { + // control voltage scaling + PWR->VOSR |= PWR_VOSR_VOS_0 | PWR_VOSR_VOS_1 | PWR_VOSR_BOOSTEN; + while ((PWR->VOSR & PWR_VOSR_VOSRDY) == 0) spin(1); + while ((PWR->SVMSR & PWR_SVMSR_ACTVOSRDY) == 0) spin(1); + } + PWR->DBPR |= PWR_DBPR_DBP; // enable backup access + CLRSET(RCC->BDCR, 3 << 3, 0); // RCC_LSEDRIVE_LOW + RCC->BDCR |= RCC_BDCR_LSEON; // LSE enable + while ((RCC->BDCR & RCC_BDCR_LSERDY) == 0) spin(1); + RCC->BDCR |= RCC_BDCR_LSESYSEN; // LSESYS enable + while ((RCC->BDCR & RCC_BDCR_LSESYSRDY) == 0) spin(1); + PWR->VOSR &= ~PWR_VOSR_BOOSTEN; + RCC->CR &= ~BIT(24); // configure PLL1 + while ((RCC->CR & RCC_CR_PLL1RDY) != 0) spin(1); + RCC->PLL1CFGR = BIT(0) | ((PLL1_M - 1) << 8) | BIT(16) | BIT(17) | + BIT(18); // source, PLL1_M, enable PLL1_P, PLL1_Q + RCC->PLL1DIVR = (PLL1_N - 1) | ((PLL1_P - 1) << 9) | ((PLL1_Q - 1) << 16) | + ((PLL1_R - 1) << 24); + PWR->VOSR |= PWR_VOSR_BOOSTEN; + RCC->CR |= BIT(24); // PLL1ON + while ((RCC->CR & RCC_CR_PLL1RDY) == 0) spin(1); + CLRSET(FLASH->ACR, 0xf, 4); // flash latency 4 + RCC->CFGR1 |= 3; // set PLL as sysclk source + CLRSET(RCC->CFGR2, 0xf, hal_ahb_div2prescval(HAL_HPRE)); // HPRE + CLRSET(RCC->CFGR2, 0x70, hal_apb_div2prescval(HAL_D1PRE) << 4); // D1PRE + CLRSET(RCC->CFGR2, 0x700, hal_apb_div2prescval(HAL_D2PRE) << 8); // D2PRE + CLRSET(RCC->CFGR3, 0x70, hal_apb_div2prescval(HAL_D3PRE) << 4); // D3PRE +} + +static inline void hal_system_init(void) { + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); // Enable FPU + __DSB(); + __ISB(); + + SCB->VTOR = FLASH_BASE; // Vector Table Relocation in Internal FLASH +} diff --git a/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/link.ld b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/link.ld new file mode 100644 index 00000000..02252dbd --- /dev/null +++ b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/link.ld @@ -0,0 +1,31 @@ +ENTRY(Reset_Handler); +MEMORY { + flash(rx) : ORIGIN = 0x08000000, LENGTH = 4096k + sram(rwx) : ORIGIN = 0x20000000, LENGTH = 256k +} +_estack = ORIGIN(sram) + LENGTH(sram); /* stack points to end of SRAM */ + +SECTIONS { + .vectors : { KEEP(*(.isr_vector)) } > flash + .text : { *(.text* .text.*) } > flash + .rodata : { *(.rodata*) } > flash + + .data : { + _sdata = .; + *(.first_data) + *(.data SORT(.data.*)) + *(.iram .iram* .iram.*) + _edata = .; + } > sram AT > flash + _sidata = LOADADDR(.data); + + .bss : { + _sbss = .; + *(.bss SORT(.bss.*) COMMON) + _ebss = .; + } > sram + + . = ALIGN(8); + _end = .; +} + diff --git a/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/main.c b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/main.c new file mode 100644 index 00000000..91e7b074 --- /dev/null +++ b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/main.c @@ -0,0 +1,90 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved +// +// Nucleo-U5A5ZJ-Q: Mongoose over USB. One USB-C cable on CN15 gives the board +// a CDC-NCM Ethernet interface and a CDC-ACM serial port that carries the log + +#include "hal.h" +#include "mongoose.h" + +static void blink_task(void) { + static uint64_t blink_timer = 0; + if (mg_timer_expired(&blink_timer, 500, mg_millis())) hal_gpio_toggle(LED); +} + +uint64_t mg_millis(void) { + return hal_get_tick(); +} + +bool mg_random(void *buf, size_t len) { + for (size_t n = 0; n < len; n += sizeof(uint32_t)) { + uint32_t r = hal_rng_read(); + memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r)); + } + return true; +} + +// Self-signed P-256 certificate and key for the HTTPS listener. Created by: +// openssl ecparam -genkey -name prime256v1 -noout -out key.pem +// openssl req -x509 -key key.pem -out cert.pem -days 3650 -subj /CN=mg +#define TLS_CERT \ + "-----BEGIN CERTIFICATE-----\n" \ + "MIIBgjCCASegAwIBAgIUIJOq77Qn7lHbH6WseMemeqorR50wCgYIKoZIzj0EAwIw\n" \ + "FjEUMBIGA1UEAwwLbnVjbGVvLWg3MjMwHhcNMjYxMDEyMTUwMjE5WhcNMzYxMDA5\n" \ + "MTUwMjE5WjAWMRQwEgYDVQQDDAtudWNsZW8taDcyMzBZMBMGByqGSM49AgEGCCqG\n" \ + "SM49AwEHA0IABB6IQJNmzrsdQL+2BnZYS7GYOaj7sz8f6cjBmz3n8D9Em19XodlU\n" \ + "uy4ybIvyhr766lL0ERoTmMUivb/lGmzx9C+jUzBRMB0GA1UdDgQWBBQqxMuc4gj7\n" \ + "MTMzreWlRMNI3QMqTzAfBgNVHSMEGDAWgBQqxMuc4gj7MTMzreWlRMNI3QMqTzAP\n" \ + "BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDY4xaJpuxq6b3rHK3b\n" \ + "lOIQyfkQX+orCRqQUkseplqpqwIhAKswZFNn+2zUNRRNY8+cHmdIwmdpsmxtoWYP\n" \ + "BCjX++LI\n" \ + "-----END CERTIFICATE-----\n" + +#define TLS_KEY \ + "-----BEGIN EC PRIVATE KEY-----\n" \ + "MHcCAQEEIJ/GBl0TlD52q9PMg1KWaNIdXqp8b/HyIsABmBpqC+O1oAoGCCqGSM49\n" \ + "AwEHoUQDQgAEHohAk2bOux1Av7YGdlhLsZg5qPuzPx/pyMGbPefwP0SbX1eh2VS7\n" \ + "LjJsi/KGvvrqUvQRGhOYxSK9v+UabPH0Lw==\n" \ + "-----END EC PRIVATE KEY-----\n" + +static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_ACCEPT && c->is_tls) { // Accepted on the https:// listener + struct mg_tls_opts opts = {.cert = mg_str(TLS_CERT), + .key = mg_str(TLS_KEY)}; + mg_tls_init(c, &opts); + } else if (ev == MG_EV_HTTP_MSG) { + struct mg_http_message *hm = (struct mg_http_message *) ev_data; + if (mg_match(hm->uri, mg_str("/api/tick"), NULL)) { + mg_http_reply(c, 200, "", "{%m:%llu}\n", MG_ESC("tick"), mg_millis()); + } else { + mg_http_reply(c, 200, "", + "Hi from Mongoose!\n" + "tick: %llu\n" + "ram used: %zu\n" + "ram free: %zu\n", + mg_millis(), hal_ram_used(), hal_ram_free()); + } + } +} + +int main(void) { + hal_rng_init(); + hal_gpio_output(LED); + hal_usb_init(); + + struct mg_mgr mgr; + mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h + mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); + mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL); + + MG_INFO(("Initialised. CPU clock: %lu MHz", SystemCoreClock / 1000000)); + MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free())); + MG_INFO(("USB Ethernet + serial")); + + for (;;) { + mg_mgr_poll(&mgr, 0); + blink_task(); + } + + return 0; +} diff --git a/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/mongoose_config.h b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/mongoose_config.h new file mode 100644 index 00000000..4c28f294 --- /dev/null +++ b/tutorials/stm32/nucleo-u5a5zj-q/minimal-usb/mongoose_config.h @@ -0,0 +1,32 @@ +#pragma once +#include "hal.h" // Device header: UID_BASE gives the USB serial number + +// See https://mongoose.ws/docs/getting-started/build-environment/ +#define MG_ARCH MG_ARCH_ARMGCC +#define MG_TLS MG_TLS_BUILTIN +#define MG_ENABLE_TCPIP 1 +#define MG_ENABLE_CUSTOM_MILLIS 1 +#define MG_ENABLE_CUSTOM_RANDOM 1 + +#define MG_ENABLE_DRIVER_USB_DWC2 1 // STM32 OTG_HS: the USB-C port, CN15 +#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface +#define MG_ENABLE_USB_SERIAL 1 // USB serial log console +#define MG_USB_DWC2_BASE USB_OTG_HS_BASE // OTG_HS +#define MG_USB_DWC2_UTMI 1 // Embedded high-speed PHY +// No VBUS sensing: tell the PHY that VBUS is valid +#define MG_USB_DWC2_GCCFG (USB_OTG_GCCFG_VBVALEXTOEN | USB_OTG_GCCFG_VBVALOVAL) + +// Static device address; the driver serves DHCP to the USB host. Remove +// these to get an address over DHCP instead, e.g. from Internet Sharing +#define MG_TCPIP_IP MG_IPV4(192, 168, 7, 1) +#define MG_TCPIP_MASK MG_IPV4(255, 255, 255, 0) + +#define MG_SET_MAC_ADDRESS(mac) \ + do { \ + mac[0] = 2; \ + mac[1] = 3; \ + mac[2] = 4; \ + mac[3] = 5; \ + mac[4] = 6; \ + mac[5] = 7; \ + } while (0) diff --git a/tutorials/stm32/portenta-h7/minimal-usb/Makefile b/tutorials/stm32/portenta-h7/minimal-usb/Makefile new file mode 100644 index 00000000..404f31fc --- /dev/null +++ b/tutorials/stm32/portenta-h7/minimal-usb/Makefile @@ -0,0 +1,43 @@ +# Environment setup: https://mongoose.ws/documentation/tutorials/tools/ +# Portenta H7: Mongoose over the USB-C port, no TinyUSB. Flash over USB with +# dfu-util: Arduino's bootloader stays at 0x08000000, the firmware goes to +# 0x08040000. Double-tap RESET to enter the bootloader, or `make flash` again +# once this firmware runs: it reboots into the bootloader on a 1200 baud touch + +MGDIR = ../../../.. + +CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion +CFLAGS += -Wformat-truncation -fno-common -Wconversion -Wno-sign-conversion +CFLAGS += -g3 -Os -ffunction-sections -fdata-sections +CFLAGS += -I. -I$(MGDIR) -Icmsis_core/CMSIS/Core/Include -Icmsis_h7/Include +CFLAGS += -mcpu=cortex-m7 -mthumb -mfloat-abi=hard -mfpu=fpv5-d16 -DCORE_CM7 +CFLAGS += $(CFLAGS_EXTRA) +LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs nano.specs -lc -lgcc -Wl,--gc-sections + +SOURCES = main.c hal.c $(MGDIR)/mongoose.c +SOURCES += cmsis_h7/Source/Templates/gcc/startup_stm32h747xx.s + +all build: firmware.bin + +firmware.bin: firmware.elf + arm-none-eabi-objcopy -O binary $< $@ + arm-none-eabi-size --format=berkeley $< + +firmware.elf: cmsis_core cmsis_h7 $(SOURCES) $(wildcard *.h) $(MGDIR)/mongoose.h link.ld Makefile + arm-none-eabi-gcc $(SOURCES) $(CFLAGS) $(LDFLAGS) -o $@ + +# Bootloader entry: open the board's serial port at 1200 baud. PORT: the +# board's USB serial port, e.g. /dev/cu.usbmodem1234. Without PORT, enter +# the bootloader by double-tapping RESET +flash: firmware.bin + $(if $(PORT),stty -f $(PORT) 1200 2>/dev/null || stty -F $(PORT) 1200;) + dfu-util -w -a 0 -s 0x8040000:leave -D $< + +cmsis_core: + git clone -q -c advice.detachedHead=false --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@ + +cmsis_h7: + git clone -q -c advice.detachedHead=false --depth 1 -b v1.10.4 https://github.com/STMicroelectronics/cmsis_device_h7 $@ + +clean: + rm -rf firmware.* cmsis_* diff --git a/tutorials/stm32/portenta-h7/minimal-usb/hal.c b/tutorials/stm32/portenta-h7/minimal-usb/hal.c new file mode 100644 index 00000000..a7f8ecca --- /dev/null +++ b/tutorials/stm32/portenta-h7/minimal-usb/hal.c @@ -0,0 +1,131 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved + +#include "hal.h" + +// Added to minimise the bin size: avoid pulling printf and friends +void __assert_func(const char *s, int line, const char *fn, const char *expr) { + (void) s, (void) line, (void) fn, (void) expr; + for (;;) (void) 0; // or trigger the fault handler +} + +bool hal_timer_expired(volatile uint64_t *t, uint64_t period, uint64_t now) { + uint64_t diff = now - *t; // Wrap-safe elapsed time since last expiry + if (period == 0) return false; // Avoid division by zero + if (diff < period) return false; // Period has not elapsed yet + *t += (diff / period) * period; // Preserve cadence, skip missed periods + return true; +} + +static volatile uint64_t s_ticks; // Milliseconds since boot +void SysTick_Handler(void) { // SyStick IRQ handler, triggered every 1ms + s_ticks++; +} + +uint64_t hal_get_tick(void) { + return s_ticks; +}; + +uint32_t SystemCoreClock = SYS_FREQUENCY; +void SystemInit(void) { // Called automatically by startup code + hal_system_init(); // Enable FPU + hal_clock_init(); + SysTick_Config(SystemCoreClock / 1000); // Sys tick every 1ms +} + +void ExitRun0Mode(void) { +} + +struct stat; +__attribute__((weak)) int _fstat(int fd, struct stat *st) { + (void) fd, (void) st; + return -1; +} + +extern unsigned char _end[]; // End of data section, start of heap. See link.ld +static unsigned char *s_current_heap_end = _end; + +size_t hal_ram_used(void) { + return (size_t) (s_current_heap_end - _end); +} + +size_t hal_ram_free(void) { + unsigned char endofstack; + return (size_t) (&endofstack - s_current_heap_end); +} + +void *_sbrk(int incr) { + unsigned char *prev_heap; + unsigned char *heap_end = (unsigned char *) ((size_t) &heap_end - 256); + prev_heap = s_current_heap_end; + // Check how much space we got from the heap end to the stack end + if (s_current_heap_end + incr > heap_end) return (void *) -1; + s_current_heap_end += incr; + return prev_heap; +} + +__attribute__((weak)) int _open(const char *path) { + (void) path; + return -1; +} + +__attribute__((weak)) int _close(int fd) { + (void) fd; + return -1; +} + +__attribute__((weak)) int _isatty(int fd) { + (void) fd; + return 1; +} + +__attribute__((weak)) int _lseek(int fd, int ptr, int dir) { + (void) fd, (void) ptr, (void) dir; + return 0; +} + +__attribute__((weak)) void _exit(int status) { + (void) status; + for (;;) asm volatile("BKPT #0"); +} + +__attribute__((weak)) void _kill(int pid, int sig) { + (void) pid, (void) sig; +} + +__attribute__((weak)) int _getpid(void) { + return -1; +} + +__attribute__((weak)) int _write(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +__attribute__((weak)) int _read(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +__attribute__((weak)) int _link(const char *a, const char *b) { + (void) a, (void) b; + return -1; +} + +__attribute__((weak)) int _unlink(const char *a) { + (void) a; + return -1; +} + +__attribute__((weak)) int _stat(const char *path, struct stat *st) { + (void) path, (void) st; + return -1; +} + +__attribute__((weak)) int mkdir(const char *path, int mode) { + (void) path, (void) mode; + return -1; +} + +__attribute__((weak)) void _init(void) { +} diff --git a/tutorials/stm32/portenta-h7/minimal-usb/hal.h b/tutorials/stm32/portenta-h7/minimal-usb/hal.h new file mode 100644 index 00000000..4e39841d --- /dev/null +++ b/tutorials/stm32/portenta-h7/minimal-usb/hal.h @@ -0,0 +1,198 @@ +// Copyright (c) 2022-2026 Cesanta Software Limited +// All rights reserved +// +// RM0399 +// https://www.st.com/resource/en/reference_manual/rm0399-stm32h745755-and-stm32h747757-advanced-armbased-32bit-mcus-stmicroelectronics.pdf +// https://www.st.com/resource/en/datasheet/stm32h747xi.pdf +// https://docs.arduino.cc/hardware/portenta-h7/ + +#pragma once + +#define LED_1 PIN('K', 5) // On-board LED pin (red) +#define LED_2 PIN('K', 6) // On-board LED pin (green) +#define LED_3 PIN('K', 7) // On-board LED pin (blue) +#define LED LED_2 // Use green LED for blinking + +#include + +#include +#include +#include +#include + +extern bool hal_timer_expired(volatile uint64_t *t, uint64_t prd, uint64_t now); +extern uint64_t hal_get_tick(void); +extern size_t hal_ram_free(void); +extern size_t hal_ram_used(void); +extern uint32_t SystemCoreClock; + +#define BIT(x) (1UL << (x)) +#define CLRSET(reg, clear, set) ((reg) = ((reg) & ~(clear)) | (set)) +#define PIN(bank, num) ((((bank) - 'A') << 8) | (num)) +#define PINNO(pin) (pin & 255) +#define PINBANK(pin) (pin >> 8) + +// System clock (2.1, Fig 1; 8.5, Fig 45; 8.5.5, Fig 47; 8.5.6, Fig 49) +// - This board defaults to work with an SMPS regulator, so: +// - SYS_FREQUENCY <= 400 MHz; hclk = SYS_FREQUENCY / HPRE ; hclk <= 200 MHz; +// APB clocks <= 100 MHz. +// - D1 domain bus matrix (and so flash) runs at hclk frequency. Configure flash +// latency (WS) in accordance to hclk freq (4.3.8, Table 17) +enum { + HAL_D1CPRE = 1, // actual divisor value + HAL_HPRE = 2, // actual divisor value + HAL_D1PPRE = 4, // register values, divisor value = BIT(value - 3) = / 2 + HAL_D2PPRE1 = 4, + HAL_D2PPRE2 = 4, + HAL_D3PPRE = 4 +}; +// PLL1_P: odd division factors are not allowed (8.7.13) (according to Cube, '1' +// is also an "odd division factor"). +// Make sure your chip is revision 'V', otherwise set PLL1_N = 400 +enum { PLL1_HSI = 64, PLL1_M = 32, PLL1_N = 400, PLL1_P = 2, PLL1_Q = 4 }; +#define SYS_FREQUENCY \ + ((PLL1_HSI * PLL1_N / PLL1_M / PLL1_P / HAL_D1CPRE) * 1000000) + +static inline void spin(volatile uint32_t n) { + while (n--) (void) 0; +} + +enum { + HAL_GPIO_MODE_INPUT, + HAL_GPIO_MODE_OUTPUT, + HAL_GPIO_MODE_AF, + HAL_GPIO_MODE_ANALOG +}; +enum { HAL_GPIO_OTYPE_PUSH_PULL, HAL_GPIO_OTYPE_OPEN_DRAIN }; +enum { + HAL_GPIO_SPEED_LOW, + HAL_GPIO_SPEED_MEDIUM, + HAL_GPIO_SPEED_HIGH, + HAL_GPIO_SPEED_INSANE +}; +enum { HAL_GPIO_PULL_NONE, HAL_GPIO_PULL_UP, HAL_GPIO_PULL_DOWN }; + +#define HAL_GPIO(N) ((GPIO_TypeDef *) (0x40000000 + 0x18020000UL + 0x400 * (N))) + +static inline GPIO_TypeDef *hal_gpio_bank(uint16_t pin) { + return HAL_GPIO(PINBANK(pin)); +} +static inline void hal_gpio_toggle(uint16_t pin) { + GPIO_TypeDef *gpio = hal_gpio_bank(pin); + uint32_t mask = BIT(PINNO(pin)); + gpio->BSRR = mask << (gpio->ODR & mask ? 16 : 0); +} +static inline void hal_gpio_write(uint16_t pin, bool val) { + GPIO_TypeDef *gpio = hal_gpio_bank(pin); + gpio->BSRR = BIT(PINNO(pin)) << (val ? 0 : 16); +} +static inline void hal_gpio_init(uint16_t pin, uint8_t mode, uint8_t type, + uint8_t speed, uint8_t pull, uint8_t af) { + GPIO_TypeDef *gpio = hal_gpio_bank(pin); + uint8_t n = (uint8_t) (PINNO(pin)); + RCC->AHB4ENR |= BIT(PINBANK(pin)); // Enable GPIO clock + CLRSET(gpio->OTYPER, 1UL << n, ((uint32_t) type) << n); + CLRSET(gpio->OSPEEDR, 3UL << (n * 2), ((uint32_t) speed) << (n * 2)); + CLRSET(gpio->PUPDR, 3UL << (n * 2), ((uint32_t) pull) << (n * 2)); + CLRSET(gpio->AFR[n >> 3], 15UL << ((n & 7) * 4), + ((uint32_t) af) << ((n & 7) * 4)); + CLRSET(gpio->MODER, 3UL << (n * 2), ((uint32_t) mode) << (n * 2)); +} +static inline void hal_gpio_output(uint16_t pin) { + hal_gpio_init(pin, HAL_GPIO_MODE_OUTPUT, HAL_GPIO_OTYPE_PUSH_PULL, + HAL_GPIO_SPEED_HIGH, HAL_GPIO_PULL_NONE, 0); +} + +static inline void hal_rng_init(void) { + RCC->D2CCIP2R |= RCC_D2CCIP2R_RNGSEL_0; // RNG clock source pll1_q_ck + RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN; // Enable RNG clock + RNG->CR = RNG_CR_RNGEN; // Enable RNG +} + +static inline uint32_t hal_rng_read(void) { + while ((RNG->SR & RNG_SR_DRDY) == 0) (void) 0; + return RNG->DR; +} + +// USB-C: the OTG_HS core with an external ULPI PHY, on these pins, alternate +// function 10. Pins from Arduino's mbed-os, TARGET_PORTENTA_H7 +// PeripheralPins.c. Arduino's bootloader uses the same port for DFU, and +// leaves the PHY running. The OTG_HS core's kernel clock: HSI48 +static inline void hal_usb_init(void) { + uint16_t pins[] = {PIN('A', 3), PIN('A', 5), PIN('B', 0), PIN('B', 1), + PIN('B', 5), PIN('B', 10), PIN('B', 11), PIN('B', 12), + PIN('B', 13), PIN('C', 0), PIN('H', 4), PIN('I', 11)}; + for (size_t i = 0; i < sizeof(pins) / sizeof(pins[0]); i++) { + hal_gpio_init(pins[i], HAL_GPIO_MODE_AF, HAL_GPIO_OTYPE_PUSH_PULL, + HAL_GPIO_SPEED_INSANE, HAL_GPIO_PULL_NONE, 10); + } + RCC->CR |= RCC_CR_HSI48ON; + while ((RCC->CR & RCC_CR_HSI48RDY) == 0) spin(1); + CLRSET(RCC->D2CCIP2R, RCC_D2CCIP2R_USBSEL, RCC_D2CCIP2R_USBSEL); // HSI48 + RCC->AHB1ENR |= RCC_AHB1ENR_USB1OTGHSEN | RCC_AHB1ENR_USB1OTGHSULPIEN; + RCC->AHB1RSTR |= RCC_AHB1RSTR_USB1OTGHSRST; // A clean core: the bootloader + RCC->AHB1RSTR &= ~RCC_AHB1RSTR_USB1OTGHSRST; // used it for DFU +} + +// Restart into Arduino's bootloader, in DFU mode: what ArduinoCore-mbed's +// _ontouch1200bps_() does for the Portenta H7, RTC backup register 0 = 0xDF59 +static inline void hal_reboot_to_bootloader(void) { + PWR->CR1 |= PWR_CR1_DBP; // Allow backup domain writes + RCC->APB4ENR |= RCC_APB4ENR_RTCAPBEN; + RTC->BKP0R = 0xDF59; + NVIC_SystemReset(); +} + +static inline unsigned int hal_div2prescval(unsigned int div) { + // 0 --> /1; 8 --> /2 ... 11 --> /16; 12 --> /64 ... 15 --> /512 + if (div == 1) return 0; + if (div > 16) div /= 2; + unsigned int val = 7; + while (div >>= 1) ++val; + return val; +} + +static inline unsigned int hal_pllrge(unsigned int f) { + unsigned int val = 0; + while (f >>= 1) ++val; + return val - 1; +} + +// HSE: 25MHz in PH0; LSE: in PC14; both unused +static inline void hal_clock_init(void) { // Called automatically by startup + // Set flash latency. RM section 4.9.1, section 4.3.8 table 16 + CLRSET(FLASH->ACR, (FLASH_ACR_WRHIGHFREQ_Msk | FLASH_ACR_LATENCY_Msk), + FLASH_ACR_LATENCY_2WS | FLASH_ACR_WRHIGHFREQ_1); + CLRSET(PWR->CR3, BIT(1), BIT(2)); // select SMPS + while ((PWR->CSR1 & BIT(13)) == 0) spin(1); // ACTVOSRDY + PWR->D3CR |= BIT(15) | BIT(14); // Select VOS1 + uint32_t f = PWR->D3CR; // fake read to wait for bus clocking + while ((PWR->CSR1 & BIT(13)) == 0) spin(1); // ACTVOSRDY + (void) f; + RCC->CFGR &= ~(3 << 0); // Set clock source to HSI (bootloader...) + RCC->CR &= ~BIT(24); // Disable PLL1 + CLRSET(RCC->D1CFGR, (0x0F << 8) | (7 << 4) | (0x0F << 0), + (hal_div2prescval(HAL_D1CPRE) << 8) | (HAL_D1PPRE << 4) | + (hal_div2prescval(HAL_HPRE) << 0)); + RCC->D2CFGR = (HAL_D2PPRE2 << 8) | (HAL_D2PPRE1 << 4); + RCC->D3CFGR = (HAL_D3PPRE << 4); + // DIVQ1EN DIVP1EN PLL1RGE !PLL1VCOSEL !PLL1FRACEN + CLRSET(RCC->PLLCFGR, (3 << 2) | BIT(1) | BIT(0), + BIT(17) | BIT(16) | hal_pllrge(PLL1_HSI / PLL1_M) << 2); + CLRSET(RCC->PLL1DIVR, (0x7F << 16) | (0x7F << 9) | (0x1FF << 0), + ((PLL1_Q - 1) << 16) | ((PLL1_P - 1) << 9) | ((PLL1_N - 1) << 0)); + CLRSET(RCC->PLLCKSELR, (0x3F << 4) | (3 << 0), PLL1_M << 4); // HSI/M + RCC->CR |= BIT(24); // PLL1 on + while ((RCC->CR & BIT(25)) == 0) spin(1); // Wait until done + RCC->CFGR |= (3 << 0); // Set clock source to PLL1 + while ((RCC->CFGR & (7 << 3)) != (3 << 3)) spin(1); // Wait until done + RCC->APB4ENR |= RCC_APB4ENR_SYSCFGEN; // Enable SYSCFG +} + +static inline void hal_system_init(void) { + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); // Enable FPU + SCB_DisableDCache(); // The bootloader enables caches, disable them + SCB_DisableICache(); + __DSB(); + __ISB(); +} diff --git a/tutorials/stm32/portenta-h7/minimal-usb/link.ld b/tutorials/stm32/portenta-h7/minimal-usb/link.ld new file mode 100644 index 00000000..a88f6770 --- /dev/null +++ b/tutorials/stm32/portenta-h7/minimal-usb/link.ld @@ -0,0 +1,33 @@ +/* DTCMRAM (rwx) : ORIGIN = 0x20000400, LENGTH = 128k - 1k */ /* bootloader starts at 0x20000000 */ + +ENTRY(Reset_Handler); +MEMORY { + flash(rx) : ORIGIN = 0x08040000, LENGTH = 2048k - 0x40000 /* bootloader starts at 0x08000000 */ + sram(rwx) : ORIGIN = 0x24000000, LENGTH = 512k +} +_estack = ORIGIN(sram) + LENGTH(sram); /* stack points to end of SRAM */ + +SECTIONS { + .vectors : { KEEP(*(.isr_vector)) } > flash + .text : { *(.text* .text.*) } > flash + .rodata : { *(.rodata*) } > flash + + .data : { + _sdata = .; + *(.first_data) + *(.data SORT(.data.*)) + *(.iram .iram* .iram.*) + _edata = .; + } > sram AT > flash + _sidata = LOADADDR(.data); + + .bss : { + _sbss = .; + *(.bss SORT(.bss.*) COMMON) + _ebss = .; + } > sram + + . = ALIGN(8); + _end = .; +} + diff --git a/tutorials/stm32/portenta-h7/minimal-usb/main.c b/tutorials/stm32/portenta-h7/minimal-usb/main.c new file mode 100644 index 00000000..a60cbda4 --- /dev/null +++ b/tutorials/stm32/portenta-h7/minimal-usb/main.c @@ -0,0 +1,91 @@ +// Copyright (c) 2026 Cesanta Software Limited +// All rights reserved +// +// Portenta H7: Mongoose over USB. One USB-C cable gives the board a CDC-NCM +// Ethernet interface and a CDC-ACM serial port that carries the log + +#include "hal.h" +#include "mongoose.h" + +static void blink_task(void) { + static uint64_t blink_timer = 0; + if (mg_timer_expired(&blink_timer, 500, mg_millis())) hal_gpio_toggle(LED); +} + +uint64_t mg_millis(void) { + return hal_get_tick(); +} + +bool mg_random(void *buf, size_t len) { + for (size_t n = 0; n < len; n += sizeof(uint32_t)) { + uint32_t r = hal_rng_read(); + memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r)); + } + return true; +} + +// Self-signed P-256 certificate and key for the HTTPS listener. Created by: +// openssl ecparam -genkey -name prime256v1 -noout -out key.pem +// openssl req -x509 -key key.pem -out cert.pem -days 3650 -subj /CN=mg +#define TLS_CERT \ + "-----BEGIN CERTIFICATE-----\n" \ + "MIIBgjCCASegAwIBAgIUIJOq77Qn7lHbH6WseMemeqorR50wCgYIKoZIzj0EAwIw\n" \ + "FjEUMBIGA1UEAwwLbnVjbGVvLWg3MjMwHhcNMjYxMDEyMTUwMjE5WhcNMzYxMDA5\n" \ + "MTUwMjE5WjAWMRQwEgYDVQQDDAtudWNsZW8taDcyMzBZMBMGByqGSM49AgEGCCqG\n" \ + "SM49AwEHA0IABB6IQJNmzrsdQL+2BnZYS7GYOaj7sz8f6cjBmz3n8D9Em19XodlU\n" \ + "uy4ybIvyhr766lL0ERoTmMUivb/lGmzx9C+jUzBRMB0GA1UdDgQWBBQqxMuc4gj7\n" \ + "MTMzreWlRMNI3QMqTzAfBgNVHSMEGDAWgBQqxMuc4gj7MTMzreWlRMNI3QMqTzAP\n" \ + "BgNVHRMBAf8EBTADAQH/MAoGCCqGSM49BAMCA0kAMEYCIQDY4xaJpuxq6b3rHK3b\n" \ + "lOIQyfkQX+orCRqQUkseplqpqwIhAKswZFNn+2zUNRRNY8+cHmdIwmdpsmxtoWYP\n" \ + "BCjX++LI\n" \ + "-----END CERTIFICATE-----\n" + +#define TLS_KEY \ + "-----BEGIN EC PRIVATE KEY-----\n" \ + "MHcCAQEEIJ/GBl0TlD52q9PMg1KWaNIdXqp8b/HyIsABmBpqC+O1oAoGCCqGSM49\n" \ + "AwEHoUQDQgAEHohAk2bOux1Av7YGdlhLsZg5qPuzPx/pyMGbPefwP0SbX1eh2VS7\n" \ + "LjJsi/KGvvrqUvQRGhOYxSK9v+UabPH0Lw==\n" \ + "-----END EC PRIVATE KEY-----\n" + +static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) { + if (ev == MG_EV_ACCEPT && c->is_tls) { // Accepted on the https:// listener + struct mg_tls_opts opts = {.cert = mg_str(TLS_CERT), + .key = mg_str(TLS_KEY)}; + mg_tls_init(c, &opts); + } else if (ev == MG_EV_HTTP_MSG) { + struct mg_http_message *hm = (struct mg_http_message *) ev_data; + if (mg_match(hm->uri, mg_str("/api/tick"), NULL)) { + mg_http_reply(c, 200, "", "{%m:%llu}\n", MG_ESC("tick"), mg_millis()); + } else { + mg_http_reply(c, 200, "", + "Hi from Mongoose!\n" + "tick: %llu\n" + "ram used: %zu\n" + "ram free: %zu\n", + mg_millis(), hal_ram_used(), hal_ram_free()); + } + } +} + +int main(void) { + hal_rng_init(); + hal_gpio_output(LED); + hal_gpio_write(LED, true); // Off, the LEDs are active low + hal_usb_init(); + + struct mg_mgr mgr; + mg_mgr_init(&mgr); // Also starts the USB driver, see mongoose_config.h + mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); + mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL); + + MG_INFO(("Initialised. CPU clock: %lu MHz", SystemCoreClock / 1000000)); + MG_INFO(("RAM used: %zu, free: %zu", hal_ram_used(), hal_ram_free())); + MG_INFO(("USB Ethernet + serial")); + + for (;;) { + mg_mgr_poll(&mgr, 0); + blink_task(); + } + + return 0; +} diff --git a/tutorials/stm32/portenta-h7/minimal-usb/mongoose_config.h b/tutorials/stm32/portenta-h7/minimal-usb/mongoose_config.h new file mode 100644 index 00000000..e162d89d --- /dev/null +++ b/tutorials/stm32/portenta-h7/minimal-usb/mongoose_config.h @@ -0,0 +1,31 @@ +#pragma once +#include "hal.h" // Device header: UID_BASE gives the USB serial number + +// See https://mongoose.ws/docs/getting-started/build-environment/ +#define MG_ARCH MG_ARCH_ARMGCC +#define MG_TLS MG_TLS_BUILTIN +#define MG_ENABLE_TCPIP 1 +#define MG_ENABLE_CUSTOM_MILLIS 1 +#define MG_ENABLE_CUSTOM_RANDOM 1 + +#define MG_ENABLE_DRIVER_USB_DWC2 1 // STM32 OTG: the USB-C port +#define MG_ENABLE_USB_ETHERNET 1 // USB NCM Ethernet interface +#define MG_ENABLE_USB_SERIAL 1 // USB serial log console +#define MG_USB_DWC2_BASE USB1_OTG_HS_PERIPH_BASE // OTG_HS +#define MG_USB_DWC2_ULPI 1 // External ULPI PHY +#define MG_USB_REBOOT() hal_reboot_to_bootloader() // 1200 baud touch + +// Static device address; the driver serves DHCP to the USB host. Remove +// these to get an address over DHCP instead, e.g. from Internet Sharing +#define MG_TCPIP_IP MG_IPV4(192, 168, 7, 1) +#define MG_TCPIP_MASK MG_IPV4(255, 255, 255, 0) + +#define MG_SET_MAC_ADDRESS(mac) \ + do { \ + mac[0] = 2; \ + mac[1] = 3; \ + mac[2] = 4; \ + mac[3] = 5; \ + mac[4] = 6; \ + mac[5] = 7; \ + } while (0)