Compare commits

..
Author SHA1 Message Date
Sergio R. Caprile 071cd50ef9 Merge pull request #3790 from cesanta/hu
harden WS, uniformize RFC citation
2026-11-23 15:23:41 -03:00
Sergio R. Caprile 8d616998fa Merge pull request #3789 from cesanta/hdrs
Standardize to per-driver init macros; add default driver auto-init sections to all driver headers
2026-11-23 14:24:21 -03:00
Sergio R. Caprile 255b62572c Merge branch 'master' into hdrs 2026-11-23 14:24:00 -03:00
Sergio R. Caprile bdf0de79c0 Merge pull request #3786 from cesanta/802
Add esp32c6 802.15.4
2026-11-23 14:21:11 -03:00
robert 5e7edde7e5 Update the rest of the drivers 2026-11-23 17:24:23 +02:00
cpq ecedc31e34 Add esp32c6 802.15.4 2026-11-23 14:56:21 +00:00
Sergio R. Caprile 8996d96443 harden WS, uniformize RFC citation 2026-11-23 09:56:27 -03:00
cpq 2cf96bcb19 Remove tutorials/mqtt/mqtt-client-aws-iot as tutorials/mqtt/mqtt-client covers it 2026-11-23 10:15:31 +00:00
cpq 93f2939655 Make w5500 driver like the rest 2026-11-21 11:39:54 +00:00
Sergio R. Caprile 277741ca53 Merge pull request #3787 from cesanta/hdrs
STM32F driver: per-driver INIT macro, like the radio drivers
2026-11-20 17:26:40 -03:00
Sergio R. Caprile 9d0b015217 update archs 2026-11-20 14:26:55 -03:00
cpq 5aa320658a STM32F driver: per-driver INIT macro, like the radio drivers 2026-11-20 17:17:50 +00:00
Sergio R. Caprile 1620b2ae03 Merge pull request #3785 from cesanta/bsdud
Add improved datagram support for BSD
2026-11-20 13:52:41 -03:00
Sergio R. Caprile 0914048424 Add improved datagram support for BSD 2026-11-20 13:50:25 -03:00
Sergio R. Caprile 0f319e3060 Merge pull request #3783 from cesanta/tlsmaint
make callers agree with API
2026-11-18 18:38:26 -03:00
Sergey Lyubka d612b7f1c4 Merge pull request #3782 from cesanta/no46loop
avoid IPv6 querying forever
2026-11-18 21:34:32 +00:00
Sergey Lyubka 6d5f4a5a20 Merge pull request #3781 from cesanta/freewilly
free DER data too
2026-11-18 21:34:01 +00:00
Sergey Lyubka cd10b35de4 Merge pull request #3780 from cesanta/recvfrom6
fix recvfrom in IPv6
2026-11-18 21:33:37 +00:00
Sergey Lyubka f04cb5333e Merge pull request #3779 from cesanta/nonstr
don't use strncpy on a mg_str
2026-11-18 21:33:13 +00:00
cpq 28e3b347d4 Tutorials - nits and mqtt client adoption 2026-11-18 20:28:36 +00:00
Sergio R. Caprile 63aaad829a make callers agree with API 2026-11-17 15:45:47 -03:00
Sergio R. Caprile 9322227886 avoid IPv6 querying forever 2026-11-17 11:53:09 -03:00
Sergio R. Caprile e3a78d513e free DER data too 2026-11-16 16:22:36 -03:00
Sergio R. Caprile ee338b7bba fix recvfrom in IPv6 2026-11-16 16:00:56 -03:00
Sergio R. Caprile 0f157bd23b don't use strncpy on a mg_str 2026-11-16 15:48:16 -03:00
116 changed files with 2326 additions and 1875 deletions

No files matched your search

-14
View File
@@ -1,14 +0,0 @@
name: CPQ UDP Assessment
on:
workflow_dispatch:
jobs:
cpq-udp:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with: { fetch-depth: 2 }
- run: |
source ./test/setup_ga_network.sh
make -C test/bsd -f failMakefile
+494 -187
View File
File diff suppressed because it is too large. Load diff
+361 -87
View File
@@ -113,7 +113,9 @@ extern "C" {
#if MG_ARCH == MG_ARCH_ARMGCC #if MG_ARCH == MG_ARCH_ARMGCC
#ifndef _POSIX_TIMERS // Some newlib builds, e.g. Espressif's, define it
#define _POSIX_TIMERS #define _POSIX_TIMERS
#endif
#include <ctype.h> #include <ctype.h>
#if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP #if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP
@@ -189,16 +191,18 @@ extern "C" {
#define MG_TLS MG_TLS_BUILTIN #define MG_TLS MG_TLS_BUILTIN
#endif #endif
#if !defined(MG_OTA) && defined(STM32F1) || defined(STM32F2) || \ #ifndef MG_OTA // Pick OTA for the STM32 family, unless set by the user
defined(STM32F4) || defined(STM32F7) #if defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || \
defined(STM32F7)
#define MG_OTA MG_OTA_STM32F #define MG_OTA MG_OTA_STM32F
#elif !defined(MG_OTA) && defined(STM32H5) #elif defined(STM32H5)
#define MG_OTA MG_OTA_STM32H5 #define MG_OTA MG_OTA_STM32H5
#elif !defined(MG_OTA) && defined(STM32H7) #elif defined(STM32H7)
#define MG_OTA MG_OTA_STM32H7 #define MG_OTA MG_OTA_STM32H7
#elif !defined(MG_OTA) && defined(STM32C5) #elif defined(STM32C5)
#define MG_OTA MG_OTA_STM32C5 #define MG_OTA MG_OTA_STM32C5
#endif #endif
#endif
// use HAL-defined execute-in-ram section // use HAL-defined execute-in-ram section
#ifndef MG_IRAM #ifndef MG_IRAM
@@ -1224,6 +1228,10 @@ struct timeval {
#define MG_ENABLE_CUSTOM_MILLIS 0 #define MG_ENABLE_CUSTOM_MILLIS 0
#endif #endif
#ifndef MG_ENABLE_CUSTOM_MICROS
#define MG_ENABLE_CUSTOM_MICROS 0
#endif
#ifndef MG_ENABLE_ASSERT #ifndef MG_ENABLE_ASSERT
#define MG_ENABLE_ASSERT 0 #define MG_ENABLE_ASSERT 0
#endif #endif
@@ -2832,7 +2840,7 @@ struct mg_tls_opts {
// ``` // ```
// Full examples: // Full examples:
// tutorials/http/http-server, tutorials/http/http-client, // tutorials/http/http-server, tutorials/http/http-client,
// tutorials/mqtt/mqtt-client-aws-iot, tutorials/websocket/websocket-client // tutorials/mqtt/mqtt-client, tutorials/websocket/websocket-client
// Related APIs: // Related APIs:
// mg_http_listen(), mg_http_connect(), mg_ws_connect(), mg_mqtt_connect() // mg_http_listen(), mg_http_connect(), mg_ws_connect(), mg_mqtt_connect()
// Notes: // Notes:
@@ -3408,7 +3416,7 @@ void mg_ws_upgrade(struct mg_connection *, struct mg_http_message *,
// mg_ws_connect(), mg_ws_upgrade(), mg_ws_printf(), mg_ws_wrap() // mg_ws_connect(), mg_ws_upgrade(), mg_ws_printf(), mg_ws_wrap()
// Notes: // Notes:
// op is one of WEBSOCKET_OP_*. Client connections are automatically masked // op is one of WEBSOCKET_OP_*. Client connections are automatically masked
// per RFC 6455. On OOM, the return value can be smaller than header + len. // per RFC-6455. On OOM, the return value can be smaller than header + len.
// Data is appended to c->send and sent by a later mg_mgr_poll() call. // Data is appended to c->send and sent by a later mg_mgr_poll() call.
size_t mg_ws_send(struct mg_connection *, const void *buf, size_t len, int op); size_t mg_ws_send(struct mg_connection *, const void *buf, size_t len, int op);
@@ -3430,11 +3438,13 @@ size_t mg_ws_vprintf(struct mg_connection *c, int op, const char *fmt,
// Return milliseconds since boot (uptime). Never goes backwards. // Return microseconds since boot. Never goes backwards.
// On RTOS targets (FreeRTOS, ThreadX, Zephyr, etc.) uses the RTOS tick count. // To define your own implementation, set MG_ENABLE_CUSTOM_MICROS=1
// On STM32/Cube uses HAL_GetTick(). On Arduino uses millis(). uint64_t mg_micros(void);
// On Linux/macOS uses CLOCK_MONOTONIC_RAW or CLOCK_MONOTONIC; falls back to
// CLOCK_REALTIME if neither is available. // Return milliseconds since boot. Never goes backwards. Calls mg_micros().
// To define your own implementation, set MG_ENABLE_CUSTOM_MILLIS=1
// Deprecated: use mg_micros() instead.
uint64_t mg_millis(void); uint64_t mg_millis(void);
// Boot timestamp in ms since Epoch. 0 until the first successful SNTP sync; // Boot timestamp in ms since Epoch. 0 until the first successful SNTP sync;
@@ -3606,8 +3616,7 @@ struct mg_mqtt_message {
// struct mg_mqtt_opts opts = {.client_id = mg_str("device1")}; // struct mg_mqtt_opts opts = {.client_id = mg_str("device1")};
// mg_mqtt_connect(&mgr, "mqtt://broker:1883", &opts, fn, NULL); // mg_mqtt_connect(&mgr, "mqtt://broker:1883", &opts, fn, NULL);
// Full examples: // Full examples:
// tutorials/mqtt/mqtt-client, tutorials/mqtt/mqtt-client-aws-iot, // tutorials/mqtt/mqtt-client, tutorials/mqtt/ota-over-mqtt
// tutorials/mqtt/ota-over-mqtt
// Related APIs: // Related APIs:
// mg_mqtt_pub(), mg_mqtt_sub(), mg_tls_init(), mg_mgr_poll() // mg_mqtt_pub(), mg_mqtt_sub(), mg_tls_init(), mg_mgr_poll()
// Notes: // Notes:
@@ -3642,8 +3651,7 @@ void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts);
// }; // };
// uint16_t id = mg_mqtt_pub(c, &opts); // uint16_t id = mg_mqtt_pub(c, &opts);
// Full examples: // Full examples:
// tutorials/mqtt/mqtt-client, tutorials/mqtt/mqtt-client-aws-iot, // tutorials/mqtt/mqtt-client, tutorials/mqtt/ota-over-mqtt
// tutorials/mqtt/ota-over-mqtt
// Related APIs: // Related APIs:
// mg_mqtt_connect(), mg_mqtt_sub(), mg_mqtt_send_header() // mg_mqtt_connect(), mg_mqtt_sub(), mg_mqtt_send_header()
// Notes: // Notes:
@@ -3658,8 +3666,7 @@ uint16_t mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts);
// struct mg_mqtt_opts opts = {.topic = mg_str("device/rx"), .qos = 1}; // struct mg_mqtt_opts opts = {.topic = mg_str("device/rx"), .qos = 1};
// mg_mqtt_sub(c, &opts); // mg_mqtt_sub(c, &opts);
// Full examples: // Full examples:
// tutorials/mqtt/mqtt-client, tutorials/mqtt/mqtt-client-aws-iot, // tutorials/mqtt/mqtt-client, tutorials/mqtt/ota-over-mqtt
// tutorials/mqtt/ota-over-mqtt
// Related APIs: // Related APIs:
// mg_mqtt_connect(), mg_mqtt_pub(), mg_mqtt_unsub() // mg_mqtt_connect(), mg_mqtt_pub(), mg_mqtt_unsub()
// Notes: // Notes:
@@ -3720,7 +3727,7 @@ struct mg_dns_message {
char name[256]; // Host name char name[256]; // Host name
}; };
// DNS wire-format header (RFC 1035). All fields are in network byte order; // DNS wire-format header (RFC-1035). All fields are in network byte order;
// use mg_ntohs() to read them. // use mg_ntohs() to read them.
struct mg_dns_header { struct mg_dns_header {
uint16_t txnid; // Transaction ID, matched between query and response uint16_t txnid; // Transaction ID, matched between query and response
@@ -4840,27 +4847,27 @@ void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp);
void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac); void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac);
// Built-in hardware drivers. Assign one to mg_tcpip_if.driver before calling // Built-in hardware drivers. Assign one to mg_tcpip_if.driver before calling
// mg_tcpip_init(). Each driver also requires a corresponding driver_data // mg_tcpip_init(). See the matching driver header for configuration and
// struct; see the matching driver header for details. // initialisation helpers.
extern struct mg_tcpip_driver mg_tcpip_driver_stm32f;
extern struct mg_tcpip_driver mg_tcpip_driver_w5500;
extern struct mg_tcpip_driver mg_tcpip_driver_w5100;
extern struct mg_tcpip_driver mg_tcpip_driver_tm4c;
extern struct mg_tcpip_driver mg_tcpip_driver_tms570;
extern struct mg_tcpip_driver mg_tcpip_driver_stm32h;
extern struct mg_tcpip_driver mg_tcpip_driver_imxrt;
extern struct mg_tcpip_driver mg_tcpip_driver_same54;
extern struct mg_tcpip_driver mg_tcpip_driver_cmsis;
extern struct mg_tcpip_driver mg_tcpip_driver_ra;
extern struct mg_tcpip_driver mg_tcpip_driver_xmc;
extern struct mg_tcpip_driver mg_tcpip_driver_xmc7;
extern struct mg_tcpip_driver mg_tcpip_driver_pico_w;
extern struct mg_tcpip_driver mg_tcpip_driver_rw612;
extern struct mg_tcpip_driver mg_tcpip_driver_cyw;
extern struct mg_tcpip_driver mg_tcpip_driver_nxp_wifi;
extern struct mg_tcpip_driver mg_tcpip_driver_st67w6;
extern struct mg_tcpip_driver mg_tcpip_driver_atcmd;
extern struct mg_tcpip_driver mg_tcpip_driver_netc;
@@ -4876,6 +4883,10 @@ struct mg_tcpip_spi {
void (*txn)(void *, uint8_t *write, uint8_t *read, size_t); // Full-duplex transfer: write and read len bytes simultaneously void (*txn)(void *, uint8_t *write, uint8_t *read, size_t); // Full-duplex transfer: write and read len bytes simultaneously
}; };
// SPI bus for SPI-attached network chips, defined by the application.
// Used by the drivers' INIT macros, e.g. MG_TCPIP_DRIVER_W5500_INIT
extern struct mg_tcpip_spi mg_spi;
// Alignment attributes for DMA-capable Ethernet descriptor buffers. // Alignment attributes for DMA-capable Ethernet descriptor buffers.
// Use these on driver RX/TX descriptor arrays where the hardware requires // Use these on driver RX/TX descriptor arrays where the hardware requires
// specific alignment. // specific alignment.
@@ -4933,9 +4944,6 @@ struct mg_tcpip_spi {
#if MG_ENABLE_TCPIP #if MG_ENABLE_TCPIP
// Monotonic time in microseconds.
uint64_t mg_micros(void);
// A radio standard // A radio standard
struct mg_radio { struct mg_radio {
const char *name; // For logs const char *name; // For logs
@@ -4965,6 +4973,27 @@ struct mg_radio {
#define MG_802154_CHANNEL 15 #define MG_802154_CHANNEL 15
#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_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; extern const struct mg_radio mg_radio_802154;
struct mg_mesh_node { struct mg_mesh_node {
@@ -4974,6 +5003,7 @@ struct mg_mesh_node {
size_t (*tx)(struct mg_tcpip_if *, const void *, size_t); // Radio frame TX 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 size_t rx_len; // Complete Ethernet frame in the interface RX buffer
uint64_t now; // Current driver poll time, us 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 uint64_t tx_at; // Earliest next transmission, us
void *data; // Private state owned by the strategy void *data; // Private state owned by the strategy
size_t ram_used; // Live mesh state bytes size_t ram_used; // Live mesh state bytes
@@ -4998,6 +5028,18 @@ struct mg_mesh {
extern const struct mg_mesh mg_mesh_default; 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 #endif
@@ -5065,6 +5107,18 @@ void mg_bsd_poll(struct mg_mgr *);
#ifndef ENOSPC #ifndef ENOSPC
#define ENOSPC 28 #define ENOSPC 28
#endif #endif
#ifndef EOPNOTSUPP
#define EOPNOTSUPP 95
#endif
#ifndef EISCONN
#define EISCONN 106
#endif
#ifndef EDESTADDRREQ
#define EDESTADDRREQ 121
#endif
#ifndef EMSGSIZE
#define EMSGSIZE 90
#endif
#ifndef EPROTONOSUPPORT #ifndef EPROTONOSUPPORT
#define EPROTONOSUPPORT 93 #define EPROTONOSUPPORT 93
#endif #endif
@@ -5247,12 +5301,58 @@ struct mg_tcpip_driver_atcmd_data {
bool unstuffing; // internal use: unstuffing state bool unstuffing; // internal use: unstuffing state
}; };
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ATCMD) && MG_ENABLE_DRIVER_ATCMD
extern struct mg_tcpip_driver mg_tcpip_driver_atcmd;
// Modem callbacks and AT script, defined by the application.
// See tutorials/arduino/sim800-mqtt for modem configuration.
extern struct mg_tcpip_driver_atcmd_data mg_atcmd;
#define MG_TCPIP_DRIVER_ATCMD_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_.driver = &mg_tcpip_driver_atcmd; \
mif_.driver_data = &mg_atcmd; \
mif_.l2type = MG_TCPIP_L2_PPP; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: atcmd, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ATCMD_INIT(x)
#endif
#endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_CMSIS) && MG_ENABLE_DRIVER_CMSIS
#include "Driver_ETH_MAC.h" // keep this include #include "Driver_ETH_MAC.h" // keep this include
#include "Driver_ETH_PHY.h" // keep this include #include "Driver_ETH_PHY.h" // keep this include
extern struct mg_tcpip_driver mg_tcpip_driver_cmsis;
#define MG_TCPIP_DRIVER_CMSIS_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_.driver = &mg_tcpip_driver_cmsis; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: cmsis, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_CMSIS_INIT(x)
#endif
#endif #endif
@@ -5276,7 +5376,9 @@ struct mg_tcpip_driver_cyw_data {
bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3 Table 6) bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3 Table 6)
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_cyw;
#define MG_TCPIP_DRIVER_CYW_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_cyw_data driver_data_; \ static struct mg_tcpip_driver_cyw_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5288,10 +5390,52 @@ struct mg_tcpip_driver_cyw_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: cyw, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: cyw, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_CYW_INIT(x)
#endif
#endif
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#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 #endif
@@ -5325,7 +5469,9 @@ struct mg_tcpip_driver_imxrt_data {
#define MG_DRIVER_MDC_CR 24 #define MG_DRIVER_MDC_CR 24
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_imxrt;
#define MG_TCPIP_DRIVER_IMXRT_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_imxrt_data driver_data_; \ static struct mg_tcpip_driver_imxrt_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5337,10 +5483,14 @@ struct mg_tcpip_driver_imxrt_data {
mif_.driver = &mg_tcpip_driver_imxrt; \ mif_.driver = &mg_tcpip_driver_imxrt; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: imxrt, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: imxrt, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_IMXRT_INIT(x)
#endif
#endif #endif
// Copyright (c) 2026 Cesanta Software Limited // Copyright (c) 2026 Cesanta Software Limited
// All rights reserved // All rights reserved
@@ -5357,7 +5507,7 @@ struct mg_tcpip_driver_mcxw71_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71; extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
#define MG_TCPIP_DRIVER_MCXW71_INIT(manager) \ #define MG_TCPIP_DRIVER_MCXW71_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_mcxw71_data driver_data_; \ static struct mg_tcpip_driver_mcxw71_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5365,10 +5515,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mcxw71; \ mif_.driver = &mg_tcpip_driver_mcxw71; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
@@ -5391,7 +5540,7 @@ struct mg_tcpip_driver_mg24_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mg24; extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
#define MG_TCPIP_DRIVER_MG24_INIT(manager) \ #define MG_TCPIP_DRIVER_MG24_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_mg24_data driver_data_; \ static struct mg_tcpip_driver_mg24_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5399,10 +5548,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mg24; \ mif_.driver = &mg_tcpip_driver_mg24; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
@@ -5439,10 +5587,9 @@ struct mg_tcpip_driver_netc_data {
#define MG_TCPIP_NETC_LINK 0 #define MG_TCPIP_NETC_LINK 0
#endif #endif
struct mg_tcpip_driver;
extern struct mg_tcpip_driver mg_tcpip_driver_netc; extern struct mg_tcpip_driver mg_tcpip_driver_netc;
#define MG_TCPIP_DRIVER_INIT(mgr) \ #define MG_TCPIP_DRIVER_NETC_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_netc_data driver_data_; \ static struct mg_tcpip_driver_netc_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5455,10 +5602,14 @@ extern struct mg_tcpip_driver mg_tcpip_driver_netc;
mif_.driver = &mg_tcpip_driver_netc; \ mif_.driver = &mg_tcpip_driver_netc; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: netc, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: netc, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_NETC_INIT(x)
#endif
#endif #endif
// Copyright (c) 2026 Cesanta Software Limited // Copyright (c) 2026 Cesanta Software Limited
// All rights reserved // All rights reserved
@@ -5474,7 +5625,7 @@ struct mg_tcpip_driver_nrf52_data {
extern struct mg_tcpip_driver mg_tcpip_driver_nrf52; extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
#define MG_TCPIP_DRIVER_NRF52_INIT(manager) \ #define MG_TCPIP_DRIVER_NRF52_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_nrf52_data driver_data_; \ static struct mg_tcpip_driver_nrf52_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5482,10 +5633,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_nrf52; \ mif_.driver = &mg_tcpip_driver_nrf52; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
@@ -5505,7 +5655,9 @@ struct mg_tcpip_driver_nxp_wifi_data {
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_nxp_wifi;
#define MG_TCPIP_DRIVER_NXP_WIFI_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_nxp_wifi_data driver_data_; \ static struct mg_tcpip_driver_nxp_wifi_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5517,10 +5669,14 @@ struct mg_tcpip_driver_nxp_wifi_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: nxp wifi, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: nxp wifi, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_NXP_WIFI_INIT(x)
#endif
#endif #endif
@@ -5557,7 +5713,9 @@ struct mg_tcpip_driver_pico_w_data {
struct mg_wifi_data wifi; struct mg_wifi_data wifi;
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_pico_w;
#define MG_TCPIP_DRIVER_PICO_W_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_pico_w_data driver_data_; \ static struct mg_tcpip_driver_pico_w_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5569,10 +5727,14 @@ struct mg_tcpip_driver_pico_w_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: pico-w, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: pico-w, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_PICO_W_INIT(x)
#endif
#endif #endif
@@ -5599,7 +5761,9 @@ struct mg_tcpip_driver_ra_data {
#define MG_TCPIP_PHY_ADDR 0 #define MG_TCPIP_PHY_ADDR 0
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_ra;
#define MG_TCPIP_DRIVER_RA_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_ra_data driver_data_; \ static struct mg_tcpip_driver_ra_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5612,10 +5776,14 @@ struct mg_tcpip_driver_ra_data {
mif_.driver = &mg_tcpip_driver_ra; \ mif_.driver = &mg_tcpip_driver_ra; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: ra, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: ra, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_RA_INIT(x)
#endif
#endif #endif
@@ -5646,8 +5814,9 @@ struct mg_tcpip_driver_rw612_data {
#define MG_DRIVER_MDC_HOLDTIME 3 #define MG_DRIVER_MDC_HOLDTIME 3
#endif #endif
#ifndef MG_TCPIP_DRIVER_INIT extern struct mg_tcpip_driver mg_tcpip_driver_rw612;
#define MG_TCPIP_DRIVER_INIT(mgr) \
#define MG_TCPIP_DRIVER_RW612_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_rw612_data driver_data_; \ static struct mg_tcpip_driver_rw612_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5659,9 +5828,12 @@ struct mg_tcpip_driver_rw612_data {
mif_.driver = &mg_tcpip_driver_rw612; \ mif_.driver = &mg_tcpip_driver_rw612; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: rw612, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: rw612, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_RW612_INIT(x)
#endif #endif
#endif #endif
@@ -5680,7 +5852,7 @@ struct mg_tcpip_driver_rw612w_data {
extern struct mg_tcpip_driver mg_tcpip_driver_rw612w; extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
#define MG_TCPIP_DRIVER_RW612W_INIT(manager) \ #define MG_TCPIP_DRIVER_RW612W_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_rw612w_data driver_data_; \ static struct mg_tcpip_driver_rw612w_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5688,10 +5860,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_rw612w; \ mif_.driver = &mg_tcpip_driver_rw612w; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
@@ -5718,7 +5889,9 @@ struct mg_tcpip_driver_same54_data {
uint8_t phy_addr; uint8_t phy_addr;
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_same54;
#define MG_TCPIP_DRIVER_SAME54_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_same54_data driver_data_; \ static struct mg_tcpip_driver_same54_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5730,10 +5903,14 @@ struct mg_tcpip_driver_same54_data {
mif_.driver = &mg_tcpip_driver_same54; \ mif_.driver = &mg_tcpip_driver_same54; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: same54, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: same54, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_SAME54_INIT(x)
#endif
#endif #endif
@@ -5786,7 +5963,9 @@ struct mg_tcpip_driver_st67w6_data {
struct mg_queue send_queue; // decouple tx calls from module polls struct mg_queue send_queue; // decouple tx calls from module polls
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_st67w6;
#define MG_TCPIP_DRIVER_ST67W6_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_st67w6_data driver_data_; \ static struct mg_tcpip_driver_st67w6_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5798,10 +5977,14 @@ struct mg_tcpip_driver_st67w6_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: st67w6, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: st67w6, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ST67W6_INIT(x)
#endif
#endif #endif
@@ -5839,7 +6022,9 @@ struct mg_tcpip_driver_stm32f_data {
#define MG_ENABLE_ETH_IRQ() #define MG_ENABLE_ETH_IRQ()
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_stm32f;
#define MG_TCPIP_DRIVER_STM32F_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_stm32f_data driver_data_; \ static struct mg_tcpip_driver_stm32f_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5852,10 +6037,14 @@ struct mg_tcpip_driver_stm32f_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
MG_ENABLE_ETH_IRQ(); \ MG_ENABLE_ETH_IRQ(); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_STM32F_INIT(x)
#endif
#endif #endif
@@ -5931,7 +6120,9 @@ struct mg_tcpip_driver_stm32h_data {
#define MG_IPV6_INIT(mif) #define MG_IPV6_INIT(mif)
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_stm32h;
#define MG_TCPIP_DRIVER_STM32H_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_stm32h_data driver_data_; \ static struct mg_tcpip_driver_stm32h_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5945,11 +6136,15 @@ struct mg_tcpip_driver_stm32h_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
MG_IPV6_INIT(mif_); \ MG_IPV6_INIT(mif_); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_ENABLE_ETH_IRQ(); \ MG_ENABLE_ETH_IRQ(); \
MG_INFO(("Driver: stm32h, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: stm32h, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_STM32H_INIT(x)
#endif
#endif #endif
#endif #endif
@@ -5973,7 +6168,9 @@ struct mg_tcpip_driver_tm4c_data {
#define MG_DRIVER_MDC_CR 1 #define MG_DRIVER_MDC_CR 1
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_tm4c;
#define MG_TCPIP_DRIVER_TM4C_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_tm4c_data driver_data_; \ static struct mg_tcpip_driver_tm4c_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -5984,10 +6181,14 @@ struct mg_tcpip_driver_tm4c_data {
mif_.driver = &mg_tcpip_driver_tm4c; \ mif_.driver = &mg_tcpip_driver_tm4c; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: tm4c, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: tm4c, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_TM4C_INIT(x)
#endif
#endif #endif
@@ -6005,7 +6206,9 @@ struct mg_tcpip_driver_tms570_data {
#define MG_DRIVER_MDC_CR 1 #define MG_DRIVER_MDC_CR 1
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_tms570;
#define MG_TCPIP_DRIVER_TMS570_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_tms570_data driver_data_; \ static struct mg_tcpip_driver_tms570_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -6017,11 +6220,70 @@ struct mg_tcpip_driver_tms570_data {
mif_.driver = &mg_tcpip_driver_tms570; \ mif_.driver = &mg_tcpip_driver_tms570; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: tms570, MAC: %M", mg_print_mac, mif_.mac));\ MG_INFO(("Driver: tms570, MAC: %M", mg_print_mac, mif_.mac));\
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_TMS570_INIT(x)
#endif #endif
#endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5100) && \
MG_ENABLE_DRIVER_W5100
extern struct mg_tcpip_driver mg_tcpip_driver_w5100;
// Initialises W5100 on mgr. The application defines
// struct mg_tcpip_spi mg_spi
#define MG_TCPIP_DRIVER_W5100_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_.driver = &mg_tcpip_driver_w5100; \
mif_.driver_data = &mg_spi; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: w5100, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_W5100_INIT(x)
#endif
#endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5500) && \
MG_ENABLE_DRIVER_W5500
extern struct mg_tcpip_driver mg_tcpip_driver_w5500;
// Initialises W5500 on mgr. The application defines
// struct mg_tcpip_spi mg_spi. Example: tutorials/rp/w5500-evb-pico
#define MG_TCPIP_DRIVER_W5500_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_.driver = &mg_tcpip_driver_w5500; \
mif_.driver_data = &mg_spi; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: w5500, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_W5500_INIT(x)
#endif
#endif
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC) && MG_ENABLE_DRIVER_XMC
@@ -6052,7 +6314,9 @@ struct mg_tcpip_driver_xmc_data {
#define MG_DRIVER_MDC_CR 4 #define MG_DRIVER_MDC_CR 4
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_xmc;
#define MG_TCPIP_DRIVER_XMC_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_xmc_data driver_data_; \ static struct mg_tcpip_driver_xmc_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -6064,10 +6328,14 @@ struct mg_tcpip_driver_xmc_data {
mif_.driver = &mg_tcpip_driver_xmc; \ mif_.driver = &mg_tcpip_driver_xmc; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: xmc, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: xmc, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_XMC_INIT(x)
#endif
#endif #endif
@@ -6086,7 +6354,9 @@ struct mg_tcpip_driver_xmc7_data {
#define MG_DRIVER_MDC_CR 3 #define MG_DRIVER_MDC_CR 3
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_xmc7;
#define MG_TCPIP_DRIVER_XMC7_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_xmc7_data driver_data_; \ static struct mg_tcpip_driver_xmc7_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -6098,10 +6368,14 @@ struct mg_tcpip_driver_xmc7_data {
mif_.driver = &mg_tcpip_driver_xmc7; \ mif_.driver = &mg_tcpip_driver_xmc7; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: xmc7, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: xmc7, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_XMC7_INIT(x)
#endif
#endif #endif
+2
View File
@@ -1,7 +1,9 @@
#pragma once #pragma once
#if MG_ARCH == MG_ARCH_ARMGCC #if MG_ARCH == MG_ARCH_ARMGCC
#ifndef _POSIX_TIMERS // Some newlib builds, e.g. Espressif's, define it
#define _POSIX_TIMERS #define _POSIX_TIMERS
#endif
#include <ctype.h> #include <ctype.h>
#if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP #if !defined(MG_ENABLE_LWIP) || !MG_ENABLE_LWIP
+7 -5
View File
@@ -52,16 +52,18 @@
#define MG_TLS MG_TLS_BUILTIN #define MG_TLS MG_TLS_BUILTIN
#endif #endif
#if !defined(MG_OTA) && defined(STM32F1) || defined(STM32F2) || \ #ifndef MG_OTA // Pick OTA for the STM32 family, unless set by the user
defined(STM32F4) || defined(STM32F7) #if defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || \
defined(STM32F7)
#define MG_OTA MG_OTA_STM32F #define MG_OTA MG_OTA_STM32F
#elif !defined(MG_OTA) && defined(STM32H5) #elif defined(STM32H5)
#define MG_OTA MG_OTA_STM32H5 #define MG_OTA MG_OTA_STM32H5
#elif !defined(MG_OTA) && defined(STM32H7) #elif defined(STM32H7)
#define MG_OTA MG_OTA_STM32H7 #define MG_OTA MG_OTA_STM32H7
#elif !defined(MG_OTA) && defined(STM32C5) #elif defined(STM32C5)
#define MG_OTA MG_OTA_STM32C5 #define MG_OTA MG_OTA_STM32C5
#endif #endif
#endif
// use HAL-defined execute-in-ram section // use HAL-defined execute-in-ram section
#ifndef MG_IRAM #ifndef MG_IRAM
+104 -34
View File
@@ -1,5 +1,6 @@
#include "bsd.h" #include "bsd.h"
#include "dns.h" #include "dns.h"
#include "util.h"
#include <stdarg.h> #include <stdarg.h>
#if MG_ENABLE_BSD_SOCKETS && MG_ENABLE_FREERTOS #if MG_ENABLE_BSD_SOCKETS && MG_ENABLE_FREERTOS
@@ -131,6 +132,46 @@ static struct mg_connection *bsd_new_conn(struct mg_bsd_sock *s) {
return c; return c;
} }
// Mirror net_builtin.c::trim_len() logic
static bool bsd_udp_too_big(struct mg_connection *c, size_t len) {
struct mg_tcpip_if *ifp = c->mgr->ifp;
size_t hlen = c->rem.is_ip6 ? 48 : 32; // IP plus UDP headers
size_t cap = ifp->mtu - hlen;
size_t room = ifp->tx.len - (ifp->framesize - ifp->l2mtu) - hlen;
return len > cap || len > room;
}
static bool bsd_udp_queue(struct mg_connection *c, const void *buf,
size_t len) {
// One raw datagram occupies c->send until write_conn() drains it.
return mg_iobuf_add(&c->send, c->send.len, buf, len) == len;
}
static size_t bsd_recv(struct mg_bsd_sock *s, void *buf, size_t len,
int flags, struct sockaddr *src, socklen_t *addrlen) {
struct mg_connection *c = s->c;
size_t n;
if (!s->is_udp) {
n = c->recv.len < len ? c->recv.len : len;
memcpy(buf, c->recv.buf, n);
if (!(flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
} else {
n = c->recv.len < len ? c->recv.len : len;
memcpy(buf, c->recv.buf, n);
if (src != NULL && addrlen != NULL) {
struct sockaddr_in *sa = (struct sockaddr_in *) src;
sa->sin_family = AF_INET;
sa->sin_port = c->rem.port;
sa->sin_addr.s_addr = c->rem.addr.ip4;
*addrlen = sizeof(*sa);
}
if (!(flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, c->recv.len);
}
return n;
}
#if MG_ENABLE_FREERTOS #if MG_ENABLE_FREERTOS
// Complete operations blocked on c before Mongoose destroys it. // Complete operations blocked on c before Mongoose destroys it.
static void bsd_finish_waiters(struct mg_bsd_sock *s, bool error) { static void bsd_finish_waiters(struct mg_bsd_sock *s, bool error) {
@@ -315,9 +356,10 @@ static int bsd_ready(struct mg_bsd_sock *s) {
if (s->is_shut_rd || s->c->recv.len > 0 || s->c->is_draining) if (s->is_shut_rd || s->c->recv.len > 0 || s->c->is_draining)
ready |= BSD_READ; ready |= BSD_READ;
if (s->is_shut_wr) ready |= BSD_ERROR; if (s->is_shut_wr) ready |= BSD_ERROR;
if (!s->is_shut_wr && !s->is_udp && !s->c->is_connecting && if (!s->is_shut_wr && (s->is_udp || !s->c->is_connecting) &&
!s->c->is_closing && !s->c->is_draining) !s->c->is_closing && !s->c->is_draining &&
ready |= BSD_WRITE; // Established TCP socket (!s->is_udp || s->c->send.len == 0))
ready |= BSD_WRITE; // UDP socket or established TCP socket
return ready; return ready;
} }
@@ -331,7 +373,7 @@ static void bsd_close(struct mg_bsd_sock *s) {
if (t->orphan && t->listener == s) { if (t->orphan && t->listener == s) {
if (t->c != NULL) { if (t->c != NULL) {
t->c->fn_data = NULL; t->c->fn_data = NULL;
mg_close_conn(t->c); t->c->is_draining = 1;
t->c = NULL; t->c = NULL;
} }
memset(t, 0, sizeof(*t)); // Release orphan memset(t, 0, sizeof(*t)); // Release orphan
@@ -339,7 +381,7 @@ static void bsd_close(struct mg_bsd_sock *s) {
} }
if (s->c != NULL) { if (s->c != NULL) {
s->c->fn_data = NULL; s->c->fn_data = NULL;
mg_close_conn(s->c); s->c->is_draining = 1;
s->c = NULL; s->c = NULL;
} }
memset(s, 0, sizeof(*s)); // Release socket memset(s, 0, sizeof(*s)); // Release socket
@@ -529,8 +571,8 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
cmd->result = -1, cmd->err = ECONNREFUSED; cmd->result = -1, cmd->err = ECONNREFUSED;
return true; return true;
} }
if (!c->is_connecting) { if (s->is_udp || !c->is_connecting) {
cmd->result = 0; cmd->result = 0; // UDP may still resolve ARP; TCP waits for SYN/SYN-ACK
return true; return true;
} }
if (s->nonblock) { if (s->nonblock) {
@@ -555,11 +597,8 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
return true; return true;
} }
if (c->recv.len > 0) { if (c->recv.len > 0) {
size_t n = cmd->op_recv.len; cmd->result = (int) bsd_recv(s, cmd->op_recv.buf, cmd->op_recv.len,
if (c->recv.len < n) n = c->recv.len; cmd->op_recv.flags, NULL, NULL);
memcpy(cmd->op_recv.buf, c->recv.buf, n);
if (!(cmd->op_recv.flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
cmd->result = (int) n;
return true; return true;
} }
if (s->err != 0) { if (s->err != 0) {
@@ -583,7 +622,25 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
} else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 || } else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 ||
c->is_closing || c->is_draining) { c->is_closing || c->is_draining) {
cmd->result = -1, cmd->err = EPIPE; cmd->result = -1, cmd->err = EPIPE;
} else if (mg_send(c, cmd->op_send.buf, cmd->op_send.len)) { } else if (c == NULL || (s->is_udp && !c->is_client)) {
cmd->result = -1, cmd->err = s->is_udp ? EDESTADDRREQ : EPIPE;
} else if (s->is_udp && cmd->op_send.len == 0) {
cmd->result = 0;
} else if (s->is_udp && bsd_udp_too_big(c, cmd->op_send.len)) {
cmd->result = -1, cmd->err = EMSGSIZE;
} else if (s->is_udp && c->send.len > 0) {
if (s->nonblock || (cmd->op_send.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // One UDP datagram is pending, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif
}
} else if ((s->is_udp
? bsd_udp_queue(c, cmd->op_send.buf, cmd->op_send.len)
: mg_send(c, cmd->op_send.buf, cmd->op_send.len))) {
cmd->result = (int) cmd->op_send.len; cmd->result = (int) cmd->op_send.len;
} else if (s->nonblock || (cmd->op_send.flags & MSG_DONTWAIT)) { } else if (s->nonblock || (cmd->op_send.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN; cmd->result = -1, cmd->err = EAGAIN;
@@ -600,27 +657,51 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
if ((s = bsd_get(cmd->op_sendto.fd)) == NULL) { if ((s = bsd_get(cmd->op_sendto.fd)) == NULL) {
cmd->result = -1, cmd->err = EBADF; cmd->result = -1, cmd->err = EBADF;
} else if (!s->is_udp) {
cmd->result = -1, cmd->err = EOPNOTSUPP;
} else if ((err = bsd_addr4(cmd->op_sendto.addr, } else if ((err = bsd_addr4(cmd->op_sendto.addr,
cmd->op_sendto.addrlen)) != 0) { cmd->op_sendto.addrlen)) != 0) {
cmd->result = -1, cmd->err = err; cmd->result = -1, cmd->err = err;
} else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 || } else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 ||
c->is_closing || c->is_draining) { c->is_closing || c->is_draining) {
cmd->result = -1, cmd->err = EPIPE; cmd->result = -1, cmd->err = EPIPE;
} else if (c->is_client) {
cmd->result = -1, cmd->err = EISCONN;
} else { } else {
const struct sockaddr_in *sa = const struct sockaddr_in *sa =
(const struct sockaddr_in *) cmd->op_sendto.addr; (const struct sockaddr_in *) cmd->op_sendto.addr;
if (cmd->op_sendto.len == 0) {
cmd->result = 0;
} else if (bsd_udp_too_big(c, cmd->op_sendto.len)) {
cmd->result = -1, cmd->err = EMSGSIZE;
} else if (c->send.len == 0) {
struct mg_addr rem = c->rem;
bool resolve = rem.is_ip6 || rem.addr.ip4 != sa->sin_addr.s_addr;
c->rem.port = sa->sin_port; c->rem.port = sa->sin_port;
c->rem.addr.ip4 = sa->sin_addr.s_addr; c->rem.addr.ip4 = sa->sin_addr.s_addr;
c->rem.is_ip6 = false; c->rem.is_ip6 = false;
if (mg_send(c, cmd->op_sendto.buf, cmd->op_sendto.len)) { if (bsd_udp_queue(c, cmd->op_sendto.buf, cmd->op_sendto.len)) {
if (resolve) mg_connect_resolved(c);
cmd->result = (int) cmd->op_sendto.len; cmd->result = (int) cmd->op_sendto.len;
} else if (s->nonblock || (cmd->op_sendto.flags & MSG_DONTWAIT)) { } else {
c->rem = rem;
if (s->nonblock || (cmd->op_sendto.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN; cmd->result = -1, cmd->err = EAGAIN;
} else { } else {
#if MG_ENABLE_FREERTOS #if MG_ENABLE_FREERTOS
return false; // No send buffer space yet, wait return false; // No send buffer space yet, wait
#else #else
cmd->result = -1, cmd->err = EAGAIN; cmd->result = -1, cmd->err = EAGAIN;
#endif
}
}
} else if (s->nonblock || (cmd->op_sendto.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // One UDP datagram is pending, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif #endif
} }
} }
@@ -630,6 +711,9 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
if ((s = bsd_get(cmd->op_recvfrom.fd)) == NULL) { if ((s = bsd_get(cmd->op_recvfrom.fd)) == NULL) {
cmd->result = -1, cmd->err = EBADF; cmd->result = -1, cmd->err = EBADF;
return true; return true;
} else if (!s->is_udp) {
cmd->result = -1, cmd->err = EOPNOTSUPP;
return true;
} }
if (s->is_shut_rd) { if (s->is_shut_rd) {
cmd->result = 0; cmd->result = 0;
@@ -641,25 +725,11 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
return true; return true;
} }
if (c->recv.len > 0) { if (c->recv.len > 0) {
size_t n = cmd->op_recvfrom.len; cmd->result = (int) bsd_recv(s, cmd->op_recvfrom.buf,
cmd->op_recvfrom.len,
if (cmd->op_recvfrom.src != NULL && cmd->op_recvfrom.flags,
(cmd->op_recvfrom.addrlen == NULL || cmd->op_recvfrom.src,
*cmd->op_recvfrom.addrlen < sizeof(struct sockaddr_in))) { cmd->op_recvfrom.addrlen);
cmd->result = -1, cmd->err = EINVAL;
return true;
}
if (c->recv.len < n) n = c->recv.len;
memcpy(cmd->op_recvfrom.buf, c->recv.buf, n);
if (!(cmd->op_recvfrom.flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
if (cmd->op_recvfrom.src != NULL && cmd->op_recvfrom.addrlen != NULL) {
struct sockaddr_in *sa = (struct sockaddr_in *) cmd->op_recvfrom.src;
sa->sin_family = AF_INET;
sa->sin_port = c->rem.port;
sa->sin_addr.s_addr = c->rem.addr.ip4;
*cmd->op_recvfrom.addrlen = sizeof(*sa);
}
cmd->result = (int) n;
return true; return true;
} }
if (s->err != 0) { if (s->err != 0) {
+12
View File
@@ -64,6 +64,18 @@ void mg_bsd_poll(struct mg_mgr *);
#ifndef ENOSPC #ifndef ENOSPC
#define ENOSPC 28 #define ENOSPC 28
#endif #endif
#ifndef EOPNOTSUPP
#define EOPNOTSUPP 95
#endif
#ifndef EISCONN
#define EISCONN 106
#endif
#ifndef EDESTADDRREQ
#define EDESTADDRREQ 121
#endif
#ifndef EMSGSIZE
#define EMSGSIZE 90
#endif
#ifndef EPROTONOSUPPORT #ifndef EPROTONOSUPPORT
#define EPROTONOSUPPORT 93 #define EPROTONOSUPPORT 93
#endif #endif
+4
View File
@@ -94,6 +94,10 @@
#define MG_ENABLE_CUSTOM_MILLIS 0 #define MG_ENABLE_CUSTOM_MILLIS 0
#endif #endif
#ifndef MG_ENABLE_CUSTOM_MICROS
#define MG_ENABLE_CUSTOM_MICROS 0
#endif
#ifndef MG_ENABLE_ASSERT #ifndef MG_ENABLE_ASSERT
#define MG_ENABLE_ASSERT 0 #define MG_ENABLE_ASSERT 0
#endif #endif
+5 -4
View File
@@ -136,12 +136,13 @@ bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
dm->txnid = mg_ntohs(h->txnid); dm->txnid = mg_ntohs(h->txnid);
is_response = mg_ntohs(h->flags) & 0x8000; is_response = mg_ntohs(h->flags) & 0x8000;
for (i = 0; i < mg_ntohs(h->num_questions); i++) { for (i = 0; i < mg_ntohs(h->num_questions); i++) { // advance past queries
if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false; if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
// MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass)); // MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass));
dm->addr.is_ip6 = (rr.atype == MG_DNS_RTYPE_AAAA);
mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name)); mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
ofs += n; ofs += n;
} } // on unresolved responses, we got the name and query type, at least
if (!is_response) { if (!is_response) {
// For queries, there is no need to parse the answers. In this way, // For queries, there is no need to parse the answers. In this way,
@@ -440,7 +441,7 @@ static void handle_mdns_query(struct mg_connection *c) {
n = mg_dns_parse_rr(c->recv.buf, c->recv.len, 12, true, &rr); n = mg_dns_parse_rr(c->recv.buf, c->recv.len, 12, true, &rr);
MG_VERBOSE(("mDNS request parsed, result=%d", (int) n)); MG_VERBOSE(("mDNS request parsed, result=%d", (int) n));
if (n > 0) { if (n > 0) {
// RFC-6762 Appendix C, RFC2181 11: m(n + 1-63), max 255 + 0x0 // RFC-6762 Appendix C, RFC-2181 11: m(n + 1-63), max 255 + 0x0
uint8_t buf[sizeof(struct mg_dns_header) + 256 + sizeof(mdns_answer) + 4]; uint8_t buf[sizeof(struct mg_dns_header) + 256 + sizeof(mdns_answer) + 4];
struct mg_dns_header *h = (struct mg_dns_header *) buf; struct mg_dns_header *h = (struct mg_dns_header *) buf;
uint8_t *p = &buf[sizeof(*h)]; uint8_t *p = &buf[sizeof(*h)];
@@ -599,7 +600,7 @@ static void handle_mdns_response(struct mg_connection *c) {
struct mg_dns_rr rr, rr_[5]; // A, PTR, SRV, TXT, AAAA, in that order struct mg_dns_rr rr, rr_[5]; // A, PTR, SRV, TXT, AAAA, in that order
struct mg_mdns_resp resp; struct mg_mdns_resp resp;
size_t n, i, num, answers, roff_[5], roff = 12; // offset 12 is header size size_t n, i, num, answers, roff_[5], roff = 12; // offset 12 is header size
// RFC-6762 Appendix C, RFC2181 11: m(n + 1-63), max 255 + 0x0 // RFC-6762 Appendix C, RFC-2181 11: m(n + 1-63), max 255 + 0x0
char name[256], srvcproto[256], instance[256], host[256]; char name[256], srvcproto[256], instance[256], host[256];
uint16_t atype = 0; uint16_t atype = 0;
answers = mg_ntohs(rh->num_answers); answers = mg_ntohs(rh->num_answers);
+1 -1
View File
@@ -21,7 +21,7 @@ struct mg_dns_message {
char name[256]; // Host name char name[256]; // Host name
}; };
// DNS wire-format header (RFC 1035). All fields are in network byte order; // DNS wire-format header (RFC-1035). All fields are in network byte order;
// use mg_ntohs() to read them. // use mg_ntohs() to read them.
struct mg_dns_header { struct mg_dns_header {
uint16_t txnid; // Transaction ID, matched between query and response uint16_t txnid; // Transaction ID, matched between query and response
+28
View File
@@ -12,3 +12,31 @@ struct mg_tcpip_driver_atcmd_data {
bool link; // internal use: done with AT processing bool link; // internal use: done with AT processing
bool unstuffing; // internal use: unstuffing state bool unstuffing; // internal use: unstuffing state
}; };
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ATCMD) && MG_ENABLE_DRIVER_ATCMD
extern struct mg_tcpip_driver mg_tcpip_driver_atcmd;
// Modem callbacks and AT script, defined by the application.
// See tutorials/arduino/sim800-mqtt for modem configuration.
extern struct mg_tcpip_driver_atcmd_data mg_atcmd;
#define MG_TCPIP_DRIVER_ATCMD_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_.driver = &mg_tcpip_driver_atcmd; \
mif_.driver_data = &mg_atcmd; \
mif_.l2type = MG_TCPIP_L2_PPP; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: atcmd, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ATCMD_INIT(x)
#endif
#endif
+18
View File
@@ -5,4 +5,22 @@
#include "Driver_ETH_MAC.h" // keep this include #include "Driver_ETH_MAC.h" // keep this include
#include "Driver_ETH_PHY.h" // keep this include #include "Driver_ETH_PHY.h" // keep this include
extern struct mg_tcpip_driver mg_tcpip_driver_cmsis;
#define MG_TCPIP_DRIVER_CMSIS_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_.driver = &mg_tcpip_driver_cmsis; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: cmsis, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_CMSIS_INIT(x)
#endif
#endif #endif
+8 -2
View File
@@ -20,7 +20,9 @@ struct mg_tcpip_driver_cyw_data {
bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3 Table 6) bool hs; // use chip "high-speed" mode; otherwise SPI CPOL0 CPHA0 (DS 4.2.3 Table 6)
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_cyw;
#define MG_TCPIP_DRIVER_CYW_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_cyw_data driver_data_; \ static struct mg_tcpip_driver_cyw_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -32,8 +34,12 @@ struct mg_tcpip_driver_cyw_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: cyw, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: cyw, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_CYW_INIT(x)
#endif
#endif #endif
+191
View File
@@ -0,0 +1,191 @@
#include "l2_mesh.h"
#include "log.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 <esp_attr.h>
#include <esp_ieee802154.h>
#include <esp_timer.h>
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
+38
View File
@@ -0,0 +1,38 @@
// 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
+8 -2
View File
@@ -30,7 +30,9 @@ struct mg_tcpip_driver_imxrt_data {
#define MG_DRIVER_MDC_CR 24 #define MG_DRIVER_MDC_CR 24
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_imxrt;
#define MG_TCPIP_DRIVER_IMXRT_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_imxrt_data driver_data_; \ static struct mg_tcpip_driver_imxrt_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -42,8 +44,12 @@ struct mg_tcpip_driver_imxrt_data {
mif_.driver = &mg_tcpip_driver_imxrt; \ mif_.driver = &mg_tcpip_driver_imxrt; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: imxrt, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: imxrt, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_IMXRT_INIT(x)
#endif
#endif #endif
+6 -20
View File
@@ -51,7 +51,6 @@ struct mg_zll {
// PHY_CTRL[XCVSEQ] // PHY_CTRL[XCVSEQ]
enum { MGI_SEQ_IDLE = 0, MGI_SEQ_RX = 1, MGI_SEQ_TX = 2 }; enum { MGI_SEQ_IDLE = 0, MGI_SEQ_RX = 1, MGI_SEQ_TX = 2 };
#define MGI_SEND_TIMEOUT_MS 60
static struct mg_tcpip_if *s_mcxw71_ifp; static struct mg_tcpip_if *s_mcxw71_ifp;
static struct mg_queue s_mcxw71_rx; static struct mg_queue s_mcxw71_rx;
@@ -110,15 +109,7 @@ void RF_802_15_4_IRQHandler(void) {
n = n >= 2 ? n - 2 : 0; n = n >= 2 ? n - 2 : 0;
if (n > 0 && n <= sizeof(frame)) { if (n > 0 && n <= sizeof(frame)) {
for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i]; for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i];
{ mg_mesh_rx_queue(&s_mcxw71_rx, s_mcxw71_ifp, frame, n);
char *dst;
if (mg_queue_book(&s_mcxw71_rx, &dst, n) >= n) {
memcpy(dst, frame, n);
mg_queue_add(&s_mcxw71_rx, n);
} else {
s_mcxw71_ifp->ndrop++;
}
}
} }
} }
mg_mcxw71_listen(); mg_mcxw71_listen();
@@ -179,11 +170,9 @@ static bool mgi_mcxw71_poll(struct mg_tcpip_if *ifp, bool s1) {
struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data; struct mg_tcpip_driver_mcxw71_data *data = ifp->driver_data;
struct mg_mesh_node *node = data->mesh; struct mg_mesh_node *node = data->mesh;
uint64_t now = mg_micros(); uint64_t now = mg_micros();
char *buf;
size_t len;
(void) s1; (void) s1;
if (s_mcxw71_txing && if (s_mcxw71_txing &&
mg_millis() > s_mcxw71_sendstart + MGI_SEND_TIMEOUT_MS) { mg_millis() > s_mcxw71_sendstart + MG_MESH_TX_TIMEOUT_US / 1000) {
mg_mcxw71_lock(); mg_mcxw71_lock();
if (s_mcxw71_txing) { if (s_mcxw71_txing) {
mg_mcxw71_abort(); mg_mcxw71_abort();
@@ -199,10 +188,7 @@ static bool mgi_mcxw71_poll(struct mg_tcpip_if *ifp, bool s1) {
node->tx_at = now + node->strategy->radio->ifs_us; node->tx_at = now + node->strategy->radio->ifs_us;
} }
node->now = now; node->now = now;
while (node->rx_len == 0 && (len = mg_queue_next(&s_mcxw71_rx, &buf)) != 0) { mg_mesh_rx_drain(node, &s_mcxw71_rx);
node->strategy->rx(node, buf, len);
mg_queue_del(&s_mcxw71_rx, len);
}
node->strategy->tick(node, now); node->strategy->tick(node, now);
return node->joined; return node->joined;
} }
@@ -214,10 +200,10 @@ static bool mgi_mcxw71_init(struct mg_tcpip_if *ifp) {
address = address =
(uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u);
if (strategy == NULL) strategy = &mg_mesh_default; if (strategy == NULL) strategy = &mg_mesh_default;
data->mesh = calloc(1, sizeof(*data->mesh)); data->mesh = mg_calloc(1, sizeof(*data->mesh));
if (data->mesh == NULL) return false; if (data->mesh == NULL) return false;
if (!strategy->init(data->mesh, ifp, NULL, address)) { if (!strategy->init(data->mesh, ifp, NULL, address)) {
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
@@ -226,7 +212,7 @@ static bool mgi_mcxw71_init(struct mg_tcpip_if *ifp) {
mg_queue_init(&s_mcxw71_rx, s_mcxw71_queue, sizeof(s_mcxw71_queue)); mg_queue_init(&s_mcxw71_rx, s_mcxw71_queue, sizeof(s_mcxw71_queue));
if (mgi_mcxw71_radio_init(ifp)) return true; if (mgi_mcxw71_radio_init(ifp)) return true;
strategy->free(data->mesh); strategy->free(data->mesh);
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
+2 -3
View File
@@ -13,7 +13,7 @@ struct mg_tcpip_driver_mcxw71_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71; extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
#define MG_TCPIP_DRIVER_MCXW71_INIT(manager) \ #define MG_TCPIP_DRIVER_MCXW71_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_mcxw71_data driver_data_; \ static struct mg_tcpip_driver_mcxw71_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -21,10 +21,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mcxw71; \ mif_.driver = &mg_tcpip_driver_mcxw71; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
+6 -18
View File
@@ -8,7 +8,6 @@
#include <rail_ieee802154.h> #include <rail_ieee802154.h>
// RAIL delivers raw frames and transmit completion from interrupt context. // RAIL delivers raw frames and transmit completion from interrupt context.
#define MG_MG24_TX_TIMEOUT_US 60000
static struct mg_tcpip_if *s_mg24_ifp; static struct mg_tcpip_if *s_mg24_ifp;
static RAIL_Handle_t s_mg24_rail; static RAIL_Handle_t s_mg24_rail;
@@ -23,7 +22,6 @@ static void mg_mg24_rx_frame(RAIL_Handle_t h) {
RAIL_RxPacketInfo_t info; RAIL_RxPacketInfo_t info;
uint8_t f[128]; uint8_t f[128];
size_t n; size_t n;
char *dst;
if (RAIL_GetRxPacketInfo(h, RAIL_RX_PACKET_HANDLE_NEWEST, &info) == if (RAIL_GetRxPacketInfo(h, RAIL_RX_PACKET_HANDLE_NEWEST, &info) ==
RAIL_RX_PACKET_HANDLE_INVALID || RAIL_RX_PACKET_HANDLE_INVALID ||
info.packetStatus != RAIL_RX_PACKET_READY_SUCCESS || info.packetStatus != RAIL_RX_PACKET_READY_SUCCESS ||
@@ -33,12 +31,7 @@ static void mg_mg24_rx_frame(RAIL_Handle_t h) {
RAIL_CopyRxPacket(f, &info); RAIL_CopyRxPacket(f, &info);
n = info.packetBytes - 1U; // Strip PHR n = info.packetBytes - 1U; // Strip PHR
if (n == f[0]) n -= 2; // FCS stored, strip it if (n == f[0]) n -= 2; // FCS stored, strip it
if (mg_queue_book(&s_mg24_rx, &dst, n) >= n) { mg_mesh_rx_queue(&s_mg24_rx, s_mg24_ifp, f + 1, n);
memcpy(dst, f + 1, n);
mg_queue_add(&s_mg24_rx, n);
} else {
s_mg24_ifp->ndrop++;
}
} }
// RAIL event callback, runs in interrupt context // RAIL event callback, runs in interrupt context
@@ -136,12 +129,10 @@ static bool mgi_mg24_poll(struct mg_tcpip_if *ifp, bool s1) {
struct mg_tcpip_driver_mg24_data *data = ifp->driver_data; struct mg_tcpip_driver_mg24_data *data = ifp->driver_data;
struct mg_mesh_node *node = data->mesh; struct mg_mesh_node *node = data->mesh;
uint64_t now = mg_micros(); uint64_t now = mg_micros();
char *buf;
size_t len;
(void) s1; (void) s1;
node->now = now; node->now = now;
if (s_mg24_txing && (s_mg24_tx_done || RAIL_GetTime() - s_mg24_txstart > if (s_mg24_txing && (s_mg24_tx_done || RAIL_GetTime() - s_mg24_txstart >
MG_MG24_TX_TIMEOUT_US)) { MG_MESH_TX_TIMEOUT_US)) {
if (!s_mg24_tx_done) { if (!s_mg24_tx_done) {
RAIL_Idle(s_mg24_rail, RAIL_IDLE_ABORT, true); RAIL_Idle(s_mg24_rail, RAIL_IDLE_ABORT, true);
RAIL_StartRx(s_mg24_rail, MG_802154_CHANNEL, NULL); RAIL_StartRx(s_mg24_rail, MG_802154_CHANNEL, NULL);
@@ -149,10 +140,7 @@ static bool mgi_mg24_poll(struct mg_tcpip_if *ifp, bool s1) {
s_mg24_txing = false; s_mg24_txing = false;
node->tx_at = now + node->strategy->radio->ifs_us; node->tx_at = now + node->strategy->radio->ifs_us;
} }
while (node->rx_len == 0 && (len = mg_queue_next(&s_mg24_rx, &buf)) != 0) { mg_mesh_rx_drain(node, &s_mg24_rx);
node->strategy->rx(node, buf, len);
mg_queue_del(&s_mg24_rx, len);
}
node->strategy->tick(node, now); node->strategy->tick(node, now);
return node->joined; return node->joined;
} }
@@ -162,10 +150,10 @@ static bool mgi_mg24_init(struct mg_tcpip_if *ifp) {
uint16_t address = uint16_t address =
(uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u);
if (strategy == NULL) strategy = &mg_mesh_default; if (strategy == NULL) strategy = &mg_mesh_default;
data->mesh = calloc(1, sizeof(*data->mesh)); data->mesh = mg_calloc(1, sizeof(*data->mesh));
if (data->mesh == NULL) return false; if (data->mesh == NULL) return false;
if (!strategy->init(data->mesh, ifp, NULL, address)) { if (!strategy->init(data->mesh, ifp, NULL, address)) {
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
@@ -174,7 +162,7 @@ static bool mgi_mg24_init(struct mg_tcpip_if *ifp) {
mg_queue_init(&s_mg24_rx, s_mg24_rxbuf, sizeof(s_mg24_rxbuf)); mg_queue_init(&s_mg24_rx, s_mg24_rxbuf, sizeof(s_mg24_rxbuf));
if (mgi_mg24_radio_init(ifp)) return true; if (mgi_mg24_radio_init(ifp)) return true;
data->mesh->strategy->free(data->mesh); data->mesh->strategy->free(data->mesh);
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
+2 -3
View File
@@ -12,7 +12,7 @@ struct mg_tcpip_driver_mg24_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mg24; extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
#define MG_TCPIP_DRIVER_MG24_INIT(manager) \ #define MG_TCPIP_DRIVER_MG24_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_mg24_data driver_data_; \ static struct mg_tcpip_driver_mg24_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -20,10 +20,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mg24; \ mif_.driver = &mg_tcpip_driver_mg24; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
+6 -3
View File
@@ -26,10 +26,9 @@ struct mg_tcpip_driver_netc_data {
#define MG_TCPIP_NETC_LINK 0 #define MG_TCPIP_NETC_LINK 0
#endif #endif
struct mg_tcpip_driver;
extern struct mg_tcpip_driver mg_tcpip_driver_netc; extern struct mg_tcpip_driver mg_tcpip_driver_netc;
#define MG_TCPIP_DRIVER_INIT(mgr) \ #define MG_TCPIP_DRIVER_NETC_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_netc_data driver_data_; \ static struct mg_tcpip_driver_netc_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -42,8 +41,12 @@ extern struct mg_tcpip_driver mg_tcpip_driver_netc;
mif_.driver = &mg_tcpip_driver_netc; \ mif_.driver = &mg_tcpip_driver_netc; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: netc, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: netc, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_NETC_INIT(x)
#endif
#endif #endif
+6 -17
View File
@@ -45,13 +45,7 @@ void RADIO_IRQHandler(void) {
mg_radio_802154.parse_hdr(&mg_radio_802154, frame, len, &dst, &src) != mg_radio_802154.parse_hdr(&mg_radio_802154, frame, len, &dst, &src) !=
0 && 0 &&
(dst == 0xffffu || dst == node->radio_address)) { (dst == 0xffffu || dst == node->radio_address)) {
char *dst; mg_mesh_rx_queue(&s_nrf52_rx, s_nrf52_ifp, frame, len);
if (mg_queue_book(&s_nrf52_rx, &dst, len) >= len) {
memcpy(dst, frame, len);
mg_queue_add(&s_nrf52_rx, len);
} else {
s_nrf52_ifp->ndrop++;
}
} }
} }
mgi_nrf52_listen(); mgi_nrf52_listen();
@@ -126,10 +120,8 @@ static bool mgi_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) {
struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data; struct mg_tcpip_driver_nrf52_data *data = ifp->driver_data;
struct mg_mesh_node *node = data->mesh; struct mg_mesh_node *node = data->mesh;
uint64_t now = mg_micros(); uint64_t now = mg_micros();
char *buf;
size_t len;
(void) s1; (void) s1;
if (s_nrf52_txing && mg_micros() - s_nrf52_started > 60000) { if (s_nrf52_txing && mg_micros() - s_nrf52_started > MG_MESH_TX_TIMEOUT_US) {
NVIC_DisableIRQ(RADIO_IRQn); NVIC_DisableIRQ(RADIO_IRQn);
mgi_nrf52_disable(); mgi_nrf52_disable();
s_nrf52_txing = false; s_nrf52_txing = false;
@@ -142,10 +134,7 @@ static bool mgi_nrf52_poll(struct mg_tcpip_if *ifp, bool s1) {
node->tx_at = now + node->strategy->radio->ifs_us; node->tx_at = now + node->strategy->radio->ifs_us;
} }
node->now = now; node->now = now;
while (node->rx_len == 0 && (len = mg_queue_next(&s_nrf52_rx, &buf)) != 0) { mg_mesh_rx_drain(node, &s_nrf52_rx);
node->strategy->rx(node, buf, len);
mg_queue_del(&s_nrf52_rx, len);
}
node->strategy->tick(node, now); node->strategy->tick(node, now);
return node->joined; return node->joined;
} }
@@ -157,10 +146,10 @@ static bool mgi_nrf52_init(struct mg_tcpip_if *ifp) {
address = address =
(uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u);
if (strategy == NULL) strategy = &mg_mesh_default; if (strategy == NULL) strategy = &mg_mesh_default;
data->mesh = calloc(1, sizeof(*data->mesh)); data->mesh = mg_calloc(1, sizeof(*data->mesh));
if (data->mesh == NULL) return false; if (data->mesh == NULL) return false;
if (!strategy->init(data->mesh, ifp, NULL, address)) { if (!strategy->init(data->mesh, ifp, NULL, address)) {
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
@@ -169,7 +158,7 @@ static bool mgi_nrf52_init(struct mg_tcpip_if *ifp) {
mg_queue_init(&s_nrf52_rx, s_nrf52_queue, sizeof(s_nrf52_queue)); mg_queue_init(&s_nrf52_rx, s_nrf52_queue, sizeof(s_nrf52_queue));
if (mgi_nrf52_radio_init(ifp)) return true; if (mgi_nrf52_radio_init(ifp)) return true;
strategy->free(data->mesh); strategy->free(data->mesh);
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
+2 -3
View File
@@ -12,7 +12,7 @@ struct mg_tcpip_driver_nrf52_data {
extern struct mg_tcpip_driver mg_tcpip_driver_nrf52; extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
#define MG_TCPIP_DRIVER_NRF52_INIT(manager) \ #define MG_TCPIP_DRIVER_NRF52_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_nrf52_data driver_data_; \ static struct mg_tcpip_driver_nrf52_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -20,10 +20,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_nrf52; \ mif_.driver = &mg_tcpip_driver_nrf52; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
+8 -2
View File
@@ -9,7 +9,9 @@ struct mg_tcpip_driver_nxp_wifi_data {
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_nxp_wifi;
#define MG_TCPIP_DRIVER_NXP_WIFI_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_nxp_wifi_data driver_data_; \ static struct mg_tcpip_driver_nxp_wifi_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -21,8 +23,12 @@ struct mg_tcpip_driver_nxp_wifi_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: nxp wifi, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: nxp wifi, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_NXP_WIFI_INIT(x)
#endif
#endif #endif
+8 -2
View File
@@ -11,7 +11,9 @@ struct mg_tcpip_driver_pico_w_data {
struct mg_wifi_data wifi; struct mg_wifi_data wifi;
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_pico_w;
#define MG_TCPIP_DRIVER_PICO_W_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_pico_w_data driver_data_; \ static struct mg_tcpip_driver_pico_w_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -23,8 +25,12 @@ struct mg_tcpip_driver_pico_w_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: pico-w, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: pico-w, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_PICO_W_INIT(x)
#endif
#endif #endif
+8 -2
View File
@@ -23,7 +23,9 @@ struct mg_tcpip_driver_ra_data {
#define MG_TCPIP_PHY_ADDR 0 #define MG_TCPIP_PHY_ADDR 0
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_ra;
#define MG_TCPIP_DRIVER_RA_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_ra_data driver_data_; \ static struct mg_tcpip_driver_ra_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -36,8 +38,12 @@ struct mg_tcpip_driver_ra_data {
mif_.driver = &mg_tcpip_driver_ra; \ mif_.driver = &mg_tcpip_driver_ra; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: ra, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: ra, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_RA_INIT(x)
#endif
#endif #endif
+7 -3
View File
@@ -27,8 +27,9 @@ struct mg_tcpip_driver_rw612_data {
#define MG_DRIVER_MDC_HOLDTIME 3 #define MG_DRIVER_MDC_HOLDTIME 3
#endif #endif
#ifndef MG_TCPIP_DRIVER_INIT extern struct mg_tcpip_driver mg_tcpip_driver_rw612;
#define MG_TCPIP_DRIVER_INIT(mgr) \
#define MG_TCPIP_DRIVER_RW612_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_rw612_data driver_data_; \ static struct mg_tcpip_driver_rw612_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -40,9 +41,12 @@ struct mg_tcpip_driver_rw612_data {
mif_.driver = &mg_tcpip_driver_rw612; \ mif_.driver = &mg_tcpip_driver_rw612; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: rw612, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: rw612, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_RW612_INIT(x)
#endif #endif
#endif #endif
+5 -18
View File
@@ -138,15 +138,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) { 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);
char *dst;
if (mg_queue_book(&s_rw612w_rx, &dst, len) >= len) {
memcpy(dst, frame, len);
mg_queue_add(&s_rw612w_rx, len);
} else {
s_rw612.ifp->ndrop++;
}
}
} }
// Spinel packed unsigned integer: 7 bits per byte, LSB first // Spinel packed unsigned integer: 7 bits per byte, LSB first
@@ -457,8 +449,6 @@ static bool mgi_rw612w_poll(struct mg_tcpip_if *ifp, bool s1) {
struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data; struct mg_tcpip_driver_rw612w_data *data = ifp->driver_data;
struct mg_mesh_node *node = data->mesh; struct mg_mesh_node *node = data->mesh;
uint64_t now = mg_micros(); uint64_t now = mg_micros();
char *buf;
size_t len;
(void) s1; (void) s1;
bool was_sending = s_rw612.txing; bool was_sending = s_rw612.txing;
mg_rw612_poll_imu(); mg_rw612_poll_imu();
@@ -470,10 +460,7 @@ static bool mgi_rw612w_poll(struct mg_tcpip_if *ifp, bool s1) {
if (was_sending && !s_rw612.txing) if (was_sending && !s_rw612.txing)
node->tx_at = now + node->strategy->radio->ifs_us; node->tx_at = now + node->strategy->radio->ifs_us;
node->now = now; node->now = now;
while (node->rx_len == 0 && (len = mg_queue_next(&s_rw612w_rx, &buf)) != 0) { mg_mesh_rx_drain(node, &s_rw612w_rx);
node->strategy->rx(node, buf, len);
mg_queue_del(&s_rw612w_rx, len);
}
node->strategy->tick(node, now); node->strategy->tick(node, now);
return node->joined; return node->joined;
} }
@@ -491,10 +478,10 @@ static bool mgi_rw612w_init(struct mg_tcpip_if *ifp) {
address = address =
(uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u); (uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u);
if (strategy == NULL) strategy = &mg_mesh_default; if (strategy == NULL) strategy = &mg_mesh_default;
data->mesh = calloc(1, sizeof(*data->mesh)); data->mesh = mg_calloc(1, sizeof(*data->mesh));
if (data->mesh == NULL) return false; if (data->mesh == NULL) return false;
if (!strategy->init(data->mesh, ifp, NULL, address)) { if (!strategy->init(data->mesh, ifp, NULL, address)) {
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
@@ -503,7 +490,7 @@ static bool mgi_rw612w_init(struct mg_tcpip_if *ifp) {
mg_queue_init(&s_rw612w_rx, s_rw612w_queue, sizeof(s_rw612w_queue)); mg_queue_init(&s_rw612w_rx, s_rw612w_queue, sizeof(s_rw612w_queue));
if (mgi_rw612w_radio_init(ifp)) return true; if (mgi_rw612w_radio_init(ifp)) return true;
strategy->free(data->mesh); strategy->free(data->mesh);
free(data->mesh); mg_free(data->mesh);
data->mesh = NULL; data->mesh = NULL;
return false; return false;
} }
+2 -3
View File
@@ -13,7 +13,7 @@ struct mg_tcpip_driver_rw612w_data {
extern struct mg_tcpip_driver mg_tcpip_driver_rw612w; extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
#define MG_TCPIP_DRIVER_RW612W_INIT(manager) \ #define MG_TCPIP_DRIVER_RW612W_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_rw612w_data driver_data_; \ static struct mg_tcpip_driver_rw612w_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -21,10 +21,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
mif_.ip = MG_TCPIP_IP; \ mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \ mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \ mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_rw612w; \ mif_.driver = &mg_tcpip_driver_rw612w; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
+8 -2
View File
@@ -16,7 +16,9 @@ struct mg_tcpip_driver_same54_data {
uint8_t phy_addr; uint8_t phy_addr;
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_same54;
#define MG_TCPIP_DRIVER_SAME54_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_same54_data driver_data_; \ static struct mg_tcpip_driver_same54_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -28,8 +30,12 @@ struct mg_tcpip_driver_same54_data {
mif_.driver = &mg_tcpip_driver_same54; \ mif_.driver = &mg_tcpip_driver_same54; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: same54, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: same54, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_SAME54_INIT(x)
#endif
#endif #endif
+8 -2
View File
@@ -10,7 +10,9 @@ struct mg_tcpip_driver_st67w6_data {
struct mg_queue send_queue; // decouple tx calls from module polls struct mg_queue send_queue; // decouple tx calls from module polls
}; };
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_st67w6;
#define MG_TCPIP_DRIVER_ST67W6_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_st67w6_data driver_data_; \ static struct mg_tcpip_driver_st67w6_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -22,8 +24,12 @@ struct mg_tcpip_driver_st67w6_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
mif_.recv_queue.size = 8192; \ mif_.recv_queue.size = 8192; \
mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \ mif_.mac[0] = 2; /* MAC read from OTP at driver init */ \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: st67w6, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: st67w6, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ST67W6_INIT(x)
#endif
#endif #endif
+8 -2
View File
@@ -34,7 +34,9 @@ struct mg_tcpip_driver_stm32f_data {
#define MG_ENABLE_ETH_IRQ() #define MG_ENABLE_ETH_IRQ()
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_stm32f;
#define MG_TCPIP_DRIVER_STM32F_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_stm32f_data driver_data_; \ static struct mg_tcpip_driver_stm32f_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -47,8 +49,12 @@ struct mg_tcpip_driver_stm32f_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
MG_ENABLE_ETH_IRQ(); \ MG_ENABLE_ETH_IRQ(); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_STM32F_INIT(x)
#endif
#endif #endif
+8 -2
View File
@@ -72,7 +72,9 @@ struct mg_tcpip_driver_stm32h_data {
#define MG_IPV6_INIT(mif) #define MG_IPV6_INIT(mif)
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_stm32h;
#define MG_TCPIP_DRIVER_STM32H_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_stm32h_data driver_data_; \ static struct mg_tcpip_driver_stm32h_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -86,10 +88,14 @@ struct mg_tcpip_driver_stm32h_data {
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
MG_IPV6_INIT(mif_); \ MG_IPV6_INIT(mif_); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_ENABLE_ETH_IRQ(); \ MG_ENABLE_ETH_IRQ(); \
MG_INFO(("Driver: stm32h, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: stm32h, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_STM32H_INIT(x)
#endif
#endif #endif
#endif #endif
+8 -2
View File
@@ -19,7 +19,9 @@ struct mg_tcpip_driver_tm4c_data {
#define MG_DRIVER_MDC_CR 1 #define MG_DRIVER_MDC_CR 1
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_tm4c;
#define MG_TCPIP_DRIVER_TM4C_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_tm4c_data driver_data_; \ static struct mg_tcpip_driver_tm4c_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -30,8 +32,12 @@ struct mg_tcpip_driver_tm4c_data {
mif_.driver = &mg_tcpip_driver_tm4c; \ mif_.driver = &mg_tcpip_driver_tm4c; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: tm4c, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: tm4c, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_TM4C_INIT(x)
#endif
#endif #endif
+9 -2
View File
@@ -14,7 +14,9 @@ struct mg_tcpip_driver_tms570_data {
#define MG_DRIVER_MDC_CR 1 #define MG_DRIVER_MDC_CR 1
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_tms570;
#define MG_TCPIP_DRIVER_TMS570_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_tms570_data driver_data_; \ static struct mg_tcpip_driver_tms570_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -26,8 +28,13 @@ struct mg_tcpip_driver_tms570_data {
mif_.driver = &mg_tcpip_driver_tms570; \ mif_.driver = &mg_tcpip_driver_tms570; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: tms570, MAC: %M", mg_print_mac, mif_.mac));\ MG_INFO(("Driver: tms570, MAC: %M", mg_print_mac, mif_.mac));\
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_TMS570_INIT(x)
#endif
#endif #endif
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5100) && \
MG_ENABLE_DRIVER_W5100
extern struct mg_tcpip_driver mg_tcpip_driver_w5100;
// Initialises W5100 on mgr. The application defines
// struct mg_tcpip_spi mg_spi
#define MG_TCPIP_DRIVER_W5100_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_.driver = &mg_tcpip_driver_w5100; \
mif_.driver_data = &mg_spi; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: w5100, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_W5100_INIT(x)
#endif
#endif
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_W5500) && \
MG_ENABLE_DRIVER_W5500
extern struct mg_tcpip_driver mg_tcpip_driver_w5500;
// Initialises W5500 on mgr. The application defines
// struct mg_tcpip_spi mg_spi. Example: tutorials/rp/w5500-evb-pico
#define MG_TCPIP_DRIVER_W5500_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_.driver = &mg_tcpip_driver_w5500; \
mif_.driver_data = &mg_spi; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: w5500, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_W5500_INIT(x)
#endif
#endif
+8 -2
View File
@@ -28,7 +28,9 @@ struct mg_tcpip_driver_xmc_data {
#define MG_DRIVER_MDC_CR 4 #define MG_DRIVER_MDC_CR 4
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_xmc;
#define MG_TCPIP_DRIVER_XMC_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_xmc_data driver_data_; \ static struct mg_tcpip_driver_xmc_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -40,8 +42,12 @@ struct mg_tcpip_driver_xmc_data {
mif_.driver = &mg_tcpip_driver_xmc; \ mif_.driver = &mg_tcpip_driver_xmc; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: xmc, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: xmc, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_XMC_INIT(x)
#endif
#endif #endif
+8 -2
View File
@@ -15,7 +15,9 @@ struct mg_tcpip_driver_xmc7_data {
#define MG_DRIVER_MDC_CR 3 #define MG_DRIVER_MDC_CR 3
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_xmc7;
#define MG_TCPIP_DRIVER_XMC7_INIT(mgr) \
do { \ do { \
static struct mg_tcpip_driver_xmc7_data driver_data_; \ static struct mg_tcpip_driver_xmc7_data driver_data_; \
static struct mg_tcpip_if mif_; \ static struct mg_tcpip_if mif_; \
@@ -27,9 +29,13 @@ struct mg_tcpip_driver_xmc7_data {
mif_.driver = &mg_tcpip_driver_xmc7; \ mif_.driver = &mg_tcpip_driver_xmc7; \
mif_.driver_data = &driver_data_; \ mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \ MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \ mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: xmc7, MAC: %M", mg_print_mac, mif_.mac)); \ MG_INFO(("Driver: xmc7, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0) } while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_XMC7_INIT(x)
#endif
#endif #endif
+1 -1
View File
@@ -1197,7 +1197,7 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
// POST and PUT should include an entity body. Therefore, they should // POST and PUT should include an entity body. Therefore, they should
// contain a Content-length header (unless the body length is 0, in // contain a Content-length header (unless the body length is 0, in
// which case it can be omitted). Other requests can also contain a // which case it can be omitted). Other requests can also contain a
// body, but their content has no defined semantics (RFC 7231) // body, but their content has no defined semantics (RFC-7231)
// It is a non-chunked request, so the offset (ofs) is updated after // It is a non-chunked request, so the offset (ofs) is updated after
// exiting this branch. // exiting this branch.
if (hm.body.len != 0) require_content_len = true; if (hm.body.len != 0) require_content_len = true;
+71 -10
View File
@@ -108,6 +108,8 @@ static size_t mgi_mesh_b_queue(struct mg_mesh_node *node, struct mg_queue *q,
#define MGI_JOIN_JITTER_US 640 #define MGI_JOIN_JITTER_US 640
#define MGI_DATA_QUEUE_SIZE 2048 #define MGI_DATA_QUEUE_SIZE 2048
#define MGI_TX_RETRY_US 32 #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 // Our frames: the radio header, with the radio addresses, then the mesh
// header MG_MESH_HDR_LEN, then the payload // header MG_MESH_HDR_LEN, then the payload
#define MGI_JOIN_UP_LEN \ #define MGI_JOIN_UP_LEN \
@@ -134,6 +136,7 @@ struct mgi_mesh_b_data {
int8_t missed_rounds; // -1 after a grant; otherwise completed rounds missed int8_t missed_rounds; // -1 after a grant; otherwise completed rounds missed
uint16_t coordinator; // Coordinator radio address uint16_t coordinator; // Coordinator radio address
uint8_t phase; // MGI_TURN_IDLE, MGI_TURN_JOIN, or MGI_TURN_DATA 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 {
@@ -246,11 +249,24 @@ static void mgi_mesh_b_tx_step(struct mgi_mesh_b_data *data, uint64_t now) {
} else { } else {
mgi_mesh_b_frame_header(frame, dst, node->radio_address, command, 0); 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) { if (now < data->node->tx_at || data->node->tx(radio, frame, len) != len) {
data->tx_at = now + MGI_TX_RETRY_US; data->tx_at = now + MGI_TX_RETRY_US;
return; return;
} }
if (data->tx_offset == 0 || (data->tx_offset += len + 1) == record_len) { 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); mgi_mesh_b_tx_finish(data);
} else { } else {
data->tx_at = now + mgi_mesh_b_airtime(len) + s_mesh_default_radio->ifs_us; data->tx_at = now + mgi_mesh_b_airtime(len) + s_mesh_default_radio->ifs_us;
@@ -260,6 +276,7 @@ static void mgi_mesh_b_tx_step(struct mgi_mesh_b_data *data, uint64_t now) {
static void mgi_mesh_b_tx_begin(struct mgi_mesh_b_data *data, bool burst, static void mgi_mesh_b_tx_begin(struct mgi_mesh_b_data *data, bool burst,
uint64_t now, uint64_t deadline) { uint64_t now, uint64_t deadline) {
data->phase = MGI_TURN_DATA; 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_offset = burst ? MGI_TX_DST_LEN : 0;
data->tx_at = now; data->tx_at = now;
data->deadline = deadline; data->deadline = deadline;
@@ -290,6 +307,11 @@ static int mgi_mesh_b_data_receive(struct mgi_mesh_b_data *data,
memcpy(data->rx_buf + offset, frame + MG_MESH_FRAME_HDR_LEN, chunk); memcpy(data->rx_buf + offset, frame + MG_MESH_FRAME_HDR_LEN, chunk);
if (index < last) { if (index < last) {
data->rx_expected = (uint8_t) (burst + 0x10); 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; return -1;
} }
data->rx_expected = 0xff; data->rx_expected = 0xff;
@@ -299,7 +321,6 @@ static int mgi_mesh_b_data_receive(struct mgi_mesh_b_data *data,
// Bridge scheduling and Ethernet forwarding. // Bridge scheduling and Ethernet forwarding.
#define MGI_MAX_MISSES 3 // Turns in a row without an answer: remove the member
static uint16_t mgi_mesh_b_join_field(const uint8_t *p) { static uint16_t mgi_mesh_b_join_field(const uint8_t *p) {
return (uint16_t) ((unsigned) p[0] * 256 + p[1]); return (uint16_t) ((unsigned) p[0] * 256 + p[1]);
@@ -400,13 +421,13 @@ static void mgi_mesh_b_bridge_rx(uint64_t now, struct mg_mesh_node *b,
memcpy(peer->mac, frame + MG_MESH_FRAME_HDR_LEN, sizeof(peer->mac)); memcpy(peer->mac, frame + MG_MESH_FRAME_HDR_LEN, sizeof(peer->mac));
} }
// Member peer did not answer its turn. After MGI_MAX_MISSES in a row, it is // Member peer did not answer its turn. After MG_MESH_MAX_MISSES in a row, it
// gone: remove it, and its queued downlink frames // is gone: remove it, and its queued downlink frames
static void mgi_mesh_b_member_missed(struct mgi_mesh_b_data *data, static void mgi_mesh_b_member_missed(struct mgi_mesh_b_data *data,
struct mgi_mesh_b_peer *peer) { struct mgi_mesh_b_peer *peer) {
if (++peer->misses < MGI_MAX_MISSES) return; if (++peer->misses < MG_MESH_MAX_MISSES) return;
MG_INFO(("Member %M removed: no answer %d times", mg_print_mac, peer->mac, MG_INFO(("Member %M removed: no answer %d times", mg_print_mac, peer->mac,
MGI_MAX_MISSES)); MG_MESH_MAX_MISSES));
if (data->fanout == peer) { if (data->fanout == peer) {
data->fanout = peer->next; data->fanout = peer->next;
if (data->fanout == NULL) { if (data->fanout == NULL) {
@@ -499,7 +520,7 @@ static void mgi_mesh_b_node_rx(struct mg_mesh_node *n, uint64_t now,
if (command == MGI_JOIN_DOWN && len == MG_MESH_FRAME_HDR_LEN && if (command == MGI_JOIN_DOWN && len == MG_MESH_FRAME_HDR_LEN &&
dst == 0xffffu) { dst == 0xffffu) {
if (n->joined && src == data->coordinator && if (n->joined && src == data->coordinator &&
++data->missed_rounds >= MGI_MAX_MISSES) { ++data->missed_rounds >= MG_MESH_MAX_MISSES) {
n->joined = false; n->joined = false;
data->phase = MGI_TURN_IDLE; data->phase = MGI_TURN_IDLE;
data->tx_at = (uint64_t) -1; data->tx_at = (uint64_t) -1;
@@ -534,17 +555,22 @@ static void mgi_mesh_b_node_rx(struct mg_mesh_node *n, uint64_t now,
now + mgi_mesh_b_burst_time(MGI_ETH_MAX) + now + mgi_mesh_b_burst_time(MGI_ETH_MAX) +
2 * s_mesh_default_radio->ifs_us + 2 * s_mesh_default_radio->ifs_us +
MGI_JOIN_TURN_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) { 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 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; if (node->tx_at < ready) node->tx_at = ready;
node->next_tick = node->now; node->next_tick = node->now;
if (node->lan != NULL) if (node->lan != NULL) {
mgi_mesh_b_bridge_rx(node->now, node, (const uint8_t *) buf, len); mgi_mesh_b_bridge_rx(arrived, node, (const uint8_t *) buf, len);
else } else {
mgi_mesh_b_node_rx(node, node->now, (uint8_t *) buf, len); 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) { static void mgi_mesh_b_tick(struct mg_mesh_node *node, uint64_t now) {
@@ -601,6 +627,41 @@ static void mgi_mesh_b_free(struct mg_mesh_node *node) {
node->data = NULL; 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 = { const struct mg_mesh mg_mesh_default = {
"default", "default",
mgi_mesh_b_init, mgi_mesh_b_init,
+34 -3
View File
@@ -12,9 +12,6 @@
#if MG_ENABLE_TCPIP #if MG_ENABLE_TCPIP
// Monotonic time in microseconds.
uint64_t mg_micros(void);
// A radio standard // A radio standard
struct mg_radio { struct mg_radio {
const char *name; // For logs const char *name; // For logs
@@ -44,6 +41,27 @@ struct mg_radio {
#define MG_802154_CHANNEL 15 #define MG_802154_CHANNEL 15
#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_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; extern const struct mg_radio mg_radio_802154;
struct mg_mesh_node { struct mg_mesh_node {
@@ -53,6 +71,7 @@ struct mg_mesh_node {
size_t (*tx)(struct mg_tcpip_if *, const void *, size_t); // Radio frame TX 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 size_t rx_len; // Complete Ethernet frame in the interface RX buffer
uint64_t now; // Current driver poll time, us 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 uint64_t tx_at; // Earliest next transmission, us
void *data; // Private state owned by the strategy void *data; // Private state owned by the strategy
size_t ram_used; // Live mesh state bytes size_t ram_used; // Live mesh state bytes
@@ -77,4 +96,16 @@ struct mg_mesh {
extern const struct mg_mesh mg_mesh_default; 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 #endif
+3 -6
View File
@@ -117,8 +117,7 @@ struct mg_mqtt_message {
// struct mg_mqtt_opts opts = {.client_id = mg_str("device1")}; // struct mg_mqtt_opts opts = {.client_id = mg_str("device1")};
// mg_mqtt_connect(&mgr, "mqtt://broker:1883", &opts, fn, NULL); // mg_mqtt_connect(&mgr, "mqtt://broker:1883", &opts, fn, NULL);
// Full examples: // Full examples:
// tutorials/mqtt/mqtt-client, tutorials/mqtt/mqtt-client-aws-iot, // tutorials/mqtt/mqtt-client, tutorials/mqtt/ota-over-mqtt
// tutorials/mqtt/ota-over-mqtt
// Related APIs: // Related APIs:
// mg_mqtt_pub(), mg_mqtt_sub(), mg_tls_init(), mg_mgr_poll() // mg_mqtt_pub(), mg_mqtt_sub(), mg_tls_init(), mg_mgr_poll()
// Notes: // Notes:
@@ -153,8 +152,7 @@ void mg_mqtt_login(struct mg_connection *c, const struct mg_mqtt_opts *opts);
// }; // };
// uint16_t id = mg_mqtt_pub(c, &opts); // uint16_t id = mg_mqtt_pub(c, &opts);
// Full examples: // Full examples:
// tutorials/mqtt/mqtt-client, tutorials/mqtt/mqtt-client-aws-iot, // tutorials/mqtt/mqtt-client, tutorials/mqtt/ota-over-mqtt
// tutorials/mqtt/ota-over-mqtt
// Related APIs: // Related APIs:
// mg_mqtt_connect(), mg_mqtt_sub(), mg_mqtt_send_header() // mg_mqtt_connect(), mg_mqtt_sub(), mg_mqtt_send_header()
// Notes: // Notes:
@@ -169,8 +167,7 @@ uint16_t mg_mqtt_pub(struct mg_connection *c, const struct mg_mqtt_opts *opts);
// struct mg_mqtt_opts opts = {.topic = mg_str("device/rx"), .qos = 1}; // struct mg_mqtt_opts opts = {.topic = mg_str("device/rx"), .qos = 1};
// mg_mqtt_sub(c, &opts); // mg_mqtt_sub(c, &opts);
// Full examples: // Full examples:
// tutorials/mqtt/mqtt-client, tutorials/mqtt/mqtt-client-aws-iot, // tutorials/mqtt/mqtt-client, tutorials/mqtt/ota-over-mqtt
// tutorials/mqtt/ota-over-mqtt
// Related APIs: // Related APIs:
// mg_mqtt_connect(), mg_mqtt_pub(), mg_mqtt_unsub() // mg_mqtt_connect(), mg_mqtt_pub(), mg_mqtt_unsub()
// Notes: // Notes:
+33 -18
View File
@@ -395,7 +395,7 @@ static size_t driver_output(struct mg_tcpip_if *ifp, size_t len) {
return n; return n;
} }
// RFC826, ARP assumes Ethernet MAC addresses // RFC-826, ARP assumes Ethernet MAC addresses
void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac) { void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac) {
uint8_t *l2p = (uint8_t *) ifp->tx.buf; uint8_t *l2p = (uint8_t *) ifp->tx.buf;
struct arp *arp = (struct arp *) mg_l2_header( struct arp *arp = (struct arp *) mg_l2_header(
@@ -536,7 +536,7 @@ static void tx_dhcp(struct mg_tcpip_if *ifp, uint8_t *l2_dst, uint32_t ip_src,
sizeof(dhcp)); sizeof(dhcp));
} }
// RFC-2131 #4.3.6, #4.4.1; RFC-2132 #9.8 // RFC-2131 4.3.6, 4.4.1; RFC-2132 9.8
static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req, static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
uint32_t ip_srv) { uint32_t ip_srv) {
uint8_t extra = (uint8_t) ((ifp->enable_req_dns ? 1 : 0) + uint8_t extra = (uint8_t) ((ifp->enable_req_dns ? 1 : 0) +
@@ -563,7 +563,7 @@ static void tx_dhcp_request_sel(struct mg_tcpip_if *ifp, uint32_t ip_req,
MG_DEBUG(("DHCP req sent")); MG_DEBUG(("DHCP req sent"));
} }
// RFC-2131 #4.3.6, #4.4.5 (renewing: unicast, rebinding: bcast) // RFC-2131 4.3.6, 4.4.5 (renewing: unicast, rebinding: bcast)
static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *l2_dst, static void tx_dhcp_request_re(struct mg_tcpip_if *ifp, uint8_t *l2_dst,
uint32_t ip_src, uint32_t ip_dst) { uint32_t ip_src, uint32_t ip_dst) {
uint8_t opts[] = { uint8_t opts[] = {
@@ -617,7 +617,7 @@ static void l2addr_resolved(struct mg_connection *c);
static uint8_t *get_return_l2addr(struct mg_tcpip_if *ifp, struct mg_addr *rem, static uint8_t *get_return_l2addr(struct mg_tcpip_if *ifp, struct mg_addr *rem,
bool is_udp, struct pkt *pkt); bool is_udp, struct pkt *pkt);
// RFC826, ARP assumes Ethernet MAC addresses // RFC-826, ARP assumes Ethernet MAC addresses
static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) { static void rx_arp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) { if (pkt->arp->op == mg_htons(1) && pkt->arp->tpa == ifp->ip) {
// ARP request. Make a response, then send // ARP request. Make a response, then send
@@ -1023,13 +1023,13 @@ static void rx_ndp_ra(struct mg_tcpip_if *ifp, struct pkt *pkt) {
if (pkt->pay.len < sizeof(*ra)) return; if (pkt->pay.len < sizeof(*ra)) return;
if (ifp->state6 == MG_TCPIP_STATE_UP) { if (ifp->state6 == MG_TCPIP_STATE_UP) {
MG_DEBUG(("Received NDP RA")); // fill gw6 address if RFC 4861 6.1.2 MG_DEBUG(("Received NDP RA")); // fill gw6 address if RFC-4861 6.1.2
if (memcmp(pkt->ip6->src, locpx, 8) != 0 || pkt->ip6->hops != 255) return; if (memcmp(pkt->ip6->src, locpx, 8) != 0 || pkt->ip6->hops != 255) return;
// parse options // parse options
while (opt_left >= 2) { while (opt_left >= 2) {
uint8_t type = opts[0], len = opts[1]; uint8_t type = opts[0], len = opts[1];
size_t length = (size_t) len * 8; size_t length = (size_t) len * 8;
if (length == 0 || length > opt_left) return; // RFC 4861 6.1.2 if (length == 0 || length > opt_left) return; // RFC-4861 6.1.2
if (type == 1 && length >= 8) { if (type == 1 && length >= 8) {
// Received router's L2 address // Received router's L2 address
if (!mg_l2_ip6get(ifp->l2type, l2, opts + 2, len)) break; if (!mg_l2_ip6get(ifp->l2type, l2, opts + 2, len)) break;
@@ -1110,7 +1110,7 @@ static void rx_icmp6(struct mg_tcpip_if *ifp, struct pkt *pkt) {
} }
} break; } break;
case 134: // Router Advertisement case 134: // Router Advertisement
if (pkt->icmp6->code == 0) rx_ndp_ra(ifp, pkt); // RFC 4861 6.1.2 if (pkt->icmp6->code == 0) rx_ndp_ra(ifp, pkt); // RFC-4861 6.1.2
break; break;
case 135: // Neighbor Solicitation case 135: // Neighbor Solicitation
rx_ndp_ns(ifp, pkt); rx_ndp_ns(ifp, pkt);
@@ -1224,24 +1224,34 @@ static void proto_error(struct mg_connection *c, bool r, const char *f, ...) {
static bool rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) { static bool rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
struct mg_connection *c = getpeer(ifp->mgr, pkt, true); struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
struct connstate *s; struct connstate *s;
struct mg_addr rem;
uint8_t *l2addr; uint8_t *l2addr;
if (c == NULL) return false; // No UDP listener on this port if (c == NULL) return false; // No UDP listener on this port
// BSD socket has an unread datagram: drop this one to keep boundaries // BSD socket has an unread datagram: drop this one to keep boundaries
if (c->is_bsd && c->recv.len > 0) return true; if (c->is_bsd && c->recv.len > 0) return true;
if (c->is_bsd && !c->is_client && c->send.len > 0) return true;
s = (struct connstate *) (c + 1); s = (struct connstate *) (c + 1);
c->rem.port = pkt->udp->sport;
#if MG_ENABLE_IPV6 #if MG_ENABLE_IPV6
if (c->loc.is_ip6) { // matching of v4/v6 to dest is done bt getpeer() if (c->loc.is_ip6) { // matching of v4/v6 to dest is done bt getpeer()
if (!udp6csum_ok(pkt->ip6, pkt->udp)) return false; if (!udp6csum_ok(pkt->ip6, pkt->udp)) return false;
c->rem.addr.ip6[0] = pkt->ip6->src[0], if (c->is_bsd && c->is_client &&
c->rem.addr.ip6[1] = pkt->ip6->src[1], c->rem.is_ip6 = true; (c->rem.port != pkt->udp->sport ||
!MG_IP6MATCH(c->rem.addr.ip6, pkt->ip6->src)))
return true;
rem.addr.ip6[0] = pkt->ip6->src[0],
rem.addr.ip6[1] = pkt->ip6->src[1], rem.is_ip6 = true;
} else } else
#endif #endif
{ {
if (!udpcsum_ok(pkt->ip, pkt->udp)) return false; if (!udpcsum_ok(pkt->ip, pkt->udp)) return false;
c->rem.addr.ip4 = pkt->ip->src; if (c->is_bsd && c->is_client &&
(c->rem.port != pkt->udp->sport || c->rem.addr.ip4 != pkt->ip->src))
return true;
rem.addr.ip4 = pkt->ip->src, rem.is_ip6 = false;
} }
if ((l2addr = get_return_l2addr(ifp, &c->rem, true, pkt)) == NULL) rem.port = pkt->udp->sport;
c->rem = rem;
if ((l2addr = get_return_l2addr(ifp, &rem, true, pkt)) == NULL)
return false; // safety net for lousy networks return false; // safety net for lousy networks
memcpy(s->mac, l2addr, sizeof(s->mac)); memcpy(s->mac, l2addr, sizeof(s->mac));
if (c->recv.len >= MG_MAX_RECV_SIZE) { if (c->recv.len >= MG_MAX_RECV_SIZE) {
@@ -2347,20 +2357,25 @@ void mg_connect_resolved(struct mg_connection *c) {
s->retransmit = ifp->enable_tcp_retransmit; s->retransmit = ifp->enable_tcp_retransmit;
s->txq.align = MG_TCPIP_TXQ_ALIGN; s->txq.align = MG_TCPIP_TXQ_ALIGN;
c->is_resolving = 0; c->is_resolving = 0;
if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE; if (c->loc.port == 0) {
if (ifp->eport < MG_EPHEMERAL_PORT_BASE)
ifp->eport = MG_EPHEMERAL_PORT_BASE;
c->loc.port = mg_htons(ifp->eport++); c->loc.port = mg_htons(ifp->eport++);
} // otherwise retain an existing bound port
#if MG_ENABLE_IPV6 #if MG_ENABLE_IPV6
if (c->rem.is_ip6) { if (c->rem.is_ip6) {
if (c->rem.addr.ip6[0] == ifp->ip6ll[0]) { // same local LAN, use ll if (c->loc.addr.ip6[0] == 0 && c->loc.addr.ip6[1] == 0 &&
c->rem.addr.ip6[0] == ifp->ip6ll[0]) { // same local LAN, use ll
c->loc.addr.ip6[0] = ifp->ip6ll[0], c->loc.addr.ip6[1] = ifp->ip6ll[1]; c->loc.addr.ip6[0] = ifp->ip6ll[0], c->loc.addr.ip6[1] = ifp->ip6ll[1];
} else { // use global address } else if (c->loc.addr.ip6[0] == 0 && c->loc.addr.ip6[1] == 0) {
// Use global address
c->loc.addr.ip6[0] = ifp->ip6[0], c->loc.addr.ip6[1] = ifp->ip6[1]; c->loc.addr.ip6[0] = ifp->ip6[0], c->loc.addr.ip6[1] = ifp->ip6[1];
} } // otherwise retain an existing bound address
c->loc.is_ip6 = true; c->loc.is_ip6 = true;
} else } else
#endif #endif
{ {
c->loc.addr.ip4 = ifp->ip; if (c->loc.addr.ip4 == 0) c->loc.addr.ip4 = ifp->ip;
} }
MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port, MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
&c->rem)); &c->rem));
@@ -2391,7 +2406,7 @@ void mg_connect_resolved(struct mg_connection *c) {
uint32_t rem_ip = c->rem.addr.ip4; uint32_t rem_ip = c->rem.addr.ip4;
if (ifp->ip && MG_IPISLOCAL(ifp, rem_ip) && if (ifp->ip && MG_IPISLOCAL(ifp, rem_ip) &&
rem_ip != ifp->gw) { // skip if gw (onstatechange -> ARP) rem_ip != ifp->gw) { // skip if gw (onstatechange -> ARP)
// If we're in the same LAN, fire an ARP lookup. // We're in the same LAN, fire an ARP lookup.
MG_DEBUG(("%lu ARP lookup...", c->id)); MG_DEBUG(("%lu ARP lookup...", c->id));
mg_tcpip_arp_request(ifp, rem_ip, NULL); mg_tcpip_arp_request(ifp, rem_ip, NULL);
settmout(c, MIP_TTYPE_ARP); settmout(c, MIP_TTYPE_ARP);
+27 -23
View File
@@ -133,32 +133,32 @@ void mg_tcpip_qwrite(void *buf, size_t len, struct mg_tcpip_if *ifp);
void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac); void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac);
// Built-in hardware drivers. Assign one to mg_tcpip_if.driver before calling // Built-in hardware drivers. Assign one to mg_tcpip_if.driver before calling
// mg_tcpip_init(). Each driver also requires a corresponding driver_data // mg_tcpip_init(). See the matching driver header for configuration and
// struct; see the matching driver header for details. // initialisation helpers.
extern struct mg_tcpip_driver mg_tcpip_driver_stm32f; #include "drivers/at_cmd.h"
extern struct mg_tcpip_driver mg_tcpip_driver_w5500; #include "drivers/cmsis.h"
extern struct mg_tcpip_driver mg_tcpip_driver_w5100; #include "drivers/cyw.h"
extern struct mg_tcpip_driver mg_tcpip_driver_tm4c; #include "drivers/imxrt.h"
extern struct mg_tcpip_driver mg_tcpip_driver_tms570;
extern struct mg_tcpip_driver mg_tcpip_driver_stm32h;
extern struct mg_tcpip_driver mg_tcpip_driver_imxrt;
extern struct mg_tcpip_driver mg_tcpip_driver_same54;
extern struct mg_tcpip_driver mg_tcpip_driver_cmsis;
extern struct mg_tcpip_driver mg_tcpip_driver_ra;
extern struct mg_tcpip_driver mg_tcpip_driver_xmc;
extern struct mg_tcpip_driver mg_tcpip_driver_xmc7;
extern struct mg_tcpip_driver mg_tcpip_driver_pico_w;
extern struct mg_tcpip_driver mg_tcpip_driver_rw612;
extern struct mg_tcpip_driver mg_tcpip_driver_cyw;
extern struct mg_tcpip_driver mg_tcpip_driver_nxp_wifi;
extern struct mg_tcpip_driver mg_tcpip_driver_st67w6;
extern struct mg_tcpip_driver mg_tcpip_driver_atcmd;
extern struct mg_tcpip_driver mg_tcpip_driver_netc;
#include "drivers/mg24.h"
#include "drivers/mcxw71.h" #include "drivers/mcxw71.h"
#include "drivers/mg24.h"
#include "drivers/netc.h"
#include "drivers/nrf52.h" #include "drivers/nrf52.h"
#include "drivers/nxp_wifi.h"
#include "drivers/pico-w.h"
#include "drivers/ra.h"
#include "drivers/rw612.h"
#include "drivers/rw612w.h" #include "drivers/rw612w.h"
#include "drivers/same54.h"
#include "drivers/st67w6.h"
#include "drivers/stm32f.h"
#include "drivers/stm32h.h"
#include "drivers/tm4c.h"
#include "drivers/tms570.h"
#include "drivers/w5100.h"
#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). // SPI bus abstraction for SPI-attached network chips (e.g. W5500).
// Populate and assign to the driver's driver_data field. // Populate and assign to the driver's driver_data field.
@@ -169,6 +169,10 @@ struct mg_tcpip_spi {
void (*txn)(void *, uint8_t *write, uint8_t *read, size_t); // Full-duplex transfer: write and read len bytes simultaneously void (*txn)(void *, uint8_t *write, uint8_t *read, size_t); // Full-duplex transfer: write and read len bytes simultaneously
}; };
// SPI bus for SPI-attached network chips, defined by the application.
// Used by the drivers' INIT macros, e.g. MG_TCPIP_DRIVER_W5500_INIT
extern struct mg_tcpip_spi mg_spi;
// Alignment attributes for DMA-capable Ethernet descriptor buffers. // Alignment attributes for DMA-capable Ethernet descriptor buffers.
// Use these on driver RX/TX descriptor arrays where the hardware requires // Use these on driver RX/TX descriptor arrays where the hardware requires
// specific alignment. // specific alignment.
+7 -5
View File
@@ -4,11 +4,13 @@
#include "net.h" #include "net.h"
// Return milliseconds since boot (uptime). Never goes backwards. // Return microseconds since boot. Never goes backwards.
// On RTOS targets (FreeRTOS, ThreadX, Zephyr, etc.) uses the RTOS tick count. // To define your own implementation, set MG_ENABLE_CUSTOM_MICROS=1
// On STM32/Cube uses HAL_GetTick(). On Arduino uses millis(). uint64_t mg_micros(void);
// On Linux/macOS uses CLOCK_MONOTONIC_RAW or CLOCK_MONOTONIC; falls back to
// CLOCK_REALTIME if neither is available. // Return milliseconds since boot. Never goes backwards. Calls mg_micros().
// To define your own implementation, set MG_ENABLE_CUSTOM_MILLIS=1
// Deprecated: use mg_micros() instead.
uint64_t mg_millis(void); uint64_t mg_millis(void);
// Boot timestamp in ms since Epoch. 0 until the first successful SNTP sync; // Boot timestamp in ms since Epoch. 0 until the first successful SNTP sync;
+2 -2
View File
@@ -297,9 +297,9 @@ static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
long n = 0; long n = 0;
if (c->is_udp) { if (c->is_udp) {
union usa usa; union usa usa;
socklen_t slen = tousa(&c->rem, &usa); socklen_t slen = sizeof(usa);
n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen); n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin)); if (n > 0) tomgaddr(&usa, &c->rem, usa.sa.sa_family == AF_INET6);
} else { } else {
n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING); n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
} }
+1 -1
View File
@@ -66,7 +66,7 @@ struct mg_tls_opts {
// ``` // ```
// Full examples: // Full examples:
// tutorials/http/http-server, tutorials/http/http-client, // tutorials/http/http-server, tutorials/http/http-client,
// tutorials/mqtt/mqtt-client-aws-iot, tutorials/websocket/websocket-client // tutorials/mqtt/mqtt-client, tutorials/websocket/websocket-client
// Related APIs: // Related APIs:
// mg_http_listen(), mg_http_connect(), mg_ws_connect(), mg_mqtt_connect() // mg_http_listen(), mg_http_connect(), mg_ws_connect(), mg_mqtt_connect()
// Notes: // Notes:
+26 -26
View File
@@ -29,14 +29,14 @@ static const uint8_t mg_secp256r1_oid[] = {
0x3d, 0x03, 0x01, 0x07 // 1.2.840.10045.3.1.7 secp256r1 0x3d, 0x03, 0x01, 0x07 // 1.2.840.10045.3.1.7 secp256r1
}; };
/* TLS 1.3 Record Content Type (RFC8446 B.1) */ /* TLS 1.3 Record Content Type (RFC-8446 B.1) */
#define MG_TLS_CHANGE_CIPHER 20 #define MG_TLS_CHANGE_CIPHER 20
#define MG_TLS_ALERT 21 #define MG_TLS_ALERT 21
#define MG_TLS_HANDSHAKE 22 #define MG_TLS_HANDSHAKE 22
#define MG_TLS_APP_DATA 23 #define MG_TLS_APP_DATA 23
#define MG_TLS_HEARTBEAT 24 #define MG_TLS_HEARTBEAT 24
/* TLS 1.3 Handshake Message Type (RFC8446 B.3) */ /* TLS 1.3 Handshake Message Type (RFC-8446 B.3) */
#define MG_TLS_CLIENT_HELLO 1 #define MG_TLS_CLIENT_HELLO 1
#define MG_TLS_SERVER_HELLO 2 #define MG_TLS_SERVER_HELLO 2
#define MG_TLS_ENCRYPTED_EXTENSIONS 8 #define MG_TLS_ENCRYPTED_EXTENSIONS 8
@@ -48,7 +48,7 @@ static const uint8_t mg_secp256r1_oid[] = {
#define MG_TLS_RSA_USE_CRT 1 // CRT instead of naive RSA #define MG_TLS_RSA_USE_CRT 1 // CRT instead of naive RSA
// handshake is re-entrant, so we need to keep track of its state state names // handshake is re-entrant, so we need to keep track of its state state names
// refer to RFC8446#A.1 // refer to RFC-8446 A.1
enum mg_tls_hs_state { enum mg_tls_hs_state {
// Client state machine: // Client state machine:
MG_TLS_STATE_CLIENT_START, // Send ClientHello MG_TLS_STATE_CLIENT_START, // Send ClientHello
@@ -761,8 +761,8 @@ static bool mg_tls_server_send_hello(struct mg_connection *c) {
// calculate P-256 keyshare and the shared secret // calculate P-256 keyshare and the shared secret
pub[0] = 0x04; // uncompressed point 0x04 || X || Y pub[0] = 0x04; // uncompressed point 0x04 || X || Y
if (!mg_p256_make_key(pub + 1, prv) || if (mg_p256_make_key(pub + 1, prv) == 0 ||
!mg_p256_shared_secret(tls->p256_peer, prv, tls->ecdhe_sec)) { mg_p256_shared_secret(tls->p256_peer, prv, tls->ecdhe_sec) == 0) {
mg_bzero(prv, sizeof(prv)); mg_bzero(prv, sizeof(prv));
mg_error(c, "bad key"); mg_error(c, "bad key");
return false; return false;
@@ -773,7 +773,7 @@ static bool mg_tls_server_send_hello(struct mg_connection *c) {
hello[0] = 0x02; // server hello, tls 1.2 hello[0] = 0x02; // server hello, tls 1.2
MG_STORE_BE24(hello + 1, n - 4); MG_STORE_BE24(hello + 1, n - 4);
hello[4] = 0x03, hello[5] = 0x03; hello[4] = 0x03, hello[5] = 0x03;
if (!mg_random(hello + 6, 32)) { // server random, RFC 8446 4.1.3 if (!mg_random(hello + 6, 32)) { // server random, RFC-8446 4.1.3
mg_error(c, "RNG"); mg_error(c, "RNG");
return false; return false;
} }
@@ -807,14 +807,14 @@ static bool mg_tls_server_send_hello(struct mg_connection *c) {
return true; return true;
} }
// HelloRetryRequest random, SHA-256 of "HelloRetryRequest", RFC 8446 4.1.3 // HelloRetryRequest random, SHA-256 of "HelloRetryRequest", RFC-8446 4.1.3
static const uint8_t hrr_random[32] = { static const uint8_t hrr_random[32] = {
0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c,
0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb,
0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c}; 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c};
// put HelloRetryRequest record into wio buffer, asking for a P-256 key share. // put HelloRetryRequest record into wio buffer, asking for a P-256 key share.
// Replace ClientHello in the transcript with message_hash, RFC 8446 4.4.1 // Replace ClientHello in the transcript with message_hash, RFC-8446 4.4.1
static bool mg_tls_server_send_hrr(struct mg_connection *c) { static bool mg_tls_server_send_hrr(struct mg_connection *c) {
struct tls_data *tls = (struct tls_data *) c->tls; struct tls_data *tls = (struct tls_data *) c->tls;
struct mg_iobuf *wio = &tls->send; struct mg_iobuf *wio = &tls->send;
@@ -1177,7 +1177,7 @@ static bool mg_tls_send_cert_verify(struct mg_connection *c, bool is_client) {
size_t sigsz, verifysz = 0; size_t sigsz, verifysz = 0;
int adj1, adj2; int adj1, adj2;
uint8_t sig[64] = {0}; uint8_t sig[64] = {0};
if (!mg_p256_sign(tls->ec_key, hash, sizeof(hash), sig)) { if (mg_p256_sign(tls->ec_key, hash, sizeof(hash), sig) != 1) {
mg_error(c, "P-256 sign"); mg_error(c, "P-256 sign");
return false; return false;
} }
@@ -1309,7 +1309,7 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
} }
// calc+fill keyshare; X || Y, sent as an uncompressed point 0x04 || X || Y // calc+fill keyshare; X || Y, sent as an uncompressed point 0x04 || X || Y
if (!mg_p256_make_key(msg_client_hello + 95, tls->p256_cli)) { if (mg_p256_make_key(msg_client_hello + 95, tls->p256_cli) == 0) {
mg_error(c, "P-256 key"); mg_error(c, "P-256 key");
return false; return false;
} }
@@ -1399,8 +1399,8 @@ static int mg_tls_client_recv_hello(struct mg_connection *c) {
return -1; return -1;
} }
if (key_exchange_len != 65 || key_exchange[0] != 0x04 || if (key_exchange_len != 65 || key_exchange[0] != 0x04 ||
!mg_p256_shared_secret(key_exchange + 1, tls->p256_cli, mg_p256_shared_secret(key_exchange + 1, tls->p256_cli,
tls->ecdhe_sec)) { // Validates the point tls->ecdhe_sec) == 0) { // Validates the point
mg_error(c, "bad key"); mg_error(c, "bad key");
return -1; return -1;
} }
@@ -1690,7 +1690,7 @@ static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,
return 0; // No SAN return 0; // No SAN
} }
if (mg_der_parse(field.value, field.len, &field) < 0 || field.type != 0x30) { if (mg_der_parse(field.value, field.len, &field) < 0 || field.type != 0x30) {
MG_ERROR(("SAN is not a constructed object")); // RFC 5280 4.2.1.6 MG_ERROR(("SAN is not a constructed object")); // RFC-5280 4.2.1.6
return -1; return -1;
} }
while (mg_der_next(&field, &name) > 0) { while (mg_der_next(&field, &name) > 0) {
@@ -1781,14 +1781,14 @@ static bool mg_tls_verify_cert_signature(const struct mg_tls_cert *cert,
} }
} }
static int mg_tls_verify_cert_cn(struct mg_der_tlv *subj, const char *host) { static bool mg_tls_verify_cert_cn(struct mg_der_tlv *subj, const char *host) {
struct mg_der_tlv v; struct mg_der_tlv v;
int matched = 0; bool matched = false;
if (mg_der_find_oid(subj, (uint8_t *) "\x55\x04\x03", 3, &v) > 0) { if (mg_der_find_oid(subj, (uint8_t *) "\x55\x04\x03", 3, &v) > 0) {
struct mg_str hn, cn; struct mg_str hn, cn;
MG_VERBOSE(("using CN: %.*s <-> %s", v.len, v.value, host)); MG_VERBOSE(("using CN: %.*s <-> %s", v.len, v.value, host));
hn = mg_str(host), cn = mg_str_n((char *) v.value, v.len); hn = mg_str(host), cn = mg_str_n((char *) v.value, v.len);
matched = (int) (countdots(hn) == countdots(cn) && mg_match(hn, cn, NULL)); matched = (countdots(hn) == countdots(cn) && mg_match(hn, cn, NULL));
} }
return matched; return matched;
} }
@@ -1910,9 +1910,9 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
is_addr = mg_aton_(mg_str_s(tls->hostname), &addr); is_addr = mg_aton_(mg_str_s(tls->hostname), &addr);
san = mg_tls_verify_cert_san(cert, certsz, tls->hostname, san = mg_tls_verify_cert_san(cert, certsz, tls->hostname,
is_addr ? &addr : NULL); is_addr ? &addr : NULL);
if (san < 0 || // RFC 6125 6.4.4 allow legacy fallback to CN if (san < 0 || // RFC-6125 6.4.4 allow legacy fallback to CN
(san == 0 && (is_addr || mg_tls_verify_cert_cn( (san == 0 &&
&ci->subj, tls->hostname) <= 0))) { (is_addr || !mg_tls_verify_cert_cn(&ci->subj, tls->hostname)))) {
mg_error(c, "failed to verify host"); mg_error(c, "failed to verify host");
return -1; return -1;
} }
@@ -2345,7 +2345,7 @@ static int mg_rsa_parse_der_int(const uint8_t **p, const uint8_t *end,
return 0; return 0;
} }
// RFC 5915 ECPrivateKey ::= SEQUENCE { // RFC-5915 ECPrivateKey ::= SEQUENCE {
// version INTEGER { ecPrivkeyVer1(1) }, // version INTEGER { ecPrivkeyVer1(1) },
// privateKey OCTET STRING, // privateKey OCTET STRING,
// parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, // parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
@@ -2748,8 +2748,8 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
mg_error(c, "hostname too long"); mg_error(c, "hostname too long");
return; return;
} }
strncpy((char *) tls->hostname, opts->name.buf, sizeof(tls->hostname) - 1); memcpy(tls->hostname, opts->name.buf, opts->name.len);
tls->hostname[opts->name.len] = 0; tls->hostname[opts->name.len] = '\0';
} }
// server CA certificate; parse PEM [bundle] or DER // server CA certificate; parse PEM [bundle] or DER
@@ -2762,8 +2762,9 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
tls->ca_bundle_der = all_certs; tls->ca_bundle_der = all_certs;
MG_VERBOSE(("%d-cert bundle", cert_count)); MG_VERBOSE(("%d-cert bundle", cert_count));
} else if (cert_count > 0) { } else if (cert_count > 0) {
tls->ca_der.buf = all_certs[0].buf; int i;
tls->ca_der.len = all_certs[0].len; tls->ca_der = all_certs[0];
for (i = 1; i < cert_count; i++) mg_free((void *) all_certs[i].buf);
mg_free(all_certs); mg_free(all_certs);
} else { // parse again for a possible DER (or a truncated begin string) } else { // parse again for a possible DER (or a truncated begin string)
if (mg_parse_pem(opts->ca, mg_str_s("CERTIFICATE"), &tls->ca_der) < 0) { if (mg_parse_pem(opts->ca, mg_str_s("CERTIFICATE"), &tls->ca_der) < 0) {
@@ -2789,8 +2790,7 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
int cert_count = mg_parse_pem_certs(opts->cert, &all_certs); int cert_count = mg_parse_pem_certs(opts->cert, &all_certs);
if (cert_count > 0) { if (cert_count > 0) {
tls->cert_der.buf = all_certs[0].buf; tls->cert_der = all_certs[0];
tls->cert_der.len = all_certs[0].len;
if (cert_count > 1) { if (cert_count > 1) {
tls->chain_len = (size_t) cert_count; tls->chain_len = (size_t) cert_count;
tls->chain_der = all_certs; tls->chain_der = all_certs;
+29 -18
View File
@@ -197,33 +197,38 @@ bool mg_path_is_sane(const struct mg_str path) {
return true; return true;
} }
#if MG_ENABLE_CUSTOM_MILLIS // The clock lives in mg_micros(), mg_millis() is derived from it. Either one
#else // can be replaced, see MG_ENABLE_CUSTOM_MICROS and MG_ENABLE_CUSTOM_MILLIS
uint64_t mg_millis(void) { #if MG_ENABLE_CUSTOM_MICROS == 0
#if MG_ARCH == MG_ARCH_ESP32 || MG_ENABLE_FREERTOS uint64_t mg_micros(void) {
return xTaskGetTickCount() * portTICK_PERIOD_MS; #if MG_ARCH == MG_ARCH_ESP32
return (uint64_t) esp_timer_get_time();
#elif MG_ENABLE_FREERTOS
return (uint64_t) xTaskGetTickCount() * portTICK_PERIOD_MS * 1000;
#elif MG_ARCH == MG_ARCH_THREADX #elif MG_ARCH == MG_ARCH_THREADX
return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND); return (uint64_t) tx_time_get() *
(1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND) * 1000;
#elif MG_ARCH == MG_ARCH_TIRTOS #elif MG_ARCH == MG_ARCH_TIRTOS
return (uint64_t) Clock_getTicks(); return (uint64_t) Clock_getTicks() * 1000;
#elif MG_ARCH == MG_ARCH_ZEPHYR #elif MG_ARCH == MG_ARCH_ZEPHYR
return (uint64_t) k_uptime_get(); return k_ticks_to_us_floor64((uint64_t) k_uptime_ticks());
#elif MG_ARCH == MG_ARCH_CMSIS_RTOS1 #elif MG_ARCH == MG_ARCH_CMSIS_RTOS1
return (uint64_t) rt_time_get(); return (uint64_t) rt_time_get() * 1000;
#elif MG_ARCH == MG_ARCH_CMSIS_RTOS2 #elif MG_ARCH == MG_ARCH_CMSIS_RTOS2
return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq()); return (uint64_t) ((osKernelGetTickCount() * 1000) / osKernelGetTickFreq()) *
1000;
#elif MG_ARCH == MG_ARCH_RTTHREAD #elif MG_ARCH == MG_ARCH_RTTHREAD
return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND); return (uint64_t) ((rt_tick_get() * 1000) / RT_TICK_PER_SECOND) * 1000;
#elif MG_ARCH == MG_ARCH_WIN32 #elif MG_ARCH == MG_ARCH_WIN32
return GetTickCount(); return (uint64_t) GetTickCount() * 1000;
#elif MG_ARCH == MG_ARCH_PICOSDK #elif MG_ARCH == MG_ARCH_PICOSDK
return time_us_64() / 1000; return time_us_64();
#elif MG_ARCH == MG_ARCH_CUBE #elif MG_ARCH == MG_ARCH_CUBE
return (uint64_t) HAL_GetTick(); return (uint64_t) HAL_GetTick() * 1000;
#elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__) #elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
// Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux // Apple CLOCK_MONOTONIC_RAW is equivalent to CLOCK_BOOTTIME on linux
// Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux // Apple CLOCK_UPTIME_RAW is equivalent to CLOCK_MONOTONIC_RAW on linux
return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000000; return clock_gettime_nsec_np(CLOCK_UPTIME_RAW) / 1000;
#elif MG_ARCH == MG_ARCH_UNIX #elif MG_ARCH == MG_ARCH_UNIX
struct timespec ts = {0, 0}; struct timespec ts = {0, 0};
// See #1615 - prefer monotonic clock // See #1615 - prefer monotonic clock
@@ -238,15 +243,21 @@ uint64_t mg_millis(void) {
// adjustments performed by adjtime and NTP // adjustments performed by adjtime and NTP
clock_gettime(CLOCK_REALTIME, &ts); clock_gettime(CLOCK_REALTIME, &ts);
#endif #endif
return ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000); return ((uint64_t) ts.tv_sec * 1000000 + (uint64_t) ts.tv_nsec / 1000);
#elif defined(ARDUINO) #elif defined(ARDUINO)
return (uint64_t) millis(); return (uint64_t) micros();
#else #else
return (uint64_t) (time(NULL) * 1000); return (uint64_t) time(NULL) * 1000000;
#endif #endif
} }
#endif #endif
#if MG_ENABLE_CUSTOM_MILLIS == 0
uint64_t mg_millis(void) {
return mg_micros() / 1000;
}
#endif
// network format equates big endian order // network format equates big endian order
uint16_t mg_ntohs(uint16_t net) { uint16_t mg_ntohs(uint16_t net) {
return MG_LOAD_BE16(&net); return MG_LOAD_BE16(&net);
+5 -1
View File
@@ -192,6 +192,10 @@ static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
op = msg.flags & 15; op = msg.flags & 15;
// MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op, // MG_VERBOSE ("fin %d op %d len %d [%.*s]", final, op,
// (int) m.data.len, (int) m.data.len, m.data.buf)); // (int) m.data.len, (int) m.data.len, m.data.buf));
if (op >= WEBSOCKET_OP_CLOSE && (!final || msg.data_len > 125)) {
mg_error(c, "invalid WS control frame");
return;
} // RFC-6455 5.5: control frames must be final and at most 125 bytes
if ((op == WEBSOCKET_OP_CONTINUE && ofs == 0) || if ((op == WEBSOCKET_OP_CONTINUE && ofs == 0) ||
((op == WEBSOCKET_OP_TEXT || op == WEBSOCKET_OP_BINARY) && ((op == WEBSOCKET_OP_TEXT || op == WEBSOCKET_OP_BINARY) &&
ofs != 0)) { ofs != 0)) {
@@ -222,7 +226,7 @@ static void mg_ws_cb(struct mg_connection *c, int ev, void *ev_data) {
c->is_draining = 1; c->is_draining = 1;
break; break;
default: default:
// Per RFC6455, close conn when an unknown op is recvd // Per RFC-6455, close conn when an unknown op is recvd
mg_error(c, "unknown WS op %d", op); mg_error(c, "unknown WS op %d", op);
break; break;
} }
+1 -1
View File
@@ -72,7 +72,7 @@ void mg_ws_upgrade(struct mg_connection *, struct mg_http_message *,
// mg_ws_connect(), mg_ws_upgrade(), mg_ws_printf(), mg_ws_wrap() // mg_ws_connect(), mg_ws_upgrade(), mg_ws_printf(), mg_ws_wrap()
// Notes: // Notes:
// op is one of WEBSOCKET_OP_*. Client connections are automatically masked // op is one of WEBSOCKET_OP_*. Client connections are automatically masked
// per RFC 6455. On OOM, the return value can be smaller than header + len. // per RFC-6455. On OOM, the return value can be smaller than header + len.
// Data is appended to c->send and sent by a later mg_mgr_poll() call. // Data is appended to c->send and sent by a later mg_mgr_poll() call.
size_t mg_ws_send(struct mg_connection *, const void *buf, size_t len, int op); size_t mg_ws_send(struct mg_connection *, const void *buf, size_t len, int op);
+9 -6
View File
@@ -13,7 +13,7 @@ else
C_WARN ?= -Wno-deprecated C_WARN ?= -Wno-deprecated
endif endif
.PHONY: all bsd bsd_test bsd_client bsd_nortos bsd_nortos_test shm_tap_bridge \ .PHONY: all bsd bsd_test bsd_client bsd_udp bsd_nortos bsd_nortos_test shm_tap_bridge \
shm_port_bridge bsd_s390 bsd_nortos_s390 clean shm_port_bridge bsd_s390 bsd_nortos_s390 clean
TEST_SOURCES = bsd_shm_test.c TEST_SOURCES = bsd_shm_test.c
@@ -47,11 +47,11 @@ DOCKER ?= $(DOCKER_BIN) run --platform linux/amd64 --net=host --rm $(ENV) -v $(R
CFLAGS_MONGOOSE += -DMG_ARCH=MG_ARCH_CUSTOM CFLAGS_MONGOOSE += -DMG_ARCH=MG_ARCH_CUSTOM
all bsd: shm_tap_bridge bsd_client FreeRTOS-Kernel bsd_test all bsd: shm_tap_bridge bsd_client bsd_udp FreeRTOS-Kernel bsd_test
ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./bsd_test $(ARGS) ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./bsd_test $(ARGS)
# also # also
bsd_nortos: shm_tap_bridge bsd_client bsd_nortos_test bsd_nortos: shm_tap_bridge bsd_client bsd_udp bsd_nortos_test
ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./bsd_nortos_test $(ARGS) ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./bsd_nortos_test $(ARGS)
# requires shm_tap_bridge to be running # requires shm_tap_bridge to be running
@@ -70,6 +70,9 @@ bsd_nortos_test:
bsd_client: bsd_client.c bsd_client: bsd_client.c
$(CC) bsd_client.c -pthread -o $@ $(CC) bsd_client.c -pthread -o $@
bsd_udp: bsd_udp.c
$(CC) bsd_udp.c -o $@
# bridge shm queue <--> TAP interface # bridge shm queue <--> TAP interface
shm_tap_bridge: shm_tap_bridge.c shm_queue.h shm_tap_bridge: shm_tap_bridge.c shm_queue.h
$(CC) shm_tap_bridge.c -pthread -o $@ $(CC) shm_tap_bridge.c -pthread -o $@
@@ -79,7 +82,7 @@ bsd_s390: CFLAGS_MONGOOSE += -DMG_ENABLE_BSD_PROTOTYPES=0
bsd_s390: ASAN= bsd_s390: ASAN=
bsd_s390: CC = $(DOCKER) mdashnet/s390 cc bsd_s390: CC = $(DOCKER) mdashnet/s390 cc
bsd_s390: RUN = $(DOCKER) --init mdashnet/s390 bsd_s390: RUN = $(DOCKER) --init mdashnet/s390
bsd_s390: shm_port_bridge bsd_client FreeRTOS-Kernel bsd_test bsd_s390: shm_port_bridge bsd_client bsd_udp FreeRTOS-Kernel bsd_test
$(RUN) sh -c './shm_port_bridge & pid=$$!; sleep 1; ./bsd_test; rc=$$?; kill $$pid >/dev/null 2>&1; wait $$pid >/dev/null 2>&1; exit $$rc' $(RUN) sh -c './shm_port_bridge & pid=$$!; sleep 1; ./bsd_test; rc=$$?; kill $$pid >/dev/null 2>&1; wait $$pid >/dev/null 2>&1; exit $$rc'
#also #also
@@ -87,14 +90,14 @@ bsd_nortos_s390: CFLAGS_MONGOOSE += -DMG_ENABLE_BSD_PROTOTYPES=0
bsd_nortos_s390: ASAN= bsd_nortos_s390: ASAN=
bsd_nortos_s390: CC = $(DOCKER) mdashnet/s390 cc bsd_nortos_s390: CC = $(DOCKER) mdashnet/s390 cc
bsd_nortos_s390: RUN = $(DOCKER) --init mdashnet/s390 bsd_nortos_s390: RUN = $(DOCKER) --init mdashnet/s390
bsd_nortos_s390: shm_port_bridge bsd_client bsd_nortos_test bsd_nortos_s390: shm_port_bridge bsd_client bsd_udp bsd_nortos_test
$(RUN) sh -c './shm_port_bridge & pid=$$!; sleep 1; ./bsd_nortos_test; rc=$$?; kill $$pid >/dev/null 2>&1; wait $$pid >/dev/null 2>&1; exit $$rc' $(RUN) sh -c './shm_port_bridge & pid=$$!; sleep 1; ./bsd_nortos_test; rc=$$?; kill $$pid >/dev/null 2>&1; wait $$pid >/dev/null 2>&1; exit $$rc'
shm_port_bridge: shm_port_bridge.c shm_queue.h shm_port_bridge: shm_port_bridge.c shm_queue.h
$(CC) shm_port_bridge.c $(CFLAGS) -pthread -o $@ $(CC) shm_port_bridge.c $(CFLAGS) -pthread -o $@
clean: # Cleanup. Delete built program and all build artifacts clean: # Cleanup. Delete built program and all build artifacts
rm -rf bsd_test bsd_client shm_port_bridge *.o *.obj FreeRTOS-Kernel rm -rf bsd_test bsd_client bsd_udp shm_port_bridge *.o *.obj FreeRTOS-Kernel
FreeRTOS-Kernel: # FreeRTOS sources FreeRTOS-Kernel: # FreeRTOS sources
git clone -q -c advice.detachedHead=false --depth 1 -b V11.2.0 https://github.com/FreeRTOS/FreeRTOS-Kernel $@ git clone -q -c advice.detachedHead=false --depth 1 -b V11.2.0 https://github.com/FreeRTOS/FreeRTOS-Kernel $@
-120
View File
@@ -1,120 +0,0 @@
#include <errno.h>
#include <spawn.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include "FreeRTOS.h"
#include "task.h"
volatile bool s_cpq_done;
volatile bool s_cpq_ready;
bool s_cpq_remote;
static bool s_cpq_ok;
#include "bsd_udp_cpq_fail.c"
static void cpq_log(char ch, void *param) {
(void) param;
putchar(ch);
}
static void cpq_task1(void *args) {
struct mg_mgr *mgr = (struct mg_mgr *) args;
const char *remote_peer = getenv("CPQ_REMOTE_PEER");
char *ip = NULL;
char *argv[5];
pid_t pid;
pid_t r;
int status;
extern char **environ;
while (mgr->ifp->ip == 0 && mg_millis() < 5000) {
mg_mgr_poll(mgr, 0);
vTaskDelay(1);
}
if (mgr->ifp->ip == 0) {
printf("FAIL setup: DHCP lease timed out\n");
s_cpq_ok = false;
goto done;
}
while (mgr->ifp->state != MG_TCPIP_STATE_READY) {
mg_mgr_poll(mgr, 0);
vTaskDelay(1);
}
s_cpq_remote = remote_peer != NULL && remote_peer[0] != '\0';
s_cpq_done = false;
s_cpq_ready = false;
if (xTaskCreate(bsd_udp_cpq_fail_task, "cpq", 1024, NULL,
configMAX_PRIORITIES - 1, NULL) != pdPASS) {
printf("FAIL setup: cannot create CPQ task\n");
s_cpq_ok = false;
goto done;
}
while (!s_cpq_ready && !s_cpq_done) {
mg_mgr_poll(mgr, 0);
vTaskDelay(1);
}
if (!s_cpq_ready) {
printf("FAIL setup: CPQ task did not bind sockets\n");
s_cpq_ok = false;
goto done;
}
printf("CPQ: sockets ready\n");
ip = mg_mprintf("%M", mg_print_ip4, &mgr->ifp->ip);
printf("CPQ: Mongoose IP %s\n", ip);
argv[0] = (char *) "./bsd_udp_cpq_peer";
argv[1] = s_cpq_remote ? (char *) "--helper" : ip;
argv[2] = s_cpq_remote ? (char *) remote_peer : NULL;
argv[3] = s_cpq_remote ? ip : NULL;
argv[4] = NULL;
if (posix_spawn(&pid, argv[0], NULL, NULL, argv, environ) != 0) {
printf("FAIL setup: cannot start CPQ helper\n");
s_cpq_ok = false;
goto done;
}
printf("CPQ: %s started\n", s_cpq_remote ? "helper" : "peer");
while (!s_cpq_done) {
mg_mgr_poll(mgr, 0);
vTaskDelay(1);
}
while ((r = waitpid(pid, &status, WNOHANG)) == 0) {
mg_mgr_poll(mgr, 0);
vTaskDelay(1);
}
if (r != pid || !WIFEXITED(status) || WEXITSTATUS(status) != 0) {
printf("FAIL setup: CPQ peer failed\n");
s_cpq_ok = false;
}
done:
mg_free(ip);
mg_mgr_free(mgr);
vTaskEndScheduler();
}
static bool bsd_cpq_test(struct mg_tcpip_driver *driver, void *driver_data,
const char *mac, const char *debug_level) {
struct mg_mgr mgr;
struct mg_tcpip_if mif;
mg_log_set(atoi(debug_level == NULL ? "3" : debug_level));
mg_log_set_fn(cpq_log, NULL);
mg_mgr_init(&mgr);
memset(&mif, 0, sizeof(mif));
mif.driver = driver;
mif.driver_data = driver_data;
sscanf(mac, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx", &mif.mac[0], &mif.mac[1],
&mif.mac[2], &mif.mac[3], &mif.mac[4], &mif.mac[5]);
mg_tcpip_init(&mgr, &mif);
if (mgr.ifp == NULL ||
xTaskCreate(cpq_task1, "cpqnet", 2048, &mgr,
configMAX_PRIORITIES - 2, NULL) != pdPASS)
return false;
s_cpq_ok = true;
vTaskStartScheduler();
return s_cpq_ok;
}
-8
View File
@@ -95,11 +95,7 @@ bool mg_random(void *buf, size_t len) {
} }
#ifdef CPQ_TEST
#include "bsd_cpq_test.c"
#else
#include "bsd_x_test.c" #include "bsd_x_test.c"
#endif
int main(void) { int main(void) {
@@ -111,11 +107,7 @@ int main(void) {
printf("Opening SHM interface\n"); printf("Opening SHM interface\n");
usleep(200000); // 200 ms usleep(200000); // 200 ms
#ifdef CPQ_TEST
result = bsd_cpq_test(&shm_driver, &shm_data, mac, debug_level);
#else
result = bsd_x_test(&shm_driver, &shm_data, mac, debug_level); result = bsd_x_test(&shm_driver, &shm_data, mac, debug_level);
#endif
if (shm_data.shm != NULL) munmap(shm_data.shm, sizeof(*shm_data.shm)); if (shm_data.shm != NULL) munmap(shm_data.shm, sizeof(*shm_data.shm));
if (shm_data.fp != NULL) fclose(shm_data.fp); if (shm_data.fp != NULL) fclose(shm_data.fp);
if (!result) return EXIT_FAILURE; if (!result) return EXIT_FAILURE;
+60
View File
@@ -0,0 +1,60 @@
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#define PORT 1235
int main(int argc, char *argv[]) {
struct sockaddr_in sa;
struct timeval timeout;
char buf[8];
ssize_t n;
int fd, rogue;
if (argc != 2) return 1;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(PORT);
if (inet_pton(AF_INET, argv[1], &sa.sin_addr) != 1) return 1;
timeout.tv_sec = 5, timeout.tv_usec = 0;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0 ||
connect(fd, (struct sockaddr *) &sa, sizeof(sa)) != 0 ||
send(fd, "hello", 5, 0) != 5 || recv(fd, buf, sizeof(buf), 0) != 5 ||
memcmp(buf, "ready", 5) != 0)
goto fail;
if ((rogue = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ||
setsockopt(rogue, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) !=
0 ||
sendto(rogue, "rogueid", 7, 0, (struct sockaddr *) &sa, sizeof(sa)) !=
7 ||
recv(fd, buf, sizeof(buf), 0) != 7 || memcmp(buf, "peerone", 7) != 0 ||
recv(rogue, buf, sizeof(buf), 0) != 7 || memcmp(buf, "rogueok", 7) != 0 ||
send(fd, "one", 3, 0) != 3 ||
sendto(rogue, "two2", 4, 0, (struct sockaddr *) &sa, sizeof(sa)) != 4 ||
recv(fd, buf, sizeof(buf), 0) != 4 || memcmp(buf, "drop", 4) != 0 ||
send(fd, "truncate", 8, 0) != 8 ||
recv(fd, buf, sizeof(buf), 0) != 5 || memcmp(buf, "short", 5) != 0 ||
send(fd, "peek", 4, 0) != 4 ||
recv(fd, buf, sizeof(buf), 0) != 4 || memcmp(buf, "peek", 4) != 0 ||
sendto(rogue, "rogue", 5, 0, (struct sockaddr *) &sa, sizeof(sa)) != 5 ||
send(fd, "more", 4, 0) != 4 ||
recv(fd, buf, sizeof(buf), 0) != 7 || memcmp(buf, "checked", 7) != 0 ||
recv(fd, buf, sizeof(buf), 0) != 3 || memcmp(buf, "one", 3) != 0 ||
recv(fd, buf, sizeof(buf), 0) != 4 || memcmp(buf, "two2", 4) != 0 ||
send(fd, "echo", 4, 0) != 4 || recv(fd, buf, sizeof(buf), 0) != 4 ||
memcmp(buf, "echo", 4) != 0)
goto fail_close_rogue;
close(rogue);
close(fd);
return 0;
fail_close_rogue:
close(rogue);
fail:
close(fd);
return 1;
}
-174
View File
@@ -1,174 +0,0 @@
// Demonstrates UDP behavior with the CPQ patch. Run this task with
// bsd_udp_cpq_peer against a Mongoose interface whose address it receives.
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "mongoose.h"
#include "FreeRTOS.h"
#include "task.h"
#define DATA_PORT 1234
#define CONTROL_PORT 1235
#define SEND_PORT 1236
#define PEER_A_PORT 14001
static char s_big[1600];
extern volatile bool s_cpq_done;
extern volatile bool s_cpq_ready;
extern bool s_cpq_remote;
void bsd_udp_cpq_fail_task(void *args);
static int udp_bind(unsigned port) {
struct sockaddr_in sa;
int fd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons((uint16_t) port);
if (fd < 0 || bind(fd, (struct sockaddr *) &sa, sizeof(sa)) != 0) {
printf("cannot bind UDP port %u: %d\n", port, errno);
return -1;
}
return fd;
}
static void go(int fd) {
if (send(fd, "go", 2, 0) != 2) printf("control send failed: %d\n", errno);
}
static void wait_for_packets(void) {
vTaskDelay(pdMS_TO_TICKS(100)); // Let the manager collect peer datagrams
}
void bsd_udp_cpq_fail_task(void *args) {
struct sockaddr_in control_peer, peer, local, other;
socklen_t peerlen, locallen;
char buf[16];
int data = -1, control = -1, out = -1, fd = -1, connected = -1;
ssize_t n;
(void) args;
data = udp_bind(DATA_PORT);
control = udp_bind(CONTROL_PORT);
out = udp_bind(SEND_PORT);
if (data < 0 || control < 0 || out < 0) goto done;
s_cpq_ready = true;
printf("CPQ: control socket waiting\n");
// The peer identifies itself on the control socket, which learns its MAC.
peerlen = sizeof(control_peer);
n = recvfrom(control, buf, sizeof(buf), 0,
(struct sockaddr *) &control_peer, &peerlen);
if (n != 5 || memcmp(buf, "ready", 5) != 0) goto done;
printf("CPQ: peer ready\n");
fd = udp_bind(1237);
n = fd < 0 ? -1 : send(fd, "x", 1, 0);
printf("%s send: expected EDESTADDRREQ, got %d: no peer check\n",
n < 0 && errno == EDESTADDRREQ ? "PASS" : "FAIL", (int) n);
if (fd >= 0) close(fd);
fd = udp_bind(1238);
n = fd < 0 ? -1 : connect(fd, (struct sockaddr *) &control_peer, peerlen);
locallen = sizeof(local);
if (n == 0 && getsockname(fd, (struct sockaddr *) &local, &locallen) == 0) {
printf("%s bind: expected 1238, got %u: connect replaced bind\n",
mg_ntohs(local.sin_port) == 1238 ? "PASS" : "FAIL",
(unsigned) mg_ntohs(local.sin_port));
} else {
printf("FAIL bind: connect failed errno %d\n", errno);
}
if (fd >= 0) close(fd);
fd = udp_bind(1239);
other = control_peer, other.sin_port = htons(14998);
n = fd < 0 ? -1 : sendto(fd, s_big, sizeof(s_big), 0,
(struct sockaddr *) &other, sizeof(other));
printf("%s oversize: expected EMSGSIZE, got %d: later truncated\n",
n < 0 && errno == EMSGSIZE ? "PASS" : "FAIL", (int) n);
if (fd >= 0) close(fd);
// The patch keeps the first nonempty datagram and drops the second.
go(control);
wait_for_packets();
peerlen = sizeof(peer);
n = recvfrom(data, buf, sizeof(buf), 0, (struct sockaddr *) &peer, &peerlen);
if (n == 3 && memcmp(buf, "one", 3) == 0 &&
mg_ntohs(peer.sin_port) == PEER_A_PORT &&
recvfrom(data, buf, sizeof(buf), MSG_DONTWAIT, NULL, NULL) < 0 &&
errno == EAGAIN) {
printf("PASS drop: kept one, dropped two\n");
} else {
printf("FAIL drop: expected one then EAGAIN, got %d \"%.*s\"\n", (int) n,
(int) (n > 0 ? n : 0), buf);
}
// A short UDP receive must discard the rest of that datagram.
go(control);
wait_for_packets();
n = recvfrom(data, buf, 2, 0, NULL, NULL);
n = recvfrom(data, buf, sizeof(buf), MSG_DONTWAIT, NULL, NULL);
printf("%s short: expected EAGAIN, got %d \"%.*s\": tail retained\n",
n < 0 && errno == EAGAIN ? "PASS" : "FAIL", (int) n,
(int) (n > 0 ? n : 0), buf);
// A zero-length datagram is data and recvfrom() must return zero for it.
go(control);
wait_for_packets();
n = recvfrom(data, buf, sizeof(buf), MSG_DONTWAIT, NULL, NULL);
printf("%s empty: expected 0, got %d errno %d: no marker\n",
n == 0 ? "PASS" : "FAIL", (int) n, errno);
// An unbound connected socket must reject another sender's datagram.
if (send(control, "connect", 7, 0) != 7 ||
(connected = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ||
connect(connected, (struct sockaddr *) &control_peer,
sizeof(control_peer)) != 0 ||
send(connected, "hello", 5, 0) != 5) {
goto done;
}
wait_for_packets();
n = recv(connected, buf, sizeof(buf), MSG_DONTWAIT);
printf("%s peer: expected EAGAIN, got %d \"%.*s\": no peer filter\n",
n < 0 && errno == EAGAIN ? "PASS" : "FAIL", (int) n,
(int) (n > 0 ? n : 0), buf);
n = send(connected, "reply", 5, 0);
printf("reply: sent %d bytes; peer reports its destination below\n", (int) n);
if (recv(control, buf, sizeof(buf), 0) < 0) goto done; // Peer checked reply
other = control_peer, other.sin_port = htons(14999);
n = sendto(connected, "x", 1, 0, (struct sockaddr *) &other, sizeof(other));
printf("%s sendto: expected EISCONN, got %d: connected socket accepted it\n",
n < 0 && errno == EISCONN ? "PASS" : "FAIL", (int) n);
// sendto() reports success before this socket has learned a destination MAC.
go(control);
if (recv(control, buf, sizeof(buf), 0) < 0) goto done;
n = sendto(out, "lost", 4, 0, (struct sockaddr *) &control_peer,
sizeof(control_peer));
printf("%s sendto: expected delivery, got %d: no resolution\n",
n == 4 ? "FAIL" : "PASS", (int) n);
if (recv(control, buf, sizeof(buf), 0) < 0) goto done; // Peer reports miss
// sendto() changes c->rem, so send() incorrectly succeeds on this socket.
go(control);
if (recvfrom(out, buf, sizeof(buf), 0, NULL, NULL) < 0) goto done;
n = sendto(out, s_cpq_remote ? "stale" : "sendto", s_cpq_remote ? 5 : 6,
0, (struct sockaddr *) &control_peer, sizeof(control_peer));
printf("sendto after RX: got %d\n", (int) n);
if (s_cpq_remote) go(control); // Server checks its packet used helper's MAC
n = send(out, "send", 4, 0);
printf("%s send: expected EDESTADDRREQ, got %d: sendto set peer\n",
n < 0 && errno == EDESTADDRREQ ? "PASS" : "FAIL", (int) n);
done:
if (data >= 0) close(data);
if (control >= 0) close(control);
if (out >= 0) close(out);
if (connected >= 0) close(connected);
s_cpq_done = true;
vTaskDelete(NULL);
}
-218
View File
@@ -1,218 +0,0 @@
#include <arpa/inet.h>
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#define DATA_PORT 1234
#define CONTROL_PORT 1235
#define SEND_PORT 1236
#define CONTROL_PEER_PORT 14000
#define PEER_A_PORT 14001
#define PEER_B_PORT 14002
#define HELPER_PORT 14003
static int open_peer(unsigned port) {
struct sockaddr_in sa;
struct timeval timeout = {1, 0};
int fd = socket(AF_INET, SOCK_DGRAM, 0);
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl(INADDR_ANY);
sa.sin_port = htons((uint16_t) port);
if (fd < 0 || bind(fd, (struct sockaddr *) &sa, sizeof(sa)) != 0 ||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0)
return -1;
return fd;
}
static int make_peer(struct sockaddr_in *sa, const char *ip, unsigned port) {
memset(sa, 0, sizeof(*sa));
sa->sin_family = AF_INET;
sa->sin_port = htons((uint16_t) port);
return inet_pton(AF_INET, ip, &sa->sin_addr) == 1 ? 0 : -1;
}
static int send_packet(int fd, const struct sockaddr_in *sa, const char *buf,
size_t len) {
return sendto(fd, buf, len, 0, (const struct sockaddr *) sa, sizeof(*sa)) ==
(ssize_t) len
? 0
: -1;
}
static int wait_go(int fd, const char *step) {
char buf[8];
int n = recv(fd, buf, sizeof(buf), 0);
if (n == 2 && memcmp(buf, "go", 2) == 0) return 0;
printf("peer: %s failed: %d\n", step, n);
return -1;
}
static void stale_packet(void) {
printf("TRACE stale MAC: Server received packet despite wrong L2 address\n");
}
static int wait_stale_go(int fd) {
char buf[8];
int n, stale = 0;
for (;;) {
n = recv(fd, buf, sizeof(buf), 0);
if (n == 5 && memcmp(buf, "stale", 5) == 0) {
stale = 1;
stale_packet();
} else if (n == 2 && memcmp(buf, "go", 2) == 0) {
if (stale) return 0;
n = recv(fd, buf, sizeof(buf), 0);
if (n == 5 && memcmp(buf, "stale", 5) == 0)
stale_packet();
else
printf("FAIL stale MAC: expected packet, got none\n");
return 0;
} else {
printf("peer: stale MAC handoff failed: %d\n", n);
return -1;
}
}
}
static int wait_connect(int fd, struct sockaddr_in *peer) {
char buf[8];
socklen_t len = sizeof(*peer);
return recv(fd, buf, sizeof(buf), 0) == 7 && memcmp(buf, "connect", 7) == 0 &&
recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) peer, &len) == 5 &&
memcmp(buf, "hello", 5) == 0
? 0
: -1;
}
static int wait_helper(int fd, struct sockaddr_in *peer) {
char buf[8];
socklen_t len = sizeof(*peer);
ssize_t n;
while ((n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) peer,
&len)) < 0)
len = sizeof(*peer);
return n == 5 && memcmp(buf, "ready", 5) == 0 ? 0 : -1;
}
static int run_helper(const char *server_ip, const char *target_ip) {
struct sockaddr_in server, target;
char buf[32];
unsigned port;
int fd, n;
if (make_peer(&server, server_ip, HELPER_PORT) != 0 ||
make_peer(&target, target_ip, 0) != 0 || (fd = open_peer(0)) < 0)
return 1;
for (;;) {
if (send_packet(fd, &server, "ready", 5) != 0) break;
n = recv(fd, buf, sizeof(buf) - 1, 0);
if (n <= 0) continue; // Retry ready until the Server receives it
buf[n] = '\0';
if (sscanf(buf, "intrude %u", &port) == 1 && port < 65536) {
target.sin_port = htons((uint16_t) port);
if (send_packet(fd, &target, "intruder", 8) != 0) break;
} else if (strcmp(buf, "prime") == 0) {
target.sin_port = htons(SEND_PORT);
if (send_packet(fd, &target, "prime", 5) != 0) break;
return 0;
} else if (strcmp(buf, "reply") == 0) {
printf("FAIL connected peer: helper received reply\n");
}
}
close(fd);
return 1;
}
static int run_peer(const char *target_ip, int remote) {
struct sockaddr_in data, control, out, peer, helper_peer;
char buf[32], cmd[32];
int a, b, ctl, helper = -1;
ssize_t n;
if (make_peer(&data, target_ip, DATA_PORT) != 0) return 1;
control = data, out = data;
control.sin_port = htons(CONTROL_PORT);
out.sin_port = htons(SEND_PORT);
ctl = open_peer(CONTROL_PEER_PORT);
a = open_peer(PEER_A_PORT);
b = open_peer(PEER_B_PORT);
if (remote) helper = open_peer(HELPER_PORT);
if (ctl < 0 || a < 0 || b < 0 || (remote && helper < 0)) return 1;
if (remote && wait_helper(helper, &helper_peer) != 0) return 1;
if (remote) printf("peer: helper ready\n");
if (send_packet(ctl, &control, "ready", 5) != 0 ||
wait_go(ctl, "initial go") != 0)
return 1;
if (send_packet(a, &data, "one", 3) != 0 ||
send_packet(b, &data, "two", 3) != 0 ||
wait_go(ctl, "two datagrams") != 0)
return 1;
if (send_packet(b, &data, "ABCDE", 5) != 0 ||
wait_go(ctl, "short datagram") != 0)
return 1;
if (send_packet(b, &data, "", 0) != 0 || wait_connect(ctl, &peer) != 0) {
printf("peer: connect handshake failed\n");
return 1;
}
if (remote) {
snprintf(cmd, sizeof(cmd), "intrude %u", (unsigned) ntohs(peer.sin_port));
if (send_packet(helper, &helper_peer, cmd, strlen(cmd)) != 0) return 1;
} else if (send_packet(b, &peer, "intruder", 8) != 0) {
return 1;
}
n = recv(ctl, buf, sizeof(buf), 0);
printf("%s reply: expected control, got %s: intruder replaced peer\n",
n < 0 ? "FAIL" : "PASS", n < 0 ? "none" : "control");
if (!remote) {
n = recv(b, buf, sizeof(buf), 0);
printf("%s reply: intruder got %.*s\n", n > 0 ? "FAIL" : "PASS",
(int) (n > 0 ? n : 0), buf);
}
if (send_packet(ctl, &control, "done", 4) != 0 ||
wait_go(ctl, "first sendto") != 0 ||
send_packet(ctl, &control, "sendlost", 8) != 0)
return 1;
n = recv(ctl, buf, sizeof(buf), 0);
printf("%s sendto: expected packet, got %s\n", n < 0 ? "FAIL" : "PASS",
n < 0 ? "none" : "packet");
if (send_packet(ctl, &control, "miss", 4) != 0 ||
wait_go(ctl, "prime") != 0)
return 1;
if (remote) {
if (send_packet(helper, &helper_peer, "prime", 5) != 0 ||
wait_stale_go(ctl) != 0)
return 1;
} else {
if (send_packet(ctl, &out, "prime", 5) != 0) return 1;
n = recv(ctl, buf, sizeof(buf), 0);
printf("sendto after RX: %.*s\n", (int) (n > 0 ? n : 0), buf);
n = recv(ctl, buf, sizeof(buf), 0);
printf("%s send: expected none, got %.*s\n", n > 0 ? "FAIL" : "PASS",
(int) (n > 0 ? n : 0), buf);
}
close(a);
close(b);
close(ctl);
if (helper >= 0) close(helper);
return 0;
}
int main(int argc, char *argv[]) {
if (argc == 2) return run_peer(argv[1], 0);
if (argc == 3 && strcmp(argv[1], "--remote") == 0)
return run_peer(argv[2], 1);
if (argc == 4 && strcmp(argv[1], "--helper") == 0)
return run_helper(argv[2], argv[3]);
return 1;
}
+253 -2
View File
@@ -33,6 +33,198 @@ static int s_abort = 0;
#define DASHBOARD(x) \ #define DASHBOARD(x) \
printf("HEALTH_DASHBOARD\t\"%s\": %s,\n", x, s_error ? "false" : "true") printf("HEALTH_DASHBOARD\t\"%s\": %s,\n", x, s_error ? "false" : "true")
#define UDP_PORT 1235
#if MG_ENABLE_FREERTOS
static volatile bool s_tx_held, s_tx_waits;
#endif
static int open_udp(void) {
struct sockaddr_in sa;
char buf;
int fd;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(UDP_PORT);
sa.sin_addr.s_addr = INADDR_ANY;
ASSERT((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0);
ASSERT(bind(fd, (struct sockaddr *) &sa, sizeof(sa)) == 0);
ASSERT(send(fd, &buf, sizeof(buf), 0) < 0 && errno == EDESTADDRREQ);
ASSERT(fcntl(fd, F_SETFL, O_NONBLOCK) == 0);
return fd;
}
static void check_udp_oversize(struct mg_mgr *mgr, int fd,
const struct sockaddr *dst, socklen_t dstlen) {
static char buf[1600];
size_t len = mgr->ifp->mtu + 1;
ASSERT(len <= sizeof(buf));
if (dst == NULL) {
ASSERT(send(fd, buf, len, 0) < 0 && errno == EMSGSIZE);
} else {
ASSERT(sendto(fd, buf, len, 0, dst, dstlen) < 0 && errno == EMSGSIZE);
}
}
static void udp_exchange(struct mg_mgr *mgr, int fd,
void (*progress)(struct mg_mgr *)) {
struct sockaddr_in peer, sender;
socklen_t peerlen, senderlen;
uint64_t deadline;
struct timeval zero = {0, 0};
struct pollfd p;
fd_set r, w, e;
char buf[8];
ssize_t n;
for (;;) {
peerlen = sizeof(peer);
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) &peer, &peerlen);
if (n >= 0) break;
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 5 && memcmp(buf, "hello", 5) == 0);
ASSERT(sendto(fd, "ready", 5, 0, (struct sockaddr *) &peer, peerlen) ==
5);
check_udp_oversize(mgr, fd, (struct sockaddr *) &peer, peerlen);
do {
senderlen = sizeof(sender);
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) &sender,
&senderlen);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 7 && memcmp(buf, "rogueid", 7) == 0 &&
sender.sin_port != peer.sin_port);
#if MG_ENABLE_FREERTOS
s_tx_waits = false, s_tx_held = true;
#endif
ASSERT(sendto(fd, "peerone", 7, 0, (struct sockaddr *) &peer, peerlen) ==
7);
ASSERT(sendto(fd, "rogueok", 7, 0, (struct sockaddr *) &sender,
senderlen) < 0 && errno == EAGAIN);
#if MG_ENABLE_FREERTOS
while (!s_tx_waits) progress(mgr); // Keep peerone in the UDP slot
s_tx_held = false;
#endif
while ((n = sendto(fd, "rogueok", 7, 0, (struct sockaddr *) &sender,
senderlen)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 7);
deadline = mg_millis() + 100;
while (mg_millis() < deadline) progress(mgr); // Queue both; drop the second
do {
senderlen = sizeof(sender);
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) &sender,
&senderlen);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 3 && memcmp(buf, "one", 3) == 0 &&
sender.sin_port == peer.sin_port);
ASSERT(recvfrom(fd, buf, sizeof(buf), MSG_DONTWAIT, NULL, NULL) < 0 &&
errno == EAGAIN);
ASSERT(connect(fd, (struct sockaddr *) &peer, peerlen) == 0);
senderlen = sizeof(sender);
ASSERT(getsockname(fd, (struct sockaddr *) &sender, &senderlen) == 0 &&
sender.sin_port == htons(UDP_PORT));
ASSERT(sendto(fd, "no", 2, 0, (struct sockaddr *) &peer, peerlen) < 0 &&
errno == EISCONN);
check_udp_oversize(mgr, fd, NULL, 0);
ASSERT(send(fd, "drop", 4, 0) == 4);
do {
n = recv(fd, buf, 3, 0);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 3 && memcmp(buf, "tru", 3) == 0);
ASSERT(recv(fd, buf, sizeof(buf), MSG_DONTWAIT) < 0 && errno == EAGAIN);
ASSERT(send(fd, "short", 5, 0) == 5);
do {
n = recv(fd, buf, sizeof(buf), MSG_PEEK);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 4 && memcmp(buf, "peek", 4) == 0);
ASSERT(recv(fd, buf, sizeof(buf), 0) == 4 && memcmp(buf, "peek", 4) == 0);
ASSERT(send(fd, "peek", 4, 0) == 4);
deadline = mg_millis() + 100;
while (mg_millis() < deadline) progress(mgr); // Let rogue arrive; ignore it
do {
p.fd = fd, p.events = POLLIN | POLLOUT, p.revents = 0;
ASSERT(poll(&p, 1, 0) == 1);
if (!(p.revents & POLLIN)) progress(mgr);
} while (!(p.revents & POLLIN));
ASSERT(p.revents == (POLLIN | POLLOUT));
FD_ZERO(&r);
FD_ZERO(&w);
FD_ZERO(&e);
FD_SET(fd, &r);
FD_SET(fd, &w);
FD_SET(fd, &e);
ASSERT(select(fd + 1, &r, &w, &e, &zero) == 1);
ASSERT(FD_ISSET(fd, &r) && FD_ISSET(fd, &w) && !FD_ISSET(fd, &e));
do {
n = recv(fd, buf, sizeof(buf), 0);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 4 && memcmp(buf, "more", 4) == 0);
p.events = POLLIN | POLLOUT, p.revents = 0;
ASSERT(poll(&p, 1, 0) == 1 && p.revents == POLLOUT);
while ((n = send(fd, "checked", 7, 0)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 7);
while ((n = send(fd, "one", 3, MSG_DONTWAIT)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 3);
p.fd = fd, p.events = POLLOUT, p.revents = 0;
ASSERT(poll(&p, 1, 0) == 0 && p.revents == 0);
#if MG_ENABLE_FREERTOS
s_tx_waits = false, s_tx_held = true;
#endif
ASSERT(send(fd, "two2", 4, MSG_DONTWAIT) < 0 && errno == EAGAIN);
ASSERT(send(fd, "", 0, 0) == 0);
#if MG_ENABLE_FREERTOS
while (!s_tx_waits) progress(mgr); // MG_IO_WAIT keeps one datagram queued
s_tx_held = false;
#endif
while ((n = send(fd, "two2", 4, MSG_DONTWAIT)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 4);
for (;;) {
n = recv(fd, buf, sizeof(buf), 0);
if (n >= 0) break;
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 4 && memcmp(buf, "echo", 4) == 0);
ASSERT(send(fd, "echo", 4, 0) == 4);
progress(mgr); // Drain the last queued datagram before close
ASSERT(close(fd) == 0);
}
static pid_t start_client(const char *ip, const char *connections) { static pid_t start_client(const char *ip, const char *connections) {
char *cmd[4]; char *cmd[4];
pid_t pid; pid_t pid;
@@ -46,6 +238,18 @@ static pid_t start_client(const char *ip, const char *connections) {
return pid; return pid;
} }
static pid_t start_udp(const char *ip) {
char *cmd[3];
pid_t pid;
extern char **environ;
cmd[0] = (char *) "./bsd_udp";
cmd[1] = (char *) ip;
cmd[2] = NULL;
ASSERT(posix_spawn(&pid, cmd[0], NULL, NULL, cmd, environ) == 0);
return pid;
}
static bool client_done(pid_t pid, int *status) { static bool client_done(pid_t pid, int *status) {
pid_t r = waitpid(pid, status, WNOHANG); pid_t r = waitpid(pid, status, WNOHANG);
ASSERT(r >= 0); ASSERT(r >= 0);
@@ -60,12 +264,17 @@ static void check_client(int status) {
static int open_listener(int backlog, bool nonblock) { static int open_listener(int backlog, bool nonblock) {
int lfd = socket(AF_INET, SOCK_STREAM, 0); int lfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sa; struct sockaddr_in sa;
char buf;
memset(&sa, 0, sizeof(sa)); memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET; sa.sin_family = AF_INET;
sa.sin_port = htons(1234); sa.sin_port = htons(1234);
sa.sin_addr.s_addr = INADDR_ANY; sa.sin_addr.s_addr = INADDR_ANY;
ASSERT(lfd >= 0); ASSERT(lfd >= 0);
ASSERT(sendto(lfd, &buf, sizeof(buf), 0, (struct sockaddr *) &sa,
sizeof(sa)) < 0 && errno == EOPNOTSUPP);
ASSERT(recvfrom(lfd, &buf, sizeof(buf), 0, NULL, NULL) < 0 &&
errno == EOPNOTSUPP);
ASSERT(bind(lfd, (struct sockaddr *) &sa, sizeof(sa)) == 0); ASSERT(bind(lfd, (struct sockaddr *) &sa, sizeof(sa)) == 0);
ASSERT(listen(lfd, backlog) == 0); ASSERT(listen(lfd, backlog) == 0);
if (nonblock) ASSERT(fcntl(lfd, F_SETFL, O_NONBLOCK) == 0); if (nonblock) ASSERT(fcntl(lfd, F_SETFL, O_NONBLOCK) == 0);
@@ -146,12 +355,13 @@ static volatile bool s_select_waiting, s_select_done;
static volatile bool s_poll_waiting, s_poll_done; static volatile bool s_poll_waiting, s_poll_done;
static volatile bool s_ready_waiting, s_ready_done; static volatile bool s_ready_waiting, s_ready_done;
static volatile bool s_backlog_ready, s_backlog_full, s_backlog_accept; static volatile bool s_backlog_ready, s_backlog_full, s_backlog_accept;
static volatile bool s_tx_held, s_tx_waits, s_tx_fail, s_tx_error; static volatile bool s_tx_fail, s_tx_error;
static volatile bool s_send_waiting; static volatile bool s_send_waiting;
static volatile bool s_send_done, s_send_expect_error, s_send_expect_shutdown; static volatile bool s_send_done, s_send_expect_error, s_send_expect_shutdown;
static volatile bool s_recv_start, s_recv_waiting, s_recv_done; static volatile bool s_recv_start, s_recv_waiting, s_recv_done;
static volatile bool s_recv_expect_error; static volatile bool s_recv_expect_error;
static volatile bool s_shutdown_waiting, s_shutdown_done; static volatile bool s_shutdown_waiting, s_shutdown_done;
static volatile bool s_udp_ready, s_udp_done;
static size_t (*s_tx)(const void *, size_t, struct mg_tcpip_if *); static size_t (*s_tx)(const void *, size_t, struct mg_tcpip_if *);
struct client_data { struct client_data {
@@ -170,6 +380,7 @@ static void readiness_task(void *args);
static void backlog_task(void *args); static void backlog_task(void *args);
static void tx_gate_task(void *args); static void tx_gate_task(void *args);
static void shutdown_task(void *args); static void shutdown_task(void *args);
static void udp_task(void *args);
struct atask_args { struct atask_args {
bool listener_nonblock; bool listener_nonblock;
@@ -329,6 +540,21 @@ static void tx_gate_task(void *args) {
(void) args; (void) args;
} }
static void udp_delay(struct mg_mgr *mgr) {
(void) mgr;
vTaskDelay(1);
}
static void udp_task(void *args) {
struct mg_mgr *mgr = (struct mg_mgr *) args;
int fd = open_udp();
s_udp_ready = true;
udp_exchange(mgr, fd, udp_delay);
s_udp_done = true;
vTaskDelete(NULL);
}
static void recv_wait_task(void *args) { static void recv_wait_task(void *args) {
char buf; char buf;
int fd = (int) (uintptr_t) args; int fd = (int) (uintptr_t) args;
@@ -599,12 +825,22 @@ static void task2(void *args) {
struct mg_mgr *mgr = (struct mg_mgr *)args; // Event manager struct mg_mgr *mgr = (struct mg_mgr *)args; // Event manager
char *ip; char *ip;
int status; int status;
pid_t first, second; pid_t first, second, udp;
vTaskDelay(pdMS_TO_TICKS(500)); // 500 ms vTaskDelay(pdMS_TO_TICKS(500)); // 500 ms
s_error = false; s_error = false;
s_wait = false; s_wait = false;
ip = mg_mprintf("%M", mg_print_ip4, &mgr->ifp->ip); ip = mg_mprintf("%M", mg_print_ip4, &mgr->ifp->ip);
s_udp_ready = s_udp_done = false;
ASSERT(xTaskCreate(udp_task, "udp", 512, mgr, configMAX_PRIORITIES - 1,
NULL) == pdPASS);
while (!s_udp_ready) vTaskDelay(1);
udp = start_udp(ip);
while (!client_done(udp, &status)) vTaskDelay(1);
check_client(status);
while (!s_udp_done) vTaskDelay(1);
DASHBOARD("udp");
s_poll_waiting = s_poll_done = false; s_poll_waiting = s_poll_done = false;
ASSERT(xTaskCreate(poll_task, "poll", 512, NULL, ASSERT(xTaskCreate(poll_task, "poll", 512, NULL,
configMAX_PRIORITIES - 1, NULL) == pdPASS); configMAX_PRIORITIES - 1, NULL) == pdPASS);
@@ -963,6 +1199,20 @@ static void nortos_echo(struct mg_mgr *mgr, struct nortos_echo_client *clients,
nortos_wait_client(mgr, pid); nortos_wait_client(mgr, pid);
} }
static void udp_poll(struct mg_mgr *mgr) {
mg_mgr_poll(mgr, 0);
}
static void nortos_udp(struct mg_mgr *mgr, const char *ip) {
pid_t pid;
int fd = open_udp();
pid = start_udp(ip);
udp_exchange(mgr, fd, udp_poll);
nortos_wait_client(mgr, pid);
DASHBOARD("nortos_udp");
}
static void nortos_test(struct mg_mgr *mgr) { static void nortos_test(struct mg_mgr *mgr) {
static const char bootstrap = '\0'; static const char bootstrap = '\0';
static const char grow[512] = {0}; static const char grow[512] = {0};
@@ -1083,6 +1333,7 @@ static void nortos_test(struct mg_mgr *mgr) {
ASSERT(close(fd) == 0); ASSERT(close(fd) == 0);
mg_mgr_poll(mgr, 0); mg_mgr_poll(mgr, 0);
DASHBOARD("nortos_nonblocking_connect"); DASHBOARD("nortos_nonblocking_connect");
nortos_udp(mgr, ip);
mg_free(ip); mg_free(ip);
} }
-14
View File
@@ -1,14 +0,0 @@
.DEFAULT_GOAL := cpq_udp
include Makefile
.PHONY: cpq_udp bsd_cpq_test bsd_udp_cpq_peer
cpq_udp: shm_tap_bridge bsd_cpq_test bsd_udp_cpq_peer
sh -c 'TRACE_UDP=1 ./shm_tap_bridge & pid=$$!; sleep 1; timeout 30s ./bsd_cpq_test; rc=$$?; kill $$pid >/dev/null 2>&1; wait $$pid >/dev/null 2>&1; exit $$rc'
bsd_cpq_test: CFLAGS_MONGOOSE += -DMG_ENABLE_FREERTOS=1 -DCPQ_TEST
bsd_cpq_test: FreeRTOS-Kernel bsd_cpq_test.c bsd_udp_cpq_fail.c bsd_shm_test.c
$(CC) $(C_INPUTS) $(FREERTOS_INPUTS) -x c bsd_shm_test.c $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) -o $@
bsd_udp_cpq_peer: bsd_udp_cpq_peer.c
$(CC) bsd_udp_cpq_peer.c -o $@
-11
View File
@@ -18,15 +18,6 @@
#include "shm_queue.h" #include "shm_queue.h"
static volatile sig_atomic_t s_signo; static volatile sig_atomic_t s_signo;
static int s_trace_udp;
static void trace_udp(const uint8_t *p, size_t len) {
if (!s_trace_udp || len < 34 || p[12] != 8 || p[13] != 0 || p[23] != 17)
return;
printf("UDP IP dst %u.%u.%u.%u -> Ethernet dst %02x:%02x:%02x:%02x:%02x:%02x\n",
p[30], p[31], p[32], p[33], p[0], p[1], p[2], p[3], p[4], p[5]);
}
void signal_handler(int signo) { void signal_handler(int signo) {
s_signo = signo; s_signo = signo;
} }
@@ -67,7 +58,6 @@ int main(void) {
} }
memset(shm, 0, sizeof(*shm)); memset(shm, 0, sizeof(*shm));
s_trace_udp = getenv("TRACE_UDP") != NULL;
printf("Opened shared memory: %s\n", SHM_NAME); printf("Opened shared memory: %s\n", SHM_NAME);
signal(SIGINT, signal_handler); signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler); signal(SIGTERM, signal_handler);
@@ -104,7 +94,6 @@ int main(void) {
uint8_t buf[FRAME_SIZE]; uint8_t buf[FRAME_SIZE];
size_t n = shm_queue_pop(&shm->to_tap, buf, sizeof(buf)); size_t n = shm_queue_pop(&shm->to_tap, buf, sizeof(buf));
if (n > 0) { if (n > 0) {
trace_udp(buf, n);
// printf("Got at SHM: %d bytes\n", (int) f->len); // printf("Got at SHM: %d bytes\n", (int) f->len);
write(fd, buf, n); write(fd, buf, n);
// printf("Sent to TAP\n"); // printf("Sent to TAP\n");
-457
View File
@@ -1,457 +0,0 @@
# UDP CPQ Patch Assessment
## Scope
This assesses the CPQ patch applied to `master`, with only this receive-side
change:
```c
if (c->is_bsd && c->recv.len > 0) return true;
```
It deliberately does not require the bsdudp TX framing, peer filtering, or
neighbor-cache work. The rule keeps the first unread nonempty datagram and
discards later ones.
## What The CPQ Patch Provides
When two nonempty UDP datagrams arrive before a BSD application calls
`recv()` or `recvfrom()`, the first remains in `c->recv` and later packets are
discarded. Therefore the first payload is no longer concatenated with the
second one, and its source address remains in `c->rem` until it is read.
That is a valid deliberately lossy receive policy. It only addresses this one
case. The rest of the odd/incorrect behaviors found when initially writing code in the bsdudp branch are detailed in subsequent paragraphs. The rest of the missing functionality also observed before is NOT described here, only what is claimed to be functional is evaluated; these are somehow enumerated at the end of this document, just before the appendixes
See [B.1](#b1-cpq-unread-datagram-policy) for the test evidence.
## Rate Limit Of The One-Datagram Policy
The retained datagram is a one-slot loss queue: while the BSD application has
not called `recv()` or `recvfrom()`, every later nonempty datagram is dropped.
If the application needs 4 ms to read it, independent traffic has these
approximate collision probabilities:
| Aggregate UDP rate | Probability of another datagram within 4 ms |
| ---: | ---: |
| 25 packets/s | 9.5% |
| 50 packets/s | 18.1% |
| 100 packets/s | 33.0% |
| 250 packets/s | 63.2% |
| 1000 packets/s | 98.2% |
This is basic queueing theory under an independent-arrivals assumption. See
[Appendix A](#appendix-a-one-slot-queue-model) for the model and limits of the
estimate.
## Baseline Failures
`bsd_udp_cpq_fail.c` and `bsd_udp_cpq_peer.c` print the wire-level effects for
short receives, empty datagrams, connected peers, and `sendto()`.
The target runs Mongoose's built-in TCP/IP stack. A bridge connects its packet
interface to the LAN because this path cannot use BSD sockets: BSD is the API
being tested.
The default runner is self-contained for CI: it starts the peer on the same
host (Workstation) and exercises every failure except a mismatched Ethernet destination. To
show that L2 failure, run the primary peer on a second machine (Laptop):
```text
Laptop: ./bsd_udp_cpq_peer --remote <Mongoose-IP>
Workstation: CPQ_REMOTE_PEER=<Laptop-IP> ./bsd_cpq_test
```
Remote mode starts a Workstation helper automatically. The Laptop and helper
have distinct MAC addresses. The helper first redirects a connected-socket
reply, then populates the unconnected `sendto()` socket with its MAC. The
following `sendto()` names the Laptop IP, but `TRACE_UDP=1` shows the helper's
Ethernet destination. The evidence below was collected with Workstation IP
forwarding disabled, so the Laptop cannot receive a frame addressed to the
helper MAC.
### Short `recvfrom()` turns one datagram into two reads
The CPQ code removes only the copied byte count from `c->recv`. Reading two
bytes of `ABCDE` leaves `CDE` in the buffer, so the next `recvfrom()` returns
it as if it were a new UDP datagram. UDP must discard the unread tail of a
datagram after a non-peek short receive. Dropping later packets does not repair
this: the tail is already in the retained packet.
See [B.2](#b2-short-recvfrom) for the test evidence.
### A connected UDP socket accepts traffic from any sender
`rx_udp()` overwrites `c->rem` and the return L2 address for every accepted
packet. It does not check that an incoming peer matches the peer selected by
`connect()`. An unrelated sender can therefore place data in a connected
socket and replace its reply destination. The demonstrator sends `intruder`
from a third peer: the connected receive succeeds when it should return
`EAGAIN`, and the subsequent `send()` goes to the intruder rather than the
connected peer.
See [B.3](#b3-connected-udp-accepts-another-peer) for the test evidence.
### Unconnected `send()` reports success
`bsd_dispatch(BSD_OP_SEND)` passes UDP bytes to `mg_send()` without checking
whether the socket has a peer. A real UDP socket has nowhere to send in this
state and reports `EDESTADDRREQ`. Here, the API reports that the datagram was
accepted even though it has no valid destination.
See [B.4](#b4-unconnected-send) for the test evidence.
### `sendto()` uses one stale L2 destination
`BSD_OP_SENDTO` changes the destination IP and UDP port in `c->rem`, but calls
`mg_send()` with the one L2 MAC currently stored for the socket. That MAC was
learned when a packet arrived, or while a UDP `connect()` resolved its peer;
there is no resolution or MAC lookup for each `sendto()` destination. An
application using `sendto()` for several peers therefore has one usable L2
destination, not one per peer.
- A single-destination application can appear to work: its only peer is the
one that caused the MAC to be learned. This is likely the tested case.
- Sending to another local-LAN host changes the IP address but keeps that first
host's MAC. The Ethernet frame reaches the first host, which drops it
because its IP destination names the second host. `sendto()` still reports
success.
- Several off-link destinations can also appear to work if the stored MAC is
the common router MAC. The router is the correct L2 next hop for all of
them. This does not make the socket generally correct.
- A socket that has neither received a datagram nor been connected has no
usable destination MAC. Its first proactive `sendto()` reports success but
cannot be delivered correctly.
Receiving an unrelated datagram can also break a destination that was working.
For example, A sends to this UDP port, so the socket stores A's MAC and a
later `sendto(A)` works. B then sends any datagram to the same port.
`rx_udp()` replaces the stored MAC with B's. The next `sendto(A)` still names
A in the IP header, but addresses the Ethernet frame to B; A no longer gets
it. The same overwrite occurs after UDP `connect()`, because the CPQ code does
not filter non-peer senders. Remote traffic through the same router can hide
this again because its Ethernet source MAC remains the router's MAC.
The two-host remote test covers both cases: [B.5](#b5-first-unconnected-sendto)
shows the first `sendto()` without an L2 address, and
[B.6](#b6-sendto-corrupts-later-sends-and-uses-a-stale-mac) shows a Laptop IP
sent with the helper MAC. Two sockets on one Linux host are not sufficient for
the latter because they share one NIC MAC. The bridge prints each outgoing UDP
IP destination beside its Ethernet destination MAC, independently confirming
the wrong L2 destination.
(In branch bsdudp, we fixed this by using a framing transporting TX records between the BSD side and the Mongoose side; a correct `sendto()` must wait
for ARP resolution without losing that destination, so those records/frames are queued at the send buffer and the extraction then can decide whether to start an ARP, thing that is minimized with a small cache-like table holding 4 entries)
See [B.5](#b5-first-unconnected-sendto) and
[B.6](#b6-sendto-corrupts-later-sends-and-uses-a-stale-mac) for the test
evidence.
### `sendto()` changes the meaning of later `send()` calls
The same direct update makes an unconnected socket look connected after a
`sendto()`. A later `send()` succeeds and uses the previous `sendto()` target,
although BSD requires `EDESTADDRREQ` until `connect()` selects a peer. It is
state corruption from the application's point of view: an operation intended
to name one datagram's destination changes the socket's default destination.
See [B.6](#b6-sendto-corrupts-later-sends-and-uses-a-stale-mac) for the test
evidence.
### `bind()` followed by UDP `connect()` loses the bound port
`mg_connect_resolved()` assigns an ephemeral local port unconditionally.
Calling `connect()` on a UDP socket already bound to a specific port replaces
that port. This is independent of receive buffering; the local identity used
by replies changes after `connect()`.
See [B.7](#b7-bind-followed-by-udp-connect) for the test evidence.
### `sendto()` on a connected UDP socket reports success
A connected UDP socket already has a selected peer. `sendto()` must fail with
`EISCONN`, but the CPQ implementation accepts it and changes that peer.
See [B.8](#b8-sendto-on-a-connected-udp-socket) for the test evidence.
### Oversized UDP writes report success after truncation
The CPQ code passes an oversized payload through `mg_send()`. The built-in UDP
path trims to its payload capacity and transmits only that prefix. BSD callers
are told that the whole datagram was sent. A UDP datagram must be sent whole
or fail; partial transmission is not meaningful.
See [B.9](#b9-oversized-udp-write) for the test evidence.
### Empty datagrams disappear
An empty UDP datagram does not increase `c->recv.len`. No later `recv()` can
distinguish it from no packet, so it returns `EAGAIN` or blocks instead of
returning zero. The proposed condition is also false for an empty retained
datagram, so it cannot represent or protect one.
Yes, it has been agreed that is a known and accepted behavior.
For completeness, see [B.10](#b10-empty-datagram) for the test evidence.
## bsdudp Branch Fixes and Additions
These are additional capabilities, not prerequisites for the one-datagram
drop policy above:
- RX drops the complete retained datagram after a short non-peek read.
- RX filters packets from non-peer senders on connected UDP sockets.
- TX records carry each UDP destination, so queued `sendto()` calls retain
their individual targets.
- TX triggers and reuses L2 resolution for `sendto()` destinations.
- Unconnected `send()` returns `EDESTADDRREQ`; connected UDP `sendto()`
returns `EISCONN`.
- `bind()` followed by UDP `connect()` keeps the selected local port.
- BSD writes reject oversized datagrams with `EMSGSIZE` before queuing them.
Empty UDP receives still require an explicit marker or framing record and are
not solved by either the CPQ patch or the current bsdudp simplification.
## Appendix A: One-Slot Queue Model
Let `D` be the time from receiving a datagram until the BSD application reads
it. Let `N` peers each send at `r` packets/s, so the aggregate arrival rate is
`lambda = N * r`. For independent arrivals approximated as a Poisson process,
the probability that at least one later datagram arrives during the unread
window is:
```text
P(collision) = 1 - exp(-lambda * D)
```
The table above uses `D = 4 ms`. It is a collision probability, not a precise
packet-loss percentage: the latter also depends on the scheduler and on when
the application calls `recv()`.
For evenly spaced periodic traffic, the aggregate packet spacing must be at
least `D` to avoid drops. Therefore each of `N` equal-rate peers needs a period
of at least `N * D`: with `D = 4 ms`, 10 peers need at least 40 ms per packet
per peer, while 100 peers need at least 400 ms.
## Appendix B: Two-Host Test Evidence
This run used Mongoose at `192.168.69.231`, the Laptop at
`192.168.69.73`, and a Workstation helper at `192.168.69.11`. The Laptop MAC
learned for normal control traffic was `3c:0a:f3:8c:ce:ef`; the helper MAC was
`06:3f:ad:7e:3f:1c`. Startup and
DHCP are omitted below.
### B.1 CPQ unread-datagram policy
**Test.** Two peers send `one` and `two` before the application reads port
`1234`.
**Expected.** The CPQ rule retains `one` and drops `two`.
**Observed.**
```text
Workstation: PASS drop: kept one, dropped two
Laptop: no separate observation
Bridge: no separate observation
```
**Internal reason.** `rx_udp()` returns once a BSD connection has a nonempty
`c->recv`. It is a one-datagram loss queue, not a UDP receive queue.
### B.2 Short `recvfrom()`
**Test.** A peer sends one five-byte datagram, `ABCDE`. The application first
reads two bytes, then reads again.
**Expected.** The first call returns `AB`; UDP discards the unread `CDE` tail.
The second call returns `EAGAIN` until another datagram arrives.
**Observed.**
```text
Workstation: FAIL short: expected EAGAIN, got 3 "CDE": tail retained
Laptop: sent ABCDE
Bridge: no separate observation
```
**Internal reason.** `BSD_OP_RECVFROM` removes only the copied byte count from
the stream-shaped `c->recv` iobuf. It has no record length to discard the rest
of the datagram.
### B.3 Connected UDP accepts another peer
**Test.** The socket connects to the Laptop. The Workstation helper then sends
`intruder` to that connected socket.
**Expected.** The helper datagram is ignored. A following `send()` still goes
to the Laptop.
**Observed.**
```text
Workstation: FAIL peer: expected EAGAIN, got 8 "intruder": no peer filter
Mongoose: mg_connect_ 7 192.168.69.231:64103 -> 192.168.69.73:14000
Mongoose: mg_connect_ 7 ARP lookup...
Mongoose: rx_arp 7 ARP resolved 192.168.69.73 -> 3c:0a:f3:8c:ce:ef
Workstation: reply: sent 5 bytes; peer reports its destination below
Laptop: FAIL reply: expected control, got none: intruder replaced peer
Helper: FAIL connected peer: helper received reply
Bridge: UDP IP dst 192.168.69.11 -> Ethernet dst 06:3f:ad:7e:3f:1c
```
**Internal reason.** `mg_connect_resolved()` correctly starts an ARP lookup for
the configured Laptop peer and stores its MAC. `rx_udp()` then accepts every
sender matching the local port. Before the BSD read runs, it overwrites
`c->rem` and the connection return MAC with the helper's source. The later
`send()` therefore replies to the helper instead of the peer that was resolved
at `connect()` time.
### B.4 Unconnected `send()`
**Test.** Send one byte on a bound UDP socket that has never called
`connect()` or `sendto()`.
**Expected.** `send()` fails with `EDESTADDRREQ`: there is no peer.
**Observed.**
```text
Workstation: FAIL send: expected EDESTADDRREQ, got 1: no peer check
Laptop: no packet expected
Bridge: UDP IP dst 0.0.0.0 -> Ethernet dst 00:00:00:00:00:00
```
**Internal reason.** `BSD_OP_SEND` calls `mg_send()` without checking whether
the UDP socket has a selected peer. The zeroed remote address reaches the L2
transmit path.
### B.5 First unconnected `sendto()`
**Test.** Call `sendto()` to the Laptop before this socket has received any
packet or connected to a peer.
**Expected.** The implementation resolves the Laptop L2 address, waits if
needed, then delivers the datagram.
**Observed.**
```text
Workstation: FAIL sendto: expected delivery, got 4: no resolution
Laptop: FAIL sendto: expected packet, got none
Bridge: UDP IP dst 192.168.69.73 -> Ethernet dst 00:00:00:00:00:00
```
**Internal reason.** `BSD_OP_SENDTO` replaces only `c->rem` and immediately
calls `mg_send()`. Unlike the preceding `connect()` cases, this operation
produces no `mg_connect_ ... ARP lookup...` or `rx_arp ... ARP resolved ...`
log for the Laptop destination. It neither performs ARP/L2 resolution nor
retains the destination while resolution would be pending. The zero Ethernet
destination in the bridge trace is the direct result.
### B.6 `sendto()` corrupts later sends and uses a stale MAC
**Test.** The helper sends a datagram to the unconnected socket, establishing
the helper MAC. The application then calls `sendto()` to the Laptop and, after
that, calls `send()` on the same socket.
**Expected.** `sendto()` sends to the Laptop MAC without changing the socket's
default peer. The later `send()` fails with `EDESTADDRREQ`.
**Observed.**
```text
Workstation: sendto after RX: got 5
Workstation: FAIL send: expected EDESTADDRREQ, got 4: sendto set peer
Laptop: FAIL stale MAC: expected packet, got none
Bridge: UDP IP dst 192.168.69.73 -> Ethernet dst 3c:0a:f3:8c:ce:ef
Bridge: UDP IP dst 192.168.69.73 -> Ethernet dst 06:3f:ad:7e:3f:1c
```
The first bridge line is normal Laptop control traffic. The second names the
same Laptop IP but uses the helper MAC. The Laptop receives no packet.
**Internal reason.** The implementation keeps only one mutable `c->rem` and
one return MAC per Mongoose UDP connection. Receiving the helper datagram
updates that one MAC to `06:3f:ad:7e:3f:1c`. `sendto()` overwrites `c->rem`,
but does not start an ARP lookup for the Laptop and therefore retains the
helper MAC. There is no `mg_connect_ ... ARP lookup...` or `rx_arp ... ARP
resolved ...` sequence between this `sendto()` and the second bridge line. No
per-datagram destination record or neighbor cache exists.
### B.7 `bind()` followed by UDP `connect()`
**Test.** Bind local port `1238`, then connect to the Laptop and query the
local address.
**Expected.** The socket remains bound to `1238`.
**Observed.**
```text
Workstation: FAIL bind: expected 1238, got 64102: connect replaced bind
Mongoose: mg_connect_ 5 192.168.69.231:64102 -> 192.168.69.73:14000
Mongoose: mg_connect_ 5 ARP lookup...
Mongoose: rx_arp 5 ARP resolved 192.168.69.73 -> 3c:0a:f3:8c:ce:ef
Laptop: normal ARP/control peer
```
**Internal reason.** `mg_connect_resolved()` assigns an ephemeral local port
without preserving the BSD socket's existing bind state.
### B.8 `sendto()` on a connected UDP socket
**Test.** After UDP `connect()`, call `sendto()` with a different destination.
**Expected.** Fail with `EISCONN`; a connected UDP socket uses `send()`.
**Observed.**
```text
Workstation: FAIL sendto: expected EISCONN, got 1: connected socket accepted it
Laptop: no separate observation
Bridge: no separate observation
```
**Internal reason.** `BSD_OP_SENDTO` has no connected-UDP state check and
blindly replaces the peer address. The connected socket's ARP lookup happened
at `connect()` time in B.3; this operation does not validate that state or
start resolution for its replacement destination.
### B.9 Oversized UDP write
**Test.** Send a 1600-byte datagram.
**Expected.** Fail with `EMSGSIZE`; UDP cannot partially send one datagram.
**Observed.**
```text
Workstation: FAIL oversize: expected EMSGSIZE, got 1600: later truncated
Laptop: no receiving socket in this run
Bridge: no payload-length assertion in this run
```
**Internal reason.** The BSD layer does not reject an over-capacity datagram.
The built-in UDP transmit path later limits payload to its available capacity,
while the BSD caller has already been told all 1600 bytes were accepted.
This run proves the false-success API result. A receiver-side payload-length
assertion would additionally demonstrate the transmitted prefix length.
### B.10 Empty datagram
**Test.** Send a zero-byte UDP datagram, then call `recvfrom()`.
**Expected.** `recvfrom()` returns zero and preserves the source address.
**Observed.**
```text
Workstation: FAIL empty: expected 0, got -1 errno 11: no marker
Laptop: sent a zero-byte datagram
Bridge: no separate observation
```
**Internal reason.** An empty payload does not increase `c->recv.len`; the
stream iobuf cannot distinguish an empty datagram from no pending data.
+1 -1
View File
@@ -6,7 +6,7 @@ HDRS = simulator.h $(ROOT)/mongoose.h
WARN = -pedantic -W -Wall -Werror -Wshadow -Wdouble-promotion -fno-common \ WARN = -pedantic -W -Wall -Werror -Wshadow -Wdouble-promotion -fno-common \
-Wconversion -Wundef -Wmissing-prototypes -Wstrict-prototypes -Wconversion -Wundef -Wmissing-prototypes -Wstrict-prototypes
DEFS = -DMG_ENABLE_TCPIP=1 -DMG_ENABLE_TCPIP_DRIVER_INIT=0 -DMG_ENABLE_IPV6=0 \ DEFS = -DMG_ENABLE_TCPIP=1 -DMG_ENABLE_TCPIP_DRIVER_INIT=0 -DMG_ENABLE_IPV6=0 \
-DMG_ENABLE_CUSTOM_MILLIS=1 -DMG_ENABLE_TCPIP_TCPRTX=1 \ -DMG_ENABLE_CUSTOM_MICROS=1 -DMG_ENABLE_TCPIP_TCPRTX=1 \
-DMG_IO_SIZE=512 \ -DMG_IO_SIZE=512 \
-DMG_TCPIP_ARP_MS=1000 -DMG_TCPIP_ACK_MS=500 # Slow radio: wait longer -DMG_TCPIP_ARP_MS=1000 -DMG_TCPIP_ACK_MS=500 # Slow radio: wait longer
CFLAGS ?= -O2 -g0 $(WARN) CFLAGS ?= -O2 -g0 $(WARN)
+3 -3
View File
@@ -277,7 +277,7 @@ The FRDM-RW612 example is the Ethernet bridge. The XIAO MG24 and
FRDM-MCXW71 examples are radio clients. All three use the slotted mesh. FRDM-MCXW71 examples are radio clients. All three use the slotted mesh.
```sh ```sh
make -C tutorials/nxp/frdm-rw612/bridge make -C tutorials/nxp/frdm-rw612/ethernet-to-802.15.4-bridge
make -C tutorials/silabs/xiao-mg24/minimal make -C tutorials/silabs/xiao-mg24/minimal
make -C tutorials/nxp/frdm-mcxw71/minimal make -C tutorials/nxp/frdm-mcxw71/minimal
``` ```
@@ -292,7 +292,7 @@ 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. The drivers in `src/drivers` send and receive raw 802.15.4 frames.
They use the same slotted mesh implementation as the simulator. They use the same slotted mesh implementation as the simulator.
The board driver is initialized by `mg_mgr_init()`. The RW612 bridge The board driver is initialized by `mg_mgr_init()`. The RW612 bridge
has its own `bridge/main.c`, which initializes and polls the two drivers 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. directly, without an event manager or local IP stack.
## Hardware integration ## Hardware integration
@@ -306,7 +306,7 @@ A NULL strategy selects `mg_mesh_default`, named `"default"`; assigning another
raw radio frames; the selected strategy owns joining, scheduling and Ethernet raw radio frames; the selected strategy owns joining, scheduling and Ethernet
fragmentation. Driver initialization goes through `mg_tcpip_init()`. fragmentation. Driver initialization goes through `mg_tcpip_init()`.
Board examples are under `tutorials/nxp/frdm-rw612/bridge`, 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/nxp/frdm-mcxw71/minimal`, `tutorials/silabs/xiao-mg24/minimal`, and
`tutorials/nordic/xiao-52840/minimal`. Their HALs supply `mg_micros()`. `tutorials/nordic/xiao-52840/minimal`. Their HALs supply `mg_micros()`.
-4
View File
@@ -18,10 +18,6 @@ uint64_t mg_micros(void) {
return s_sim.now; return s_sim.now;
} }
uint64_t mg_millis(void) {
return mg_micros() / 1000;
}
// Parse "X,Y,Z", or "X,Y" with Z 0. Return false if it is not that // Parse "X,Y,Z", or "X,Y" with Z 0. Return false if it is not that
static bool parse_pos(const char *s, struct pos *p) { static bool parse_pos(const char *s, struct pos *p) {
int n = 0; // Characters parsed int n = 0; // Characters parsed
+1 -1
View File
@@ -4548,7 +4548,7 @@ static void test_split(void) {
ASSERT(mg_strcmp(b, mg_str("")) == 0); ASSERT(mg_strcmp(b, mg_str("")) == 0);
} }
// RFC 6979 A.2.5: P-256, SHA-256, message "sample" // RFC-6979 A.2.5: P-256, SHA-256, message "sample"
static void test_p256(void) { static void test_p256(void) {
#if MG_TLS == MG_TLS_BUILTIN #if MG_TLS == MG_TLS_BUILTIN
static const uint8_t x[32] = { static const uint8_t x[32] = {
@@ -10,7 +10,12 @@
#define MG_ARCH MG_ARCH_CUSTOM #define MG_ARCH MG_ARCH_CUSTOM
#define MG_ENABLE_TCPIP 1 #define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_W5500 1 #define MG_ENABLE_DRIVER_W5500 1
#define MG_ENABLE_TCPIP_DRIVER_INIT 0 // Fixed MAC address for the W5500 module
#define MG_SET_MAC_ADDRESS(mac) \
do { \
mac[0] = 2, mac[1] = 0, mac[2] = 1, mac[3] = 2; \
mac[4] = 3, mac[5] = 5; \
} while (0)
#define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0 #define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0
#define MG_ENABLE_CUSTOM_MILLIS 1 #define MG_ENABLE_CUSTOM_MILLIS 1
#define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_ENABLE_CUSTOM_RANDOM 1
@@ -8,7 +8,8 @@
#define LED_PIN 21 // LED pin #define LED_PIN 21 // LED pin
struct mg_connection *mqtt_connection; struct mg_connection *mqtt_connection;
struct mg_tcpip_spi spi = { // SPI bus used by the W5500 driver, see MG_TCPIP_DRIVER_W5500_INIT
struct mg_tcpip_spi mg_spi = {
NULL, // SPI metadata NULL, // SPI metadata
[](void *) { digitalWrite(SS_PIN, LOW); SPI.beginTransaction(SPISettings()); }, [](void *) { digitalWrite(SS_PIN, LOW); SPI.beginTransaction(SPISettings()); },
[](void *) { digitalWrite(SS_PIN, HIGH); SPI.endTransaction(); }, [](void *) { digitalWrite(SS_PIN, HIGH); SPI.endTransaction(); },
@@ -21,7 +22,6 @@ struct mg_tcpip_spi spi = {
}, },
}; };
struct mg_mgr mgr; // Mongoose event manager struct mg_mgr mgr; // Mongoose event manager
struct mg_tcpip_if mif = {.mac = {2, 0, 1, 2, 3, 5}}; // Network interface
uint64_t mg_millis(void) { uint64_t mg_millis(void) {
return millis(); return millis();
@@ -79,7 +79,7 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
} }
void reconnect_if_not_connected(void) { void reconnect_if_not_connected(void) {
if (mif.state == MG_TCPIP_STATE_READY && mqtt_connection == NULL) { if (mgr.ifp->state == MG_TCPIP_STATE_READY && mqtt_connection == NULL) {
struct mg_mqtt_opts opts = {}; struct mg_mqtt_opts opts = {};
opts.clean = true; opts.clean = true;
mqtt_connection = mqtt_connection =
@@ -95,12 +95,9 @@ void setup() {
pinMode(SS_PIN, OUTPUT); // to communicate with W5500 Ethernet module pinMode(SS_PIN, OUTPUT); // to communicate with W5500 Ethernet module
pinMode(LED_PIN, OUTPUT); // Initialise LED pinMode(LED_PIN, OUTPUT); // Initialise LED
mg_mgr_init(&mgr); // Initialise Mongoose event manager
mg_log_set(MG_LL_DEBUG); // Set debug log level mg_log_set(MG_LL_DEBUG); // Set debug log level
mg_log_set_fn([](char ch, void *) { Serial.print(ch); }, NULL); // Log serial mg_log_set_fn([](char ch, void *) { Serial.print(ch); }, NULL); // Log serial
mif.driver = &mg_tcpip_driver_w5500; // Use W5500 built-in driver mg_mgr_init(&mgr); // Initialise Mongoose event manager and W5500 driver
mif.driver_data = &spi; // Pass SPI interface to W5500 driver
mg_tcpip_init(&mgr, &mif); // Initialise built-in TCP/IP stack
} }
void loop() { void loop() {
@@ -10,7 +10,12 @@
#define MG_ARCH MG_ARCH_CUSTOM #define MG_ARCH MG_ARCH_CUSTOM
#define MG_ENABLE_TCPIP 1 #define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_W5500 1 #define MG_ENABLE_DRIVER_W5500 1
#define MG_ENABLE_TCPIP_DRIVER_INIT 0 // Fixed MAC address for the W5500 module
#define MG_SET_MAC_ADDRESS(mac) \
do { \
mac[0] = 2, mac[1] = 0, mac[2] = 1, mac[3] = 2; \
mac[4] = 3, mac[5] = 5; \
} while (0)
#define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0 #define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0
#define MG_ENABLE_CUSTOM_MILLIS 1 #define MG_ENABLE_CUSTOM_MILLIS 1
#define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_ENABLE_CUSTOM_RANDOM 1
+3 -6
View File
@@ -4,7 +4,8 @@
#define LED_PIN LED_BUILTIN // LED pin #define LED_PIN LED_BUILTIN // LED pin
#define SS_PIN 17 // Slave select pin for the W5500 module #define SS_PIN 17 // Slave select pin for the W5500 module
struct mg_tcpip_spi spi = { // SPI bus used by the W5500 driver, see MG_TCPIP_DRIVER_W5500_INIT
struct mg_tcpip_spi mg_spi = {
NULL, // SPI metadata NULL, // SPI metadata
[](void *) { digitalWrite(SS_PIN, LOW); SPI.beginTransaction(SPISettings()); }, [](void *) { digitalWrite(SS_PIN, LOW); SPI.beginTransaction(SPISettings()); },
[](void *) { digitalWrite(SS_PIN, HIGH); SPI.endTransaction(); }, [](void *) { digitalWrite(SS_PIN, HIGH); SPI.endTransaction(); },
@@ -17,7 +18,6 @@ struct mg_tcpip_spi spi = {
}, },
}; };
struct mg_mgr mgr; // Mongoose event manager struct mg_mgr mgr; // Mongoose event manager
struct mg_tcpip_if mif = {.mac = {2, 0, 1, 2, 3, 5}}; // Network interface
// Used by Mongoose for time tracking // Used by Mongoose for time tracking
uint64_t mg_millis(void) { uint64_t mg_millis(void) {
@@ -99,12 +99,9 @@ void setup() {
pinMode(SS_PIN, OUTPUT); // to communicate with W5500 Ethernet module pinMode(SS_PIN, OUTPUT); // to communicate with W5500 Ethernet module
pinMode(LED_PIN, OUTPUT); // Initialise LED pinMode(LED_PIN, OUTPUT); // Initialise LED
mg_mgr_init(&mgr); // Initialise Mongoose event manager
mg_log_set(MG_LL_DEBUG); // Set debug log level mg_log_set(MG_LL_DEBUG); // Set debug log level
mg_log_set_fn([](char ch, void *) { Serial.print(ch); }, NULL); // Log serial mg_log_set_fn([](char ch, void *) { Serial.print(ch); }, NULL); // Log serial
mif.driver = &mg_tcpip_driver_w5500; // Use W5500 built-in driver mg_mgr_init(&mgr); // Initialise Mongoose event manager and W5500 driver
mif.driver_data = &spi; // Pass SPI interface to W5500 driver
mg_tcpip_init(&mgr, &mif); // Initialise built-in TCP/IP stack
// Setup HTTP & HTTPS listeners. Respond "ok" on any HTTP request // Setup HTTP & HTTPS listeners. Respond "ok" on any HTTP request
mg_http_listen(&mgr, "http://0.0.0.0:80", http_ev_handler, NULL); mg_http_listen(&mgr, "http://0.0.0.0:80", http_ev_handler, NULL);
@@ -11,7 +11,12 @@
#define MG_ENABLE_SOCKET 0 #define MG_ENABLE_SOCKET 0
#define MG_ENABLE_TCPIP 1 #define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_W5500 1 #define MG_ENABLE_DRIVER_W5500 1
#define MG_ENABLE_TCPIP_DRIVER_INIT 0 // Fixed MAC address for the W5500 module
#define MG_SET_MAC_ADDRESS(mac) \
do { \
mac[0] = 2, mac[1] = 0, mac[2] = 1, mac[3] = 2; \
mac[4] = 3, mac[5] = 5; \
} while (0)
#define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0 #define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0
#define MG_ENABLE_CUSTOM_MILLIS 1 #define MG_ENABLE_CUSTOM_MILLIS 1
#define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_ENABLE_CUSTOM_RANDOM 1
+4 -7
View File
@@ -8,7 +8,8 @@
#define LED_PIN 21 // LED pin #define LED_PIN 21 // LED pin
struct mg_connection *mqtt_connection; struct mg_connection *mqtt_connection;
struct mg_tcpip_spi spi = { // SPI bus used by the W5500 driver, see MG_TCPIP_DRIVER_W5500_INIT
struct mg_tcpip_spi mg_spi = {
NULL, // SPI metadata NULL, // SPI metadata
[](void *) { digitalWrite(SS_PIN, LOW); SPI.beginTransaction(SPISettings()); }, [](void *) { digitalWrite(SS_PIN, LOW); SPI.beginTransaction(SPISettings()); },
[](void *) { digitalWrite(SS_PIN, HIGH); SPI.endTransaction(); }, [](void *) { digitalWrite(SS_PIN, HIGH); SPI.endTransaction(); },
@@ -21,7 +22,6 @@ struct mg_tcpip_spi spi = {
}, },
}; };
struct mg_mgr mgr; // Mongoose event manager struct mg_mgr mgr; // Mongoose event manager
struct mg_tcpip_if mif = {.mac = {2, 0, 1, 2, 3, 5}}; // Network interface
uint64_t mg_millis(void) { uint64_t mg_millis(void) {
return millis(); return millis();
@@ -79,7 +79,7 @@ static void mqtt_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
} }
void reconnect_if_not_connected(void) { void reconnect_if_not_connected(void) {
if (mif.state == MG_TCPIP_STATE_READY && mqtt_connection == NULL) { if (mgr.ifp->state == MG_TCPIP_STATE_READY && mqtt_connection == NULL) {
struct mg_mqtt_opts opts = {}; struct mg_mqtt_opts opts = {};
opts.clean = true; opts.clean = true;
mqtt_connection = mqtt_connection =
@@ -95,12 +95,9 @@ void setup() {
pinMode(SS_PIN, OUTPUT); // to communicate with W5500 Ethernet module pinMode(SS_PIN, OUTPUT); // to communicate with W5500 Ethernet module
pinMode(LED_PIN, OUTPUT); // Initialise LED pinMode(LED_PIN, OUTPUT); // Initialise LED
mg_mgr_init(&mgr); // Initialise Mongoose event manager
mg_log_set(MG_LL_DEBUG); // Set debug log level mg_log_set(MG_LL_DEBUG); // Set debug log level
mg_log_set_fn([](char ch, void *) { Serial.print(ch); }, NULL); // Log serial mg_log_set_fn([](char ch, void *) { Serial.print(ch); }, NULL); // Log serial
mif.driver = &mg_tcpip_driver_w5500; // Use W5500 built-in driver mg_mgr_init(&mgr); // Initialise Mongoose event manager and W5500 driver
mif.driver_data = &spi; // Pass SPI interface to W5500 driver
mg_tcpip_init(&mgr, &mif); // Initialise built-in TCP/IP stack
} }
void loop() { void loop() {
@@ -0,0 +1,4 @@
cmake_minimum_required(VERSION 3.16)
set(IDF_TARGET esp32c6)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(mongoose-minimal-802154)
+23
View File
@@ -0,0 +1,23 @@
# Environment setup: https://mongoose.ws/documentation/tutorials/tools/
# Build: ESP-IDF from the espressif/idf Docker image. Flash: esptool.
# Monitor: esputil, https://github.com/cpq/esputil
THISDIR = $(realpath $(CURDIR))
ROOTDIR = $(realpath $(CURDIR)/../../..)
DOCKER ?= docker run --rm -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf
PORT ?= /dev/cu.usbmodem2101
all build:
$(DOCKER) idf.py build
flash: build
cd build && esptool --chip esp32c6 -p $(PORT) -b 460800 write-flash @flash_args
monitor:
esputil -p $(PORT) monitor
menuconfig:
docker run --rm -it -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf idf.py menuconfig
clean:
test -d build && $(DOCKER) rm -rf build sdkconfig || true
@@ -0,0 +1,5 @@
idf_component_register(SRCS "main.c" "../../../../mongoose.c"
"../../../mqtt/mqtt-client/mongoose_mqtt.c"
INCLUDE_DIRS "." "../../../.."
REQUIRES ieee802154 esp_timer esp_hw_support
esp_driver_gpio app_update)
@@ -0,0 +1,99 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#include <driver/gpio.h>
#include <esp_heap_caps.h>
#include "mongoose.h"
void mg_mqtt_init(struct mg_mgr *mgr); // From tutorials/mqtt/mqtt-client
void mg_mqtt_poll(struct mg_mgr *mgr);
// Seeed XIAO ESP32-C6
#define LED1 GPIO_NUM_15 // User LED, active low
#define RF_SW_PWR GPIO_NUM_3 // RF switch power, active low
#define RF_SW_SEL GPIO_NUM_14 // Antenna select: low built-in, high U.FL
// 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"
// Power the XIAO RF switch and select the built-in antenna
static void antenna_init(void) {
gpio_set_direction(RF_SW_PWR, GPIO_MODE_OUTPUT);
gpio_set_level(RF_SW_PWR, 0);
gpio_set_direction(RF_SW_SEL, GPIO_MODE_OUTPUT);
gpio_set_level(RF_SW_SEL, 0);
}
// Toggle the user LED twice a second
static void blink_task(void) {
static uint64_t blink_timer = 0;
static int on = 0;
if (mg_timer_expired(&blink_timer, 500, mg_millis())) {
gpio_set_level(LED1, on ^= 1);
}
}
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 if (mg_match(hm->uri, mg_str("/api/crash"), NULL)) {
__asm volatile("unimp"); // Illegal instruction: ESP-IDF prints a panic
} else {
mg_http_reply(c, 200, "",
"Hi from Mongoose!\n"
"tick: %llu\n"
"ram free: %zu\n"
"ram min: %zu\n",
mg_millis(), heap_caps_get_free_size(MALLOC_CAP_DEFAULT),
heap_caps_get_minimum_free_size(MALLOC_CAP_DEFAULT));
}
}
}
void app_main(void) {
struct mg_mgr mgr;
antenna_init();
gpio_set_direction(LED1, GPIO_MODE_OUTPUT);
mg_mgr_init(&mgr); // Also starts the 802.15.4 driver
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);
MG_INFO(("Initialised. RAM free: %zu",
heap_caps_get_free_size(MALLOC_CAP_DEFAULT)));
for (;;) {
mg_mgr_poll(&mgr, 0);
mg_mqtt_poll(&mgr);
blink_task();
}
}
@@ -0,0 +1,25 @@
#pragma once
#include <esp_mac.h>
// See https://mongoose.ws/docs/getting-started/build-options/
#define MG_ARCH MG_ARCH_ESP32
#define MG_TLS MG_TLS_BUILTIN
#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_TCPIP_TCPRTX 1 // Link can be lossy, enable retransmit
// Stable MAC, so the DHCP address stays the same across reboots: the factory
// MAC, locally administered
#define MG_SET_MAC_ADDRESS(mac) \
do { \
esp_read_mac(mac, ESP_MAC_BASE); \
(mac)[0] |= 2; \
} while (0)
// mdash.net device management service support
#define MG_ENABLE_MDASH 0
#define MG_MDASH_KEY "..." // Set this - mDash device token
#define MG_FIRMWARE_VERSION "esp32c6.1.0.0"
@@ -0,0 +1,8 @@
CONFIG_IDF_TARGET="esp32c6"
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y
CONFIG_IEEE802154_ENABLED=y
# Built-in TLS handshakes need a larger stack
CONFIG_ESP_MAIN_TASK_STACK_SIZE=12288
# The main task busy-loops the mesh, so the idle task does not run
CONFIG_ESP_TASK_WDT_CHECK_IDLE_TASK_CPU0=n
+1 -3
View File
@@ -17,6 +17,4 @@ flash:
cd build && esptool --chip $(ARCH) --baud 460800 --port $(PORT) write-flash @flash_args cd build && esptool --chip $(ARCH) --baud 460800 --port $(PORT) write-flash @flash_args
clean: clean:
test -d build && (rm -rf build sdkconfig || true) test -d build && $(DOCKER) rm -rf build sdkconfig || true
.PHONY: build
+1 -1
View File
@@ -67,7 +67,7 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) {
keysz = keysz =
mg_p256_parse_private_key(mg_str(s_ec_private_key), key, sizeof(key)); mg_p256_parse_private_key(mg_str(s_ec_private_key), key, sizeof(key));
// ES256 uses a raw 64-byte r || s signature. mg_jwt_sign_es256() signs it // ES256 uses a raw 64-byte r || s signature. mg_jwt_sign_es256() signs it
// deterministically (RFC 6979), see mg_p256_sign() // deterministically (RFC-6979), see mg_p256_sign()
mg_snprintf(claims, CLAIMS_LEN, "{%m:%m,%m:%m}", MG_ESC("sub"), mg_snprintf(claims, CLAIMS_LEN, "{%m:%m,%m:%m}", MG_ESC("sub"),
MG_ESC("admin"), MG_ESC("scope"), MG_ESC("dash:read")); MG_ESC("admin"), MG_ESC("scope"), MG_ESC("dash:read"));
opts.claims = mg_str(claims); opts.claims = mg_str(claims);
@@ -1,43 +0,0 @@
REPO_ROOT ?= ../../..
PROG ?= client # Program we are building
DELETE = rm -rf # Command to remove files
OUT ?= -o $(PROG) # Compiler argument for output file
CFLAGS = -I$(REPO_ROOT) -W -Wall -Wextra -g -I. # Build options
SOURCES = main.c $(REPO_ROOT)/mongoose.c mongoose_fs.c
CFLAGS_EXTRA ?= -DMG_TLS=MG_TLS_BUILTIN
# Mongoose build options. See https://mongoose.ws/docs/getting-started/build-environment/
# CFLAGS_MONGOOSE +=
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
PROG ?= client.exe # Use .exe suffix for the binary
CC = gcc # Use MinGW gcc compiler
CFLAGS += -lws2_32 # Link against Winsock library
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
OUT ?= -o $(PROG) # Build output
MAKE += WINDOWS=1 CC=$(CC)
endif
all: $(PROG)
$(RUN) ./$(PROG) $(ARGS)
$(PROG): $(SOURCES) Makefile
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
csr: FORCE
openssl ecparam -noout -name prime256v1 -genkey -out key.pem
openssl req -new -key key.pem -subj /CN=Mongoose -out crt.csr
mongoose_fs.c: ca.pem crt.pem key.pem
node ../../../test/pack.js ca.pem crt.pem key.pem > $@
clean:
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
# For automated test purposes only
example: FORCE
touch mongoose_fs.c
FORCE:
@@ -1,2 +0,0 @@
- This example requires generating AWS and user credentials and downloading certificates
- This example requires building with TLS support; before running, see detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-client-aws-iot/
-102
View File
@@ -1,102 +0,0 @@
// Copyright (c) 2020 Cesanta Software Limited
// All rights reserved
//
// Example MQTT client. It performs the following steps:
// 1. Connects to the AWS IoT MQTT server
// 2. When connected, subscribes to the topic `s_rx_topic`
// 3. Publishes message `hello` to the `s_tx_topic` periodically
//
// How to build and run this example:
// 1. Login to AWS IoT
// 2. Click "Settings" on the left bar, copy the domain, change s_url below
// 3. Click Security -> Policies -> Create Policy, fill fields:
// Name : PolicyAllow
// Action : iot:*
// Resource ARN: *
// Effect : allow
// then, click "Create"
// 4. Create EC private key file and CSR (Certificate Signing Request)
// type "make csr", see Makefile
// 5. Click Security -> Certificates -> Add Certificate -> Create Certificate
// Choose "Create certificate with certificate signing request (CSR)"
// Choose "crt.csr" created on a previous step
// Choose "Active" to activate certificate
// Click Create
// Attach PolicyAllow policy to the created certificate
// Downoad AmazonRootCA1.pem as ca.pem and generated certificate as crt.pem
// Select certificate, attach PolicyAllow to it
// 6. Type "make" to build and run the example
static const char *s_url =
"mqtts://a1pjwh2bop1ojt-ats.iot.eu-west-1.amazonaws.com";
static const char *s_rx_topic = "d/rx";
static const char *s_tx_topic = "d/tx";
static int s_qos = 1;
#include "mongoose.h"
static void fn(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_OPEN) {
// c->is_hexdumping = 1;
} else if (ev == MG_EV_CONNECT) {
if (c->is_tls) {
struct mg_tls_opts opts = {.ca = mg_unpacked("/ca.pem"),
.cert = mg_unpacked("/crt.pem"),
.key = mg_unpacked("/key.pem"),
.name = mg_url_host(s_url)};
mg_tls_init(c, &opts);
}
} else if (ev == MG_EV_ERROR) {
// On error, log error message
MG_ERROR(("%p %s", c->fd, (char *) ev_data));
} else if (ev == MG_EV_MQTT_OPEN) {
// MQTT connect is successful
struct mg_str topic = mg_str(s_rx_topic);
MG_INFO(("Connected to %s", s_url));
MG_INFO(("Subscribing to %s", s_rx_topic));
struct mg_mqtt_opts sub_opts;
memset(&sub_opts, 0, sizeof(sub_opts));
sub_opts.topic = topic;
sub_opts.qos = s_qos;
mg_mqtt_sub(c, &sub_opts);
c->data[0] = 'X'; // Set a label that we're logged in
} else if (ev == MG_EV_MQTT_MSG) {
// When we receive MQTT message, print it
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
MG_INFO(("Received on %.*s : %.*s", (int) mm->topic.len, mm->topic.buf,
(int) mm->data.len, mm->data.buf));
} else if (ev == MG_EV_POLL && c->data[0] == 'X') {
static unsigned long prev_second;
unsigned long now_second = (*(unsigned long *) ev_data) / 1000;
if (now_second != prev_second) {
struct mg_str topic = mg_str(s_tx_topic), data = mg_str("{\"a\":123}");
MG_INFO(("Publishing to %s", s_tx_topic));
struct mg_mqtt_opts pub_opts;
memset(&pub_opts, 0, sizeof(pub_opts));
pub_opts.topic = topic;
pub_opts.message = data;
pub_opts.qos = s_qos, pub_opts.retain = false;
mg_mqtt_pub(c, &pub_opts);
prev_second = now_second;
}
}
if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE) {
MG_INFO(("Got event %d, stopping...", ev));
*(bool *) c->fn_data = true; // Signal that we're done
}
}
int main(void) {
struct mg_mgr mgr;
struct mg_mqtt_opts opts = {.clean = true};
bool done = false;
mg_log_set(MG_LL_DEBUG);
mg_mgr_init(&mgr); // Initialise event manager
MG_INFO(("Connecting to %s", s_url)); // Inform that we're starting
mg_mqtt_connect(&mgr, s_url, &opts, fn, &done); // Create client connection
while (!done) mg_mgr_poll(&mgr, 1000); // Loop until done
mg_mgr_free(&mgr); // Finished, cleanup
return 0;
}
@@ -17,9 +17,6 @@ static void blink_task(void) {
} }
} }
uint64_t mg_millis(void) {
return hal_get_tick();
}
bool mg_random(void *buf, size_t len) { bool mg_random(void *buf, size_t len) {
for (size_t n = 0; n < len; n += sizeof(uint32_t)) { for (size_t n = 0; n < len; n += sizeof(uint32_t)) {
@@ -4,7 +4,7 @@
#define MG_ENABLE_TCPIP 1 #define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_NRF52 1 #define MG_ENABLE_DRIVER_NRF52 1
#define MG_ENABLE_TCPIP_TCPRTX 1 #define MG_ENABLE_TCPIP_TCPRTX 1
#define MG_ENABLE_CUSTOM_MILLIS 1 #define MG_ENABLE_CUSTOM_MICROS 1
#define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_TLS MG_TLS_BUILTIN #define MG_TLS MG_TLS_BUILTIN
#define MQTT_CLIENT_ID "xiao-nrf52840" #define MQTT_CLIENT_ID "xiao-nrf52840"
-3
View File
@@ -25,9 +25,6 @@ static void blink_task(void) {
} }
} }
uint64_t mg_millis(void) {
return hal_get_tick();
}
bool mg_random(void *buf, size_t len) { bool mg_random(void *buf, size_t len) {
for (size_t n = 0; n < len; n += sizeof(uint32_t)) { for (size_t n = 0; n < len; n += sizeof(uint32_t)) {
@@ -9,7 +9,7 @@
#define MG_ENABLE_TCPIP 1 #define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_MCXW71 1 #define MG_ENABLE_DRIVER_MCXW71 1
#define MG_ENABLE_CUSTOM_MILLIS 1 #define MG_ENABLE_CUSTOM_MICROS 1
#define MG_ENABLE_CUSTOM_RANDOM 1 #define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_ENABLE_TCPIP_TCPRTX 1 // Link can be lossy, enable retransmit #define MG_ENABLE_TCPIP_TCPRTX 1 // Link can be lossy, enable retransmit
@@ -43,9 +43,6 @@ static void log_fn(char ch, void *arg) {
hal_uart_write_buf(arg, &ch, 1); hal_uart_write_buf(arg, &ch, 1);
} }
uint64_t mg_millis(void) {
return hal_get_tick();
}
int main(void) { int main(void) {
static struct mg_tcpip_driver_rw612_data eth_data; static struct mg_tcpip_driver_rw612_data eth_data;
@@ -6,7 +6,7 @@
#define MG_ENABLE_TCPIP 1 #define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_RW612 1 // Ethernet #define MG_ENABLE_DRIVER_RW612 1 // Ethernet
#define MG_ENABLE_DRIVER_RW612W 1 // Mesh bridge over raw 802.15.4 #define MG_ENABLE_DRIVER_RW612W 1 // Mesh bridge over raw 802.15.4
#define MG_ENABLE_CUSTOM_MILLIS 1 #define MG_ENABLE_CUSTOM_MICROS 1
// The bridge initializes and polls its two L2 interfaces directly. // The bridge initializes and polls its two L2 interfaces directly.
@@ -15,6 +15,7 @@ CFLAGS += -mcpu=cortex-m33+nodsp -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16 $(CF
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lgcc -Wl,--gc-sections LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lgcc -Wl,--gc-sections
SOURCES = main.c hal.c startup.c flexspi.c flash_config.c $(MGDIR)/mongoose.c SOURCES = main.c hal.c startup.c flexspi.c flash_config.c $(MGDIR)/mongoose.c
SOURCES += $(MGDIR)/tutorials/mqtt/mqtt-client/mongoose_mqtt.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_clock.c SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_clock.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_trng.c SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_trng.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_reset.c SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_reset.c
@@ -44,5 +45,8 @@ flash: firmware.bin
(echo 'loadfile firmware.elf'; echo 'reset'; echo 'exit';) | JLinkExe -device RW612 -if SWD -speed 4000 -autoconnect 1 -NoGui 1 -ExitOnError 1 (echo 'loadfile firmware.elf'; echo 'reset'; echo 'exit';) | JLinkExe -device RW612 -if SWD -speed 4000 -autoconnect 1 -NoGui 1 -ExitOnError 1
# JRun --nogui --device RW612 --if SWD firmware.elf # JRun --nogui --device RW612 --if SWD firmware.elf
erase:
(echo halt && echo exec EnableEraseAllFlashBanks && echo erase && echo exit) | JLinkExe -device RW612 -if SWD -speed 4000 -autoconnect 1 -NoGui 1 -ExitOnError 1
clean: clean:
rm -rf firmware.* cmsis_* mongoose/mongoose.* rm -rf firmware.* cmsis_* mongoose/mongoose.*
+2
View File
@@ -104,6 +104,7 @@ int main(void) {
// Start a minimal web server // Start a minimal web server
struct mg_mgr mgr; struct mg_mgr mgr;
mg_mgr_init(&mgr); mg_mgr_init(&mgr);
mg_mqtt_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL); 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_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL);
@@ -113,6 +114,7 @@ int main(void) {
for (;;) { for (;;) {
mg_mgr_poll(&mgr, 0); mg_mgr_poll(&mgr, 0);
mg_mqtt_poll(&mgr);
blink_task(); blink_task();
} }
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more