Compare commits

..
211 Commits
Author SHA1 Message Date
cpq 76fbf3c713 BLE radio support 2026-11-25 13:58:07 +00:00
cpq a8d6573ccc Add USB NCM drivers 2026-11-25 13:31:12 +00:00
Sergio R. Caprile bae9e53f00 Merge pull request #3793 from cesanta/unamalgamated-rest
Fix unamalgamation for the rest of the drivers
2026-11-24 13:22:57 -03:00
robert 9f4e6a25bd Fix unamalgamation for the rest of the drivers 2026-11-24 17:08:44 +02:00
Sergio R. Caprile 4f5997a8b4 silence Clang 2026-11-24 10:49:58 -03:00
Sergio R. Caprile 542f7b6c2f Merge pull request #3792 from cesanta/unamalgamated
Make unamalgamated builds work on STM32
2026-11-24 10:34:00 -03:00
robert 65a6582d96 Make unamalgamated builds work on STM32 2026-11-24 14:18:10 +02:00
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 069ab78c02 Merge pull request #3784 from cesanta/picosdk
update to Pico-SDK 2.2.0 (to be able to build with GCC 15)
2026-11-18 13:52:53 -03:00
Sergio R. Caprile 91b87a6bd8 update version 2026-11-18 10:05:47 -03:00
Sergio R. Caprile 1ce7e416b0 update to Pico-SDK 2.2.0 (to be able to build with GCC 15) 2026-11-17 17:43:44 -03: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
robert 49e71ba666 Update Claude models 2026-11-16 16:26:11 +02:00
robert 166c1a7708 update partitions 2026-11-16 12:06:35 +02:00
robert 2ef7f7a44a Increase partition size on ESP32 2026-11-16 10:46:06 +02:00
cpq e7335e063b Update readme & dash html 2026-11-15 12:39:48 +00:00
cpq 88096d3f4d Update graph1 2026-11-15 12:16:49 +00:00
cpq 1b9177ae64 Update READMEs 2026-11-15 07:58:33 +00:00
Sergio R. Caprile 053b8ed824 Merge pull request #3777 from cesanta/nocnfb
Correct #3775 CN fallback handling
2026-11-13 11:42:42 -03:00
Sergio R. Caprile 2ea1cf6817 Correct #3775 CN fallback handling 2026-11-13 11:42:13 -03:00
Sergio R. Caprile 323326ce8b Merge pull request #3778 from cesanta/pad
make padding stricter
2026-11-13 11:41:14 -03:00
Sergio R. Caprile c5344af9fc make padding stricter 2026-11-13 11:04:01 -03:00
Sergio R. Caprile d73b009bbc unbreak test 2026-11-13 09:53:19 -03:00
cpq dba6479b23 Update Agents 2026-11-13 12:23:35 +00:00
cpq 28ca01eb2b Update Agents 2026-11-13 12:10:05 +00:00
cpq e999239ca7 Add guidance for the AI engines inside mongoose.h 2026-11-13 11:57:04 +00:00
Sergio R. Caprile d545526ba2 unbreak test 2026-11-12 15:56:25 -03:00
Sergio R. Caprile 0b888e8f3f Merge pull request #3776 from cesanta/embnul
reject embedded NULs in paths
2026-11-12 15:42:18 -03:00
Sergio R. Caprile 27a87dee8b reject embedded NULs in paths 2026-11-12 14:24:46 -03:00
Sergio R. Caprile 94ccc4a130 Merge pull request #3775 from cesanta/nocnfb
do not fallback to CN after SAN
2026-11-12 13:59:16 -03:00
Sergio R. Caprile 454bf4036f do not fallback to CN after SAN 2026-11-12 13:53:51 -03:00
robertc2000 c835c72202 Merge pull request #3774 from cesanta/rpc
Validate RPC buffer
2026-11-12 17:50:41 +02:00
robert 52ebac833f Validate RPC buffer 2026-11-12 17:46:04 +02:00
Sergio R. Caprile 5f1aaa21eb Merge pull request #3772 from cesanta/farewellsymlinks
Remove symlinks
2026-11-12 12:05:09 -03:00
Sergio R. Caprile 1c3a7a89dd Merge pull request #3773 from cesanta/ws
Remove unnecessary Websocket sent frame
2026-11-12 12:01:00 -03:00
robert d7a4130905 Remove unncessary Websocket sent frame 2026-11-12 16:43:51 +02:00
Sergio R. Caprile 5b0675584c Remove symlinks 2026-11-12 10:59:35 -03:00
Sergio R. Caprile 21b998c882 Merge pull request #3771 from cesanta/mg_match
Improve mg_match checks
2026-11-12 10:35:30 -03:00
robert 2cab36e882 Improve mg_match checks 2026-11-12 13:43:48 +02:00
Sergio R. Caprile 3a4f044e41 nitpicks 2026-11-11 17:51:49 -03:00
Sergio R. Caprile d47cfa183d unbreak test 2026-11-10 17:42:53 -03:00
Sergio R. Caprile 0905b93b97 Merge pull request #3769 from cesanta/nocaquit
close connection on bad CA or missing server cert for builtin TLS
2026-11-10 17:12:38 -03:00
Sergio R. Caprile 65d15bb002 close connection on bad CA or missing server cert for builtin TLS 2026-11-10 17:11:46 -03:00
Sergio R. Caprile c77e578a19 Merge pull request #3768 from cesanta/mbedfail
correctly close connection on mg_tls_init() failure for MbedTLS
2026-11-10 15:58:02 -03:00
Sergio R. Caprile 080159a50e correctly close connection on mg_tls_init() failure for MbedTLS 2026-11-10 15:01:36 -03:00
Sergio R. Caprile 25294a5ecc Merge pull request #3767 from cesanta/pad
make padding strict
2026-11-10 14:17:30 -03:00
Sergio R. Caprile 9e9693db6f make padding strict 2026-11-10 12:51:25 -03:00
cpq b47bd89cbd Increase app part size 2026-11-10 14:30:39 +00:00
Sergio R. Caprile 49cd3153ce Merge pull request #3766 from cesanta/frag
tighten IP fragment behavior
2026-11-10 11:30:09 -03:00
Sergio R. Caprile c1f8dafc72 silence some compilers 2026-11-10 11:27:10 -03:00
Sergio R. Caprile 7d77d8f3d7 silence some compilers 2026-11-10 11:26:36 -03:00
Sergio R. Caprile 0ec2a0252b tighten IP fragment behavior 2026-11-10 11:07:19 -03:00
Sergey Lyubka c01a1b613f Merge pull request #3761 from cesanta/ms
Flatten mem stats
2026-11-10 13:25:39 +00:00
Sergio R. Caprile 73950e863a Merge pull request #3765 from cesanta/del
Enforce DELETE request
2026-11-10 09:16:02 -03:00
robert b4ca50b3c6 Enforce DELETE request 2026-11-10 13:52:12 +02:00
cpq 069024b41c Flatten mem stats 2026-11-10 11:21:36 +00:00
Sergio R. Caprile 706f4787e2 fix unbalanced allocator set 2026-11-09 17:25:56 -03:00
Sergio R. Caprile 4d8831f2b6 unbreak VC98 weird 64-bit handling 2026-11-09 14:31:17 -03:00
Sergio R. Caprile 5b6c08acfb unbreak VC98 weird 64-bit handling 2026-11-09 12:00:04 -03:00
Sergio R. Caprile 528be76a23 unbreak tests against cesanta.com 2026-11-09 11:40:26 -03:00
Sergio R. Caprile b6ba6a56d9 Merge commit from fork
avoid cross IP version feeds
2026-11-09 11:18:41 -03:00
Sergio R. Caprile 1efc211a51 Merge commit from fork
change mg_tls_verify_cert_signature() to boolean and enforce consistent return values
2026-11-09 11:16:01 -03:00
Sergio R. Caprile ca5ca3403c change mg_tls_verify_cert_signature() to boolean and enforce consistent return values 2026-11-09 11:12:30 -03:00
Sergio R. Caprile 7a86c401b9 Merge commit from fork
fix checks
2026-11-09 11:04:19 -03:00
Sergio R. Caprile 52cc8ef1d3 Merge commit from fork
honor WS mask
2026-11-09 10:58:29 -03:00
Sergio R. Caprile b975a8e761 Merge commit from fork
honor parse and next return values
2026-11-09 10:55:39 -03:00
Sergio R. Caprile 2d7e44201d honor parse and next return values 2026-11-09 10:53:05 -03:00
Sergio R. Caprile b415c23bc5 Merge commit from fork
fix ws data length handling
2026-11-09 10:12:25 -03:00
Sergio R. Caprile cba6c4f8df Merge commit from fork
add safety checks for month
2026-11-09 10:06:41 -03:00
Sergio R. Caprile 9d6d064b39 Merge commit from fork
Check header table bounds
2026-11-09 09:56:57 -03:00
cpq de037d6ef9 calloc -> mg_calloc 2026-11-06 19:58:46 +00:00
Sergey Lyubka e7c8aa017d Merge pull request #3747 from cesanta/memory-report
Add heap/stack reporting for mdash
2026-11-06 19:42:11 +00:00
Sergio R. Caprile fe8ebced03 more tightness and nitpicks 2026-11-06 15:52:03 -03:00
Sergio R. Caprile 62cd82df81 Merge pull request #3760 from cesanta/rtx
improve RTX tests for coverage and resiliency
2026-11-06 14:58:29 -03:00
Sergio R. Caprile e2408a2cfc improve RTX tests for coverage and resiliency 2026-11-06 14:28:23 -03:00
robert da33868409 Add memory stats reporting for mdash with FreeRTOS example for H723 2026-11-06 17:33:28 +02:00
Sergio R. Caprile aaf202ba2f Merge pull request #3759 from cesanta/tlstight
misc tightening and cleanup
2026-11-06 09:54:17 -03:00
Sergio R. Caprile 5c7b7b68bc misc tightening and cleanup 2026-11-06 09:51:41 -03:00
Sergio R. Caprile 28f88f016c Merge pull request #3758 from cesanta/4861
be more RFC4861 6.1.2 friendly
2026-11-06 09:47:15 -03:00
Sergio R. Caprile e8bb01b547 per family close on IP change 2026-11-06 09:37:02 -03:00
Sergio R. Caprile 324f59abc5 Merge pull request #3744 from cesanta/hcd
Add coredump RPC method
2026-11-06 07:34:38 +00:00
Sergey Lyubka 3eb33ab349 Merge pull request #3757 from cesanta/m3
Add radio simulation
2026-11-06 07:33:27 +00:00
Sergio R. Caprile 66eb0384be be more RFC4861 6.1.2 friendly 2026-11-05 19:54:31 -03:00
Sergio R. Caprile 1f276ba70a add coredump RPC 2026-11-05 19:49:07 -03:00
Sergio R. Caprile 1a9bc9d3f3 Merge pull request #3742 from cesanta/hesp
Integrate ESP32 health support
2026-11-05 22:34:20 +00:00
cpq d39519b92f Add radio simulation 2026-11-05 22:23:06 +00:00
Sergio R. Caprile 3e11429cac workaround Pico-SDK 2.1.1 vs GCC15 2026-11-05 16:18:45 -03:00
Sergio R. Caprile 9337a78cd0 unbreak BSD on some systems 2026-11-05 11:44:27 -03:00
Sergio R. Caprile d99cc0959b workaround Pico-SDK 2.1.1 vs GCC15 2026-11-05 11:30:23 -03:00
Sergio R. Caprile 02b5504e60 Merge pull request #3756 from cesanta/trasher
fix Docker breaking Win32
2026-11-04 17:15:50 -03:00
Sergio R. Caprile 822c6a9489 fix GCC15 2026-11-04 16:41:04 -03:00
Sergio R. Caprile 03c022080f fix Docker breaking Win32 2026-11-04 16:02:10 -03:00
Sergey Lyubka 84198c7e70 Merge pull request #3753 from cesanta/mesh
Add skeleton for the radio mesh simulator
2026-11-04 18:09:10 +00:00
Sergio R. Caprile f3d531938c Merge pull request #3754 from cesanta/bsdmin
Add missing BSD functions
2026-11-04 14:56:58 -03:00
Sergio R. Caprile b6975ab08f pin Ubuntu runners during migration 2026-11-04 14:56:11 -03:00
Sergio R. Caprile 66afa5e551 Add missing BSD functions 2026-11-04 13:35:49 -03:00
Sergio R. Caprile fc79fd0be5 avoid cross IP version feeds 2026-11-03 10:59:34 -03:00
Sergey Lyubka 7886a73807 Merge pull request #3749 from cesanta/defuri
harden root_dir
2026-11-02 12:42:29 +00:00
Sergey Lyubka ccc953318a Merge pull request #3750 from cesanta/strpres
survive to width.precision screw ups in %s
2026-11-02 12:41:05 +00:00
cpq 684ae27dc2 Add udp echo server to tutorials/stm32/nucleo-h723zg/minimal-bsd-baremetal 2026-11-02 12:30:23 +00:00
cpq fc71bc0588 Add skeleton for the radio mesh simulator 2026-11-01 11:05:59 +00:00
Sergey Lyubka 08305b9000 Merge pull request #3751 from cesanta/dhcp
Fix: DHCP client stuck in REQUESTING state forever if the REQUEST or ACK is lost
2026-10-30 12:43:26 +00:00
cpq 69e8c0a92f Fix: DHCP client stuck in REQUESTING state forever if the REQUEST or ACK is lost 2026-10-30 09:42:12 +00:00
Sergio R. Caprile 8eceacc0d3 survive to width.precision screw ups in %s 2026-10-27 17:30:26 -03:00
Sergio R. Caprile b6df410570 Integrate ESP32 health support 2026-10-27 11:32:36 -03:00
Sergio R. Caprile 26b971b4a8 harden root_dir 2026-10-27 11:09:08 -03:00
Sergio R. Caprile b766c65615 avoid 802.15.4 using a standard BSD function name, enable BSD test after mg_error() fix 2026-10-23 14:00:24 -03:00
cpq 8296b88fb6 Update readme 2026-10-23 15:21:10 +01:00
Sergio R. Caprile a5efbf0592 misc cleanups and standardizations 2026-10-22 16:53:56 -03:00
Sergio R. Caprile 37c98dd893 mg_delay_ms() survives mg_millis() restarting on some 32-bit platforms 2026-10-22 13:49:21 -03:00
cpq 770a4ff27e Sync description 2026-10-22 17:21:05 +01:00
Sergio R. Caprile b6560306ba avoid reconnect timer being disrupted by possible SNTP updates 2026-10-22 12:12:27 -03:00
Sergio R. Caprile 5b39c93478 Merge pull request #3746 from cesanta/ota
Make mg_http_ota_cb public, add /ota endpoints to MCU examples
2026-10-22 11:30:35 -03:00
cpq 086008b716 Nit 2026-10-22 14:55:19 +01:00
cpq 35eb50a1e6 Nit 2026-10-22 14:46:19 +01:00
cpq 431e35ae8c Update README 2026-10-22 14:44:50 +01:00
cpq 25e2a99d8e Make mg_http_ota_cb public, add /ota endpoints to MCU examples 2026-10-22 14:30:10 +01:00
cpq 88b01ef6f0 Add security.md 2026-10-21 11:48:41 +01:00
cpq bd8ee86f9e Cube pack 7.23.3 2026-10-21 11:33:05 +01:00
Sergey Lyubka ef96f7a28c Merge pull request #3741 from cesanta/w71_2
Ethernet + IPv4 over 802.15.4 + bridge, mcxw71 and rw612
2026-10-21 10:22:43 +01:00
Sergey Lyubka 03f240a244 Merge pull request #3743 from cesanta/c5
Add nucleo-c5a3zg
2026-10-21 10:21:25 +01:00
cpq c775f31ca7 Add nucleo-c5a3zg 2026-10-21 10:16:02 +01:00
cpq 1ca4fd1fef Add frdm-mcxw71 support 2026-10-20 21:48:34 +01:00
Sergio R. Caprile 22a94c0906 fix checks 2026-10-19 11:48:51 -03:00
cpq a6b6a0d779 Add frdm-mcxw71 support 2026-10-19 14:10:48 +01:00
cpq 38c326644f Add params for MX2 2026-10-19 14:10:23 +01:00
cpq e6e7a690a7 New Cube pack 2026-10-19 14:06:49 +01:00
cpq c76f092ba1 Change build env reference 2026-10-17 16:04:45 +01:00
Sergio R. Caprile 60840d0d89 Merge pull request #3739 from cesanta/post3732
make TLS error reporting consistent
2026-10-16 17:07:13 -03:00
Sergio R. Caprile 298ee549da make error reporting consistent 2026-10-16 15:59:20 -03:00
Sergio R. Caprile 5e4ae64e1b Merge pull request #3738 from cesanta/iserror
Misc fixes and regression unbreaks
2026-10-16 14:56:40 -03:00
Sergio R. Caprile c5778aa608 Misc fixes and regression unbreaks 2026-10-16 13:51:58 -03:00
Sergio R. Caprile 6d32a7c238 Merge pull request #3736 from cesanta/esp8266
Remove esp8266 support
2026-10-15 17:49:50 -03:00
cpq 497a3f5e73 Remove esp8266 support 2026-10-15 21:14:31 +01:00
Sergey Lyubka 10e67fdf2b Merge pull request #3734 from cesanta/esp32
Add TLS and health backtrace to esp32
2026-10-15 21:05:47 +01:00
cpq 2f2a5f2f02 Add TLS and health backtrace to esp32 2026-10-15 20:57:10 +01:00
Sergio R. Caprile aa21ed443a Merge pull request #3735 from cesanta/bsd
fix new bsd test
2026-10-15 14:43:33 -03:00
Sergio R. Caprile 10adde595c fix new bsd test 2026-10-15 14:39:37 -03:00
Sergey Lyubka c957f29f23 Merge pull request #3732 from cesanta/tls_p256
Drop x25519, use p256 only
2026-10-15 15:23:56 +01:00
cpq 37f3ed5ba4 Drop x25519, use p256 only 2026-10-15 13:36:24 +01:00
cpq b68da1548b Restore logging, make WiFi creds settable from make 2026-10-15 12:03:04 +01:00
novlean a9a94a6904 Merge pull request #3733 from cesanta/novlean-patch-1
Add new articles to README links section
2026-10-14 15:36:45 +02:00
novlean 3a4660cd40 Add new articles to README links section 2026-10-14 15:36:25 +02:00
Sergey Lyubka fc478a70f7 Merge pull request #3700 from cesanta/bsd
Reimplement BSD layer
2026-10-14 11:30:26 +01:00
Sergio R. Caprile a6b5565e9d Merge pull request #3727 from cesanta/mgerror
correctly close TCP on mg_error()
2026-10-13 12:04:15 -03:00
Sergio R. Caprile e7113408a9 correctly close TCP on mg_error() 2026-10-13 12:00:20 -03:00
Sergio R. Caprile fdf12844e3 Reimplement BSD layer 2026-10-12 18:09:41 -03:00
Sergio R. Caprile bc5afa4519 Merge pull request #3731 from cesanta/iserror
close connection besides logging, when gateway is down
2026-10-12 17:52:09 -03:00
Sergio R. Caprile a4607933a4 close connection besides logging, when gateway is down 2026-10-12 17:47:25 -03:00
cpq fd7db76324 Fix clean target 2026-10-11 09:17:16 +01:00
Sergey Lyubka b1e6cb320f Merge pull request #3729 from cesanta/unify
Unify bare metal projects
2026-10-11 09:09:42 +01:00
cpq 2b9d805d84 Unify bare metal projects 2026-10-11 08:42:00 +01:00
Sergey Lyubka a9a843d6e2 Merge pull request #3728 from cesanta/min
Minimise build size
2026-10-11 03:17:29 +01:00
cpq aae179177c Minimise build size 2026-10-10 12:25:44 +01:00
Sergio R. Caprile f347dbf2b5 honor WS mask 2026-10-09 11:58:25 -03:00
robertc2000 300011a882 Merge pull request #3726 from cesanta/h5
Add H5 and H7 to health monitor
2026-10-09 09:40:31 +03:00
cpq eda9a5726c Add H5 and H7 to health monitor 2026-10-08 15:15:11 +01:00
Sergey Lyubka 16a5a7d9fb Merge pull request #3712 from jnnrgd/feat/mqtt5-connack-props
mqtt: parse properties in MQTT 5.0 CONNACK packets
2026-10-08 04:37:45 +01:00
Sergey Lyubka 69c3bb8d12 Merge pull request #3725 from cesanta/protoclean
move embedded tutorials out of protocol tree
2026-10-08 04:33:52 +01:00
Sergio R. Caprile 8fc5651044 move embedded tutorials out of protocol tree 2026-10-07 16:10:28 -03:00
Sergio R. Caprile 338756d0b0 Merge pull request #3724 from cesanta/tls
Fix RSA signing
2026-10-07 11:37:25 -03:00
cpq c30afffcee Fix RSA signing 2026-10-07 11:36:37 -03:00
cpq 76c0953210 Update readme 2026-10-07 10:13:23 +01:00
Sergio R. Caprile 381e31198b Merge pull request #3722 from cesanta/fixmdashenable
fix mdash enablement trashing tests
2026-10-06 12:40:58 -03:00
Sergio R. Caprile 28ba381bd9 fix mdash enablement trashing tests 2026-10-06 12:24:19 -03:00
cpq 567963b034 Nit in mqtt example 2026-10-06 15:41:31 +01:00
Sergio R. Caprile 7d3fe4f9cb Merge pull request #3721 from cesanta/tls
Built-in TLS: accept a chain that contains the configured CA
2026-10-06 08:58:36 -03:00
cpq c8bf39dcd8 Built-in TLS: accept a chain that contains the configured CA 2026-10-06 12:41:25 +01:00
cpq 393c811f31 Fixed cert emptiness check 2026-10-06 12:33:02 +01:00
robert be40827e17 Add links for STM32 cubemx projects 2026-10-06 12:32:46 +03:00
cpq ad45248327 Fix URL 2026-10-05 18:20:28 +01:00
cpq c2d95cc19b Nit 2026-10-05 14:00:38 +01:00
cpq 4aa0a243f9 Nit 2026-10-05 13:17:46 +01:00
cpq 65a7996ef9 nit 2026-10-05 12:59:23 +01:00
Sergey Lyubka 5879c3cbf2 Merge pull request #3719 from cesanta/azure
Add support for MS Azure MQTT
2026-10-05 12:43:41 +01:00
cpq cf9d56be79 Add support for MS Azure MQTT 2026-10-05 12:41:56 +01:00
cpq da82df2041 Add firmware.signed.bin target 2026-10-03 16:50:02 +01:00
Sergey Lyubka 954eb07b6d Merge pull request #3718 from cesanta/cr
Move crash handler to src/health.c
2026-10-02 13:00:56 +01:00
cpq d7e708b9bc Move crash handler to src/health.c 2026-10-02 12:47:05 +01:00
robertc2000 ce35cbf586 Merge pull request #3716 from cesanta/crash
Print crash record optionally
2026-10-01 14:48:36 +03:00
cpq 3aa5f2a1fd Print crash record optionally 2026-10-01 14:42:16 +03:00
cpq 1b0906510b Rename MG_OTA_FIRMWARE_VERSION -> MG_FIRMWARE_VERSION, rw612 nits 2026-10-01 10:10:42 +01:00
Sergey Lyubka 8a116d9289 Merge pull request #3715 from cesanta/is_resp
Remove c->is_resp, keep it private to http.c
2026-10-01 08:25:38 +01:00
cpq 71e0176944 Remove c->is_resp, keep it private to http.c 2026-09-30 15:12:54 +01:00
jnnrgd 1f2b14bb66 mqtt: parse properties in MQTT 5.0 CONNACK packets
Under MQTT 5.0, decode the property length and set props_start and
props_size for MQTT_CMD_CONNACK. Add unit test coverage.
2026-09-30 10:51:41 +02:00
Sergio R. Caprile 39a3478429 fix ws data length handling 2026-09-02 16:28:35 -03:00
Sergio R. Caprile 7fccc2b75f add safety checks for month 2026-09-02 12:51:31 -03:00
robert 07e580d956 Check header table bounds 2026-08-21 15:07:11 +03:00
925 changed files with 292310 additions and 39454 deletions

No files matched your search

@@ -211,7 +211,7 @@ jobs:
claude_args: | claude_args: |
--allowedTools "Read,Glob,Grep,Bash(git:*),Bash(find:*),Bash(grep:*),Bash(sed:*),Bash(cat:*)" --allowedTools "Read,Glob,Grep,Bash(git:*),Bash(find:*),Bash(grep:*),Bash(sed:*),Bash(cat:*)"
--model claude-opus-5 --model claude-opus-5-5
- name: Prepare private security scan outputs - name: Prepare private security scan outputs
if: always() && steps.claude_scan.outputs.execution_file != '' if: always() && steps.claude_scan.outputs.execution_file != ''
@@ -108,4 +108,4 @@ jobs:
claude_args: | claude_args: |
--allowedTools "Read,Bash(cat:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr comment:*)" --allowedTools "Read,Bash(cat:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr comment:*)"
--model claude-opus-5 --model claude-opus-5-5
+42 -39
View File
@@ -53,7 +53,7 @@ jobs:
scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/linux_${{ matrix.target }}_${{ matrix.cc }}_${{ matrix.ssl }}_${{ matrix.select }}_$(date +"%Y%m%d").json" scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/linux_${{ matrix.target }}_${{ matrix.cc }}_${{ matrix.ssl }}_${{ matrix.select }}_$(date +"%Y%m%d").json"
c89: c89:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -137,7 +137,7 @@ jobs:
make -C test mip_tap_test make -C test mip_tap_test
mip89: mip89:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -149,7 +149,7 @@ jobs:
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test ${{ matrix.target }} IPV6=${{ matrix.ipv6 }} - run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test ${{ matrix.target }} IPV6=${{ matrix.ipv6 }}
mipbe: mipbe:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -165,10 +165,10 @@ jobs:
- run: | - run: |
sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
if [[ "${{ matrix.target }}" == *port* ]]; then source ./test/setup_ga_network.sh ; export ENV="-e Tmp=. -e WINEDEBUG=-all -e HOST_IP -e HOST_IPV6 -e HOST_IFC" ; sed -i -e "s/127.0.0.1//" test/mosquitto.conf; cat test/mosquitto.conf; ./test/setup_mqtt_server.sh ; make -C test port_tap_bridge ; test/port_tap_bridge & sleep 2 ; fi if [[ "${{ matrix.target }}" == *port* ]]; then source ./test/setup_ga_network.sh ; export ENV="-e Tmp=. -e WINEDEBUG=-all -e HOST_IP -e HOST_IPV6 -e HOST_IFC" ; sed -i -e "s/127.0.0.1//" test/mosquitto.conf; cat test/mosquitto.conf; ./test/setup_mqtt_server.sh ; make -C test port_tap_bridge ; test/port_tap_bridge & sleep 2 ; fi
make -C test ${{ matrix.target }} IPV6=${{ matrix.ipv6 }} SSL=${{ matrix.ssl }} MULTIREC=NO make -C test ${{ matrix.target }} IPV6=${{ matrix.ipv6 }} SSL=${{ matrix.ssl }}
miprtxbe: miprtxbe:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
name: MIP RTX be s390 port name: MIP RTX be s390 port
env: env:
IPV6: 0 IPV6: 0
@@ -180,7 +180,7 @@ jobs:
- run: | - run: |
sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
source ./test/setup_ga_network.sh ; export ENV="-e Tmp=. -e WINEDEBUG=-all -e HOST_IP -e HOST_IPV6 -e HOST_IFC -e RTX" ; sed -i -e "s/127.0.0.1//" test/mosquitto.conf ; ./test/setup_mqtt_server.sh ; make -C test port_tap_bridge ; test/port_tap_bridge & sleep 2 source ./test/setup_ga_network.sh ; export ENV="-e Tmp=. -e WINEDEBUG=-all -e HOST_IP -e HOST_IPV6 -e HOST_IFC -e RTX" ; sed -i -e "s/127.0.0.1//" test/mosquitto.conf ; ./test/setup_mqtt_server.sh ; make -C test port_tap_bridge ; test/port_tap_bridge & sleep 2
make -C test mip_port_s390 MULTIREC=NO make -C test mip_port_s390
l2: l2:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -204,7 +204,7 @@ jobs:
test/health.awk < log > json test/health.awk < log > json
scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/${{ matrix.target }}_${{ matrix.cc }}_${{ matrix.ipv6 }}_$(date +"%Y%m%d").json" scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/${{ matrix.target }}_${{ matrix.cc }}_${{ matrix.ipv6 }}_$(date +"%Y%m%d").json"
l289: l289:
runs-on: ubuntu-latest runs-on: ubuntu-24.04 # Ubuntu 26.04 Docker 29.4.2 breaks 32-bit Wine; switch at >= 29.4.3
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -216,7 +216,7 @@ jobs:
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: make -C test ${{ matrix.target }} IPV6=${{ matrix.ipv6 }} - run: make -C test ${{ matrix.target }} IPV6=${{ matrix.ipv6 }}
l2be: l2be:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -272,7 +272,7 @@ jobs:
test/health.awk < log > json test/health.awk < log > json
scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/ATcmd_${{ matrix.cc }}_$(date +"%Y%m%d").json" scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/ATcmd_${{ matrix.cc }}_$(date +"%Y%m%d").json"
atcmd89: atcmd89:
runs-on: ubuntu-latest runs-on: ubuntu-24.04 # Ubuntu 26.04 Docker 29.4.2 breaks 32-bit Wine; switch at >= 29.4.3
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -285,7 +285,7 @@ jobs:
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: make -C test ${{ matrix.target }} - run: make -C test ${{ matrix.target }}
atcmdbe: atcmdbe:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -303,6 +303,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
target: [bsd, bsd_nortos]
cc: [gcc, clang, g++, clang++] cc: [gcc, clang, g++, clang++]
name: bsd CC=${{ matrix.cc }} name: bsd CC=${{ matrix.cc }}
steps: steps:
@@ -316,7 +317,7 @@ jobs:
make -C test/bsd shm_tap_bridge make -C test/bsd shm_tap_bridge
test/bsd/shm_tap_bridge & test/bsd/shm_tap_bridge &
sleep 2 sleep 2
make -C test/bsd CC=${{ matrix.cc }} > log make -C test/bsd ${{ matrix.target }} CC=${{ matrix.cc }} > log
- if: success() || failure() - if: success() || failure()
run: | run: |
cat log cat log
@@ -324,7 +325,7 @@ jobs:
scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/bsd_${{ matrix.cc }}_$(date +"%Y%m%d").json" scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/bsd_${{ matrix.cc }}_$(date +"%Y%m%d").json"
bsdbe: bsdbe:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -342,7 +343,7 @@ jobs:
make -C test/bsd ${{ matrix.target }} make -C test/bsd ${{ matrix.target }}
s390: s390:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -353,9 +354,9 @@ jobs:
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && ./test/setup_mqtt_server.sh && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test s390 SSL=${{ matrix.ssl }} MULTIREC=NO - run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && ./test/setup_mqtt_server.sh && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test s390 SSL=${{ matrix.ssl }}
armhf: armhf:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -366,7 +367,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && ./test/setup_mqtt_server.sh && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test armhf SSL=${{ matrix.ssl }} MULTIREC=NO - run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && ./test/setup_mqtt_server.sh && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test armhf SSL=${{ matrix.ssl }}
unamalgamated-mg_prefix: unamalgamated-mg_prefix:
runs-on: ubuntu-latest runs-on: ubuntu-latest
strategy: strategy:
@@ -428,7 +429,7 @@ jobs:
scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/macos_test_cc_${{ matrix.ssl }}_${{ matrix.select }}_$(date +"%Y%m%d").json" scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/macos_test_cc_${{ matrix.ssl }}_${{ matrix.select }}_$(date +"%Y%m%d").json"
windows: windows:
runs-on: ubuntu-latest runs-on: ubuntu-24.04 # Ubuntu 26.04 Docker 29.4.2 breaks 32-bit Wine; switch at >= 29.4.3
strategy: strategy:
fail-fast: false fail-fast: false
max-parallel: 1 # no parallel runs, to minimize MQTT errors max-parallel: 1 # no parallel runs, to minimize MQTT errors
@@ -478,7 +479,7 @@ jobs:
- run: make -C test riscv SSL=${{ matrix.ssl }} - run: make -C test riscv SSL=${{ matrix.ssl }}
tutorials: tutorials:
runs-on: ubuntu-latest runs-on: ubuntu-24.04 # MicroPython v1.22.2 fails with Ubuntu 26.04 GCC 15
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -589,10 +590,12 @@ jobs:
stm32/nucleo-f746zg/minimal stm32/nucleo-f746zg/minimal
stm32/nucleo-f746zg/minimal-pppoe stm32/nucleo-f746zg/minimal-pppoe
stm32/nucleo-f756zg/minimal stm32/nucleo-f756zg/minimal
stm32/nucleo-h563zi/minimal
stm32/nucleo-h723zg/minimal stm32/nucleo-h723zg/minimal
stm32/nucleo-h723zg/minimal-bsd-baremetal
stm32/nucleo-h723zg/minimal-bsd-freertos
- group: stm32-2 - group: stm32-2
examples: | examples: |
stm32/nucleo-h563zi/minimal
stm32/nucleo-h743zi/minimal stm32/nucleo-h743zi/minimal
stm32/nucleo-n657x0-q/minimal stm32/nucleo-n657x0-q/minimal
stm32/nucleo-u5a5zj-q/minimal stm32/nucleo-u5a5zj-q/minimal
@@ -633,8 +636,8 @@ jobs:
matrix: matrix:
example: example:
- path: micropython/esp32 - path: micropython/esp32
- path: http/uart-bridge/esp32 - path: esp32/uart-bridge
- path: http/http-client/esp8266/http-client-server - path: esp32/minimal
name: ${{ matrix.example.path }} name: ${{ matrix.example.path }}
env: env:
GO: 0 GO: 0
@@ -652,7 +655,7 @@ jobs:
include: include:
- group: other - group: other
examples: | examples: |
mqtt/mqtt-client/microchip/same54-xpro microchip/same54-xpro/mqtt-client
rp/pico-rmii rp/pico-rmii
stm32/nucleo-f746zg/minimal-rm2 stm32/nucleo-f746zg/minimal-rm2
stm32/nucleo-f746zg/minimal-rndis stm32/nucleo-f746zg/minimal-rndis
@@ -691,13 +694,13 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
example: example:
- path: esp32 - path: esp32/device-dashboard
name: ${{ matrix.example.path }} name: ${{ matrix.example.path }}
steps: steps:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: echo # nothing specific to install or do - run: echo # nothing specific to install or do
- run: make -C tutorials/http/device-dashboard/${{ matrix.example.path }} build - run: make -C tutorials/${{ matrix.example.path }} build
device_dashboard_examples_arm: device_dashboard_examples_arm:
@@ -709,12 +712,12 @@ jobs:
- group: none - group: none
cflags: "" cflags: ""
examples: | examples: |
http/device-dashboard/microchip/same54-xpro microchip/same54-xpro/device-dashboard
renesas/ek-ra6m4-make-baremetal-builtin renesas/ek-ra6m4-make-baremetal-builtin
- group: builtin - group: builtin
cflags: -DMG_TLS=MG_TLS_BUILTIN cflags: -DMG_TLS=MG_TLS_BUILTIN
examples: | examples: |
http/device-dashboard/microchip/same54-xpro microchip/same54-xpro/device-dashboard
renesas/ek-ra6m4-make-baremetal-builtin renesas/ek-ra6m4-make-baremetal-builtin
name: device dashboard ARM ${{ matrix.group }} name: device dashboard ARM ${{ matrix.group }}
steps: steps:
@@ -740,19 +743,19 @@ jobs:
done done
exit $failed exit $failed
# mqtt_dashboard_examples: mqtt_dashboard_examples_arm:
# runs-on: ubuntu-latest runs-on: ubuntu-latest
# strategy: strategy:
# fail-fast: false fail-fast: false
# matrix: matrix:
# example: example:
# - path: - path: rp/pico-rndis-device
# name: ${{ matrix.example.path }} name: ${{ matrix.example.path }}
# steps: steps:
# - uses: actions/checkout@v5 - uses: actions/checkout@v5
# with: { fetch-depth: 2 } with: { fetch-depth: 2 }
# - run: echo # nothing specific to install or do - run: sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
# - run: make -C tutorials/${{ matrix.example.path }} build - run: make -C tutorials/${{ matrix.example.path }} build
# dual_examples: # dual_examples:
+2 -2
View File
@@ -98,8 +98,8 @@ jobs:
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- name: baremetal - name: baremetal
run: sudo apt -y update && sudo apt -y install gcc-arm-none-eabi run: sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
- run: make -C tutorials/http/device-dashboard/microchip/same54-xpro test VCON_API_KEY=${{secrets.VCON_API_KEY}} - run: make -C tutorials/microchip/same54-xpro/device-dashboard test VCON_API_KEY=${{secrets.VCON_API_KEY}}
- run: make -C tutorials/mqtt/mqtt-client/microchip/same54-xpro test VCON_API_KEY=${{secrets.VCON_API_KEY}} - run: make -C tutorials/microchip/same54-xpro/mqtt-client test VCON_API_KEY=${{secrets.VCON_API_KEY}}
test_pico_w5500: test_pico_w5500:
runs-on: ubuntu-latest runs-on: ubuntu-latest
+2 -2
View File
@@ -24,7 +24,7 @@ jobs:
test/health.awk < log > json test/health.awk < log > json
scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/atcmd_${{ matrix.cc }}_$(date +"%Y%m%d").json" scp -o "StrictHostKeyChecking=no" json "root@176.9.217.245:/data/downloads/health/atcmd_${{ matrix.cc }}_$(date +"%Y%m%d").json"
atcmd89: atcmd89:
runs-on: ubuntu-latest runs-on: ubuntu-24.04 # Ubuntu 26.04 Docker 29.4.2 breaks 32-bit Wine; switch at >= 29.4.3
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -35,7 +35,7 @@ jobs:
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: make -C test ${{ matrix.target }} - run: make -C test ${{ matrix.target }}
atcmdbe: atcmdbe:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
+32 -10
View File
@@ -35,7 +35,7 @@ jobs:
- if: ${{ env.GO == 1 }} - if: ${{ env.GO == 1 }}
run: if [ "${{ matrix.target }}" == "test" ]; then ./test/setup_mqtt_server.sh ; fi && make -C test ${{ matrix.target }} run: if [ "${{ matrix.target }}" == "test" ]; then ./test/setup_mqtt_server.sh ; fi && make -C test ${{ matrix.target }}
s390: s390:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
env: env:
TFLAGS: -DMQTT_LOCALHOST TFLAGS: -DMQTT_LOCALHOST
steps: steps:
@@ -45,7 +45,7 @@ jobs:
- if: ${{ env.GO == 1 }} - if: ${{ env.GO == 1 }}
run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && ./test/setup_mqtt_server.sh && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test s390 run: sudo apt -y update ; sudo apt -y install binfmt-support qemu-user-static && ./test/setup_mqtt_server.sh && docker run --rm --privileged multiarch/qemu-user-static --reset -p yes && make -C test s390
armhf: armhf:
runs-on: ubuntu-latest runs-on: ubuntu-24.04
env: env:
TFLAGS: -DMQTT_LOCALHOST TFLAGS: -DMQTT_LOCALHOST
steps: steps:
@@ -83,7 +83,7 @@ jobs:
/opt/homebrew/opt/mosquitto/sbin/mosquitto -c /Users/runner/work/mongoose/mongoose/test/mosquitto.conf.macos & /opt/homebrew/opt/mosquitto/sbin/mosquitto -c /Users/runner/work/mongoose/mongoose/test/mosquitto.conf.macos &
make -C test test ASAN_OPTIONS= make -C test test ASAN_OPTIONS=
windows: windows:
runs-on: ubuntu-latest runs-on: ubuntu-24.04 # Ubuntu 26.04 Docker 29.4.2 breaks 32-bit Wine; switch at >= 29.4.3
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
@@ -158,7 +158,8 @@ jobs:
- path: stm32/nucleo-f746zg/minimal - path: stm32/nucleo-f746zg/minimal
- path: stm32/nucleo-h563zi/minimal - path: stm32/nucleo-h563zi/minimal
- path: stm32/nucleo-h723zg/minimal - path: stm32/nucleo-h723zg/minimal
- path: stm32/nucleo-h723zg/minimal-bsd - path: stm32/nucleo-h723zg/minimal-bsd-baremetal
- path: stm32/nucleo-h723zg/minimal-bsd-freertos
- path: stm32/nucleo-h743zi/minimal - path: stm32/nucleo-h743zi/minimal
- path: stm32/stm32h573i-dk/minimal - path: stm32/stm32h573i-dk/minimal
- path: ti/ek-tm4c1294xl-make-baremetal-builtin - path: ti/ek-tm4c1294xl-make-baremetal-builtin
@@ -184,8 +185,8 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
example: example:
- path: http/uart-bridge/esp32 - path: esp32/uart-bridge
- path: http/http-client/esp8266/http-client-server - path: esp32/minimal
name: ${{ matrix.example.path }} name: ${{ matrix.example.path }}
env: env:
GO: 0 GO: 0
@@ -227,7 +228,7 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
example: example:
- path: esp32 - path: esp32/device-dashboard
name: ${{ matrix.example.path }} name: ${{ matrix.example.path }}
env: env:
GO: 0 GO: 0
@@ -235,12 +236,12 @@ jobs:
- uses: actions/checkout@v5 - uses: actions/checkout@v5
with: { fetch-depth: 2 } with: { fetch-depth: 2 }
- run: | - run: |
if ./test/match_changed_files.sh '^src|tutorials/http/device-dashboard'; then if ./test/match_changed_files.sh '^src|^tutorials/http/device-dashboard|^tutorials/${{ matrix.example.path }}'; then
echo GO=1 >> $GITHUB_ENV echo GO=1 >> $GITHUB_ENV
# nothing specific to install or do # nothing specific to install or do
fi fi
- if: ${{ env.GO == 1 }} - if: ${{ env.GO == 1 }}
run: make -C tutorials/http/device-dashboard/${{ matrix.example.path }} build run: make -C tutorials/${{ matrix.example.path }} build
device_dashboard_examples_arm: device_dashboard_examples_arm:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -248,7 +249,7 @@ jobs:
fail-fast: false fail-fast: false
matrix: matrix:
example: example:
- path: http/device-dashboard/microchip/same54-xpro - path: microchip/same54-xpro/device-dashboard
- path: renesas/ek-ra6m4-make-baremetal-builtin - path: renesas/ek-ra6m4-make-baremetal-builtin
- path: rp/pico-rndis - path: rp/pico-rndis
- path: rp/pico-w - path: rp/pico-w
@@ -267,3 +268,24 @@ jobs:
fi fi
- if: ${{ env.GO == 1 }} - if: ${{ env.GO == 1 }}
run: make -C tutorials/${{ matrix.example.path }} build run: make -C tutorials/${{ matrix.example.path }} build
mqtt_dashboard_examples_arm:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
example:
- path: rp/pico-rndis-device
name: ${{ matrix.example.path }}
env:
GO: 0
steps:
- uses: actions/checkout@v5
with: { fetch-depth: 2 }
- run: |
if ./test/match_changed_files.sh '^src|^tutorials/mqtt/mqtt-dashboard/device|^tutorials/${{ matrix.example.path }}'; then
echo GO=1 >> $GITHUB_ENV
sudo apt -y update && sudo apt -y install gcc-arm-none-eabi
fi
- if: ${{ env.GO == 1 }}
run: make -C tutorials/${{ matrix.example.path }} build
-1
View File
@@ -179,7 +179,6 @@ jobs:
example: example:
- path: esp32/uart-bridge - path: esp32/uart-bridge
- path: esp32/micropython - path: esp32/micropython
- path: esp8266/http-client-server
name: ${{ matrix.example.path }} name: ${{ matrix.example.path }}
env: env:
GO: 0 GO: 0
+108 -31
View File
@@ -1,14 +1,20 @@
# Mongoose - Embedded Network Library # Mongoose: a full-stack embedded networking library
Mongoose is a full-stack embedded networking library for C and C++. It includes
a TCP/IP stack with drivers, TLS 1.3, an embedded web server with HTTP and
WebSocket support, MQTT, and firmware OTA updates. All in just two files:
`mongoose.c` and `mongoose.h`. Mongoose runs on STM32, NXP and other
microcontrollers, on bare metal or with an RTOS, with no external dependencies.
Ideal for cloud connectivity, device web dashboards, secure firmware updates
and remote control.
Mongoose is an open source, two-file C networking library and embedded web server for
microcontrollers that combines TCP/IP stack, HTTP, WebSocket, MQTT, TLS 1.3
stack, built-in firmware OTA updates, and device-dashboard infrastructure.
License: GPLv2 or commercial. License: GPLv2 or commercial.
Website: https://mongoose.ws/ Website: https://mongoose.ws/
GitHub repo: https://github.com/cesanta/mongoose GitHub repo: https://github.com/cesanta/mongoose
## General rules ## General rules
- All relative file names mentioned in this file are related to the repo root.
- Always re-read files before editing, so you do not overwrite existing changes. - Always re-read files before editing, so you do not overwrite existing changes.
- Never guess. If you don't know, say you don't know and stop. - Never guess. If you don't know, say you don't know and stop.
- Resolve relative paths from the repo root: https://github.com/cesanta/mongoose - Resolve relative paths from the repo root: https://github.com/cesanta/mongoose
@@ -35,6 +41,7 @@ This is a navigation aid, not an API reference. Read `mongoose.h` for exact
function signatures, structs, options, examples, and constraints. function signatures, structs, options, examples, and constraints.
- `mg_mgr_*` - event manager and polling loop - `mg_mgr_*` - event manager and polling loop
- `mg_dash_*` - dashboard API for device web UIs, fieldsets, and live updates
- `mg_http_*` - HTTP server, HTTP client, uploads, serving files - `mg_http_*` - HTTP server, HTTP client, uploads, serving files
- `mg_ws_*` - WebSocket server and client - `mg_ws_*` - WebSocket server and client
- `mg_mqtt_*` - MQTT client - `mg_mqtt_*` - MQTT client
@@ -225,12 +232,41 @@ xTaskCreate(net_task, "net", 8192, NULL, tskIDLE_PRIORITY + 1, NULL);
## HTTP / Web Device Dashboard ## HTTP / Web Device Dashboard
For a web UI with real-time device state over WebSocket, use the Mongoose When building a device web UI, control panel, monitoring page, or live
device dashboard. display, you MUST use the `mg_dash_*` dashboard framework unless the user
explicitly requests another architecture. Do not add your own HTTP event handler.
Read the dashboard declarations in `mongoose.h` before implementing the UI.
Use only the dashboard files listed below. Download missing reference files;
preserve existing files. Integrate the dashboard into the existing application
and build files.
Start from the minimal reference implementation and adapt its fields and UI.
Keep dashboard fieldsets, callbacks, update timers, and small metric helpers
in `dashboard.c`. Do not create `dashboard.h`, or other dashboard
helper modules. `mongoose.h` already declares `mg_dash_init()` and
`mg_dash_poll()`. Reuse existing board/HAL helpers for hardware measurements;
if none exists, put a small private helper in `dashboard.c` or extend the
existing board/HAL implementation.
Expose device state through mg_field / mg_field_set.
Call mg_dash_init() once and mg_dash_poll() in the event loop.
For live updates, call mg_dash_send_change() from a backend timer.
Display values using dashboard.js and HTML data-bind attributes.
Example: free RAM updated every 50 ms means a read-only fieldset pushed
over the dashboard WebSocket every 50 ms. Do not implement browser polling,
fetch(), setInterval(), or a custom WebSocket client for dashboard state.
### Required files ### Required files
The following files must exist at these exact paths, regardless of the build environment: Keep all the following Mongoose files together in one project directory.
The example uses `mongoose/`; you may choose another directory name.
If Mongoose is already installed, use the directory containing the actual
`mongoose.c` and `mongoose.h` files, including an existing CubeMX middleware
directory. Add the dashboard files there and update the build paths. Do not
create a second Mongoose directory or use symlinks, forwarding headers, or
duplicate library copies to make files appear colocated.
``` ```
your_project/ your_project/
@@ -240,6 +276,7 @@ your_project/
├── mongoose.c # single source file ├── mongoose.c # single source file
├── dashboard.c # C-side dashboard logic ├── dashboard.c # C-side dashboard logic
├── dashboard.html # HTML/JS UI (source) ├── dashboard.html # HTML/JS UI (source)
├── html2c.js # HTML-to-C generator
└── file_data.c # generated from dashboard.html (see below) └── file_data.c # generated from dashboard.html (see below)
``` ```
@@ -251,16 +288,24 @@ node html2c.js dashboard.html -o file_data.c
`html2c.js` is at https://github.com/cesanta/mongoose/blob/master/resources/html2c.js `html2c.js` is at https://github.com/cesanta/mongoose/blob/master/resources/html2c.js
If the project does not yet have `dashboard.c` and `dashboard.html`, fetch the For each missing `dashboard.c`, `dashboard.html`, or `html2c.js`, download its
minimal reference versions: reference version from the Mongoose repository and place it beside `mongoose.c`
and `mongoose.h`:
``` ```
https://github.com/cesanta/mongoose/blob/master/tutorials/device-dashboard/minimal/dashboard.c https://github.com/cesanta/mongoose/blob/master/tutorials/device-dashboard/minimal/dashboard.c
https://github.com/cesanta/mongoose/blob/master/tutorials/device-dashboard/minimal/dashboard.html https://github.com/cesanta/mongoose/blob/master/tutorials/device-dashboard/minimal/dashboard.html
https://github.com/cesanta/mongoose/blob/master/resources/html2c.js
``` ```
If the project already has `dashboard.c` and `dashboard.html`, do **not** fetch Add a build rule that regenerates `file_data.c` whenever `dashboard.html` or
anything from the repository. `html2c.js` changes. Keep the upstream generator unchanged; it already inlines
the script referenced by the HTML, so the served page does not need internet
access. Do not download a separate `dashboard.js` or add a local `--use`
override unless the user explicitly requests offline builds or local assets.
Compile both `dashboard.c` and `file_data.c` into the
application. Call `mg_dash_init()` once and `mg_dash_poll()` on every iteration
of the existing Mongoose event loop, from the same task or thread.
### C integration (bare metal or RTOS main loop) ### C integration (bare metal or RTOS main loop)
@@ -279,15 +324,17 @@ for (;;) {
### dashboard.html rules ### dashboard.html rules
- Use `dashboard.js` from `https://mongoose.ws/resources/dashboard.js` - Reference `<script src="https://mongoose.ws/resources/dashboard.js"></script>`
in the source HTML. Let `html2c.js` inline it into the generated asset.
- Call `Dashboard.init({ data: { ... } })` once - this is the only direct - Call `Dashboard.init({ data: { ... } })` once - this is the only direct
Dashboard API call. Treat the rest of Dashboard as a black box. Dashboard API call. Treat the rest of Dashboard as a black box.
- Do **not** add vanilla JS event listeners, `fetch()` calls, or custom - Do **not** add vanilla JS event listeners, `fetch()` calls, or custom
reactive logic to `dashboard.html`. reactive logic to `dashboard.html`.
- Do **not** modify `dashboard.html` unless the user explicitly asks. - Modify `dashboard.html` only for requested UI work. A request to create or
modify the web UI authorizes the necessary `dashboard.html` edits.
- Bind controls to device state using `data-bind` attributes - Bind controls to device state using `data-bind` attributes
- The `__status` object in evaluations is read-only, do not alter it - The `__status` object in evaluations is read-only, do not alter it
- If you need to pass data between the UI and backend.c, add extra - If you need to pass data between the UI and `dashboard.c`, add extra
fieldsets/fields - see next section about it fieldsets/fields - see next section about it
- If you want to display device data in HTML, use `${}` evaluations - If you want to display device data in HTML, use `${}` evaluations
@@ -311,17 +358,24 @@ for (;;) {
### dashboard.c rules ### dashboard.c rules
Mongoose backend exports device data as a collection of "fieldsets". Each fieldset groups several fields Mongoose exports device data as fieldsets. Each fieldset groups several fields
and has one `bool fn(enum mg_dash_op, struct mg_dash_user *)` callback for
read/write/add/delete operations. Use the declarations in the project's
`mongoose.h`; do not copy older descriptors with separate reader/writer
members or positional access-level arguments. Use designated initializers.
Example fieldset: Example fieldset:
```c ```c
static struct mg_dash s_dash;
static bool settings_fn(enum mg_dash_op op, struct mg_dash_user *u);
static struct settings { static struct settings {
double volume; double volume;
char name[10]; char name[10];
int log_level; int log_level;
bool enable_login; bool enable_login;
} s_settings = {2.7, "Dublin", 2, false, false}; } s_settings = {2.7, "Dublin", 2, false};
static struct mg_field fields_settings[] = { static struct mg_field fields_settings[] = {
{"volume", MG_VAL_DBL, &s_settings.volume, sizeof(s_settings.volume)}, {"volume", MG_VAL_DBL, &s_settings.volume, sizeof(s_settings.volume)},
@@ -332,14 +386,12 @@ static struct mg_field fields_settings[] = {
}; };
static struct mg_field_set set_settings = { static struct mg_field_set set_settings = {
"settings", fields_settings, read_settings, write_settings, 3, 7, NULL, .name = "settings", .fields = fields_settings, .fn = settings_fn,
}; };
``` ```
To enable user authentication, set `authenticate` function for the dashboard descriptor: To enable user authentication, set `authenticate` function for the dashboard descriptor:
```c ```c
static struct mg_dash s_dash;
// Signature: (char *user, size_t userlen, const char *pass) // Signature: (char *user, size_t userlen, const char *pass)
// `user` is both input (username from the login form) and output: the function // `user` is both input (username from the login form) and output: the function
// may overwrite it with the canonical username. Return access level > 0 on // may overwrite it with the canonical username. Return access level > 0 on
@@ -356,24 +408,34 @@ static int authenticate(char *user, size_t userlen, const char *pass) {
return level; return level;
} }
static void write_settings(void) { static bool settings_fn(enum mg_dash_op op, struct mg_dash_user *u) {
s_dash.authenticate = s_settings.enable_login ? authenticate : NULL; (void) u;
if (op == MG_DASH_WRITE) {
s_dash.authenticate = s_settings.enable_login ? authenticate : NULL;
return true;
}
return op == MG_DASH_READ;
} }
``` ```
Fieldset may have reader and writer function, which acts as a hardware glue. For example, "led1" variable may reflect real LED status using reader and writer: Use the fieldset callback as hardware glue. For example, `led1` can reflect
the real LED state:
```c ```c
static struct leds { static struct leds {
bool led1; bool led1;
} s_leds = {false}; } s_leds = {false};
static void write_leds(void) { static bool leds_fn(enum mg_dash_op op, struct mg_dash_user *u) {
gpio_write(LED1_PIN, s_leds.led1); (void) u;
} if (op == MG_DASH_READ) {
s_leds.led1 = gpio_read(LED1_PIN);
static void read_leds(void) { } else if (op == MG_DASH_WRITE) {
s_leds.led1 = gpio_read(LED1_PIN); gpio_write(LED1_PIN, s_leds.led1);
} else {
return false;
}
return true;
} }
static struct mg_field fields_leds[] = { static struct mg_field fields_leds[] = {
@@ -382,7 +444,7 @@ static struct mg_field fields_leds[] = {
}; };
static struct mg_field_set set_leds = { static struct mg_field_set set_leds = {
"leds", fields_leds, read_leds, write_leds, 0, 0, NULL, .name = "leds", .fields = fields_leds, .fn = leds_fn,
}; };
``` ```
@@ -408,7 +470,8 @@ static struct event {
} s_event; } s_event;
static struct mg_field_set field_set_event = { static struct mg_field_set field_set_event = {
"event", fields_event, event_fn, &s_event.index, 0, 0, 0 .name = "event", .fields = fields_event,
.fn = event_fn, .index = &s_event.index,
}; };
``` ```
@@ -428,6 +491,20 @@ Do not rename, wrap, relocate, or replace these files or functions. Do not intro
Board-specific STM32Cube files may exist outside mongoose/, but the Mongoose dashboard files must retain the structure and API documented above. Board-specific STM32Cube files may exist outside mongoose/, but the Mongoose dashboard files must retain the structure and API documented above.
### Dashboard completion checks
- Verify actual file locations, including symlink targets, against the required
layout. Check that no extra dashboard source/header/JS files were introduced.
- Check the source HTML for the upstream script reference, a single
`Dashboard.init()`, and declarative bindings. Networking code in the upstream
script inlined into `file_data.c` is expected; do not replace or edit it.
- Verify fieldsets are registered with `MG_DASH_ADD_FIELD_SET()`, listeners use
`mg_dash_ev_handler`, and live metrics use `mg_dash_send_change()` on the
requested backend schedule. Do not resend unrelated fieldsets at that rate.
- Regenerate `file_data.c` and build the real firmware. Report separately which
behavior was verified on hardware; host mocks do not establish physical LED,
Ethernet, RAM measurement, or refresh-rate correctness.
## Filesystem ## Filesystem
| Define | Use when | | Define | Use when |
@@ -486,7 +563,7 @@ embedded devices and needs only a few lines added to `mongoose_config.h`:
```c ```c
#define MG_OTA_URL "https://mongoose.ws/ota/u/PREFIX/ota.json" // Copy from instructions panel #define MG_OTA_URL "https://mongoose.ws/ota/u/PREFIX/ota.json" // Copy from instructions panel
#define MG_OTA_FIRMWARE_VERSION "MY_PRODUCT_1.4.2" // Change this #define MG_FIRMWARE_VERSION "MY_PRODUCT_1.4.2" // Change this
``` ```
No backend programming required. The device registers itself and checks in at No backend programming required. The device registers itself and checks in at
+57 -25
View File
@@ -1,4 +1,4 @@
# Mongoose - Embedded Web Server / Embedded Network Library # Mongoose: a full-stack embedded networking library
[![License: GPLv2/Commercial](https://img.shields.io/badge/License-GPLv2%20or%20Commercial-green.svg)](https://opensource.org/licenses/gpl-2.0.php) [![License: GPLv2/Commercial](https://img.shields.io/badge/License-GPLv2%20or%20Commercial-green.svg)](https://opensource.org/licenses/gpl-2.0.php)
[![Build Status]( https://github.com/cesanta/mongoose/actions/workflows/quicktest.yml/badge.svg)](https://github.com/cesanta/mongoose/actions) [![Build Status]( https://github.com/cesanta/mongoose/actions/workflows/quicktest.yml/badge.svg)](https://github.com/cesanta/mongoose/actions)
@@ -7,11 +7,18 @@
<img src="https://mongoose.ws/images/logo.svg" width="48" height="48" <img src="https://mongoose.ws/images/logo.svg" width="48" height="48"
align="left" style="float:left;" /> align="left" style="float:left;" />
Two files. Drop `mongoose.c` and `mongoose.h` into any C/C++ project and get a Mongoose is a full-stack embedded networking library for C and C++. It includes
full network stack — HTTP, WebSocket, MQTT, TLS, firmware OTA a TCP/IP stack with drivers, TLS 1.3, an embedded web server with HTTP and
updates, device dashboard — on any microcontroller or desktop OS. WebSocket support, MQTT, and firmware OTA updates. All in just two files:
`mongoose.c` and `mongoose.h`. Mongoose runs on STM32, NXP and other
microcontrollers, on bare metal or with an RTOS, with no external dependencies.
Ideal for cloud connectivity, device web dashboards, secure firmware updates
and remote control.
On the market since 2004, used by vast number of open source and commercial Use it instead of lwIP + mbedTLS + httpd + an MQTT client + OTA glue code, or
run it on top of lwIP or Zephyr.
On the market since 2004, used by a vast number of open source and commercial
products - it even runs on the International Space Station! Features include: products - it even runs on the International Space Station! Features include:
- Cross-platform: - Cross-platform:
@@ -24,7 +31,7 @@ products - it even runs on the International Space Station! Features include:
- Source code is both ISO C and ISO C++ compliant - Source code is both ISO C and ISO C++ compliant
- Very easy to integrate - Very easy to integrate
- Own TCP/IP stack for bare metal / RTOS, or run on top of any existing one (lwIP, Zephyr, ...) - Own TCP/IP stack for bare metal / RTOS, or run on top of any existing one (lwIP, Zephyr, ...)
- Built-in TLS 1.3 ECC stack. Also can use external TLS libraries - mbedTLS, OpenSSL, or other - Built-in TLS 1.3 stack. Also can use external TLS libraries - mbedTLS, OpenSSL, or other
- Does not depend on any other software to implement networking - Does not depend on any other software to implement networking
- Built-in firmware updates for STM32 H5, STM32 H7, NXP IMXRT, RP2040/2350, ESP32 and more - Built-in firmware updates for STM32 H5, STM32 H7, NXP IMXRT, RP2040/2350, ESP32 and more
- Commercial support with proactive security updates; [CRA-compliant](https://mongoose.ws/security/cra-compliance/) - Commercial support with proactive security updates; [CRA-compliant](https://mongoose.ws/security/cra-compliance/)
@@ -35,8 +42,32 @@ See https://mongoose.ws/ for complete documentation, videos, case studies, etc.
## Supported platforms ## Supported platforms
Mongoose can work on top of any TCP/IP stack that supports BSD sockets API. Mongoose has its own built-in TCP/IP stack with drivers, so it needs no
Platforms supported by the 3rd party TCP/IP stacks: additional software to implement networking. The built-in stack runs on bare
metal and under any RTOS. Platforms supported by the Mongoose built-in TCP/IP
stack:
| MCU | Connectivity | Notes |
| :-- | :----------- | :---- |
| **STM32** | Built-in Ethernet | Ethernet-capable STM32F, STM32H5, STM32H7, STM32N6, STM32C5 variants |
| **NXP i.MX RT** | Built-in Ethernet | RT102x, RT104x, RT105x, RT106x, RT117x, RT118x (NETC) |
| **NXP MCX** | Built-in Ethernet | MCXN94x, MCXE247 |
| **NXP RW612** | Eth, WiFi, 802.15.4 | Separate Ethernet and radio drivers |
| **Microchip ATSAME54** | Built-in Ethernet | GMAC driver |
| **Renesas RA** | Built-in Ethernet | RA6M, RA8M |
| **Infineon XMC** | Built-in Ethernet | XMC4, XMC7 |
| **Texas Instruments** | Built-in Ethernet | TM4C, TMS570 |
| **RP2040, RP2350, STM32, others** | CYW43xx Wi-Fi chips | SPI or SDIO; Pico W, Pico 2 W, Pico RM2, Arduino Portenta H7 |
| **STM32, others** | ST67W6 Wi-Fi modules | SPI; for example, STM32U5 with the ST67W611M1 module |
| **MCUs with an NXP Wi-Fi SDK port** | NXP Wi-Fi | Requires the SDK's Wi-Fi port implementing the driver's network hooks |
| **NXP MCXW71** | Built-in 802.15.4 radio | IPv4 over IEEE 802.15.4 |
| **NXP RW612** | Built-in 802.15.4 radio | IPv4 over IEEE 802.15.4; requires NXP radio firmware |
| **Any MCU with SPI** | W5500 or W5100 Ethernet chips | External Wiznet MAC+PHY |
| **MCUs connected to a cellular modem** | Cellular | AT commands and PPP; for example, SIM800 |
| **MCUs with CMSIS Ethernet drivers** | Ethernet via CMSIS-Driver | Requires CMSIS Ethernet MAC and PHY drivers |
Mongoose can also run on top of any TCP/IP stack that supports the BSD
sockets API. Platforms supported via 3rd party TCP/IP stacks:
| TCP/IP stack | Notes | | TCP/IP stack | Notes |
| :-------------- | :------- | | :-------------- | :------- |
@@ -45,23 +76,6 @@ Platforms supported by the 3rd party TCP/IP stacks:
| **Other** | Any other TCP/IP stack that supports BSD socket API, for example Amazon FreeRTOS-TCP | | **Other** | Any other TCP/IP stack that supports BSD socket API, for example Amazon FreeRTOS-TCP |
| **Linux, Mac, Windows** | Workstations, server, single board computers, embedded Linux devices running on MPUs or FPGAs | | **Linux, Mac, Windows** | Workstations, server, single board computers, embedded Linux devices running on MPUs or FPGAs |
Optionally, Mongoose provides its own built-in TCP/IP stack, eliminating the
need for additional software to implement networking functionality. The
built-in stack supports operation in both bare-metal and RTOS environments.
Platforms supported by the Mongoose built-in TCP/IP stack:
| Hardware | Notes |
| :------------- | :------- |
| **STM32** | All STM32 MCUs with built-in Ethernet: STM32Fxx, STM32H5xx, STM32H7xx |
| **NXP** | All NXP MCUs with built-in Ethernet: IMXRT102x, IMXRT104x, IMXRT105x, IMXRT106x, IMXRT117x, RW612, MCXN94x |
| **Microchip** | ATSAME54 MCUs with built-int Ethernet |
| **Renesas** | RA5M, RA6M, RA8M MCUs with built-in Ethernet |
| **Infineon** | XMC4, XMC7 MCUs with built-in Ethernet |
| **Texas Instruments** | TM4C, TMS570 MCUs with built-in Ethernet |
| **Cypress WiFi** | Any MCU with CY43xx WiFi chips, like RP2040 Pico-W, RP2350 Pico2-W, Arduino Portenta |
| **Wiznet Ethernet** | Any MCU that use Wiznet W5500 or Wiznet 5100 MAC+PHY chips |
| **Cellular** | NRF9160, SIM800 |
## Usage Examples ## Usage Examples
Below are quick snippets that should give an idea how simple the API is and Below are quick snippets that should give an idea how simple the API is and
@@ -158,6 +172,17 @@ int main() {
} }
``` ```
## Licensing
Mongoose is dual-licensed:
- GPLv2: free for open source projects. Many popular open source projects use
Mongoose, for example
[SWUpdate](https://github.com/sbabic/swupdate/tree/master/mongoose), the
embedded Linux update framework
- Commercial: for closed-source products. Includes support directly from the
engineers who wrote the whole stack, and early security fixes.
See [licensing](https://mongoose.ws/licensing/)
## Commercial use ## Commercial use
- Mongoose is used by hundreds of businesses, from Fortune500 giants like - Mongoose is used by hundreds of businesses, from Fortune500 giants like
Siemens, Schneider Electric, Broadcom, Bosch, Google, Samsung, Qualcomm, Caterpillar to the small businesses Siemens, Schneider Electric, Broadcom, Bosch, Google, Samsung, Qualcomm, Caterpillar to the small businesses
@@ -222,6 +247,13 @@ Technical guides and deep dives into embedded web servers, WebUI integration and
- [lwIP vs Mongoose - TCP/IP Stack Integration Benchmark](https://mongoose.ws/articles/lwip-vs-mongoose-tcpip-stack-integration/) - [lwIP vs Mongoose - TCP/IP Stack Integration Benchmark](https://mongoose.ws/articles/lwip-vs-mongoose-tcpip-stack-integration/)
- [Embedded TCP/IP Stacks Comparison](https://mongoose.ws/embedded-tcpip-stack-comparison/) - [Embedded TCP/IP Stacks Comparison](https://mongoose.ws/embedded-tcpip-stack-comparison/)
- [STM32H5 File System on Internal Flash: LittleFS + Mongoose](https://mongoose.ws/articles/stm32h5-file-system-on-internal-flash/) - [STM32H5 File System on Internal Flash: LittleFS + Mongoose](https://mongoose.ws/articles/stm32h5-file-system-on-internal-flash/)
- [Firmware OTA and remote control on NXP FRDM-RW612](https://mongoose.ws/articles/rw612-mdash/)
- [25000 WebSocket messages per second on STM32 Nucleo-H723ZG](https://mongoose.ws/articles/stm32-websocket-benchmark/)
- [How to connect STM32 to AWS IoT Core](https://mongoose.ws/articles/stm32-aws-iot/)
- [How to connect STM32 to Azure IoT Hub](https://mongoose.ws/articles/stm32-azure-iot-hub/)
- [How to connect STM32 to EMQX](https://mongoose.ws/articles/stm32-emqx/)
- [STM32 Device Management deep dive: Secure OTA, Remote Control, health monitor](https://mongoose.ws/articles/stm32-mdash-deep-dive/)
- [STM32 TCP/IP footprint: how much flash and RAM does Mongoose take?](https://mongoose.ws/articles/tcp-ip-footprint/)
## Contributions ## Contributions
+41
View File
@@ -0,0 +1,41 @@
# Security Policy
Mongoose is a full-stack embedded networking library by Cesanta Software Ltd,
<https://mongoose.ws>. This policy covers how to report vulnerabilities
and how Cesanta handles them.
## Supported versions
Security fixes go to the `master` branch and the latest release.
## Reporting a vulnerability
Do not report security issues in public GitHub issues. Report them
privately using GitHub Security Advisories:
<https://github.com/cesanta/mongoose/security/advisories/new>
Include the Mongoose version or commit, steps or a proof of concept to reproduce, and
the impact. Cesanta usually responds the same business day.
## Disclosure process
1. Cesanta reviews the report and coordinates a fix with the reporter.
2. Eligible commercial customers receive a notification and a private fix
one month before the CVE becomes public.
3. The fix and the CVE are then published. The reporter is credited in the
GitHub Security Advisory.
## Security testing
- CI on every push, unit tests built with ASAN and UBSan
- CodeQL static analysis on every commit
- Continuous fuzzing on OSS-Fuzz, plus nightly libFuzzer runs
- AI-assisted security review on every pull request
- Regular review by independent security research groups worldwide
## EU Cyber Resilience Act (CRA)
Mongoose supports CRA compliance for connected products: a documented
vulnerability handling process (this file), TLS 1.3, signed OTA firmware
updates, and an SBOM (`sbom.cdx.json`). Details:
<https://mongoose.ws/security/cra-compliance/>
+12114 -5424
View File
File diff suppressed because it is too large. Load diff
+1304 -1024
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,32 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"version": "0.0.1",
"componentid": "::Mongoose:Networking Core",
"type": "object",
"grammarVersion": "3.8.0",
"license": "Copyright (c) Cesanta Software Limited",
"properties": {
"parameters": {
"type": "object",
"properties": {
"info": {
"type": "object",
"title": "General information",
"properties": {
"description": {
"title": "Middleware description",
"type": "string",
"actions": [
{
"type": "disable",
"condition": "true"
}
],
"default": "Mongoose networking library: TCP/IP, TLS, HTTP, WebSocket, MQTT, OTA. Edit mongoose_config.h to configure it."
}
}
}
}
}
}
}
@@ -1,13 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<package schemaVersion="1.7.40" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="PACK.xsd"> <package schemaVersion="1.7.56" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:stm32="https://developer.st.com/schemas/stm32cube/1.0.0" xsi:noNamespaceSchemaLocation="PACK.xsd">
<vendor>Cesanta</vendor> <vendor>Cesanta</vendor>
<name>I-CUBE-Mongoose</name> <name>I-CUBE-Mongoose</name>
<description>Mongoose - a lightweight networking library providing TCP/IP stack, TLS, HTTP (Embedded Web Server), WebSocket, MQTT, and Firmware OTA updates. Build production-ready web device dashboards and MQTT cloud connectivity without stitching multiple components together. <description>Mongoose - a full-stack networking library for microcontrollers: Ethernet and Wi-Fi drivers, TCP/IP stack, TLS 1.3, HTTP, WebSocket, MQTT, Modbus, OTA updates and device management, in a two-file C/C++ library, on any RTOS or bare metal.</description>
</description>
<url>https://mongoose.ws/downloads/stm32pack/</url> <url>https://mongoose.ws/downloads/stm32pack/</url>
<license>License.txt</license> <license>License.txt</license>
<supportContact>https://mongoose.ws/contact/</supportContact> <supportContact>https://mongoose.ws/contact/</supportContact>
<environments>
<environment name="STM32Cube">
<stm32:pack type="MW" friendlyName="Mongoose" shortDesc="Mongoose full-stack networking library">
<relocation-info parent="middleware"/>
<no-compatibility-constraint/>
</stm32:pack>
</environment>
</environments>
<releases> <releases>
<release date="2026-10-21" version="7.23.3">See https://github.com/cesanta/mongoose/releases/tag/7.23</release>
<release date="2026-10-19" version="7.23.2">See https://github.com/cesanta/mongoose/releases/tag/7.23</release>
<release date="2026-09-28" version="7.23.1">See https://github.com/cesanta/mongoose/releases/tag/7.23</release> <release date="2026-09-28" version="7.23.1">See https://github.com/cesanta/mongoose/releases/tag/7.23</release>
<release date="2026-05-11" version="7.21.7">See https://github.com/cesanta/mongoose/releases/tag/7.21</release> <release date="2026-05-11" version="7.21.7">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
<release date="2026-05-05" version="7.21.5">See https://github.com/cesanta/mongoose/releases/tag/7.21</release> <release date="2026-05-05" version="7.21.5">See https://github.com/cesanta/mongoose/releases/tag/7.21</release>
@@ -20,7 +29,7 @@
<keyword>IMPLEMENTED_WITH_STM32CUBEMX</keyword> <keyword>IMPLEMENTED_WITH_STM32CUBEMX</keyword>
</keywords> </keywords>
<components> <components>
<component Cclass="Mongoose" Cgroup="Networking Core" Cversion="7.23.1" maxInstances="1"> <component Cclass="Mongoose" Cgroup="Networking Core" Cversion="7.23.3" maxInstances="1">
<description>Networking Core</description> <description>Networking Core</description>
<files> <files>
<file category="doc" name="README.md"/> <file category="doc" name="README.md"/>
@@ -29,6 +38,13 @@
<file category="header" name="mongoose_config.h"/> <file category="header" name="mongoose_config.h"/>
<file category="utility" name="README.md" public="false"/> <file category="utility" name="README.md" public="false"/>
</files> </files>
<environments>
<environment name="STM32Cube">
<stm32:component>
<middleware-entry-point id="Mongoose" name="Mongoose" category="TCP/IP"/>
</stm32:component>
</environment>
</environments>
</component> </component>
</components> </components>
</package> </package>
+24 -4
View File
@@ -1,10 +1,16 @@
VERSION = 7.23.1 VERSION = 7.23.3
REPO_ROOT = ../.. REPO_ROOT = ../..
MX ?= /Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/STM32CubeMX MX ?= /Applications/STMicroelectronics/STM32CubeMX.app/Contents/MacOs/STM32CubeMX
FILES = Cesanta.I-CUBE-Mongoose.pdsc Release_Notes.html mongoose_config.h README.md FILES = Cesanta.I-CUBE-Mongoose.pdsc Release_Notes.html mongoose_config.h README.md .config/mongoose_parameters.json
GENERATED = License.txt mongoose.h mongoose.c GENERATED = License.txt mongoose.h mongoose.c
MX2 ?= $(HOME)/STMicroelectronics/STM32CubeMX2_1.1.2/.bin/cube
PACKSDIR ?= $(HOME)/Library/Application Support/stm32cube/packs
MX2CPN ?= STM32C5A3ZGT6
MX2PROJ = $(CURDIR)/mx2test/test.ioc2
NAME = Cesanta.I-CUBE-Mongoose.$(VERSION)
PACK = $(NAME).pack
PACK = Cesanta.I-CUBE-Mongoose.$(VERSION).pack
all: $(PACK) all: $(PACK)
Cesanta.I-CUBE-Mongoose.$(VERSION).pack: $(FILES) $(GENERATED) Cesanta.I-CUBE-Mongoose.$(VERSION).pack: $(FILES) $(GENERATED)
@@ -44,5 +50,19 @@ mongoose.h: Mongoose
mongoose.c: Mongoose mongoose.c: Mongoose
cp $(REPO_ROOT)/mongoose.c $@ cp $(REPO_ROOT)/mongoose.c $@
test_mx2: $(PACK)
-$(MX2) pack remove --cmsis-pack-root "$(PACKSDIR)" $(NAME)
rm -f "$(PACKSDIR)/.Download/$(PACK)"
$(MX2) pack install --cmsis-pack-root "$(PACKSDIR)" "$(CURDIR)/$(PACK)"
export PATH="$(dir $(MX2)):$$PATH"; \
PORT=$$(cube lifecycle-mx start-only | sed -n 's/^BACKEND_PORT *//p'); \
cube mx project close --port $$PORT -p "$(MX2PROJ)" --discard > /dev/null 2>&1; \
rm -rf mx2test && mkdir mx2test && \
cube mx project create-from-mcu --port $$PORT --cpn $(MX2CPN) -l "$(CURDIR)/mx2test" -n test --empty-project && \
cube mx middleware enable-middleware --port $$PORT -p "$(MX2PROJ)" -n Mongoose | tee mx2test/enable.json && \
grep -q '"status": "success"' mx2test/enable.json && \
cube mx project save --port $$PORT -p "$(MX2PROJ)" && \
cube mx project close --port $$PORT -p "$(MX2PROJ)" --discard
clean: clean:
rm -rf *.pack STM32CubeMX/*.$(VERSION)_*.xml $(GENERATED) rm -rf *.pack STM32CubeMX/*.$(VERSION)_*.xml $(GENERATED) mx2test
+3 -197
View File
@@ -4,201 +4,7 @@ This pack provides an easy to use CubeMX integration.
## Mongoose Networking Core ## Mongoose Networking Core
This module installs Mongoose Library itself: `mogoose.c`, `mongoose.h` and This module installs Mongoose Library itself: `mogoose.c`, `mongoose.h` and
`mongoose_config.h`. It is required for any other module to work. Below are `mongoose_config.h`. To finish integration, follow this guide:
the steps to make it work with you CubeMX application:
## Configure peripherals https://mongoose.ws/docs/guides/stm32-tcpip-stack/#configure-peripherals
In CubeMX, configure USART (for debug), RNG (for TLS), ETH.
## Enable debug logs
Open `Core/Src/main.c` and add this snippet:
```c
/* USER CODE BEGIN 0 */
int _write(int fd, unsigned char *buf, int len) {
HAL_UART_Transmit(&huart3, buf, len, HAL_MAX_DELAY);
return len;
}
/* USER CODE END 0 */
```
## Call Mongoose
Open `Core/Src/main.c`. Add at the top of the file:
```c
/* USER CODE BEGIN Includes */
#include "mongoose.h"
/* USER CODE END Includes */
```
Inside main() function:
```c
Inside the `main()` function:
```c
/* USER CODE BEGIN WHILE */
struct mg_mgr mgr;
mg_mgr_init(&mgr);
while (1)
{
mg_mgr_poll(&mgr, 1);
/* USER CODE END WHILE */
```
This starts the TCP/IP stack. In the serial console logs, you should
see something like this:
```text
0 2 mongoose.c:26153:mg_phy_init PHY ID: 0x07 0xc131 (LAN87x)
6 2 mongoose.c:5834:mg_mgr_init Driver: stm32h, MAC: 2a:37:94:03:d5:74
d 3 mongoose.c:5841:mg_mgr_init MG_IO_SIZE: 512, TLS: builtin
13 3 mongoose.c:5758:mg_listen 1 0 http://0.0.0.0:80
19 1 mongoose.c:6260:onstatechange Link down
7d6 3 mongoose.c:28424:mg_tcpip_driv Link is 100M full-duplex
7db 3 mongoose.c:6404:tx_dhcp_discov DHCP discover sent. Our MAC: 2a:37:94:03:d5:74
831 3 mongoose.c:6382:tx_dhcp_reques DHCP req sent
836 2 mongoose.c:6559:rx_dhcp_client Lease: 3600 sec (3602)
83c 2 mongoose.c:6249:onstatechange READY, IP: 192.168.2.31
842 2 mongoose.c:6250:onstatechange GW: 192.168.2.1
847 2 mongoose.c:6253:onstatechange MAC: 2a:37:94:03:d5:74
```
Now, you should be able to ping your device.
However, it runs no network services.
## Add hello world HTTP server
Let's add the simplest web server possible. After the `mg_mgr_init()`
call, add one more line to start the HTTP listener:
```c
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0:80", http_ev_handler, NULL);
```
And after the `_write()` override, add this HTTP event handler function:
```c
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
mg_http_reply(c, 200, "", "Hi from Mongoose! Tick %lu\r\n", HAL_GetTick());
}
}
```
Rebuild, reflash your board, open the device's IP address in the browser,
and see the message displayed, something like:
```text
Hi from Mongoose! Tick 38187
```
## Add full device dashboard
Remove the hello world server if you added it.
Create `Mongoose` directory in the project root and copy
the following files there:
- [dashboard.c](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/full/dashboard.c)
- [dashboard.html](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/full/dashboard.html)
- [html2c.js](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/resources/html2c.js)
`html2c.js` is a node.js script that generates `file_data.c` using this command:
`node html2c.js dashboard.html -o file_data.c`. This script first inlines all
external resources into an amalgamated HTML file - so it does not depend on
anything external, and then zips it and packs into a Mongoose embedded
filesystem. This way it takes the minimum space on flash.
In top-level `CMakeLists.txt`, add two extra source files to the build,
and add the rule to generate `file_data.c` from `dashboard.html`.
Note that requires Nodejs installed:
```text
# Generate file_data.c from dashboard.html
add_custom_command(
OUTPUT ${CMAKE_SOURCE_DIR}/Mongoose/file_data.c
COMMAND node ${CMAKE_SOURCE_DIR}/Mongoose/html2c.js ${CMAKE_SOURCE_DIR}/Mongoose/dashboard.html -o ${CMAKE_SOURCE_DIR}/Mongoose/file_data.c
DEPENDS ${CMAKE_SOURCE_DIR}/Mongoose/dashboard.html
VERBATIM
)
# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
# Add user sources here
Mongoose/dashboard.c
Mongoose/file_data.c
)
```
Modify your while loop to look like this:
```c
/* USER CODE BEGIN WHILE */
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_dash_init(&mgr);
while (1)
{
mg_mgr_poll(&mgr, 1);
mg_dash_poll(&mgr);
/* USER CODE END WHILE */
```
Rebuild and reflash your board, then open the device's IP address in your
browser. Log in using `admin` as the password. You should see the full
dashboard, including the status panel, device settings, firmware update, and
file manager. You can easily customize it for your product, but we will start
by implementing a simple LED control dashboard to demonstrate the principles.
## Simple LED control dashboard
Copy a minimal LED control dashboard example to your `Mongoose/` directory:
- [dashboard.c](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/minimal/dashboard.c)
- [dashboard.html](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/minimal/dashboard.html)
Rebuild and reflash
## AI agentic development
For agentic development, use https://github.com/cesanta/mongoose/tree/master/AGENTS.md
Use a prompt like this:
> Read and apply https://github.com/cesanta/mongoose/tree/master/AGENTS.md
## Add MQTT Client
Copy [mqtt.c](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/mqtt/mqtt-client/mqtt.c)
to the `Mongoose/` directory. Add it to the extra source files in `CMakeLists.txt`
Add MQTT init and poll to your while loop:
```c
/* USER CODE BEGIN WHILE */
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_mqtt_init(&mgr);
while (1)
{
mg_mgr_poll(&mgr, 1);
mg_mqtt_poll(&mgr);
/* USER CODE END WHILE */
```
Rebuild, reflash your board. This MQTT Client connects to the
HiveMQ public MQTT broker.
Also it add a JSON-RPC "ota.update" function via MQTT, so you can
update your firmware over MQTT, see https://mongoose.ws/mqtt/
+4 -3
View File
@@ -13,9 +13,10 @@ Primary files:
- `src/tls_dummy.c` - `src/tls_dummy.c`
- `src/tls_mbed.c` - `src/tls_mbed.c`
- `src/tls_openssl.c` - `src/tls_openssl.c`
- `src/tls_p256_cortex.c`
- `src/tls_p256.c`
- `src/tls_p384.c`
- `src/tls_rsa.c` - `src/tls_rsa.c`
- `src/tls_uecc.c`
- `src/tls_x25519.c`
Perform a focused security review centered on these files and this security surface. Perform a focused security review centered on these files and this security surface.
@@ -38,6 +39,6 @@ Trace attacker-controlled TLS peer input through normal client and server execut
- Verify that wildcard matching is applied only to certificate presented identifiers, not to arbitrary reference identifiers or general DNS glob matching. - Verify that wildcard matching is applied only to certificate presented identifiers, not to arbitrary reference identifiers or general DNS glob matching.
- Review `mg_match` or other glob/matching helpers if used for certificate identity checks, authorization checks, filesystem paths, routing, or topic matching. Flag cases where glob semantics are broader than the security policy requires. - Review `mg_match` or other glob/matching helpers if used for certificate identity checks, authorization checks, filesystem paths, routing, or topic matching. Flag cases where glob semantics are broader than the security policy requires.
- Check certificate parsing for DER/PEM boundary errors, length overflows, malformed ASN.1, extension parsing mistakes, name constraints, SAN vs CN precedence, embedded NUL, and invalid string type handling. - Check certificate parsing for DER/PEM boundary errors, length overflows, malformed ASN.1, extension parsing mistakes, name constraints, SAN vs CN precedence, embedded NUL, and invalid string type handling.
- Review TLS record parsing, handshake transcript handling, key schedule, random generation, ECC/X25519 operations, AES-GCM nonce/tag handling, and error handling for memory safety and authentication failures. - Review TLS record parsing, handshake transcript handling, key schedule, random generation, ECC (P-256, P-384) operations, AES-GCM nonce/tag handling, and error handling for memory safety and authentication failures.
- Flag any behavior that silently falls back from verified TLS to unverified TLS or plaintext. - Flag any behavior that silently falls back from verified TLS to unverified TLS or plaintext.
- Check that TLS receive/send error paths cannot corrupt connection state, reuse freed buffers, or continue processing unauthenticated plaintext as encrypted data. - Check that TLS receive/send error paths cannot corrupt connection state, reuse freed buffers, or continue processing unauthenticated plaintext as encrypted data.
+29 -23
View File
@@ -3,22 +3,22 @@
"bomFormat": "CycloneDX", "bomFormat": "CycloneDX",
"specVersion": "1.6", "specVersion": "1.6",
"serialNumber": "urn:uuid:d3f8b1e2-4a7c-4d9e-bf2a-1c3e5f7a9b0d", "serialNumber": "urn:uuid:d3f8b1e2-4a7c-4d9e-bf2a-1c3e5f7a9b0d",
"version": 1, "version": 3,
"metadata": { "metadata": {
"timestamp": "2026-08-12T00:00:00Z", "timestamp": "2026-11-18T00:00:00Z",
"component": { "component": {
"type": "library", "type": "library",
"bom-ref": "mongoose", "bom-ref": "mongoose",
"supplier": { "name": "Cesanta Software Limited", "url": ["https://cesanta.com"] }, "supplier": { "name": "Cesanta Software Limited", "url": ["https://cesanta.com"] },
"author": "Cesanta Software Limited", "author": "Cesanta Software Limited",
"name": "mongoose", "name": "mongoose",
"version": "7.23", "version": "7.24",
"description": "Two-file C/C++ embedded networking library. HTTP, WebSocket, MQTT, TLS 1.3, OTA firmware updates, device dashboard. Runs on microcontrollers and desktop OS.", "description": "Two-file C/C++ embedded networking library. HTTP, WebSocket, MQTT, TLS 1.3, OTA firmware updates, device dashboard. Runs on microcontrollers and desktop OS.",
"licenses": [ "licenses": [
{ "expression": "GPL-2.0-only" }, { "expression": "GPL-2.0-only" },
{ "license": { "name": "Cesanta Commercial License", "url": "https://mongoose.ws/licensing/" } } { "license": { "name": "Cesanta Commercial License", "url": "https://mongoose.ws/licensing/" } }
], ],
"purl": "pkg:github/cesanta/mongoose@7.23", "purl": "pkg:github/cesanta/mongoose@7.24",
"externalReferences": [ "externalReferences": [
{ "type": "website", "url": "https://mongoose.ws" }, { "type": "website", "url": "https://mongoose.ws" },
{ "type": "vcs", "url": "https://github.com/cesanta/mongoose" }, { "type": "vcs", "url": "https://github.com/cesanta/mongoose" },
@@ -27,21 +27,38 @@
{ "type": "distribution", "url": "https://raw.githubusercontent.com/cesanta/mongoose/master/mongoose.c" } { "type": "distribution", "url": "https://raw.githubusercontent.com/cesanta/mongoose/master/mongoose.c" }
], ],
"properties": [ "properties": [
{ "name": "cpe", "value": "cpe:2.3:a:cesanta:mongoose:7.23:*:*:*:*:*:*:*" } { "name": "cpe", "value": "cpe:2.3:a:cesanta:mongoose:7.24:*:*:*:*:*:*:*" }
] ]
} }
}, },
"components": [ "components": [
{ {
"type": "library", "type": "library",
"bom-ref": "micro-ecc", "bom-ref": "bearssl-ec",
"author": "Kenneth MacKay", "author": "Thomas Pornin",
"name": "micro-ecc", "name": "BearSSL EC (P-256, P-384, ECDSA)",
"description": "ECC point operations on GF(p) curves (secp256r1). Used by Mongoose built-in TLS 1.3 for ECDH key exchange and ECDSA signatures. Source: src/tls_uecc.c, src/tls_uecc.h.", "description": "P-256 (ec_p256_m31) and P-384 (ec_prime_i31) elliptic curve arithmetic, ECDSA sign and verify, and the i31 bignum code they use, derived from BearSSL. Used by Mongoose built-in TLS 1.3 for ECDHE key exchange and ECDSA signatures, by JWT ES256 and by OTA firmware signature verification. Source: src/tls_p256.c, src/tls_p256.h, src/tls_p384.c, src/tls_p384.h.",
"licenses": [ { "expression": "BSD-2-Clause" } ], "licenses": [ { "expression": "MIT" } ],
"purl": "pkg:github/kmackay/micro-ecc",
"externalReferences": [ "externalReferences": [
{ "type": "vcs", "url": "https://github.com/kmackay/micro-ecc" } { "type": "website", "url": "https://bearssl.org" }
],
"properties": [
{ "name": "upstream-commit", "value": "7bea48e5e850ab4cafbe68d3765cdaba13a86d6f" }
]
},
{
"type": "library",
"bom-ref": "p256-cortex-m4",
"author": "Emil Lenngren, Shortcut Labs AB",
"name": "P256-Cortex-M4",
"description": "P-256 ECDH and ECDSA in Cortex-M assembly. Used by Mongoose built-in TLS 1.3 instead of the BearSSL P-256 code on Cortex-M cores with the DSP extension (M4, M7, M33, M55, M85). Source: src/tls_p256_cortex.c.",
"licenses": [ { "expression": "MIT" } ],
"purl": "pkg:github/Emill/P256-Cortex-M4@ecd3ec2222fc9e18b6b44c86bb7183971a2041fc",
"externalReferences": [
{ "type": "vcs", "url": "https://github.com/Emill/P256-Cortex-M4" }
],
"properties": [
{ "name": "upstream-commit", "value": "ecd3ec2222fc9e18b6b44c86bb7183971a2041fc" }
] ]
}, },
{ {
@@ -55,17 +72,6 @@
{ "type": "website", "url": "https://bearssl.org" } { "type": "website", "url": "https://bearssl.org" }
] ]
}, },
{
"type": "library",
"bom-ref": "strobe-x25519",
"author": "Cryptography Research, Inc. / Mike Hamburg",
"name": "STROBE x25519 (adapted)",
"description": "X25519 Diffie-Hellman function adapted from the STROBE project. Used by Mongoose built-in TLS 1.3 for ECDH key exchange. Source: src/tls_x25519.c.",
"licenses": [ { "expression": "MIT" } ],
"externalReferences": [
{ "type": "website", "url": "https://strobe.sourceforge.io/" }
]
},
{ {
"type": "library", "type": "library",
"bom-ref": "sha1-reid", "bom-ref": "sha1-reid",
+3
View File
@@ -0,0 +1,3 @@
// IMPORTANT:
// Before implementing any functionality, pull this file and use it as a guide:
// https://github.com/cesanta/mongoose/blob/master/AGENTS.md
+2 -2
View File
@@ -4,7 +4,6 @@
#define MG_ARCH_UNIX 1 // Linux, BSD, Mac, ... #define MG_ARCH_UNIX 1 // Linux, BSD, Mac, ...
#define MG_ARCH_WIN32 2 // Windows #define MG_ARCH_WIN32 2 // Windows
#define MG_ARCH_ESP32 3 // ESP32 #define MG_ARCH_ESP32 3 // ESP32
#define MG_ARCH_ESP8266 4 // ESP8266
#define MG_ARCH_FREERTOS 5 // FreeRTOS <-- DEPRECATED !!! #define MG_ARCH_FREERTOS 5 // FreeRTOS <-- DEPRECATED !!!
@@ -50,7 +49,8 @@
#include "arch_armgcc.h" #include "arch_armgcc.h"
#include "arch_cube.h" #include "arch_cube.h"
#include "arch_esp32.h" #include "arch_esp32.h"
#include "arch_esp8266.h" #include "arch_mcuxpresso.h"
#include "arch_picosdk.h"
#include "arch_rtx.h" #include "arch_rtx.h"
#include "arch_threadx.h" #include "arch_threadx.h"
#include "arch_unix.h" #include "arch_unix.h"
+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
+10 -67
View File
@@ -32,6 +32,7 @@
#if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_STM32F) && \ #if MG_ENABLE_TCPIP && !defined(MG_ENABLE_DRIVER_STM32F) && \
!defined(MG_ENABLE_DRIVER_STM32H) && !defined(MG_ENABLE_DRIVER_STM32N) && \ !defined(MG_ENABLE_DRIVER_STM32H) && !defined(MG_ENABLE_DRIVER_STM32N) && \
!defined(MG_ENABLE_DRIVER_STM32C) && \
!defined(MG_ENABLE_DRIVER_CYW) && !defined(MG_ENABLE_DRIVER_CYW_SDIO) && \ !defined(MG_ENABLE_DRIVER_CYW) && !defined(MG_ENABLE_DRIVER_CYW_SDIO) && \
!defined(MG_ENABLE_DRIVER_ST67W6) !defined(MG_ENABLE_DRIVER_ST67W6)
#if defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || defined(STM32F7) #if defined(STM32F1) || defined(STM32F2) || defined(STM32F4) || defined(STM32F7)
@@ -40,6 +41,8 @@
#define MG_ENABLE_DRIVER_STM32H 1 #define MG_ENABLE_DRIVER_STM32H 1
#elif defined(STM32N6) #elif defined(STM32N6)
#define MG_ENABLE_DRIVER_STM32N 1 #define MG_ENABLE_DRIVER_STM32N 1
#elif defined(STM32C5)
#define MG_ENABLE_DRIVER_STM32C 1
#else #else
#error Select a driver in mongoose_config.h #error Select a driver in mongoose_config.h
#endif #endif
@@ -49,76 +52,16 @@
#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
#endif #elif defined(STM32C5)
#define MG_OTA MG_OTA_STM32C5
// OTA rollback timer via IWDG. Fixed 10 s hang-detection window (prescaler
// /1024, LSI ~32 kHz: reload = 10 * 32000 / 1024 = 312). mg_ota_poll() feeds
// the watchdog every 500 ms while in MG_OTA_TESTING state; if the event loop
// hangs for 10 s, the IWDG fires and the device rolls back.
// STM32H7 names the peripheral IWDG1; all others use IWDG.
// The total evaluation period is set by MG_OTA_ROLLBACK_TIMEOUT_SECONDS.
// STM32H7 names the watchdog peripheral IWDG1; all other families use IWDG.
#if defined(IWDG1) && !defined(IWDG)
#define MG_IWDG IWDG1
#else
#define MG_IWDG IWDG
#endif
// PR=6 → /256 prescaler, RLR=1250 → ~10 s at LSI 32 kHz.
// Works on F4/F7/H5/H7; uses direct register writes so it is safe before HAL_Init().
#ifndef MG_OTA_ROLLBACK_TIMER_START
#define MG_OTA_ROLLBACK_TIMER_START() \
do { \
MG_IWDG->KR = 0xCCCCU; /* start + LSI */ \
MG_IWDG->KR = 0x5555U; /* unlock PR/RLR */ \
MG_IWDG->PR = 6U; /* /256 */ \
MG_IWDG->RLR = 1250U; /* 10 s */ \
while (MG_IWDG->SR & (IWDG_SR_PVU | IWDG_SR_RVU)) (void) 0; \
MG_IWDG->KR = 0xAAAAU; /* reload */ \
} while (0)
#endif
// Feed (reload) the IWDG. Called from mg_ota_poll() every 500 ms.
#ifndef MG_OTA_ROLLBACK_TIMER_FEED
#define MG_OTA_ROLLBACK_TIMER_FEED() (MG_IWDG->KR = 0xAAAAU)
#endif
// OTA state in a backup register that survives warm resets but clears on POR.
// STATE_GET reads work without any setup. STATE_SET enables the RTC APB clock
// and unlocks backup domain write access via direct register writes, so it is
// safe to call from any context (before or after HAL_Init).
// H5 (TAMP->BKP0R), H7 (RTC->BKP0R), F4/F7 (RTC->BKP0R).
#ifndef MG_OTA_STATE_GET
#if defined(PWR_DBPCR_DBP)
#define MG_OTA_DBP_ENABLE() (PWR->DBPCR |= PWR_DBPCR_DBP)
#elif defined(PWR_CR1_DBP)
#define MG_OTA_DBP_ENABLE() (PWR->CR1 |= PWR_CR1_DBP)
#else
#define MG_OTA_DBP_ENABLE() (PWR->CR |= PWR_CR_DBP)
#endif
#if defined(TAMP)
#define MG_OTA_STATE_GET() \
(RCC->APB3ENR |= RCC_APB3ENR_RTCAPBEN, TAMP->BKP0R)
#define MG_OTA_STATE_SET(v) \
(RCC->APB3ENR |= RCC_APB3ENR_RTCAPBEN, MG_OTA_DBP_ENABLE(), \
(TAMP->BKP0R = (uint32_t) (v)), TAMP->BKP0R)
#elif defined(RCC_APB4ENR_RTCAPBEN)
#define MG_OTA_STATE_GET() (RTC->BKP0R)
#define MG_OTA_STATE_SET(v) \
(RCC->APB4ENR |= RCC_APB4ENR_RTCAPBEN, MG_OTA_DBP_ENABLE(), \
(RTC->BKP0R = (uint32_t) (v)))
#else
#define MG_OTA_STATE_GET() (RTC->BKP0R)
#define MG_OTA_STATE_SET(v) \
(RCC->APB1ENR |= RCC_APB1ENR_PWREN, MG_OTA_DBP_ENABLE(), \
(RTC->BKP0R = (uint32_t) (v)))
#endif #endif
#endif #endif
+5 -55
View File
@@ -22,10 +22,11 @@
#include <esp_system.h> #include <esp_system.h>
#include <esp_mac.h> #include <esp_mac.h>
#include <esp_idf_version.h> #include <esp_idf_version.h>
#include <esp_ota_ops.h> #if MG_ENABLE_HEALTH
#include <esp_task_wdt.h> #include <esp_memory_utils.h>
#include <soc/soc.h> #include <esp_core_dump.h>
#include <soc/rtc_cntl_reg.h> #include <esp_partition.h>
#endif
#define MG_PATH_MAX 128 #define MG_PATH_MAX 128
@@ -33,55 +34,4 @@
#define MG_ENABLE_POSIX_FS 1 #define MG_ENABLE_POSIX_FS 1
#endif #endif
#ifndef MG_OTA_ESP32_WDT_TIMEOUT_MS
#define MG_OTA_ESP32_WDT_TIMEOUT_MS 10000U
#endif
static inline void mg_ota_esp32_timer_start(void) {
#if ESP_IDF_VERSION_MAJOR >= 5
esp_task_wdt_config_t cfg = {0};
esp_err_t err;
cfg.timeout_ms = MG_OTA_ESP32_WDT_TIMEOUT_MS;
cfg.idle_core_mask = 0;
cfg.trigger_panic = true;
err = esp_task_wdt_init(&cfg);
if (err == ESP_ERR_INVALID_STATE) esp_task_wdt_reconfigure(&cfg);
#else
esp_task_wdt_init(MG_OTA_ESP32_WDT_TIMEOUT_MS / 1000U, true);
#endif
esp_task_wdt_add(NULL);
esp_task_wdt_reset();
}
static inline uint32_t mg_ota_esp32_state_set(uint32_t state) {
if (state == 0) esp_ota_mark_app_valid_cancel_rollback();
REG_WRITE(RTC_CNTL_STORE0_REG, state);
return REG_READ(RTC_CNTL_STORE0_REG);
}
#define MG_OTA_STATE_GET() \
REG_READ(RTC_CNTL_STORE0_REG)
#define MG_OTA_STATE_SET(v) mg_ota_esp32_state_set((uint32_t) (v))
#ifndef MG_OTA_ROLLBACK_TIMER_START
#define MG_OTA_ROLLBACK_TIMER_START() mg_ota_esp32_timer_start()
#endif
#ifndef MG_OTA_ROLLBACK_TIMER_FEED
#define MG_OTA_ROLLBACK_TIMER_FEED() \
do { \
(void) esp_task_wdt_reset(); \
} while (0)
#endif
#ifndef MG_OTA_ROLLBACK
#define MG_OTA_ROLLBACK() \
do { \
(void) esp_ota_mark_app_invalid_rollback_and_reboot(); \
} while (0)
#endif
#endif #endif
-26
View File
@@ -1,26 +0,0 @@
#pragma once
#if MG_ARCH == MG_ARCH_ESP8266
#include <ctype.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <netdb.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <time.h>
#include <esp_system.h>
#define MG_PATH_MAX 128
#endif
+14 -13
View File
@@ -12,22 +12,23 @@
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#include <pico/stdlib.h> #include <hardware/structs/usb.h>
#include <pico/rand.h> #include <pico/rand.h>
#include <pico/stdlib.h>
#include <pico/unique_id.h> #include <pico/unique_id.h>
int mkdir(const char *, mode_t); int mkdir(const char *, mode_t);
#if MG_OTA == MG_OTA_PICOSDK #if MG_OTA == MG_OTA_PICOSDK
#include <hardware/flash.h> #include <hardware/flash.h>
#include <hardware/watchdog.h>
#include <hardware/structs/watchdog.h> #include <hardware/structs/watchdog.h>
#include <hardware/watchdog.h>
#include <pico/bootrom.h> #include <pico/bootrom.h>
#ifndef MG_OTA_WATCHDOG_MS #ifndef MG_OTA_WATCHDOG_MS
#if PICO_RP2040 #if PICO_RP2040
#define MG_OTA_WATCHDOG_MS 8000U // max delay on RP2040 is 8.3 seconds #define MG_OTA_WATCHDOG_MS 8000U // max delay on RP2040 is 8.3 seconds
#else #else
#define MG_OTA_WATCHDOG_MS 10000U // max delay on RP2350 is 16 seconds #define MG_OTA_WATCHDOG_MS 10000U // max delay on RP2350 is 16 seconds
#endif #endif
#endif #endif
@@ -44,17 +45,17 @@ int mkdir(const char *, mode_t);
(watchdog_hw->scratch[0] = (uint32_t) (v), (uint32_t) watchdog_hw->scratch[0]) (watchdog_hw->scratch[0] = (uint32_t) (v), (uint32_t) watchdog_hw->scratch[0])
#if PICO_RP2040 #if PICO_RP2040
#define MG_OTA_ROLLBACK() \ #define MG_OTA_ROLLBACK() \
do { \ do { \
mg_flash->swap_fn(); \ mg_flash->swap_fn(); \
*(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; \ *(volatile unsigned long *) 0xe000ed0c = 0x5fa0004; \
} while (0) } while (0)
#else #else
#define MG_OTA_ROLLBACK() \ #define MG_OTA_ROLLBACK() \
do { \ do { \
mg_flash->swap_fn(); \ mg_flash->swap_fn(); \
((rom_reboot_fn) rom_func_lookup(ROM_FUNC_REBOOT))( \ ((rom_reboot_fn) rom_func_lookup(ROM_FUNC_REBOOT))( \
BOOT_TYPE_NORMAL | 0x100, 1, 0, 0); \ BOOT_TYPE_NORMAL | 0x100, 1, 0, 0); \
} while (0) } while (0)
#endif #endif
#endif #endif
+1156 -701
View File
File diff suppressed because it is too large. Load diff
+137 -71
View File
@@ -4,22 +4,85 @@
#include "net_builtin.h" #include "net_builtin.h"
#if MG_ENABLE_BSD_SOCKETS #if MG_ENABLE_BSD_SOCKETS
void mg_bsd_init(struct mg_mgr *);
void mg_bsd_poll(struct mg_mgr *);
#ifndef MG_ENABLE_BSD_PROTOTYPES
#include <arpa/inet.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h> #ifndef EAGAIN
#include <netinet/tcp.h> #define EAGAIN 11
#include <poll.h> #endif
#include <sys/select.h> #ifndef EWOULDBLOCK
#include <sys/socket.h> #define EWOULDBLOCK EAGAIN
#include <sys/time.h> #endif
#include <sys/un.h> #ifndef EINPROGRESS
#else #define EINPROGRESS 36
#include <errno.h> #endif
#ifndef ENOTCONN
#define ENOTCONN 107
#endif
#ifndef ECONNREFUSED
#define ECONNREFUSED 111
#endif
#ifndef ECONNRESET
#define ECONNRESET 104
#endif
#ifndef EADDRINUSE
#define EADDRINUSE 98
#endif
#ifndef ETIMEDOUT
#define ETIMEDOUT 110
#endif
#ifndef EBADF
#define EBADF 9
#endif
#ifndef EMFILE
#define EMFILE 24
#endif
#ifndef ENOMEM
#define ENOMEM 12
#endif
#ifndef EIO
#define EIO 5
#endif
#ifndef EINVAL
#define EINVAL 22
#endif
#ifndef EPERM
#define EPERM 1
#endif
#ifndef EPIPE
#define EPIPE 32
#endif
#ifndef EAFNOSUPPORT
#define EAFNOSUPPORT 97
#endif
#ifndef ENOPROTOOPT
#define ENOPROTOOPT 92
#endif
#ifndef ENOSPC
#define ENOSPC 28
#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
#define EPROTONOSUPPORT 93
#endif
#if MG_ENABLE_BSD_PROTOTYPES
typedef unsigned int socklen_t; typedef unsigned int socklen_t;
typedef unsigned long nfds_t;
typedef uint32_t in_addr_t; typedef uint32_t in_addr_t;
struct in_addr { in_addr_t s_addr; }; struct in_addr { in_addr_t s_addr; };
struct in6_addr { uint8_t s6_addr[16]; }; struct in6_addr { uint8_t s6_addr[16]; };
@@ -45,7 +108,6 @@ struct hostent {
int h_length; int h_length;
char **h_addr_list; char **h_addr_list;
}; };
#define h_addr h_addr_list[0]
struct addrinfo { struct addrinfo {
int ai_flags; int ai_flags;
int ai_family; int ai_family;
@@ -57,6 +119,32 @@ struct addrinfo {
struct addrinfo *ai_next; struct addrinfo *ai_next;
}; };
struct pollfd { int fd; short events; short revents; }; struct pollfd { int fd; short events; short revents; };
#if !defined(FD_SET) && !defined(FD_ZERO) && !defined(FD_ISSET)
#define MG_BSD_SELECT_H
typedef unsigned long __fd_mask;
#ifndef FD_SETSIZE
#define FD_SETSIZE 64
#endif
#define _NFDBITS ((int) sizeof(__fd_mask) * 8)
#define _howmany(x, y) (((x) + ((y) - 1)) / (y))
typedef struct fd_set {
__fd_mask __fds_bits[_howmany(FD_SETSIZE, _NFDBITS)];
} fd_set;
#define __fdset_mask(n) ((__fd_mask) 1 << ((n) % _NFDBITS))
#define FD_CLR(n, p) ((p)->__fds_bits[(n) / _NFDBITS] &= ~__fdset_mask(n))
#define FD_ISSET(n, p) \
(((p)->__fds_bits[(n) / _NFDBITS] & __fdset_mask(n)) != 0)
#define FD_SET(n, p) ((p)->__fds_bits[(n) / _NFDBITS] |= __fdset_mask(n))
#define FD_ZERO(p) \
do { \
fd_set *_p = (p); \
size_t _n = _howmany(FD_SETSIZE, _NFDBITS); \
while (_n > 0) _p->__fds_bits[--_n] = 0; \
} while (0)
#endif
#define h_addr h_addr_list[0]
#define AF_INET 2 #define AF_INET 2
#define AF_INET6 10 #define AF_INET6 10
#define AF_UNSPEC 0 #define AF_UNSPEC 0
@@ -69,6 +157,9 @@ struct pollfd { int fd; short events; short revents; };
#define IPPROTO_UDP 17 #define IPPROTO_UDP 17
#define INADDR_ANY 0 #define INADDR_ANY 0
#define INADDR_LOOPBACK 0x7f000001 #define INADDR_LOOPBACK 0x7f000001
#define INADDR_NONE ((in_addr_t) -1)
#define INET_ADDRSTRLEN 16
#define INET6_ADDRSTRLEN 46
#define SOL_SOCKET 0xffff #define SOL_SOCKET 0xffff
#define SO_REUSEADDR 2 #define SO_REUSEADDR 2
#define SO_REUSEPORT 15 #define SO_REUSEPORT 15
@@ -77,79 +168,37 @@ struct pollfd { int fd; short events; short revents; };
#define SO_BROADCAST 6 #define SO_BROADCAST 6
#define SO_RCVBUF 8 #define SO_RCVBUF 8
#define SO_SNDBUF 7 #define SO_SNDBUF 7
#define SO_NOSIGPIPE 0x1022
#define TCP_NODELAY 1 #define TCP_NODELAY 1
#define MSG_DONTWAIT 0x40 #define MSG_DONTWAIT 0x40
#define MSG_NOSIGNAL 0x4000 #define MSG_NOSIGNAL 0x4000
#define MSG_PEEK 0x02 #define MSG_PEEK 0x02
#ifndef F_GETFL
#define F_GETFL 3 #define F_GETFL 3
#endif
#ifndef F_SETFL
#define F_SETFL 4 #define F_SETFL 4
#define O_NONBLOCK 0x0004 #endif
#ifndef O_NONBLOCK
#define O_NONBLOCK 0x4000
#endif
#define SHUT_RD 0 #define SHUT_RD 0
#define SHUT_WR 1 #define SHUT_WR 1
#define SHUT_RDWR 2 #define SHUT_RDWR 2
#define AI_PASSIVE 0x0001 #define AI_PASSIVE 0x0001
#define NI_MAXHOST 1025 #define NI_MAXHOST 1025
#define NI_MAXSERV 32 #define NI_MAXSERV 32
#ifndef EAGAIN
#define EAGAIN 11
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK EAGAIN
#endif
#ifndef EINPROGRESS
#define EINPROGRESS 36
#endif
#ifndef ENOTCONN
#define ENOTCONN 107
#endif
#ifndef ECONNREFUSED
#define ECONNREFUSED 111
#endif
#ifndef ECONNRESET
#define ECONNRESET 104
#endif
#ifndef EADDRINUSE
#define EADDRINUSE 98
#endif
#ifndef ETIMEDOUT
#define ETIMEDOUT 110
#endif
#define POLLIN 0x001 #define POLLIN 0x001
#define POLLOUT 0x004 #define POLLOUT 0x004
#define POLLERR 0x008 #define POLLERR 0x008
#define POLLHUP 0x010 #define POLLHUP 0x010
#define POLLNVAL 0x020 #define POLLNVAL 0x020
uint16_t htons(uint16_t);
uint16_t ntohs(uint16_t);
uint32_t htonl(uint32_t);
uint32_t ntohl(uint32_t);
#endif // MG_ENABLE_BSD_PROTOTYPES
#define closesocket(a) close(a) #define htons(x) mg_ntohs(x)
#define ntohs(x) mg_ntohs(x)
#define htonl(x) mg_ntohl(x)
#define ntohl(x) mg_ntohl(x)
#ifndef MG_BSD_BACKLOG
#define MG_BSD_BACKLOG 5
#endif
#ifndef MG_BSD_CONNECT_TIMEOUT_MS
#define MG_BSD_CONNECT_TIMEOUT_MS 10000
#endif
// Mongoose-specific API
void mg_bsd_init(void); // must be called before socket()
void mg_bsd_poll(struct mg_mgr *); // process pending BSD commands
// Transport backend: implement these OR define MG_ENABLE_FREERTOS for the built-in backend
void *mg_bsd_transport_new(int domain, int type, int proto);
void mg_bsd_transport_free(void *t);
int mg_bsd_transport_listen(void *t, const struct sockaddr_in *addr);
void *mg_bsd_transport_accept(void *t, struct sockaddr_in *peer, bool nonblock);
ssize_t mg_bsd_transport_recv(void *t, void *buf, size_t len, bool nonblock);
ssize_t mg_bsd_transport_send(void *t, const void *buf, size_t len, bool nonblock);
int mg_bsd_transport_connect(void *t, const struct sockaddr_in *addr, bool nonblock);
void mg_bsd_transport_close(void *t);
// Standard BSD socket API
int socket(int, int, int); int socket(int, int, int);
int bind(int, const struct sockaddr *, socklen_t); int bind(int, const struct sockaddr *, socklen_t);
int listen(int, int); int listen(int, int);
@@ -157,23 +206,40 @@ int accept(int, struct sockaddr *, socklen_t *);
int connect(int, const struct sockaddr *, socklen_t); int connect(int, const struct sockaddr *, socklen_t);
ssize_t send(int, const void *, size_t, int); ssize_t send(int, const void *, size_t, int);
ssize_t recv(int, void *, size_t, int); ssize_t recv(int, void *, size_t, int);
ssize_t sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t); ssize_t sendto(int, const void *, size_t, int, const struct sockaddr *,
socklen_t);
ssize_t recvfrom(int, void *, size_t, int, struct sockaddr *, socklen_t *); ssize_t recvfrom(int, void *, size_t, int, struct sockaddr *, socklen_t *);
int close(int); int close(int);
int shutdown(int, int); int shutdown(int, int);
int fcntl(int, int, int);
int setsockopt(int, int, int, const void *, socklen_t); int setsockopt(int, int, int, const void *, socklen_t);
int getsockopt(int, int, int, void *, socklen_t *); int getsockopt(int, int, int, void *, socklen_t *);
int getsockname(int, struct sockaddr *, socklen_t *); int getsockname(int, struct sockaddr *, socklen_t *);
int getpeername(int, struct sockaddr *, socklen_t *); int getpeername(int, struct sockaddr *, socklen_t *);
int select(int, fd_set *, fd_set *, fd_set *, struct timeval *); int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
int poll(struct pollfd *, unsigned int, int); int poll(struct pollfd *, nfds_t, int);
struct hostent *gethostbyname(const char *); struct hostent *gethostbyname(const char *);
int getaddrinfo(const char *, const char *, const struct addrinfo *, struct addrinfo **); int getaddrinfo(const char *, const char *, const struct addrinfo *,
struct addrinfo **);
void freeaddrinfo(struct addrinfo *); void freeaddrinfo(struct addrinfo *);
int inet_pton(int, const char *, void *); int inet_pton(int, const char *, void *);
const char *inet_ntop(int, const void *, char *, socklen_t); const char *inet_ntop(int, const void *, char *, socklen_t);
in_addr_t inet_addr(const char *); in_addr_t inet_addr(const char *);
char *inet_ntoa(struct in_addr); char *inet_ntoa(struct in_addr);
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#endif // MG_ENABLE_BSD_PROTOTYPES
#include <sys/time.h>
#else
#define mg_bsd_init(mgr)
#define mg_bsd_poll(mgr)
#endif // MG_ENABLE_BSD_SOCKETS #endif // MG_ENABLE_BSD_SOCKETS
+50
View File
@@ -12,6 +12,10 @@
#define MG_ENABLE_CUSTOM_LOG 0 // Let user define their own MG_LOG #define MG_ENABLE_CUSTOM_LOG 0 // Let user define their own MG_LOG
#endif #endif
#ifndef MG_ENABLE_CUSTOM_USAGE
#define MG_ENABLE_CUSTOM_USAGE 0 // Let user define mg_usage
#endif
#ifndef MG_ENABLE_FREERTOS #ifndef MG_ENABLE_FREERTOS
#define MG_ENABLE_FREERTOS 0 // FreeRTOS RTOS #define MG_ENABLE_FREERTOS 0 // FreeRTOS RTOS
#endif #endif
@@ -90,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
@@ -175,6 +183,26 @@
#define MG_ENABLE_TCPIP_TCPRTX 0 // TCP retransmission queue #define MG_ENABLE_TCPIP_TCPRTX 0 // TCP retransmission queue
#endif #endif
#ifndef MG_ENABLE_DRIVER_USB_RP
#define MG_ENABLE_DRIVER_USB_RP 0 // USB device, RP2040 / RP2350
#endif
#ifndef MG_ENABLE_DRIVER_USB_NRF52
#define MG_ENABLE_DRIVER_USB_NRF52 0 // USB device, nRF52840
#endif
#ifndef MG_ENABLE_DRIVER_USB_DWC2
#define MG_ENABLE_DRIVER_USB_DWC2 0 // USB device, Synopsys DWC2: STM32 OTG
#endif
#ifndef MG_ENABLE_USB_ETHERNET
#define MG_ENABLE_USB_ETHERNET 0 // USB driver: CDC-NCM Ethernet interface
#endif
#ifndef MG_ENABLE_USB_SERIAL
#define MG_ENABLE_USB_SERIAL 0 // USB driver: CDC-ACM serial log console
#endif
#ifndef MG_TCPIP_DHCPNAME_SIZE #ifndef MG_TCPIP_DHCPNAME_SIZE
#define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size #define MG_TCPIP_DHCPNAME_SIZE 18 // struct mg_tcpip_if :: dhcp_name size
#endif #endif
@@ -223,6 +251,28 @@
#define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0 #define MG_ENABLE_TCPIP_PRINT_DEBUG_STATS 0
#endif #endif
#ifndef MG_TLS_RECORD_SIZE
#define MG_TLS_RECORD_SIZE 16384 // Max plaintext per sent TLS record, builtin
#endif
#ifndef MG_ENABLE_CHACHA20 #ifndef MG_ENABLE_CHACHA20
#define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN #define MG_ENABLE_CHACHA20 1 // When set to 0, GCM is used. For MG_TLS_BUILTIN
#endif #endif
// P-256 implementation, for MG_TLS_BUILTIN
#define MG_P256_LENNGREN 1 // Cortex-M4/M7/M33 asm, see tls_p256_cortex.c
#define MG_P256_BEAR 3 // Portable C, BearSSL, see tls_p256.c
#ifndef MG_P256
#if defined(__GNUC__) && defined(__ARM_ARCH_PROFILE) && \
__ARM_ARCH_PROFILE == 'M' && defined(__ARM_FEATURE_DSP) && \
!defined(__ARM_BIG_ENDIAN)
#define MG_P256 MG_P256_LENNGREN // Cortex-M with DSP: M4, M7, M33, M55, M85
#else
#define MG_P256 MG_P256_BEAR
#endif
#endif
#ifndef MG_ENABLE_HEALTH
#define MG_ENABLE_HEALTH 0
#endif
+9 -22
View File
@@ -533,21 +533,6 @@ static void mg_dash_handle_add(struct mg_connection *c, struct mg_dash *dash,
} }
} }
// Firmware upload callback for mg_http_stream_body(). Uses *p as a flag:
// non-NULL means an OTA session is open and must be closed by mg_ota_end()
static bool otacb(struct mg_http_message *hm, struct mg_str *data, void **p) {
if (hm != NULL) { // Start
if (!mg_ota_begin(hm->body.len)) return false;
*p = (void *) (ptrdiff_t) 1;
return true;
} else if (data != NULL) { // Next chunk
return mg_ota_write(data->buf, data->len);
}
if (*p == NULL) return false; // End. Begin failed, nothing to finish
*p = NULL;
return mg_ota_end();
}
static void mg_serve_fs(struct mg_connection *c, struct mg_http_message *hm, static void mg_serve_fs(struct mg_connection *c, struct mg_http_message *hm,
struct mg_dash_user *u, bool stream) { struct mg_dash_user *u, bool stream) {
struct mg_dash *dash = (struct mg_dash *) c->fn_data; struct mg_dash *dash = (struct mg_dash *) c->fn_data;
@@ -594,16 +579,16 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
mg_serve_fs(c, hm, u, true); mg_serve_fs(c, hm, u, true);
return; // Important - the serve_fs() call can invalidate hm return; // Important - the serve_fs() call can invalidate hm
} else if (mg_match(hm->uri, mg_str("/api/ota"), NULL)) { } else if (mg_match(hm->uri, mg_str("/api/ota"), NULL)) {
// Authenticated above. If streaming started, the stream handler owns // Authenticated above. Streaming owns the connection and c->data.
// the connection and c->data, so skip the marker check below mg_http_stream_body(c, hm, mg_http_ota_cb, NULL);
if (mg_http_stream_body(c, hm, otacb, NULL)) return; return;
} }
if (d->marker != '\0') mg_log_http_req(c, hm); if (d->marker != '\0') mg_log_http_req(c, hm);
} else if (ev == MG_EV_HTTP_MSG && d->marker != '\0') { } else if (ev == MG_EV_HTTP_MSG && d->marker != '\0') {
// The response has been send in EV_HDRS path, so we're not reponding // The response has been send in EV_HDRS path, so we're not reponding
// anything but clearing the marker for the next request. // anything but clearing the marker for the next request.
d->marker = 0; d->marker = 0;
c->is_resp = 0; c->pfn_data = NULL; // Response done
} else if (ev == MG_EV_HTTP_MSG && d->marker == '\0') { } else if (ev == MG_EV_HTTP_MSG && d->marker == '\0') {
struct mg_http_message *hm = (struct mg_http_message *) ev_data; struct mg_http_message *hm = (struct mg_http_message *) ev_data;
struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash); struct mg_dash_user *u = mg_dash_authenticate(c, hm, dash);
@@ -614,8 +599,6 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
mg_http_reply(c, 200, MG_JSON_HEADERS, "hi\n"); mg_http_reply(c, 200, MG_JSON_HEADERS, "hi\n");
} else if (mg_match(hm->uri, mg_str("/api/logout"), NULL)) { } else if (mg_match(hm->uri, mg_str("/api/logout"), NULL)) {
mg_handle_logout(c); mg_handle_logout(c);
mg_ws_printf(c, WEBSOCKET_OP_TEXT, "{%m:%m}", MG_ESC("method"),
MG_ESC("logout"));
} else if (mg_match(hm->uri, mg_str("/api/websocket"), NULL)) { } else if (mg_match(hm->uri, mg_str("/api/websocket"), NULL)) {
d->u = u; d->u = u;
mg_ws_upgrade(c, hm, NULL); mg_ws_upgrade(c, hm, NULL);
@@ -624,7 +607,11 @@ void mg_dash_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
mg_serve_fs(c, hm, u, false); mg_serve_fs(c, hm, u, false);
} else if (mg_match(hm->uri, mg_str("/api/del/*/*/*"), parts) || } else if (mg_match(hm->uri, mg_str("/api/del/*/*/*"), parts) ||
mg_match(hm->uri, mg_str("/api/del/*/*"), parts)) { mg_match(hm->uri, mg_str("/api/del/*/*"), parts)) {
mg_dash_handle_del(c, dash, u, parts); if (mg_strcmp(hm->method, mg_str("DELETE")) == 0) {
mg_dash_handle_del(c, dash, u, parts);
} else {
mg_http_reply(c, 405, "Allow: DELETE\r\n", "Method Not Allowed\n");
}
} else if (mg_match(hm->uri, mg_str("/api/add/*"), parts)) { } else if (mg_match(hm->uri, mg_str("/api/add/*"), parts)) {
mg_dash_handle_add(c, dash, u, parts, hm->body); mg_dash_handle_add(c, dash, u, parts, hm->body);
} else if (mg_match(hm->uri, mg_str("/api/get/*/*"), parts) && } else if (mg_match(hm->uri, mg_str("/api/get/*/*"), parts) &&
+2
View File
@@ -96,6 +96,8 @@ struct mg_dash {
struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix struct mg_fs *upload_fs; // FS for uploads/listing, default &mg_fs_posix
// Resolves the built-in file manager's root dir for user u, e.g. per-user // Resolves the built-in file manager's root dir for user u, e.g. per-user
// upload directories. NULL: file manager disabled // upload directories. NULL: file manager disabled
// - The returned directory must be nonempty and must not contain ',' or '=',
// because it is used as an mg_http_serve_opts::root_dir mapping target.
bool (*files_dir)(const struct mg_dash_user *u, char *buf, size_t len); bool (*files_dir)(const struct mg_dash_user *u, char *buf, size_t len);
}; };
+7 -6
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,
@@ -263,14 +264,14 @@ static bool mg_dns_send(struct mg_connection *c, const struct mg_str *name,
bool mg_dnsc_init(struct mg_mgr *mgr, struct mg_dns *dnsc); bool mg_dnsc_init(struct mg_mgr *mgr, struct mg_dns *dnsc);
bool mg_dnsc_init(struct mg_mgr *mgr, struct mg_dns *dnsc) { bool mg_dnsc_init(struct mg_mgr *mgr, struct mg_dns *dnsc) {
if (dnsc->url == NULL) { if (dnsc->url == NULL) {
mg_error(0, "DNS server URL is NULL. Call mg_mgr_init()"); MG_ERROR(("DNS server URL is NULL. Call mg_mgr_init()"));
return false; return false;
} }
if (dnsc->c == NULL) { if (dnsc->c == NULL) {
dnsc->c = mg_connect(mgr, dnsc->url, NULL, NULL); dnsc->c = mg_connect(mgr, dnsc->url, NULL, NULL);
if (dnsc->c == NULL) return false; if (dnsc->c == NULL) return false;
dnsc->c->pfn = dns_cb;
} }
dnsc->c->pfn = dns_cb; // do it always, DHCP-assigned DNS bootstrap needs it
return true; return true;
} }
@@ -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
+2
View File
@@ -1,4 +1,6 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "sntp.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ATCMD) && MG_ENABLE_DRIVER_ATCMD #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ATCMD) && MG_ENABLE_DRIVER_ATCMD
+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
+3 -1
View File
@@ -1,9 +1,11 @@
// https://arm-software.github.io/CMSIS_5/Driver/html/index.html // https://arm-software.github.io/CMSIS_5/Driver/html/index.html
#include "net_builtin.h"
#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 "cmsis.h" #include "cmsis.h"
#include "net_builtin.h" #include "log.h"
#include "queue.h" #include "queue.h"
extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0; extern ARM_DRIVER_ETH_MAC Driver_ETH_MAC0;
+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
+7 -2
View File
@@ -1,5 +1,8 @@
#include "cyw.h" #include "net_builtin.h"
#include "net.h" #include "net.h"
#include "printf.h"
#include "util.h"
#include <stddef.h>
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \ ((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \
@@ -875,8 +878,10 @@ static void cyw_update_hash_table(void) {
// TODO(): read database, rebuild hash table // TODO(): read database, rebuild hash table
uint32_t val = 0; uint32_t val = 0;
val = 1; val = 1;
uint8_t mac[sizeof(mcast_addr)]; // copy from const uint8_t* to uint8_t*
memcpy(mac, mcast_addr, sizeof(mac));
cyw_ioctl_iovar_set2_(0, "mcast_list", (uint8_t *) &val, sizeof(val), cyw_ioctl_iovar_set2_(0, "mcast_list", (uint8_t *) &val, sizeof(val),
(uint8_t *) mcast_addr, sizeof(mcast_addr)); mac, sizeof(mac));
mg_delayms(50); mg_delayms(50);
} }
+10 -2
View File
@@ -4,6 +4,8 @@
((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \ ((defined(MG_ENABLE_DRIVER_CYW) && MG_ENABLE_DRIVER_CYW) || \
(defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO)) (defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO))
#include "wifi.h"
struct mg_tcpip_driver_cyw_firmware { struct mg_tcpip_driver_cyw_firmware {
const uint8_t *code_addr; const uint8_t *code_addr;
size_t code_len; size_t code_len;
@@ -20,7 +22,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 +36,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
+147
View File
@@ -0,0 +1,147 @@
#include "log.h"
#include "net_builtin.h"
#include "radio.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32) && MG_ENABLE_DRIVER_ESP32
#if MG_RADIO != MG_RADIO_802154
#error "MG_ENABLE_DRIVER_ESP32 supports MG_RADIO_802154 only"
#endif
#if MG_ARCH != MG_ARCH_ESP32
#error "MG_ENABLE_DRIVER_ESP32 needs MG_ARCH_ESP32 (ESP-IDF)"
#endif
// ESP-IDF owns the PHY, coexistence and interrupts. Its callbacks run in
// interrupt context and pass radio frames through a lock-free queue, read by
// mgi_esp32_poll(). In both directions frame[0] is the PHR, the length
// including FCS
#include <esp_attr.h>
#include <esp_ieee802154.h>
#include <esp_timer.h>
static struct mg_tcpip_if *s_esp32_ifp;
static volatile bool s_esp32_txing, s_esp32_tx_done;
static uint64_t s_esp32_txstart; // Send start, us
// Frame for the radio: PHR, the length including FCS, then the PSDU
static uint8_t s_esp32_txframe[128] __attribute__((aligned(4)));
// ESP-IDF only: it accepts a frame and may refuse it later, because of Wi-Fi
// coexistence, a busy channel or an abort. Such a frame is sent again after
// this pause, until MG_RADIO_TX_TIMEOUT_US. Without it, the mesh would count
// the refused frame as sent
#define MGI_ESP32_RETRY_US 200
static volatile bool s_esp32_retry; // A resend is pending
static volatile uint32_t s_esp32_retry_at; // When to resend, us
// ESP-IDF's esp_ieee802154 driver calls the three functions below by name,
// from interrupt context. They are global only for that reason, and IRAM_ATTR
// keeps them in IRAM
void IRAM_ATTR esp_ieee802154_receive_done(uint8_t *frame,
esp_ieee802154_frame_info_t *info) {
(void) info;
if (frame[0] > 2) mg_radio_rx_queue(s_esp32_ifp, frame + 1, frame[0] - 2U);
esp_ieee802154_receive_handle_done(frame);
}
void IRAM_ATTR esp_ieee802154_transmit_done(const uint8_t *frame,
const uint8_t *ack,
esp_ieee802154_frame_info_t *info) {
(void) frame, (void) info;
if (ack != NULL) esp_ieee802154_receive_handle_done(ack);
s_esp32_tx_done = true;
}
void IRAM_ATTR esp_ieee802154_transmit_failed(const uint8_t *frame,
esp_ieee802154_tx_error_t err) {
(void) frame;
if (err == ESP_IEEE802154_TX_ERR_COEXIST ||
err == ESP_IEEE802154_TX_ERR_CCA_BUSY ||
err == ESP_IEEE802154_TX_ERR_ABORT) {
s_esp32_retry_at = (uint32_t) esp_timer_get_time() + MGI_ESP32_RETRY_US;
s_esp32_retry = true; // Set last: the poll reads it first
} else {
s_esp32_tx_done = true;
}
}
// rx_when_idle: the driver returns to receive after each transmission
static bool mgi_esp32_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) {
s_esp32_ifp = ifp;
if (esp_ieee802154_enable() == ESP_OK &&
esp_ieee802154_set_promiscuous(false) == ESP_OK &&
esp_ieee802154_set_coordinator(false) == ESP_OK &&
esp_ieee802154_set_rx_when_idle(true) == ESP_OK &&
esp_ieee802154_set_panid(MG_RADIO_NETWORK) == ESP_OK &&
esp_ieee802154_set_short_address(addr) == ESP_OK &&
esp_ieee802154_set_channel(MG_RADIO_CHANNEL) == ESP_OK &&
esp_ieee802154_set_txpower(0) == ESP_OK &&
esp_ieee802154_receive() == ESP_OK) {
return true;
}
MG_ERROR(("802.15.4 radio init failed"));
return false;
}
static bool mg_esp32_hw_tx(void) {
s_esp32_retry = false;
return esp_ieee802154_transmit(s_esp32_txframe, false) == ESP_OK;
}
static void mg_esp32_hw_abort(void) {
s_esp32_retry = false;
esp_ieee802154_receive(); // Stops the current operation
}
// Resend a refused frame when its pause is over. If the radio does not take
// it, give up: the frame counts as done
static void mg_esp32_hw_poll(void) {
uint32_t now;
if (!s_esp32_retry) return;
now = (uint32_t) esp_timer_get_time();
if ((int32_t) (now - s_esp32_retry_at) < 0) return;
s_esp32_retry = false;
if (esp_ieee802154_transmit(s_esp32_txframe, false) != ESP_OK) {
s_esp32_tx_done = true;
}
}
// Mesh radio transmit. The hardware adds the FCS
static size_t mgi_esp32_radio_tx(struct mg_tcpip_if *ifp, const void *buf,
size_t len) {
(void) ifp;
if (len > 125 || s_esp32_txing) return 0;
s_esp32_txframe[0] = (uint8_t) (len + 2);
memcpy(s_esp32_txframe + 1, buf, len);
s_esp32_tx_done = false;
s_esp32_txing = true, s_esp32_txstart = mg_micros();
if (!mg_esp32_hw_tx()) {
s_esp32_txing = false;
return 0;
}
return len;
}
static bool mgi_esp32_radio_poll(struct mg_tcpip_if *ifp) {
bool done = false;
(void) ifp;
mg_esp32_hw_poll();
if (s_esp32_txing && (s_esp32_tx_done || mg_micros() - s_esp32_txstart >
MG_RADIO_TX_TIMEOUT_US)) {
if (!s_esp32_tx_done) mg_esp32_hw_abort();
s_esp32_txing = false;
done = true;
}
return done;
}
static bool mgi_esp32_init(struct mg_tcpip_if *ifp) {
return mg_radio_init(ifp, mgi_esp32_radio_init, mgi_esp32_radio_poll,
mgi_esp32_radio_tx);
}
struct mg_tcpip_driver mg_tcpip_driver_esp32 = {mgi_esp32_init, mg_radio_tx,
mg_radio_rx, mg_radio_poll};
#endif
+30
View File
@@ -0,0 +1,30 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#pragma once
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ESP32) && MG_ENABLE_DRIVER_ESP32
// ESP32-C6 IEEE 802.15.4 radio, as an Ethernet interface through the mesh.
// Needs MG_ARCH_ESP32 and CONFIG_IEEE802154_ENABLED.
// See tutorials/esp32/minimal-802.15.4
extern struct mg_tcpip_driver mg_tcpip_driver_esp32;
#define MG_TCPIP_DRIVER_ESP32_INIT(manager) \
do { \
static struct mg_tcpip_if mif_; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_esp32; \
mg_tcpip_init((manager), &mif_); \
MG_INFO(("Driver: esp32, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_ESP32_INIT(x)
#endif
#endif
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
(defined(MG_ENABLE_DRIVER_IMXRT10) && MG_ENABLE_DRIVER_IMXRT10) || \ (defined(MG_ENABLE_DRIVER_IMXRT10) && MG_ENABLE_DRIVER_IMXRT10) || \
+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
+285
View File
@@ -0,0 +1,285 @@
#include "log.h"
#include "net_builtin.h"
#include "radio.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MCXW71) && \
MG_ENABLE_DRIVER_MCXW71
// TrustZone: code built for the secure state (-mcmse) uses the secure alias
// of the radio registers, 0x5xxxxxxx. Otherwise, the non-secure alias
#if defined(__ARM_FEATURE_CMSE) && (__ARM_FEATURE_CMSE & 2)
#define MGI_RF_BASE 0x58A00000U
#define MGI_PKT_RAM ((volatile uint8_t *) 0x58A08000)
#else
#define MGI_RF_BASE 0x48A00000U
#define MGI_PKT_RAM ((volatile uint8_t *) 0x48A08000)
#endif
#define MGI_NVIC_ISER ((volatile uint32_t *) 0xE000E100) // Enable IRQ
#define MGI_NVIC_ICER ((volatile uint32_t *) 0xE000E180) // Disable IRQ
#if MG_RADIO == MG_RADIO_BLE
#define MGI_IRQN 54 // RF_Generic_IRQn
#else
#define MGI_IRQN 53 // RF_802_15_4_IRQn
#endif
// Keep the IRQ handler out while we change the radio. The NVIC disable is
// atomic, so register updates here and there do not race
static void mg_mcxw71_lock(void) {
MGI_NVIC_ICER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32);
__asm volatile("dsb; isb" ::: "memory");
}
static struct mg_tcpip_if *s_mcxw71_ifp;
static volatile bool s_mcxw71_txing, s_mcxw71_done;
static uint64_t s_mcxw71_sendstart;
#if MG_RADIO == MG_RADIO_BLE
// GENFSK Bluetooth LE uncoded mode, RM Table 489. S0 + 8-bit length, then
// our frame. The PHY supplies the preamble, whitening and 24-bit CRC.
struct mg_genfsk {
volatile uint32_t IRQ_CTRL, EVENT_TMR, T1_CMP, T2_CMP, TIMESTAMP, XCVR_CTRL,
XCVR_STS, XCVR_CFG, CHANNEL_NUM0, TX_POWER, NTW_ADR_CTRL, NTW_ADR[4],
RX_WATERMARK, DSM_CTRL, PART_ID, SLOT_PRELOAD, SLOT_TIME, TURNAROUND_TIME,
ACKDELAY, RXDELAY, TXDELAY, PACKET_CFG, H0_CFG, H1_CFG, CRC_CFG,
LENGTH_ADJ, TIMESTAMP_RX_DONE, TIMESTAMP_TX_DONE, MULT_PKT_CTRL,
RPA_WL_STATUS, LENGTH_MAX, EVENT_TMR_LD, EVENT_TMR_ADD, ENH_FEATURE;
uint32_t reserved[21];
volatile uint32_t SEQ_STS;
};
#define MGI_GFSK ((struct mg_genfsk *) (MGI_RF_BASE + 0x2000))
#define MGI_TX_PB MGI_PKT_RAM // Access address, S0, length, frame; no CRC
#define MGI_RX_PB (MGI_PKT_RAM + 0x1000) // S0, length, frame, CRC; no AA
#define MGI_RADIO_MAX 251
#define MGI_GFSK_IRQ_EN (MG_BIT(26) | MG_BIT(16)) // Master + sequence end
// BLE preamble starts with the access address's first bit; transmit LSBit
// first.
#define MGI_GFSK_CFG \
(MG_BIT(24) | (((MG_RADIO_NETWORK & 1U) ? 0x55U : 0xaaU) << 16) | (1U << 4))
static void mg_mcxw71_abort(void) {
// NXP CONNRF-767: do not abort during TX warmup.
while (MGI_GFSK->SEQ_STS & MG_BIT(2)) (void) 0;
MGI_GFSK->XCVR_CTRL = 11; // ABORT_ALL
while (MGI_GFSK->XCVR_CTRL & MG_BIT(31)) (void) 0;
MGI_GFSK->IRQ_CTRL = MGI_GFSK_IRQ_EN | 0xffffU; // W1C status
}
static void mg_mcxw71_listen(void) {
MGI_GFSK->IRQ_CTRL = MGI_GFSK_IRQ_EN | 0xffffU;
MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG;
MGI_GFSK->XCVR_CTRL = 5; // RX_START_NOW
MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32);
}
static void mg_mcxw71_go(void) {
mg_mcxw71_abort();
MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG; // ABORT disables packet processing
MGI_GFSK->XCVR_CTRL = 1; // TX_START_NOW
}
void RF_Generic_IRQHandler(void);
void RF_Generic_IRQHandler(void) {
uint32_t status = MGI_GFSK->IRQ_CTRL;
if (!(status & MG_BIT(0))) return;
mg_mcxw71_abort();
if (s_mcxw71_txing) {
s_mcxw71_txing = false;
s_mcxw71_done = true;
} else if ((status & (MG_BIT(2) | MG_BIT(10))) ==
(MG_BIT(2) | MG_BIT(10))) { // RX and CRC valid
uint8_t frame[MGI_RADIO_MAX];
size_t i, n = MGI_RX_PB[1];
if (n > 0 && n <= sizeof(frame)) {
for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i + 2];
mg_radio_rx_queue(s_mcxw71_ifp, frame, n);
}
}
mg_mcxw71_listen();
}
static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) {
s_mcxw71_ifp = ifp;
(void) addr; // Frames are filtered by mg_radio_rx_queue()
MGI_GFSK->IRQ_CTRL = 0xffffU;
mg_mcxw71_abort();
// GENFSK channels are MHz above 2360; MG_RADIO_CHANNEL is a BLE data index.
MGI_GFSK->CHANNEL_NUM0 = MG_RADIO_CHANNEL < 11 ? 44 + 2 * MG_RADIO_CHANNEL
: 46 + 2 * MG_RADIO_CHANNEL;
MGI_GFSK->TX_POWER = 0x3f;
MGI_GFSK->NTW_ADR_CTRL = 0x301; // 32-bit access address, match address 0
MGI_GFSK->NTW_ADR[0] = MG_RADIO_NETWORK;
MGI_GFSK->PACKET_CFG = 0x000800c8; // H0=8 bits, length=8, AA=4 bytes
MGI_GFSK->H0_CFG = MGI_GFSK->H1_CFG = 0; // No header filtering
MGI_GFSK->LENGTH_ADJ = 3; // Length excludes the three CRC bytes
MGI_GFSK->MULT_PKT_CTRL = 0;
MGI_GFSK->LENGTH_MAX = 16U << 16; // 256 bytes; software caps at 251
MGI_GFSK->ENH_FEATURE = 9 | MG_BIT(6); // BLE uncoded, alternate rate: 2M
MGI_GFSK->XCVR_CFG = MGI_GFSK_CFG;
mg_mcxw71_listen();
return true;
}
#else
#define MGI_ZLL ((struct mg_zll *) (MGI_RF_BASE + 0x1000))
#define MGI_RADIO_MAX 125
// ZLL, 802.15.4 link layer. See MCXW71 reference manual and NXP
// ieee_802_15_4 PHY sources: PhyPacketProcessor.c, PhyPlmeData.c, PhyISR.c
struct mg_zll {
volatile uint32_t IRQSTS, PHY_CTRL, EVENT_TMR, TIMESTAMP, T1CMP, T2CMP,
T2PRIMECMP, T3CMP, T4CMP, PA_PWR, CHANNEL_NUM0, LQI_AND_RSSI,
MACSHORTADDRS0, MACLONGADDRS0_LSB, MACLONGADDRS0_MSB, RX_FRAME_FILTER,
CCA_LQI_CTRL, CCA2_CTRL, RESERVED_0, DSM_CTRL, RESERVED_1, MACSHORTADDRS1,
MACLONGADDRS1_LSB, MACLONGADDRS1_MSB, DUAL_PAN_CTRL, CHANNEL_NUM1,
SAM_CTRL, SAM_TABLE, SAM_MATCH, SAM_FREE_IDX, SEQ_CTRL_STS, ACKDELAY,
FILTERFAIL_CODE, RX_WTR_MARK, RESERVED_2, SLOT_PRELOAD, SEQ_STATE,
TMR_PRESCALE, LENIENCY_LSB, LENIENCY_MSB, PART_ID, COEX_CTRL,
COEX_PRIORITY, ENHACK_CTRL0;
};
#define MGI_TX_PB MGI_PKT_RAM // Length byte (incl. FCS), then frame
#define MGI_RX_PB (MGI_PKT_RAM + 0x80) // Received frame, no length byte
#define MGI_IRQSTS_SEQIRQ MG_BIT(0)
#define MGI_IRQSTS_RXIRQ MG_BIT(2)
#define MGI_IRQSTS_FILTERFAIL MG_BIT(5) // Frame not for us
#define MGI_IRQSTS_CRCVALID MG_BIT(15)
#define MGI_IRQSTS_RX_LEN(x) (((x) >> 24) & 0x7f) // Frame length incl. FCS
#define MGI_PHY_CTRL_XCVSEQ 7U
#define MGI_PHY_CTRL_ALL_IRQ_MASKS 0x8007ff00U // Bits 8..18, 31: mask all IRQs
#define MGI_PHY_CTRL_SEQMSK MG_BIT(8) // Mask the sequence end IRQ
#define MGI_PHY_CTRL_TRCV_MSK MG_BIT(31) // Mask all transceiver IRQs
#define MGI_SEQ_STATE_MASK 0x1fU
#define MGI_SEQ_STATE_RX_WU 0x10U // RX warm up
#define MGI_SEQ_CTRL_NO_RX_RECYCLE MG_BIT(5)
#define MGI_FRAME_FILTER 0x70bU // Beacon, data, command; versions 0..2
// PHY_CTRL[XCVSEQ]
enum { MGI_SEQ_IDLE = 0, MGI_SEQ_RX = 1, MGI_SEQ_TX = 2 };
// Stop the current sequence, wait for the sequencer to go idle. See PhyAbort()
static void mg_mcxw71_abort(void) {
if (MGI_ZLL->PHY_CTRL & MGI_PHY_CTRL_XCVSEQ) {
while ((MGI_ZLL->SEQ_STATE & MGI_SEQ_STATE_MASK) == MGI_SEQ_STATE_RX_WU)
(void) 0;
MGI_ZLL->PHY_CTRL &= ~MGI_PHY_CTRL_XCVSEQ;
while (MGI_ZLL->SEQ_STATE & MGI_SEQ_STATE_MASK) (void) 0;
}
MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS;
}
// Start receiving, with the sequence end IRQ on, see RF_802_15_4_IRQHandler()
static void mg_mcxw71_listen(void) {
MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS;
MGI_ZLL->PHY_CTRL |= MGI_SEQ_RX;
MGI_ZLL->PHY_CTRL &= ~(MGI_PHY_CTRL_SEQMSK | MGI_PHY_CTRL_TRCV_MSK);
MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32);
}
// Start the TX sequence for the loaded frame. Its end: see the IRQ handler
static void mg_mcxw71_go(void) {
MGI_ZLL->PHY_CTRL |= MGI_PHY_CTRL_TRCV_MSK | MGI_PHY_CTRL_SEQMSK;
mg_mcxw71_abort();
MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS;
MGI_ZLL->PHY_CTRL |= MGI_SEQ_TX;
MGI_ZLL->PHY_CTRL &= ~(MGI_PHY_CTRL_SEQMSK | MGI_PHY_CTRL_TRCV_MSK);
}
void RF_802_15_4_IRQHandler(void);
void RF_802_15_4_IRQHandler(void) {
uint32_t irqsts = MGI_ZLL->IRQSTS;
if ((irqsts & MGI_IRQSTS_SEQIRQ) != 0) {
mg_mcxw71_abort();
if (s_mcxw71_txing) {
s_mcxw71_txing = false;
s_mcxw71_done = true;
} else if ((irqsts & (MGI_IRQSTS_RXIRQ | MGI_IRQSTS_FILTERFAIL |
MGI_IRQSTS_CRCVALID)) ==
(MGI_IRQSTS_RXIRQ | MGI_IRQSTS_CRCVALID)) {
uint8_t frame[125];
size_t i, n = MGI_IRQSTS_RX_LEN(irqsts);
n = n >= 2 ? n - 2 : 0;
if (n > 0 && n <= sizeof(frame)) {
for (i = 0; i < n; i++) frame[i] = MGI_RX_PB[i];
mg_radio_rx_queue(s_mcxw71_ifp, frame, n);
}
}
mg_mcxw71_listen();
}
}
static bool mgi_mcxw71_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) {
s_mcxw71_ifp = ifp;
MGI_ZLL->SEQ_CTRL_STS |= MGI_SEQ_CTRL_NO_RX_RECYCLE;
MGI_ZLL->PHY_CTRL = MGI_PHY_CTRL_ALL_IRQ_MASKS;
MGI_ZLL->IRQSTS = MGI_ZLL->IRQSTS;
MGI_ZLL->SAM_CTRL = 0;
MGI_ZLL->RX_FRAME_FILTER = MGI_FRAME_FILTER;
MGI_ZLL->CHANNEL_NUM0 = MG_RADIO_CHANNEL;
MGI_ZLL->MACSHORTADDRS0 = ((uint32_t) addr << 16) | MG_RADIO_NETWORK;
MGI_ZLL->PA_PWR = 0x3f;
mg_mcxw71_listen();
return true;
}
#endif
static size_t mgi_mcxw71_radio_tx(struct mg_tcpip_if *ifp, const void *buf,
size_t len) {
size_t i;
(void) ifp;
if (len > MGI_RADIO_MAX || s_mcxw71_txing) return 0;
mg_mcxw71_lock();
#if MG_RADIO == MG_RADIO_BLE
if (MGI_GFSK->SEQ_STS & MG_BIT(11)) { // Do not interrupt a received frame
MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32);
return 0;
}
for (i = 0; i < 4; i++)
MGI_TX_PB[i] = (uint8_t) (MG_RADIO_NETWORK >> (8 * i));
MGI_TX_PB[4] = 0, MGI_TX_PB[5] = (uint8_t) len;
for (i = 0; i < len; i++) MGI_TX_PB[i + 6] = ((const uint8_t *) buf)[i];
#else
MGI_TX_PB[0] = (uint8_t) (len + 2); // FCS is added by hardware
for (i = 0; i < len; i++)
MGI_TX_PB[i + 1] = ((const uint8_t *) buf)[i]; // 8-bit access only
#endif
s_mcxw71_done = false;
s_mcxw71_txing = true;
s_mcxw71_sendstart = mg_millis();
mg_mcxw71_go();
MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32);
return len;
}
static bool mgi_mcxw71_radio_poll(struct mg_tcpip_if *ifp) {
bool done;
(void) ifp;
if (s_mcxw71_txing &&
mg_millis() > s_mcxw71_sendstart + MG_RADIO_TX_TIMEOUT_US / 1000) {
mg_mcxw71_lock();
if (s_mcxw71_txing) {
mg_mcxw71_abort();
s_mcxw71_txing = false;
s_mcxw71_done = true;
mg_mcxw71_listen();
} else {
MGI_NVIC_ISER[MGI_IRQN / 32] = MG_BIT(MGI_IRQN % 32);
}
}
done = s_mcxw71_done;
s_mcxw71_done = false;
return done;
}
static bool mgi_mcxw71_init(struct mg_tcpip_if *ifp) {
return mg_radio_init(ifp, mgi_mcxw71_radio_init, mgi_mcxw71_radio_poll,
mgi_mcxw71_radio_tx);
}
struct mg_tcpip_driver mg_tcpip_driver_mcxw71 = {mgi_mcxw71_init, mg_radio_tx,
mg_radio_rx, mg_radio_poll};
#endif
+27
View File
@@ -0,0 +1,27 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#pragma once
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MCXW71) && \
MG_ENABLE_DRIVER_MCXW71
extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
#define MG_TCPIP_DRIVER_MCXW71_INIT(mgr) \
do { \
static struct mg_tcpip_if mif_; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.driver = &mg_tcpip_driver_mcxw71; \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_MCXW71_INIT(x)
#endif
#endif
+179
View File
@@ -0,0 +1,179 @@
#include "log.h"
#include "net_builtin.h"
#include "radio.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MG24) && MG_ENABLE_DRIVER_MG24
#include <rail.h>
// A packet in the RAIL FIFOs: the radio header, then the frame
#if MG_RADIO == MG_RADIO_BLE
#include <rail_ble.h>
#define MGI_MG24_HDR 2 // S0 byte, unused, then the frame length
#define MGI_MG24_MAX 251 // Largest frame. RAIL adds and strips the CRC
// RAIL channel: the RF channel, 2402 MHz + 2 MHz steps. Data channels 0-10
// are RF channels 1-11, data channels 11-36 are RF channels 13-38
#define MGI_MG24_CHANNEL \
(MG_RADIO_CHANNEL < 11 ? MG_RADIO_CHANNEL + 1 : MG_RADIO_CHANNEL + 2)
#else
#include <rail_ieee802154.h>
#define MGI_MG24_HDR 1 // PHR: the frame length, FCS included
#define MGI_MG24_MAX 125 // Largest frame, without the 2 byte FCS
#define MGI_MG24_CHANNEL MG_RADIO_CHANNEL
#endif
// RAIL delivers raw frames and transmit completion from interrupt context.
static struct mg_tcpip_if *s_mg24_ifp;
static RAIL_Handle_t s_mg24_rail;
static volatile bool s_mg24_txing, s_mg24_tx_done;
static RAIL_Time_t s_mg24_txstart; // Send start, us
static uint8_t s_mg24_txfifo[256] __attribute__((aligned(4))); // Power of 2
// Copy a received frame, stripping the radio header and any stored CRC
static void mg_mg24_rx_frame(RAIL_Handle_t h) {
static uint8_t f[MGI_MG24_HDR + MGI_MG24_MAX + 2]; // Interrupt use only
RAIL_RxPacketInfo_t info;
size_t n;
if (RAIL_GetRxPacketInfo(h, RAIL_RX_PACKET_HANDLE_NEWEST, &info) ==
RAIL_RX_PACKET_HANDLE_INVALID ||
info.packetStatus != RAIL_RX_PACKET_READY_SUCCESS ||
info.packetBytes <= MGI_MG24_HDR || info.packetBytes > sizeof(f)) {
return;
}
RAIL_CopyRxPacket(f, &info);
#if MG_RADIO == MG_RADIO_BLE
n = f[1];
if (n + MGI_MG24_HDR > (size_t) info.packetBytes) return;
#else
n = info.packetBytes - 1U; // Strip PHR
if (n == f[0]) n -= 2; // FCS stored, strip it
#endif
mg_radio_rx_queue(s_mg24_ifp, f + MGI_MG24_HDR, n);
}
// RAIL event callback, runs in interrupt context
static void mg_mg24_events(RAIL_Handle_t h, RAIL_Events_t events) {
if (events & RAIL_EVENT_CAL_NEEDED) {
RAIL_Calibrate(h, NULL, RAIL_CAL_ALL_PENDING);
}
if (events & RAIL_EVENT_RX_PACKET_RECEIVED) mg_mg24_rx_frame(h);
if (events & RAIL_EVENTS_TX_COMPLETION) s_mg24_tx_done = true;
}
// RAIL adds the CRC or FCS
static size_t mgi_mg24_radio_tx(struct mg_tcpip_if *ifp, const void *buf,
size_t len) {
#if MG_RADIO == MG_RADIO_BLE
uint8_t hdr[MGI_MG24_HDR] = {0, (uint8_t) len};
#else
uint8_t hdr[MGI_MG24_HDR] = {(uint8_t) (len + 2)}; // FCS added by hardware
#endif
(void) ifp;
if (len > MGI_MG24_MAX || s_mg24_txing) return 0;
RAIL_WriteTxFifo(s_mg24_rail, hdr, sizeof(hdr), true); // Reset, write hdr
RAIL_WriteTxFifo(s_mg24_rail, (const uint8_t *) buf, (uint16_t) len, false);
s_mg24_tx_done = false;
s_mg24_txing = true, s_mg24_txstart = RAIL_GetTime();
if (RAIL_StartTx(s_mg24_rail, MGI_MG24_CHANNEL, RAIL_TX_OPTIONS_DEFAULT,
NULL) != RAIL_STATUS_NO_ERROR) {
s_mg24_txing = false;
return 0;
}
return len;
}
#if MG_RADIO == MG_RADIO_BLE
// Raw BLE 2 Mbit/s PHY, standard packet as in nrf52.c. The 100 us state
// transitions fit within the mesh's 300 us gap between frames
static bool mgi_mg24_protocol_init(uint16_t addr) {
RAIL_StateTiming_t timing = {0};
(void) addr;
timing.idleToRx = 100, timing.idleToTx = 100;
timing.rxToTx = 100, timing.txToRx = 100;
return RAIL_BLE_Init(s_mg24_rail) == RAIL_STATUS_NO_ERROR &&
RAIL_BLE_ConfigPhy2MbpsViterbi(s_mg24_rail) == RAIL_STATUS_NO_ERROR &&
RAIL_BLE_ConfigChannelRadioParams(s_mg24_rail, 0x555555,
MG_RADIO_NETWORK, MG_RADIO_CHANNEL,
false) == RAIL_STATUS_NO_ERROR &&
RAIL_SetStateTiming(s_mg24_rail, &timing) == RAIL_STATUS_NO_ERROR;
}
#else
// IEEE 802.15.4 with hardware filtering by PAN ID and our short address
static bool mgi_mg24_protocol_init(uint16_t addr) {
RAIL_IEEE802154_Config_t cfg154 = {0};
RAIL_StateTransitions_t to_rx = {RAIL_RF_STATE_RX, RAIL_RF_STATE_RX};
cfg154.ackConfig.enable = false;
cfg154.ackConfig.ackTimeout = 864;
cfg154.ackConfig.rxTransitions = to_rx;
cfg154.ackConfig.txTransitions = to_rx;
cfg154.timings.idleToRx = 100, cfg154.timings.idleToTx = 100;
cfg154.timings.rxToTx = 192, cfg154.timings.txToRx = 182;
cfg154.framesMask = RAIL_IEEE802154_ACCEPT_STANDARD_FRAMES;
cfg154.promiscuousMode = false;
return RAIL_IEEE802154_Config2p4GHzRadio(s_mg24_rail) ==
RAIL_STATUS_NO_ERROR &&
RAIL_IEEE802154_Init(s_mg24_rail, &cfg154) == RAIL_STATUS_NO_ERROR &&
RAIL_IEEE802154_SetPanId(s_mg24_rail, MG_RADIO_NETWORK, 0) ==
RAIL_STATUS_NO_ERROR &&
RAIL_IEEE802154_SetShortAddress(s_mg24_rail, addr, 0) ==
RAIL_STATUS_NO_ERROR;
}
#endif
static bool mgi_mg24_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) {
RAIL_Config_t cfg = {0};
RAIL_TxPowerConfig_t pwr;
RAIL_StateTransitions_t to_rx = {RAIL_RF_STATE_RX, RAIL_RF_STATE_RX};
RAIL_Events_t events = RAIL_EVENT_CAL_NEEDED | RAIL_EVENT_RX_PACKET_RECEIVED |
RAIL_EVENTS_TX_COMPLETION;
cfg.eventsCallback = mg_mg24_events;
if ((s_mg24_rail = RAIL_Init(&cfg, NULL)) == NULL) {
MG_ERROR(("RAIL_Init failed"));
return false;
}
pwr.mode = RAIL_TX_POWER_MODE_2P4GIG_HP, pwr.voltage = 3300;
pwr.rampTime = 10;
if (RAIL_ConfigCal(s_mg24_rail, RAIL_CAL_ALL) != RAIL_STATUS_NO_ERROR ||
RAIL_ConfigEvents(s_mg24_rail, RAIL_EVENTS_ALL, events) !=
RAIL_STATUS_NO_ERROR ||
!mgi_mg24_protocol_init(addr) ||
RAIL_SetTxTransitions(s_mg24_rail, &to_rx) != RAIL_STATUS_NO_ERROR ||
RAIL_SetRxTransitions(s_mg24_rail, &to_rx) != RAIL_STATUS_NO_ERROR ||
RAIL_ConfigTxPower(s_mg24_rail, &pwr) != RAIL_STATUS_NO_ERROR ||
RAIL_SetTxPower(s_mg24_rail, RAIL_TX_POWER_LEVEL_2P4_HP_MAX) !=
RAIL_STATUS_NO_ERROR ||
RAIL_SetTxFifo(s_mg24_rail, s_mg24_txfifo, 0, sizeof(s_mg24_txfifo)) !=
sizeof(s_mg24_txfifo)) {
MG_ERROR(("RAIL setup failed"));
return false;
}
s_mg24_ifp = ifp;
return RAIL_StartRx(s_mg24_rail, MGI_MG24_CHANNEL, NULL) ==
RAIL_STATUS_NO_ERROR;
}
static bool mgi_mg24_radio_poll(struct mg_tcpip_if *ifp) {
bool done = false;
(void) ifp;
if (s_mg24_txing && (s_mg24_tx_done || RAIL_GetTime() - s_mg24_txstart >
MG_RADIO_TX_TIMEOUT_US)) {
if (!s_mg24_tx_done) {
RAIL_Idle(s_mg24_rail, RAIL_IDLE_ABORT, true);
RAIL_StartRx(s_mg24_rail, MGI_MG24_CHANNEL, NULL);
}
s_mg24_txing = false;
done = true;
}
return done;
}
static bool mgi_mg24_init(struct mg_tcpip_if *ifp) {
return mg_radio_init(ifp, mgi_mg24_radio_init, mgi_mg24_radio_poll,
mgi_mg24_radio_tx);
}
struct mg_tcpip_driver mg_tcpip_driver_mg24 = {mgi_mg24_init, mg_radio_tx,
mg_radio_rx, mg_radio_poll};
#endif
+26
View File
@@ -0,0 +1,26 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#pragma once
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_MG24) && MG_ENABLE_DRIVER_MG24
extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
#define MG_TCPIP_DRIVER_MG24_INIT(mgr) \
do { \
static struct mg_tcpip_if mif_; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.driver = &mg_tcpip_driver_mg24; \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_MG24_INIT(x)
#endif
#endif
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP && \ #if defined(MG_ENABLE_TCPIP) && MG_ENABLE_TCPIP && \
defined(MG_ENABLE_DRIVER_NETC) && MG_ENABLE_DRIVER_NETC defined(MG_ENABLE_DRIVER_NETC) && MG_ENABLE_DRIVER_NETC
+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
+168
View File
@@ -0,0 +1,168 @@
#include "log.h"
#include "net_builtin.h"
#include "radio.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NRF52) && MG_ENABLE_DRIVER_NRF52
#include <nrf.h>
// A packet in RAM: the radio header, then the frame
#if MG_RADIO == MG_RADIO_BLE
#define MGI_NRF52_HDR 2 // S0 byte, unused, then the frame length
#define MGI_NRF52_MAX 251 // Largest frame. The CRC is not in RAM
#define MGI_NRF52_RXSTART EVENTS_ADDRESS // A frame is being received
#define MGI_NRF52_MHZ \
(MG_RADIO_CHANNEL < 11 ? 2404 + 2 * MG_RADIO_CHANNEL \
: 2406 + 2 * MG_RADIO_CHANNEL)
#else
#define MGI_NRF52_HDR 1 // PHR: the frame length, FCS included
#define MGI_NRF52_MAX 125 // Largest frame, without the 2 byte FCS
#define MGI_NRF52_RXSTART EVENTS_FRAMESTART // A frame is being received
#endif
#define MGI_NRF52_IOLEN (MGI_NRF52_HDR + MGI_NRF52_MAX + 2)
static struct mg_tcpip_if *s_nrf52_ifp;
static uint8_t s_nrf52_rxbuf[MGI_NRF52_IOLEN] MG_8BYTE_ALIGNED;
static uint8_t s_nrf52_txbuf[MGI_NRF52_IOLEN] MG_8BYTE_ALIGNED;
static volatile bool s_nrf52_txing, s_nrf52_done;
static uint64_t s_nrf52_started;
static void mgi_nrf52_listen(void) {
NRF_RADIO->PACKETPTR = (uint32_t) s_nrf52_rxbuf;
NRF_RADIO->SHORTS =
RADIO_SHORTS_READY_START_Msk | RADIO_SHORTS_END_DISABLE_Msk;
NRF_RADIO->MGI_NRF52_RXSTART = 0;
NRF_RADIO->EVENTS_END = 0;
NRF_RADIO->TASKS_RXEN = 1;
}
static void mgi_nrf52_disable(void) {
NRF_RADIO->SHORTS = 0;
NRF_RADIO->EVENTS_DISABLED = 0;
NRF_RADIO->TASKS_DISABLE = 1;
while (!NRF_RADIO->EVENTS_DISABLED) (void) 0;
NRF_RADIO->EVENTS_DISABLED = 0;
}
void RADIO_IRQHandler(void);
void RADIO_IRQHandler(void) {
if (!NRF_RADIO->EVENTS_DISABLED) return;
NRF_RADIO->EVENTS_DISABLED = 0;
if (s_nrf52_txing) {
s_nrf52_txing = false;
s_nrf52_done = true;
} else if (NRF_RADIO->CRCSTATUS) {
#if MG_RADIO == MG_RADIO_BLE
size_t len = s_nrf52_rxbuf[1];
#else
size_t len = s_nrf52_rxbuf[0] >= 2 ? s_nrf52_rxbuf[0] - 2U : 0;
#endif
mg_radio_rx_queue(s_nrf52_ifp, s_nrf52_rxbuf + MGI_NRF52_HDR, len);
}
mgi_nrf52_listen();
}
static size_t mgi_nrf52_radio_tx(struct mg_tcpip_if *ifp, const void *buf,
size_t len) {
(void) ifp;
if (len > MGI_NRF52_MAX) return 0;
NVIC_DisableIRQ(RADIO_IRQn);
if (s_nrf52_txing || NRF_RADIO->MGI_NRF52_RXSTART) {
NVIC_EnableIRQ(RADIO_IRQn);
return 0;
}
mgi_nrf52_disable();
#if MG_RADIO == MG_RADIO_BLE
s_nrf52_txbuf[0] = 0, s_nrf52_txbuf[1] = (uint8_t) len;
#else
s_nrf52_txbuf[0] = (uint8_t) (len + 2);
#endif
memcpy(s_nrf52_txbuf + MGI_NRF52_HDR, buf, len);
s_nrf52_done = false;
s_nrf52_txing = true;
s_nrf52_started = mg_micros();
NRF_RADIO->PACKETPTR = (uint32_t) s_nrf52_txbuf;
NRF_RADIO->SHORTS =
RADIO_SHORTS_READY_START_Msk | RADIO_SHORTS_END_DISABLE_Msk;
NRF_RADIO->TASKS_TXEN = 1;
NVIC_EnableIRQ(RADIO_IRQn);
return len;
}
static bool mgi_nrf52_radio_init(struct mg_tcpip_if *ifp, uint16_t addr) {
s_nrf52_ifp = ifp;
(void) addr; // Frames are filtered by mg_radio_rx_queue()
NRF_RADIO->POWER = 1;
#if MG_RADIO == MG_RADIO_BLE
// Standard BLE packet: 2 byte preamble, access address, S0 byte, 8 bit
// length, payload, 24 bit CRC over everything after the access address,
// initial value 0x555555. Whitening seeded by the channel index
NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_2Mbit;
NRF_RADIO->PCNF0 = (1UL << RADIO_PCNF0_S0LEN_Pos) |
(8UL << RADIO_PCNF0_LFLEN_Pos) |
(RADIO_PCNF0_PLEN_16bit << RADIO_PCNF0_PLEN_Pos);
NRF_RADIO->PCNF1 = ((uint32_t) MGI_NRF52_MAX << RADIO_PCNF1_MAXLEN_Pos) |
(3UL << RADIO_PCNF1_BALEN_Pos) | RADIO_PCNF1_WHITEEN_Msk;
NRF_RADIO->BASE0 = (uint32_t) MG_RADIO_NETWORK << 8;
NRF_RADIO->PREFIX0 = ((uint32_t) MG_RADIO_NETWORK >> 24) & 0xff;
NRF_RADIO->TXADDRESS = 0;
NRF_RADIO->RXADDRESSES = 1;
NRF_RADIO->CRCCNF =
3 | (RADIO_CRCCNF_SKIPADDR_Skip << RADIO_CRCCNF_SKIPADDR_Pos);
NRF_RADIO->CRCPOLY = 0x65b;
NRF_RADIO->CRCINIT = 0x555555;
NRF_RADIO->DATAWHITEIV = MG_RADIO_CHANNEL;
NRF_RADIO->FREQUENCY = MGI_NRF52_MHZ - 2400;
NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_DTX_Center << RADIO_MODECNF0_DTX_Pos) |
RADIO_MODECNF0_RU_Fast;
#else
NRF_RADIO->MODE = RADIO_MODE_MODE_Ieee802154_250Kbit;
NRF_RADIO->PCNF0 = (8UL << RADIO_PCNF0_LFLEN_Pos) |
(RADIO_PCNF0_PLEN_32bitZero << RADIO_PCNF0_PLEN_Pos) |
RADIO_PCNF0_CRCINC_Msk;
NRF_RADIO->PCNF1 = 127;
NRF_RADIO->CRCCNF = 0x202;
NRF_RADIO->CRCPOLY = 0x11021;
NRF_RADIO->CRCINIT = 0;
NRF_RADIO->MODECNF0 = (RADIO_MODECNF0_DTX_Center << RADIO_MODECNF0_DTX_Pos) |
RADIO_MODECNF0_RU_Fast;
NRF_RADIO->SFD = 0xa7;
NRF_RADIO->FREQUENCY = 5 * (MG_RADIO_CHANNEL - 10);
// Correlator threshold 45 matches the RADIO reset value. A threshold of
// 20 caused false busy detections and persistent L2 retries.
NRF_RADIO->CCACTRL =
(RADIO_CCACTRL_CCAMODE_CarrierMode << RADIO_CCACTRL_CCAMODE_Pos) |
(2UL << RADIO_CCACTRL_CCACORRCNT_Pos) |
(45UL << RADIO_CCACTRL_CCACORRTHRES_Pos);
#endif
NRF_RADIO->TXPOWER = RADIO_TXPOWER_TXPOWER_Pos8dBm;
NRF_RADIO->INTENSET = RADIO_INTENSET_DISABLED_Msk;
NVIC_SetPriority(RADIO_IRQn, 0);
NVIC_EnableIRQ(RADIO_IRQn);
mgi_nrf52_listen();
return true;
}
static bool mgi_nrf52_radio_poll(struct mg_tcpip_if *ifp) {
bool done;
(void) ifp;
if (s_nrf52_txing && mg_micros() - s_nrf52_started > MG_RADIO_TX_TIMEOUT_US) {
NVIC_DisableIRQ(RADIO_IRQn);
mgi_nrf52_disable();
s_nrf52_txing = false;
s_nrf52_done = true;
mgi_nrf52_listen();
NVIC_EnableIRQ(RADIO_IRQn);
}
done = s_nrf52_done;
s_nrf52_done = false;
return done;
}
static bool mgi_nrf52_init(struct mg_tcpip_if *ifp) {
return mg_radio_init(ifp, mgi_nrf52_radio_init, mgi_nrf52_radio_poll,
mgi_nrf52_radio_tx);
}
struct mg_tcpip_driver mg_tcpip_driver_nrf52 = {mgi_nrf52_init, mg_radio_tx,
mg_radio_rx, mg_radio_poll};
#endif
+26
View File
@@ -0,0 +1,26 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#pragma once
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NRF52) && MG_ENABLE_DRIVER_NRF52
extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
#define MG_TCPIP_DRIVER_NRF52_INIT(mgr) \
do { \
static struct mg_tcpip_if mif_; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.driver = &mg_tcpip_driver_nrf52; \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_NRF52_INIT(x)
#endif
#endif
+2
View File
@@ -1,3 +1,5 @@
#include "net_builtin.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NXP_WIFI) && \ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_NXP_WIFI) && \
MG_ENABLE_DRIVER_NXP_WIFI MG_ENABLE_DRIVER_NXP_WIFI
+10 -2
View File
@@ -4,12 +4,16 @@
defined(MG_ENABLE_DRIVER_NXP_WIFI) && MG_ENABLE_DRIVER_NXP_WIFI defined(MG_ENABLE_DRIVER_NXP_WIFI) && MG_ENABLE_DRIVER_NXP_WIFI
#include "wifi.h"
struct mg_tcpip_driver_nxp_wifi_data { struct mg_tcpip_driver_nxp_wifi_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_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 +25,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
+2
View File
@@ -1,4 +1,6 @@
#include "phy.h" #include "phy.h"
#include "log.h"
#include "util.h"
enum { // ID1 ID2 enum { // ID1 ID2
MG_PHY_KSZ8x = 0x22, // 0022 156x - KSZ8081RNB, KSZ8091RNB MG_PHY_KSZ8x = 0x22, // 0022 156x - KSZ8081RNB, KSZ8091RNB
+7 -3
View File
@@ -1,9 +1,12 @@
#include "net_builtin.h"
#if MG_ENABLE_TCPIP && MG_ARCH == MG_ARCH_PICOSDK && \ #if MG_ENABLE_TCPIP && MG_ARCH == MG_ARCH_PICOSDK && \
defined(MG_ENABLE_DRIVER_PICO_W) && MG_ENABLE_DRIVER_PICO_W defined(MG_ENABLE_DRIVER_PICO_W) && MG_ENABLE_DRIVER_PICO_W
#include "drivers/pico-w.h" #include "drivers/pico-w.h"
#include "net_builtin.h"
#include "pico/stdlib.h" #include "pico/stdlib.h"
#include "printf.h"
#include "util.h"
static struct mg_tcpip_if *s_ifp; static struct mg_tcpip_if *s_ifp;
static uint32_t s_ip, s_mask; static uint32_t s_ip, s_mask;
@@ -68,8 +71,9 @@ static bool mg_tcpip_driver_pico_w_poll(struct mg_tcpip_if *ifp, bool s1) {
} }
if (ifp->update_mac_hash_table) { if (ifp->update_mac_hash_table) {
// first call to _poll() is after _init(), so this is safe // first call to _poll() is after _init(), so this is safe
cyw43_wifi_update_multicast_filter(&cyw43_state, (uint8_t *) mcast_addr, uint8_t mac[sizeof(mcast_addr)]; // copy from const uint8_t* to uint8_t*
true); memcpy(mac, mcast_addr, sizeof(mac));
cyw43_wifi_update_multicast_filter(&cyw43_state, mac, true);
ifp->update_mac_hash_table = false; ifp->update_mac_hash_table = false;
} }
if (!s1) return false; if (!s1) return false;
+10 -2
View File
@@ -7,11 +7,15 @@
#include "pico/cyw43_arch.h" // keep this include #include "pico/cyw43_arch.h" // keep this include
#include "pico/unique_id.h" // keep this include #include "pico/unique_id.h" // keep this include
#include "wifi.h"
struct mg_tcpip_driver_pico_w_data { 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 +27,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
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
(defined(MG_ENABLE_DRIVER_RA6) && MG_ENABLE_DRIVER_RA6) || \ (defined(MG_ENABLE_DRIVER_RA6) && MG_ENABLE_DRIVER_RA6) || \
+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
+718
View File
@@ -0,0 +1,718 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#include "radio.h"
#include "log.h"
#include "printf.h"
#include "util.h"
#if MG_ENABLE_TCPIP
#define MGI_ETH_MAX 1514
#define MGI_TX_DST_LEN 2
// The radio, chosen by MG_RADIO. A frame starts with the radio header, with
// the radio addresses, then the mesh header: type, then burst: the
// fragment's index << 4 | the last fragment's index. Then the payload
#if MG_RADIO == MG_RADIO_BLE
#define MGI_RADIO_MTU 251 // Largest frame: BLE 5 data length
#define MGI_RADIO_BITRATE 2000000 // Bits per second on air
#define MGI_RADIO_OVERHEAD 11 // Preamble, access address, length, CRC
#define MGI_RADIO_TURNAROUND_US 40 // Receive to transmit: nRF52840 fast ramp
#define MGI_RADIO_IFS_US 300 // Gap between transmissions
#define MGI_RADIO_HDR_LEN 4 // Destination, source
// Write the radio header. Little endian
static void mgi_radio_write_hdr(uint8_t *buf, uint16_t dst, uint16_t src) {
buf[0] = (uint8_t) dst, buf[1] = (uint8_t) (dst >> 8);
buf[2] = (uint8_t) src, buf[3] = (uint8_t) (src >> 8);
}
// Read the radio header. The access address already keeps other networks out
static bool mgi_radio_parse_hdr(const uint8_t *buf, size_t len, uint16_t *dst,
uint16_t *src) {
if (len < MGI_RADIO_HDR_LEN) return false;
*dst = (uint16_t) (buf[0] | buf[1] << 8);
*src = (uint16_t) (buf[2] | buf[3] << 8);
return true;
}
#else
#define MGI_RADIO_MTU 125 // 127 minus FCS
#define MGI_RADIO_BITRATE 250000 // Bits per second on air
#define MGI_RADIO_OVERHEAD 8 // Preamble, SFD, PHR, FCS
#define MGI_RADIO_TURNAROUND_US 100 // Receive to transmit
#define MGI_RADIO_IFS_US 640 // Gap between transmissions
#define MGI_RADIO_HDR_LEN 9 // MAC header, short addresses
// MAC header: frame control 0x8841, a data frame, PAN ID compression, short
// destination and source addresses; sequence number, 0, as nothing uses it
// yet; PAN ID; destination; source. Little endian, as the standard says
static void mgi_radio_write_hdr(uint8_t *buf, uint16_t dst, uint16_t src) {
buf[0] = 0x41, buf[1] = 0x88, buf[2] = 0;
buf[3] = (uint8_t) MG_RADIO_NETWORK;
buf[4] = (uint8_t) (MG_RADIO_NETWORK >> 8);
buf[5] = (uint8_t) dst, buf[6] = (uint8_t) (dst >> 8);
buf[7] = (uint8_t) src, buf[8] = (uint8_t) (src >> 8);
}
// Read the MAC header. Other networks' frames fail the check
static bool mgi_radio_parse_hdr(const uint8_t *buf, size_t len, uint16_t *dst,
uint16_t *src) {
if (len < MGI_RADIO_HDR_LEN || buf[0] != 0x41 || buf[1] != 0x88 ||
buf[3] != (uint8_t) MG_RADIO_NETWORK ||
buf[4] != (uint8_t) (MG_RADIO_NETWORK >> 8)) {
return false;
}
*dst = (uint16_t) (buf[5] | buf[6] << 8);
*src = (uint16_t) (buf[7] | buf[8] << 8);
return true;
}
#endif
#define MGI_FRAME_HDR_LEN (MGI_RADIO_HDR_LEN + 2) // Radio and mesh headers
#define MGI_FRAG_CAP (MGI_RADIO_MTU - MGI_FRAME_HDR_LEN) // Payload per frame
#define MGI_TX_QUEUE_SIZE 2048 // Ethernet frames to send, as bursts
#define MGI_RX_STAMP_LEN sizeof(uint64_t)
#define MGI_RX_QUEUE_SIZE (16 * (MGI_RX_STAMP_LEN + MGI_RADIO_MTU + 8))
// A radio interface's state, its driver_data, allocated by mg_radio_init()
struct mg_radio_node {
bool (*hw_poll)(struct mg_tcpip_if *); // Hardware: service it
size_t (*hw_tx)(struct mg_tcpip_if *, const void *, size_t); // Start TX
struct mg_tcpip_if *ifp; // Radio interface
struct mg_tcpip_if *lan; // Bridge: LAN interface. NULL: a node
struct mg_queue frames; // Received radio frames, with arrival times
struct mg_queue tx; // Ethernet frames to send, one burst each
uint64_t now; // Current poll time, us
uint64_t tx_at; // Earliest next radio TX, us
uint64_t burst_at; // Next fragment TX, us
uint64_t deadline; // End of the current turn, us
uint64_t expire_at; // Node: no turn by then, leave. 0: had one
uint64_t answer_by; // Node: first answer frame must end by then
size_t rx_len; // Ethernet frame waiting for the stack
size_t tx_offset; // Next fragment of the queued burst
struct mgi_radio_peer *members; // Bridge: members, round-robin order
struct mgi_radio_peer *current; // Bridge: member whose turn is active/next
struct mgi_radio_peer *fanout; // Bridge: next broadcast recipient
uint32_t random; // PRNG state, for join timing
uint16_t radio_address; // Our radio address, made from the MAC
uint16_t coordinator; // Node: the bridge's radio address
uint8_t phase; // Turn: idle, join or data
uint8_t rx_expected; // Next fragment: index << 4 | last index. 0xff: idle
bool joined; // Node: member of the mesh
bool granted; // Node: had a turn this round
uint8_t rx_buf[MGI_ETH_MAX]; // Ethernet frame being reassembled
char tx_buf[MGI_TX_QUEUE_SIZE]; // Storage of the tx queue
char frames_buf[MGI_RX_QUEUE_SIZE]; // Storage of the frames queue
};
// Time on air of a len byte frame, us
static uint64_t mgi_radio_airtime(size_t len) {
return ((uint64_t) (len + MGI_RADIO_OVERHEAD) * 8000000 + MGI_RADIO_BITRATE -
1) /
MGI_RADIO_BITRATE;
}
// Each queue record holds a destination and a complete burst.
static size_t mgi_radio_queue(struct mg_radio_node *node, struct mg_queue *q,
const void *buf, size_t len, uint16_t dst,
uint8_t type) {
const uint8_t *eth = (const uint8_t *) buf;
size_t hdr = MGI_FRAME_HDR_LEN, cap = MGI_RADIO_MTU - hdr;
size_t frames, size, i;
char *record;
uint8_t *out;
if (len < 14 || len > MGI_ETH_MAX) return 0;
frames = (len + cap - 1) / cap;
size = MGI_TX_DST_LEN + len + frames * (1 + hdr);
if (mg_queue_next(q, NULL) == 0) mg_queue_init(q, q->buf, q->size);
if (mg_queue_book(q, &record, size) < size) {
MG_ERROR(("TX queue full: need %u, head %u, tail %u, size %u",
(unsigned) size, (unsigned) q->head, (unsigned) q->tail,
(unsigned) q->size));
return 0;
}
out = (uint8_t *) record;
*out++ = (uint8_t) (dst >> 8);
*out++ = (uint8_t) dst;
for (i = 0; i < frames; i++) {
size_t chunk = len - i * cap;
if (chunk > cap) chunk = cap;
*out++ = (uint8_t) (hdr + chunk);
mgi_radio_write_hdr(out, dst, node->radio_address);
out[MGI_RADIO_HDR_LEN] = type;
out[MGI_RADIO_HDR_LEN + 1] = (uint8_t) (i << 4 | (frames - 1));
memcpy(out + hdr, eth + i * cap, chunk);
out += hdr + chunk;
}
mg_queue_add(q, size);
return len;
}
#define MGI_JOIN_WINDOW_US 3000
#define MGI_JOIN_TURN_US 192
#define MGI_JOIN_JITTER_US 640
#define MGI_TX_RETRY_US 32
// Node: finish the first answer frame this much before the bridge stops
// waiting
#define MGI_ANSWER_MARGIN_US 500
#define MGI_JOIN_UP_LEN (MGI_FRAME_HDR_LEN + 6) // Payload: the MAC address
#define MGI_MAX_FRAGMENTS 14
enum { MGI_JOIN_DOWN = 1, MGI_JOIN_UP, MGI_DATA_DOWN, MGI_DATA_UP };
enum { MGI_TURN_IDLE, MGI_TURN_JOIN, MGI_TURN_DATA };
struct mgi_radio_peer {
struct mgi_radio_peer *next; // Next member in round-robin order
uint16_t radio_address; // Source address supplied in MGI_JOIN_UP
uint8_t mac[6]; // Ethernet MAC supplied in MGI_JOIN_UP
uint64_t expire_at; // First missed turn + MG_RADIO_TIMEOUT_MS, 0: answering
};
static uint32_t mgi_radio_random(struct mg_radio_node *node) {
uint32_t *random = &node->random;
if (*random == 0) {
size_t i;
*random = (uint32_t) mg_now();
for (i = 0; i < 6; i++) *random = *random * 33u + node->ifp->mac[i];
if (*random == 0) *random = 1;
}
*random ^= *random << 13;
*random ^= *random >> 17;
*random ^= *random << 5;
return *random;
}
// Read a frame's radio addresses to dst and src, and return its type, from
// the mesh header. 0: not a frame of ours
static unsigned mgi_radio_frame_parse(const uint8_t *frame, size_t len,
uint16_t *dst, uint16_t *src) {
if (len < MGI_FRAME_HDR_LEN || !mgi_radio_parse_hdr(frame, len, dst, src)) {
return 0;
}
return frame[MGI_RADIO_HDR_LEN];
}
// Write a frame's headers: the radio's, to dst from src, then ours: type,
// and burst: high nibble is the index, low nibble is the last index
static void mgi_radio_frame_header(uint8_t *frame, uint16_t dst, uint16_t src,
uint8_t type, uint8_t burst) {
mgi_radio_write_hdr(frame, dst, src);
frame[MGI_RADIO_HDR_LEN] = type, frame[MGI_RADIO_HDR_LEN + 1] = burst;
}
// Hand a radio frame to the hardware. The interface's fn sees it first
static bool mgi_radio_send(struct mg_radio_node *node, const void *frame,
size_t len) {
struct mg_str s = mg_str_n((const char *) frame, len);
mg_tcpip_call(node->ifp, MG_TCPIP_EV_PHY_TX, &s);
return node->hw_tx(node->ifp, frame, len) == len;
}
static bool mgi_radio_control_send(struct mg_radio_node *node, uint16_t dst,
uint8_t command) {
uint8_t frame[MGI_JOIN_UP_LEN] = {0};
size_t len = MGI_FRAME_HDR_LEN;
mgi_radio_frame_header(frame, dst, node->radio_address, command, 0);
if (command == MGI_JOIN_UP) {
memcpy(frame + MGI_FRAME_HDR_LEN, node->ifp->mac, 6);
len = MGI_JOIN_UP_LEN;
}
return node->now >= node->tx_at && mgi_radio_send(node, frame, len);
}
// Time on air of a burst carrying len bytes, gaps between frames included
static uint64_t mgi_radio_burst_time(size_t len) {
size_t frames = len == 0 ? 1 : (len + MGI_FRAG_CAP - 1) / MGI_FRAG_CAP;
return (frames - 1) * (mgi_radio_airtime(MGI_RADIO_MTU) + MGI_RADIO_IFS_US) +
mgi_radio_airtime(MGI_FRAME_HDR_LEN + len -
(frames - 1) * MGI_FRAG_CAP);
}
// End the current turn. A queued burst is used up only when done: all its
// frames went out. Otherwise it stays queued, and a later turn sends it again
static void mgi_radio_tx_finish(struct mg_radio_node *node, bool done) {
if (node->tx_offset != 0 && done) {
if (node->fanout != NULL) node->fanout = node->fanout->next;
if (node->fanout == NULL) {
size_t len = mg_queue_next(&node->tx, NULL);
mg_queue_del(&node->tx, len);
}
}
node->tx_offset = 0;
node->burst_at = (uint64_t) -1;
}
static void mgi_radio_tx_step(struct mg_radio_node *node, uint64_t now) {
uint8_t empty[MGI_FRAME_HDR_LEN], *frame = empty;
size_t len = MGI_FRAME_HDR_LEN, record_len = 0;
uint16_t dst;
uint8_t command;
if (now < node->burst_at) return;
if (now >= node->deadline) {
mgi_radio_tx_finish(node, false);
return;
}
dst = node->lan == NULL ? node->coordinator : node->current->radio_address;
command = node->lan == NULL ? MGI_DATA_UP : MGI_DATA_DOWN;
if (node->tx_offset != 0) {
char *record;
uint8_t *part;
record_len = mg_queue_next(&node->tx, &record);
part = (uint8_t *) record + node->tx_offset;
len = part[0];
frame = part + 1;
mgi_radio_write_hdr(frame, dst, node->radio_address);
} else {
mgi_radio_frame_header(frame, dst, node->radio_address, command, 0);
}
// A node's first answer frame: if it cannot end on air before the bridge
// stops waiting, stay silent. The queued frame waits for the next turn
if (node->lan == NULL &&
(node->tx_offset == 0 || node->tx_offset == MGI_TX_DST_LEN) &&
now + mgi_radio_airtime(len) > node->answer_by) {
node->tx_offset = 0;
node->burst_at = (uint64_t) -1;
return;
}
if (now < node->tx_at || !mgi_radio_send(node, frame, len)) {
node->burst_at = now + MGI_TX_RETRY_US;
return;
}
if (node->tx_offset == 0 || (node->tx_offset += len + 1) == record_len) {
// Bridge: the turn's last frame is out, wait for the answer
if (node->lan != NULL)
node->deadline =
now + mgi_radio_airtime(len) + MG_RADIO_ANSWER_TIMEOUT_US;
mgi_radio_tx_finish(node, true);
} else {
node->burst_at = now + mgi_radio_airtime(len) + MGI_RADIO_IFS_US;
}
}
static void mgi_radio_tx_begin(struct mg_radio_node *node, bool burst,
uint64_t now, uint64_t deadline) {
node->phase = MGI_TURN_DATA;
node->answer_by = (uint64_t) -1; // Node sets it after a grant
node->tx_offset = burst ? MGI_TX_DST_LEN : 0;
node->burst_at = now;
node->deadline = deadline;
}
// Return the assembled length, zero for an empty frame, or -1 if incomplete
// or invalid. Full non-final fragments make the write offset derivable.
static int mgi_radio_data_receive(struct mg_radio_node *node,
const uint8_t *frame, size_t len,
uint64_t now) {
unsigned burst = frame[MGI_FRAME_HDR_LEN - 1], index = burst >> 4,
last = burst & 15;
size_t chunk = len - MGI_FRAME_HDR_LEN, cap = MGI_FRAG_CAP;
size_t offset = index * cap;
if (index == 0) {
node->rx_expected = (uint8_t) burst;
if (node->lan == NULL)
node->deadline = now + mgi_radio_burst_time(MGI_ETH_MAX) +
2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US;
}
if (last >= MGI_MAX_FRAGMENTS || index > last || burst != node->rx_expected ||
chunk > cap || now > node->deadline || (index < last && chunk != cap) ||
(last != 0 && chunk == 0) || offset + chunk > sizeof(node->rx_buf)) {
MG_ERROR(
("%s: fragment %u/%u dropped, expected %u/%u, %u bytes, %lld us "
"past deadline",
node->lan == NULL ? "Node" : "Bridge", index, last,
(unsigned) node->rx_expected >> 4, node->rx_expected & 15U,
(unsigned) chunk, (long long) (now - node->deadline)));
node->rx_expected = 0xff;
return -1;
}
memcpy(node->rx_buf + offset, frame + MGI_FRAME_HDR_LEN, chunk);
if (index < last) {
node->rx_expected = (uint8_t) (burst + 0x10);
// Bridge: an answer is under way, wait for its next fragment
if (node->lan != NULL)
node->deadline = now + mgi_radio_airtime(MGI_RADIO_MTU) +
MGI_RADIO_IFS_US + MG_RADIO_ANSWER_TIMEOUT_US;
return -1;
}
node->rx_expected = 0xff;
return offset + chunk == 0 || offset + chunk >= 14 ? (int) (offset + chunk)
: -1;
}
// Bridge scheduling and Ethernet forwarding.
static uint16_t mgi_radio_join_field(const uint8_t *p) {
return (uint16_t) ((unsigned) p[0] * 256 + p[1]);
}
// Return chaddr for an Ethernet DHCP server reply, even when broadcast.
static const uint8_t *mgi_radio_dhcp_client(const uint8_t *frame, size_t len) {
size_t ip_len, ihl, udp_len;
const uint8_t *udp, *dhcp;
if (len < 34 || mgi_radio_join_field(frame + 12) != 0x0800 ||
(frame[14] >> 4) != 4 || frame[23] != 17 ||
(mgi_radio_join_field(frame + 20) & 0x3fff) != 0)
return NULL;
ip_len = mgi_radio_join_field(frame + 16);
ihl = (size_t) (frame[14] & 15) * 4;
if (ihl < 20 || ip_len > len - 14 || ip_len < ihl + 8 + 240) return NULL;
udp = frame + 14 + ihl;
udp_len = mgi_radio_join_field(udp + 4);
if (mgi_radio_join_field(udp) != 67 || mgi_radio_join_field(udp + 2) != 68 ||
udp_len < 8 + 240 || udp_len > ip_len - ihl)
return NULL;
dhcp = udp + 8;
if (dhcp[0] != 2 || dhcp[1] != 1 || dhcp[2] != 6 ||
memcmp(dhcp + 236, "\x63\x82\x53\x63", 4) != 0)
return NULL;
return dhcp + 28;
}
static size_t mgi_radio_enqueue(struct mg_radio_node *node, const void *buf,
size_t len) {
const uint8_t *frame = (const uint8_t *) buf;
if (node->lan == NULL)
return mgi_radio_queue(node, &node->tx, buf, len, node->coordinator,
MGI_DATA_UP);
if (len >= 14 && len <= MGI_ETH_MAX) {
const uint8_t *client = mgi_radio_dhcp_client(frame, len);
const uint8_t *dst = client == NULL ? frame : client;
bool multicast = client == NULL && (frame[0] & 1) != 0;
struct mgi_radio_peer *peer;
for (peer = node->members; peer != NULL; peer = peer->next) {
if (multicast || memcmp(dst, peer->mac, 6) == 0) {
uint16_t addr = multicast ? 0xffffu : peer->radio_address;
return mgi_radio_queue(node, &node->tx, buf, len, addr, MGI_DATA_DOWN);
}
}
}
return 0;
}
static void mgi_radio_bridge_queue_lan(struct mg_radio_node *bridge) {
struct mg_queue *rx = &bridge->lan->recv_queue;
char *buf;
size_t len;
while ((len = mg_queue_next(rx, &buf)) > 0) {
bridge->ifp->driver->tx(buf, len, bridge->ifp);
mg_queue_del(rx, len);
}
}
static void mgi_radio_bridge_rx(uint64_t now, struct mg_radio_node *b,
const uint8_t *frame, size_t len) {
struct mgi_radio_peer *peer;
uint16_t dst = 0, src = 0;
unsigned command = mgi_radio_frame_parse(frame, len, &dst, &src);
if (command == MGI_DATA_UP && dst == b->radio_address &&
b->phase == MGI_TURN_DATA && b->current != NULL &&
src == b->current->radio_address && now <= b->deadline) {
int received = mgi_radio_data_receive(b, frame, len, now);
if (received < 0) return;
if (received != 0) {
b->lan->driver->tx(b->rx_buf, (size_t) received, b->lan);
}
b->current->expire_at = 0;
b->current = b->current->next;
b->phase = MGI_TURN_IDLE;
b->deadline = now;
return;
}
if (command == MGI_DATA_UP && dst == b->radio_address) {
MG_ERROR(
("Bridge: fragment %u/%u from %04x outside its turn: phase %u, "
"turn of %04x, %lld us past deadline",
frame[MGI_FRAME_HDR_LEN - 1] >> 4U, frame[MGI_FRAME_HDR_LEN - 1] & 15U,
src, b->phase, b->current == NULL ? 0 : b->current->radio_address,
(long long) (now - b->deadline)));
return;
}
if (len != MGI_JOIN_UP_LEN || command != MGI_JOIN_UP ||
dst != b->radio_address || b->phase != MGI_TURN_JOIN ||
now >= b->deadline) {
return;
}
if (src == 0 || src == 0xffffu) return;
for (peer = b->members; peer != NULL; peer = peer->next) {
if (peer->radio_address == src) break;
}
if (peer == NULL) {
peer = (struct mgi_radio_peer *) mg_calloc(1, sizeof(*peer));
if (peer == NULL) return;
peer->radio_address = src;
peer->next = b->members;
b->members = peer;
MG_DEBUG(("Member %M joined, radio address %04x", mg_print_mac,
frame + MGI_FRAME_HDR_LEN, src));
}
memcpy(peer->mac, frame + MGI_FRAME_HDR_LEN, sizeof(peer->mac));
peer->expire_at = 0;
}
// Member peer did not answer its turn. The first miss starts the timeout. If
// it is still silent when that ends, it is gone: remove it, and its queued
// downlink frames
static void mgi_radio_member_missed(struct mg_radio_node *node,
struct mgi_radio_peer *peer, uint64_t now) {
if (peer->expire_at == 0) peer->expire_at = now + MG_RADIO_TIMEOUT_MS * 1000;
if (now < peer->expire_at) return;
MG_DEBUG(("Member %M removed: no answer for %d ms", mg_print_mac, peer->mac,
MG_RADIO_TIMEOUT_MS));
if (node->fanout == peer) {
node->fanout = peer->next;
if (node->fanout == NULL) {
size_t len = mg_queue_next(&node->tx, NULL);
mg_queue_del(&node->tx, len);
}
}
LIST_DELETE(struct mgi_radio_peer, &node->members, peer);
mg_free(peer);
}
// A broadcast occupies one record and is sent once to each member in list
// order.
static size_t mgi_radio_bridge_burst(struct mg_radio_node *node,
struct mgi_radio_peer *peer) {
char *record;
size_t len;
while ((len = mg_queue_next(&node->tx, &record)) != 0) {
uint16_t dst = mgi_radio_join_field((const uint8_t *) record);
struct mgi_radio_peer *member;
if (dst == 0xffffu) {
if (node->fanout == NULL) node->fanout = node->members;
return node->fanout == peer ? len : 0;
}
if (dst == peer->radio_address) return len;
for (member = node->members; member != NULL; member = member->next) {
if (member->radio_address == dst) return 0;
}
mg_queue_del(&node->tx, len); // Its destination has left.
}
return 0;
}
static uint64_t mgi_radio_queued_burst_time(struct mg_radio_node *node,
size_t len) {
char *record;
size_t frames;
if (len == 0) return mgi_radio_burst_time(0);
mg_queue_next(&node->tx, &record);
// Fragment zero carries the final index. Count overhead and IFS per frame.
frames = ((uint8_t) record[MGI_TX_DST_LEN + MGI_FRAME_HDR_LEN] & 15u) + 1u;
return mgi_radio_airtime(len - MGI_TX_DST_LEN - frames +
(frames - 1) * MGI_RADIO_OVERHEAD) +
(frames - 1) * MGI_RADIO_IFS_US;
}
static void mgi_radio_bridge_io(uint64_t now, struct mg_radio_node *b) {
mgi_radio_bridge_queue_lan(b);
if (now >= b->deadline) {
if (b->burst_at != (uint64_t) -1) mgi_radio_tx_finish(b, false);
if (b->phase == MGI_TURN_DATA && b->current != NULL) {
struct mgi_radio_peer *peer = b->current;
b->current = peer->next;
mgi_radio_member_missed(b, peer, now);
} else if (b->phase == MGI_TURN_JOIN) {
b->current = b->members;
}
b->phase = MGI_TURN_IDLE;
if (b->current != NULL) {
size_t burst = mgi_radio_bridge_burst(b, b->current);
uint64_t down = mgi_radio_queued_burst_time(b, burst);
b->rx_expected = 0xff;
down += mgi_radio_burst_time(MGI_ETH_MAX);
mgi_radio_tx_begin(b, burst != 0, now,
now + down + 2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US);
} else if (mgi_radio_control_send(b, 0xffffu, MGI_JOIN_DOWN)) {
b->phase = MGI_TURN_JOIN;
b->deadline = now + MGI_JOIN_WINDOW_US;
}
if (b->deadline <= now) b->deadline = now + MGI_JOIN_TURN_US;
}
}
static void mgi_radio_node_rx(struct mg_radio_node *n, uint64_t now,
uint8_t *frame, size_t len) {
uint16_t dst = 0, src = 0;
unsigned command = mgi_radio_frame_parse(frame, len, &dst, &src);
if (command == MGI_JOIN_DOWN && len == MGI_FRAME_HDR_LEN && dst == 0xffffu) {
// A round without our turn starts the timeout, a turn clears it
if (n->joined && src == n->coordinator && n->granted) {
n->granted = false;
} else if (n->joined && src == n->coordinator && n->expire_at == 0) {
n->expire_at = now + MG_RADIO_TIMEOUT_MS * 1000;
} else if (n->joined && src == n->coordinator && now >= n->expire_at) {
MG_INFO(("Left the mesh: no turn for %d ms", MG_RADIO_TIMEOUT_MS));
n->joined = false;
n->phase = MGI_TURN_IDLE;
n->burst_at = (uint64_t) -1;
n->tx_offset = 0;
n->rx_expected = 0xff;
}
if (!n->joined && (mgi_radio_random(n) % 64) == 0) {
// Spread contenders across windows as well as within the reply window.
n->coordinator = src;
n->phase = MGI_TURN_JOIN;
n->burst_at =
now + MGI_JOIN_TURN_US + mgi_radio_random(n) % MGI_JOIN_JITTER_US;
}
} else if (command == MGI_DATA_DOWN && n->coordinator != 0 &&
dst == n->radio_address && src == n->coordinator) {
int received = mgi_radio_data_receive(n, frame, len, now);
if (received < 0) return;
if (!n->joined) MG_INFO(("Joined the mesh, bridge address %04x", src));
n->joined = true;
n->granted = true;
n->expire_at = 0;
if (received != 0) {
struct mg_tcpip_if *ifp = n->ifp;
if (n->rx_len != 0 || (size_t) received > ifp->recv_queue.size) {
ifp->ndrop++;
} else {
memcpy(ifp->recv_queue.buf, n->rx_buf, (size_t) received);
n->rx_len = (size_t) received;
}
}
// A grant that waited in the receive queue while the node was busy, e.g.
// computing TLS keys, is too old to answer. Leave the turn state alone:
// queued frames go out on the first grant that can still be answered
if (n->now + MGI_ANSWER_MARGIN_US >= now + MG_RADIO_ANSWER_TIMEOUT_US) {
return;
}
if (n->burst_at != (uint64_t) -1) mgi_radio_tx_finish(n, false);
mgi_radio_tx_begin(n, mg_queue_next(&n->tx, NULL) != 0, now,
now + mgi_radio_burst_time(MGI_ETH_MAX) +
2 * MGI_RADIO_IFS_US + MGI_JOIN_TURN_US);
n->answer_by = now + MG_RADIO_ANSWER_TIMEOUT_US - MGI_ANSWER_MARGIN_US;
}
}
// Handle a received radio frame. Its timing counts from its arrival, us
static void mgi_radio_input(struct mg_radio_node *node, uint64_t arrived,
void *buf, size_t len) {
uint64_t ready = node->now + MGI_RADIO_TURNAROUND_US;
if (node->tx_at < ready) node->tx_at = ready;
if (node->lan != NULL) {
mgi_radio_bridge_rx(arrived, node, (const uint8_t *) buf, len);
} else {
mgi_radio_node_rx(node, arrived, (uint8_t *) buf, len);
}
}
static void mgi_radio_tick(struct mg_radio_node *node, uint64_t now) {
node->now = now;
if (node->lan != NULL) {
mgi_radio_bridge_io(now, node);
mgi_radio_tx_step(node, now);
return;
}
if (node->phase == MGI_TURN_JOIN) {
if (node->burst_at <= now) {
if (now - node->burst_at <= MGI_JOIN_TURN_US && !node->joined)
mgi_radio_control_send(node, node->coordinator, MGI_JOIN_UP);
node->burst_at = (uint64_t) -1;
node->phase = MGI_TURN_IDLE;
}
} else {
mgi_radio_tx_step(node, now);
}
}
bool mg_radio_init(struct mg_tcpip_if *ifp,
bool (*hw_init)(struct mg_tcpip_if *, uint16_t addr),
bool (*hw_poll)(struct mg_tcpip_if *),
size_t (*hw_tx)(struct mg_tcpip_if *, const void *,
size_t)) {
struct mg_radio_node *node =
(struct mg_radio_node *) mg_calloc(1, sizeof(*node));
if (node == NULL) return false;
node->hw_poll = hw_poll, node->hw_tx = hw_tx;
node->ifp = ifp;
node->radio_address =
(uint16_t) (2 + ((unsigned) ifp->mac[4] * 256 + ifp->mac[5]) % 65532u);
node->burst_at = (uint64_t) -1;
node->rx_expected = 0xff;
mg_queue_init(&node->tx, node->tx_buf, sizeof(node->tx_buf));
mg_queue_init(&node->frames, node->frames_buf, sizeof(node->frames_buf));
ifp->driver_data = node;
if (hw_init(ifp, node->radio_address)) return true;
ifp->driver_data = NULL;
mg_free(node);
return false;
}
void mg_radio_bridge(struct mg_tcpip_if *ifp, struct mg_tcpip_if *lan) {
struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data;
node->lan = lan;
}
size_t mg_radio_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data;
size_t n = mgi_radio_enqueue(node, buf, len);
if (n != len) { // Mongoose ignores a failed send: count and report it
ifp->nerr++;
MG_ERROR(("Mesh refused a %u byte frame", (unsigned) len));
}
return n;
}
size_t mg_radio_rx(void *buf, size_t len, struct mg_tcpip_if *ifp) {
struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data;
size_t n = node->rx_len;
if (n > len) return 0;
if (n != 0 && buf != ifp->recv_queue.buf) memcpy(buf, ifp->recv_queue.buf, n);
node->rx_len = 0;
return n;
}
void mg_radio_rx_queue(struct mg_tcpip_if *ifp, const void *frame, size_t len) {
struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data;
uint64_t arrived = mg_micros();
size_t need = MGI_RX_STAMP_LEN + len;
uint16_t dst, src;
char *p;
if (len > MGI_RADIO_MTU ||
!mgi_radio_parse_hdr((const uint8_t *) frame, len, &dst, &src) ||
(dst != 0xffffu && dst != node->radio_address)) {
return;
}
if (mg_queue_book(&node->frames, &p, need) < need) {
ifp->ndrop++;
return;
}
memcpy(p, &arrived, MGI_RX_STAMP_LEN);
memcpy(p + MGI_RX_STAMP_LEN, frame, len);
mg_queue_add(&node->frames, need);
}
// Process queued radio frames, oldest first, each with its arrival time.
// Stop while the node holds an Ethernet frame the TCP/IP stack has not taken
// yet
bool mg_radio_poll(struct mg_tcpip_if *ifp, bool s1) {
struct mg_radio_node *node = (struct mg_radio_node *) ifp->driver_data;
bool tx_done = node->hw_poll(ifp);
uint64_t now = mg_micros();
char *record;
size_t len;
(void) s1;
if (tx_done) node->tx_at = now + MGI_RADIO_IFS_US;
node->now = now;
while (node->rx_len == 0 &&
(len = mg_queue_next(&node->frames, &record)) != 0) {
if (len > MGI_RX_STAMP_LEN) {
struct mg_str s =
mg_str_n(record + MGI_RX_STAMP_LEN, len - MGI_RX_STAMP_LEN);
uint64_t arrived;
memcpy(&arrived, record, MGI_RX_STAMP_LEN);
mg_tcpip_call(ifp, MG_TCPIP_EV_PHY_RX, &s);
mgi_radio_input(node, arrived, s.buf, s.len);
}
mg_queue_del(&node->frames, len);
}
mgi_radio_tick(node, now);
return node->joined;
}
#endif
+74
View File
@@ -0,0 +1,74 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
//
// Ethernet over radio: shared framing, scheduling and bridge forwarding.
// Hardware drivers pass their functions to mg_radio_init().
#pragma once
#include "net_builtin.h"
#define MG_RADIO_802154 1 // IEEE 802.15.4, 250 kbit/s
#define MG_RADIO_BLE 2 // Bluetooth LE 2 Mbit/s PHY, raw: no BLE link layer
#ifndef MG_RADIO
#define MG_RADIO MG_RADIO_802154
#endif
// The radio network: a channel, and an id that keeps other networks out.
// A bridge and its nodes must use the same values
#if MG_RADIO == MG_RADIO_BLE
#ifndef MG_RADIO_CHANNEL
#define MG_RADIO_CHANNEL 36 // Data channel 0-36. 36: 2478 MHz, clear of Wi-Fi
#endif
#ifndef MG_RADIO_NETWORK
#define MG_RADIO_NETWORK 0x71764129 // Access address
#endif
#else
#ifndef MG_RADIO_CHANNEL
#define MG_RADIO_CHANNEL 15 // Channel 11-26
#endif
#ifndef MG_RADIO_NETWORK
#define MG_RADIO_NETWORK 0xabcd // PAN ID
#endif
#endif
// A turn's answer must arrive this soon after the turn's last frame ends on
// air, or the turn ends. A node that would answer later stays silent and keeps
// its frame for the next turn. Covers the node's poll latency, the radio
// turnaround and one full fragment's airtime, 4.3 ms on 802.15.4
#ifndef MG_RADIO_ANSWER_TIMEOUT_US
#define MG_RADIO_ANSWER_TIMEOUT_US 8000
#endif
// A radio driver aborts a transmission that has not finished this soon, and
// reports it done to mg_radio_poll()
#ifndef MG_RADIO_TX_TIMEOUT_US
#define MG_RADIO_TX_TIMEOUT_US 60000
#endif
// Membership timeout. The bridge removes a member that has not answered its
// turns for this long, counted from the first missed turn. A node leaves the
// mesh when it has had no turn for this long
#ifndef MG_RADIO_TIMEOUT_MS
#define MG_RADIO_TIMEOUT_MS 1000
#endif
#if MG_ENABLE_TCPIP
bool mg_radio_init(struct mg_tcpip_if *ifp,
bool (*hw_init)(struct mg_tcpip_if *, uint16_t addr),
bool (*hw_poll)(struct mg_tcpip_if *),
size_t (*hw_tx)(struct mg_tcpip_if *, const void *, size_t));
bool mg_radio_poll(struct mg_tcpip_if *, bool s1); // Run it. true: joined
size_t mg_radio_tx(const void *, size_t, struct mg_tcpip_if *); // Queue
size_t mg_radio_rx(void *, size_t, struct mg_tcpip_if *); // Received frame
// Bridge LAN and radio Ethernet frames. Call after both interfaces initialize.
void mg_radio_bridge(struct mg_tcpip_if *, struct mg_tcpip_if *lan);
// Queue a received radio frame with its arrival time. Call it from the
// receive interrupt. Frames for other radios are skipped
void mg_radio_rx_queue(struct mg_tcpip_if *, const void *, size_t);
#endif
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612) && MG_ENABLE_DRIVER_RW612 #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612) && MG_ENABLE_DRIVER_RW612
+8 -2
View File
@@ -27,7 +27,9 @@ struct mg_tcpip_driver_rw612_data {
#define MG_DRIVER_MDC_HOLDTIME 3 #define MG_DRIVER_MDC_HOLDTIME 3
#endif #endif
#define MG_TCPIP_DRIVER_INIT(mgr) \ extern struct mg_tcpip_driver mg_tcpip_driver_rw612;
#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_; \
@@ -39,8 +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
+459
View File
@@ -0,0 +1,459 @@
#include "log.h"
#include "net_builtin.h"
#include "radio.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612W) && \
MG_ENABLE_DRIVER_RW612W
#if MG_RADIO != MG_RADIO_802154
#error "MG_ENABLE_DRIVER_RW612W supports MG_RADIO_802154 only"
#endif
#include "sha256.h"
#ifdef ENET
#undef ENET
#endif
#include <fsl_ocotp.h>
// The 802.15.4 radio runs NXP combo firmware on CPU2, an OpenThread RCP. We
// are CPU3. Messages go through the IMU mailbox: IMU messages carry IMUMC
// messages, IMUMC messages carry HDLC framed Spinel. See NXP sources:
// mcuxsdk-core drivers/imu/fsl_imu.c, mcux-component
// imu_adapter/fsl_adapter_imu.c, connectivity framework
// platform/rw61x/fwk_platform_hdlc.c; OpenThread src/lib/spinel/spinel.h
// IMU message FIFO registers, one block per direction. See fsl_imu.h
struct mg_rw612_imu {
volatile uint32_t WR_MSG, RD_MSG, STATUS, CNTL, RD_MSG_DBG;
};
#define MGI_IMU ((struct mg_rw612_imu *) 0x443ff804) // CPU3 -> CPU2
#define MGI_IMU_PEER ((struct mg_rw612_imu *) 0x443ff818) // CPU2 -> CPU3
#define MGI_IMU_LOCKED MG_BIT(0) // STATUS: FIFO locked
#define MGI_IMU_ALMOST_FULL MG_BIT(1) // STATUS: FIFO almost full
#define MGI_IMU_EMPTY MG_BIT(3) // STATUS: FIFO empty
#define MGI_IMU_WR_PTR(s) (((s) >> 16) & 15U)
#define MGI_IMU_INT_CLR MG_BIT(0) // CNTL: clear message ready IRQ
#define MGI_IMU_FLUSH MG_BIT(16) // CNTL: flush send FIFO
#define MGI_IMU_WAIT_FOR_ACK MG_BIT(17) // CNTL: lock send FIFO
#define MGI_IMU_WATERMARK(x) ((uint32_t) (x) << 20)
#define MGI_IMU_WATERMARK_MASK (15U << 20)
// IMU message: header, then payload words. See IMU_Msg_t
struct mg_rw612_msg {
uint8_t type, subtype, seq, len; // len: number of payload words
uint32_t payload[8];
};
// Mailbox in SMU2 shared memory, at the address CPU2 firmware expects
struct mg_rw612_mbox {
uint32_t magic[2]; // Sync pattern: [0] CPU2, [1] us
struct mg_rw612_msg q[2][16]; // Message slots: [0] CPU2 -> us, [1] ours
};
#define MGI_MBOX ((volatile struct mg_rw612_mbox *) 0x443c0000)
#define MGI_TXBUF 0x443c1508U // Our IMUMC buffers: 16 x 264 bytes
#define MGI_TXBUF_CNT 16
#define MGI_TXBUF_LEN 264U
#define MGI_SLEEP_FLAG (*(volatile uint32_t *) 0x443c2588)
#define MGI_SYNC_MAGIC 0xabcdef89U
// IMUMC message, carried in IMU payload words. See imumc_std_msg
struct mg_rw612_imumc {
uint32_t src, dst; // Endpoint addresses
uint16_t rfu, idx; // Reserved
uint16_t len; // Payload length, bytes
uint16_t flags; // Message flags
uint32_t data; // Payload buffer address
};
#define MGI_EPT_LOCAL 10 // Our 802.15.4 endpoint
#define MGI_EPT_REMOTE 20 // Firmware 802.15.4 endpoint
enum { MGI_MSG_CONTROL = 0, MGI_MSG_IMUMC = 8 }; // IMU message types
enum { // Control message subtypes
MGI_CTL_SYNC = 1,
MGI_CTL_SYNC_ACK = 2,
MGI_CTL_ACK_FOR_UNLOCK = 3,
MGI_CTL_CMD_BUF_ADDR = 6,
MGI_CTL_EPT_QUERY = 11,
MGI_CTL_EPT_QUERY_RSP = 12,
MGI_CTL_BUF_FREE = 13
};
// Spinel commands, properties and statuses we use
enum { MGI_CMD_RESET = 1, MGI_CMD_GET = 2, MGI_CMD_SET = 3, MGI_CMD_IS = 6 };
enum {
MGI_PROP_LAST_STATUS = 0,
MGI_PROP_NCP_VERSION = 2,
MGI_PROP_PHY_ENABLED = 0x20,
MGI_PROP_PHY_CHAN = 0x21,
MGI_PROP_SADDR = 0x35, // Short address, little endian
MGI_PROP_PANID = 0x36,
MGI_PROP_RAW_STREAM = 0x37,
MGI_PROP_PROMISCUOUS = 0x38,
MGI_PROP_STREAM_RAW = 0x71
};
#define MGI_RESET_STACK 2 // RESET argument: reset the RCP stack only
#define MGI_STATUS_RESET_MIN 112 // LAST_STATUS: RCP has reset
#define MGI_STATUS_RESET_MAX 127
#define MGI_TX_TIMEOUT_MS 200 // Wait for transmit done, incl. retries
#define MGI_RSP_TIMEOUT_MS 500
// Driver state, one radio
struct mg_rw612 {
bool up; // IMU link synchronised
bool ept_ready; // IMUMC endpoints connected
bool reset; // RCP reported a reset
uint8_t seq; // IMU message sequence number
uint16_t free_bufs; // Free IMUMC buffers, bit per buffer
uint8_t hdlc[300]; // HDLC frame being received, unescaped
size_t hlen; // Bytes in hdlc
bool esc; // Previous byte was an escape
uint8_t tid; // Spinel transaction ID of the pending request
bool rsp; // Response to the pending request received
uint32_t rsp_status; // Its status, if LAST_STATUS, else 0
char version[64]; // RCP version string
bool txing; // A send is on, see mg_rw612_start()
uint64_t txstart; // Its start, ms
struct mg_tcpip_if *ifp; // Our interface, for the L2 receive pool
};
static struct mg_rw612 s_rw612;
static void mg_rw612_imu_send(uint8_t type, uint8_t subtype,
const uint32_t *payload, uint8_t len) {
volatile struct mg_rw612_msg *m;
uint64_t expire = mg_millis() + 100;
uint8_t i;
while ((MGI_IMU->STATUS & (MGI_IMU_ALMOST_FULL | MGI_IMU_LOCKED)) &&
mg_millis() < expire) {
(void) 0;
}
m = &MGI_MBOX->q[1][MGI_IMU_WR_PTR(MGI_IMU->STATUS)];
m->type = type, m->subtype = subtype, m->seq = s_rw612.seq++, m->len = len;
for (i = 0; i < len; i++) m->payload[i] = payload[i];
MGI_IMU->WR_MSG = (uint32_t) (uintptr_t) m;
}
static void mg_rw612_control(uint8_t subtype, uint32_t a, uint32_t b,
uint8_t len) {
uint32_t payload[2] = {a, b};
mg_rw612_imu_send(MGI_MSG_CONTROL, subtype, payload, len);
}
static void mg_rw612_queue_rx(const uint8_t *frame, size_t len) {
mg_radio_rx_queue(s_rw612.ifp, frame, len);
}
// Spinel packed unsigned integer: 7 bits per byte, LSB first
static size_t mg_rw612_unpack(const uint8_t *p, size_t len, uint32_t *v) {
size_t i;
*v = 0;
for (i = 0; i < len && i < 4; i++) {
*v |= (uint32_t) (p[i] & 0x7f) << (7 * i);
if ((p[i] & 0x80) == 0) return i + 1;
}
return 0;
}
// Handle a received Spinel frame: header, command, property, value
static void mg_rw612_spinel(const uint8_t *f, size_t len) {
struct mg_rw612 *s = &s_rw612;
uint32_t cmd, prop, status = 0;
size_t n, ofs = 1;
uint8_t tid = f[0] & 15;
if (len < 3 || (n = mg_rw612_unpack(f + ofs, len - ofs, &cmd)) == 0) return;
ofs += n;
if ((n = mg_rw612_unpack(f + ofs, len - ofs, &prop)) == 0) return;
ofs += n;
if (cmd != MGI_CMD_IS) return;
if (prop == MGI_PROP_STREAM_RAW && tid == 0 && len - ofs >= 2) {
size_t flen = (size_t) (f[ofs] | (f[ofs + 1] << 8)); // Incl. FCS
if (flen >= 2 && ofs + 2 + flen <= len) {
mg_rw612_queue_rx(f + ofs + 2, flen - 2);
}
} else if (prop == MGI_PROP_LAST_STATUS) {
mg_rw612_unpack(f + ofs, len - ofs, &status);
if (tid == 0 && status >= MGI_STATUS_RESET_MIN &&
status <= MGI_STATUS_RESET_MAX) {
s->reset = true;
}
} else if (prop == MGI_PROP_NCP_VERSION) {
n = len - ofs < sizeof(s->version) - 1 ? len - ofs : sizeof(s->version) - 1;
memcpy(s->version, f + ofs, n);
s->version[n] = '\0';
}
if (tid != 0 && tid == s->tid) s->rsp = true, s->rsp_status = status;
}
// HDLC-lite: 0x7e delimits frames, 0x7d escapes, FCS-16 at the end
static uint16_t mg_rw612_fcs(uint16_t fcs, uint8_t c) {
int i;
fcs ^= c;
for (i = 0; i < 8; i++) fcs = (fcs & 1) ? (fcs >> 1) ^ 0x8408 : fcs >> 1;
return fcs;
}
static void mg_rw612_hdlc_rx(const uint8_t *p, size_t len) {
struct mg_rw612 *s = &s_rw612;
size_t i, j;
for (i = 0; i < len; i++) {
uint8_t c = p[i];
if (c == 0x7e) {
if (s->hlen >= 3) {
uint16_t fcs = 0xffff;
for (j = 0; j < s->hlen; j++) fcs = mg_rw612_fcs(fcs, s->hdlc[j]);
if (fcs == 0xf0b8) mg_rw612_spinel(s->hdlc, s->hlen - 2);
}
s->hlen = 0, s->esc = false;
} else if (c == 0x7d) {
s->esc = true;
} else if (s->hlen < sizeof(s->hdlc)) {
s->hdlc[s->hlen++] = s->esc ? c ^ 0x20 : c;
s->esc = false;
}
}
}
static void mg_rw612_control_rx(volatile struct mg_rw612_msg *m) {
struct mg_rw612 *s = &s_rw612;
switch (m->subtype) {
case MGI_CTL_ACK_FOR_UNLOCK:
MGI_IMU->CNTL &= ~MGI_IMU_WAIT_FOR_ACK;
break;
case MGI_CTL_SYNC: // As HAL_ImuCtrlHandler(): acknowledge twice
mg_rw612_control(MGI_CTL_SYNC_ACK, 0, 0, 0);
mg_rw612_control(MGI_CTL_SYNC_ACK, 0, 0, 0);
s->up = true;
break;
case MGI_CTL_SYNC_ACK:
case MGI_CTL_CMD_BUF_ADDR:
s->up = true;
break;
case MGI_CTL_EPT_QUERY: { // Firmware asks if our endpoint exists
bool ours = m->payload[0] == MGI_EPT_LOCAL;
mg_rw612_control(MGI_CTL_EPT_QUERY_RSP, m->payload[0], ours, 2);
if (ours) s->ept_ready = true;
break;
}
case MGI_CTL_EPT_QUERY_RSP:
if (m->payload[0] == MGI_EPT_REMOTE && m->payload[1] != 0) {
s->ept_ready = true;
}
break;
case MGI_CTL_BUF_FREE: { // Firmware is done with one of our buffers
uint32_t i = (m->payload[0] - MGI_TXBUF) / MGI_TXBUF_LEN;
if (i < MGI_TXBUF_CNT) s->free_bufs |= (uint16_t) MG_BIT(i);
break;
}
default:
break;
}
}
// Process all received IMU messages. See HAL_ImuReceive()
static void mg_rw612_poll_imu(void) {
bool unlock = false;
while ((MGI_IMU_PEER->STATUS & MGI_IMU_EMPTY) == 0) {
struct mg_rw612_msg m;
volatile struct mg_rw612_msg *p;
uint8_t i;
MGI_SLEEP_FLAG &= ~1U;
p = (volatile struct mg_rw612_msg *) (uintptr_t) MGI_IMU->RD_MSG;
if (MGI_IMU_PEER->STATUS & MGI_IMU_LOCKED) unlock = true;
if (p == NULL) continue;
m.type = p->type, m.subtype = p->subtype, m.len = p->len;
for (i = 0; i < 8; i++) m.payload[i] = p->payload[i];
if (m.type == MGI_MSG_CONTROL) {
mg_rw612_control_rx(&m);
} else if (m.type == MGI_MSG_IMUMC) {
struct mg_rw612_imumc im;
memcpy(&im, m.payload, sizeof(im));
if (im.dst == MGI_EPT_LOCAL) {
mg_rw612_hdlc_rx((const uint8_t *) (uintptr_t) im.data, im.len);
}
mg_rw612_control(MGI_CTL_BUF_FREE, im.data, 0, 1);
}
}
MGI_IMU->CNTL |= MGI_IMU_INT_CLR;
MGI_SLEEP_FLAG |= 1U;
if (unlock) mg_rw612_control(MGI_CTL_ACK_FOR_UNLOCK, 0, 0, 0);
}
// Send bytes to the firmware endpoint, in IMUMC buffer sized chunks
static bool mg_rw612_imumc_send(const uint8_t *p, size_t len) {
struct mg_rw612 *s = &s_rw612;
while (len > 0) {
size_t n = len < MGI_TXBUF_LEN ? len : MGI_TXBUF_LEN;
uint64_t expire = mg_millis() + 100;
struct mg_rw612_imumc im;
uint32_t i;
while (s->free_bufs == 0) {
mg_rw612_poll_imu();
if (mg_millis() > expire) return false;
}
for (i = 0; (s->free_bufs & MG_BIT(i)) == 0; i++) (void) 0;
s->free_bufs &= (uint16_t) ~MG_BIT(i);
memset(&im, 0, sizeof(im));
im.src = MGI_EPT_LOCAL, im.dst = MGI_EPT_REMOTE, im.len = (uint16_t) n;
im.data = MGI_TXBUF + i * MGI_TXBUF_LEN;
memcpy((void *) (uintptr_t) im.data, p, n);
mg_rw612_imu_send(MGI_MSG_IMUMC, 0, (uint32_t *) &im, sizeof(im) / 4);
p += n, len -= n;
}
return true;
}
// Send a Spinel frame, HDLC encoded, with a new transaction ID. Its
// response sets rsp, see mg_rw612_spinel()
static bool mg_rw612_post(uint8_t *f, size_t len) {
struct mg_rw612 *s = &s_rw612;
uint8_t buf[2 * 160 + 6];
uint16_t fcs = 0xffff;
size_t i, n = 0;
s->tid = (uint8_t) (s->tid % 15 + 1);
f[0] = (uint8_t) (0x80 | s->tid); // Header: flag, interface 0, TID
s->rsp = false;
buf[n++] = 0x7e;
for (i = 0; i < len + 2 && n + 3 < sizeof(buf); i++) {
uint8_t c;
if (i < len) {
c = f[i], fcs = mg_rw612_fcs(fcs, c);
} else {
c = (uint8_t) (i == len ? ~fcs & 0xff : ~fcs >> 8);
}
if (c == 0x7e || c == 0x7d || c == 0x11 || c == 0x13 || c == 0xf8) {
buf[n++] = 0x7d, c ^= 0x20;
}
buf[n++] = c;
}
buf[n++] = 0x7e;
return mg_rw612_imumc_send(buf, n);
}
// Send a Spinel frame and wait for its response. Return false on timeout
static bool mg_rw612_request(uint8_t *f, size_t len, uint32_t timeout_ms) {
uint64_t expire = mg_millis() + timeout_ms;
if (!mg_rw612_post(f, len)) return false;
while (!s_rw612.rsp && mg_millis() < expire) mg_rw612_poll_imu();
return s_rw612.rsp;
}
static bool mg_rw612_set(uint32_t prop, const uint8_t *val, size_t len) {
uint8_t f[16];
if (len > sizeof(f) - 3) return false;
f[1] = MGI_CMD_SET, f[2] = (uint8_t) prop; // Properties used are < 0x80
memcpy(f + 3, val, len);
return mg_rw612_request(f, len + 3, MGI_RSP_TIMEOUT_MS) &&
s_rw612.rsp_status == 0;
}
// Log an init error, return false
static bool mg_rw612_fail(const char *msg) {
MG_ERROR(("%s", msg));
return false;
}
// Start one raw transmission. The RCP adds the FCS and reports completion.
static size_t mgi_rw612w_radio_tx(struct mg_tcpip_if *ifp, const void *buf,
size_t len) {
uint8_t f[3 + 2 + 127 + 4];
size_t n = 3;
if (len > 125 || s_rw612.txing) return 0;
f[1] = MGI_CMD_SET, f[2] = MGI_PROP_STREAM_RAW;
f[n++] = (uint8_t) (len + 2), f[n++] = 0; // PSDU length, incl. FCS
memcpy(f + n, buf, len), n += len;
f[n++] = 0, f[n++] = 0; // FCS, filled in by the radio
(void) ifp;
f[n++] = MG_RADIO_CHANNEL;
f[n++] = 0; // Max CSMA backoffs
f[n++] = 0; // Max frame retries
f[n++] = 0; // CSMA disabled for scheduled turns
if (!mg_rw612_post(f, n)) return 0;
s_rw612.txing = true, s_rw612.txstart = mg_millis();
return len;
}
static bool mgi_rw612w_radio_init(struct mg_tcpip_if *ifp, uint16_t address) {
struct mg_rw612 *s = &s_rw612;
uint8_t f[8], one = 1, zero = 0, pan[2], addr[2], channel = MG_RADIO_CHANNEL;
uint64_t expire;
if (MGI_MBOX->magic[0] != MGI_SYNC_MAGIC) {
MG_ERROR(("Radio firmware is not running on CPU2"));
return false;
}
memset(s, 0, sizeof(*s));
s->free_bufs = 0xffff, s->ifp = ifp;
// Reset our send FIFO, drop stale messages. See IMU_Init()
MGI_IMU->CNTL |= MGI_IMU_FLUSH;
MGI_IMU->CNTL &= ~(MGI_IMU_FLUSH | MGI_IMU_WAIT_FOR_ACK);
MGI_IMU->CNTL =
(MGI_IMU->CNTL & ~MGI_IMU_WATERMARK_MASK) | MGI_IMU_WATERMARK(15);
while ((MGI_IMU_PEER->STATUS & MGI_IMU_EMPTY) == 0) (void) MGI_IMU->RD_MSG;
// Synchronise the IMU link, then connect the IMUMC endpoints
MGI_MBOX->magic[1] = MGI_SYNC_MAGIC;
mg_rw612_control(MGI_CTL_SYNC, 0, 0, 0);
expire = mg_millis() + 1000;
while (!s->up && mg_millis() < expire) mg_rw612_poll_imu();
if (!s->up) return mg_rw612_fail("IMU sync timeout");
expire = mg_millis() + 2000;
while (!s->ept_ready && mg_millis() < expire) {
uint64_t retry = mg_millis() + 100;
mg_rw612_control(MGI_CTL_EPT_QUERY, MGI_EPT_REMOTE, 0, 1);
while (!s->ept_ready && mg_millis() < retry) mg_rw612_poll_imu();
}
if (!s->ept_ready) return mg_rw612_fail("IMUMC endpoint timeout");
// Reset the RCP stack, wait for its reset status, read its version
f[1] = MGI_CMD_RESET, f[2] = MGI_RESET_STACK;
mg_rw612_request(f, 3, MGI_RSP_TIMEOUT_MS);
expire = mg_millis() + 1000;
while (!s->reset && mg_millis() < expire) mg_rw612_poll_imu();
if (!s->reset) return mg_rw612_fail("RCP reset timeout");
f[1] = MGI_CMD_GET, f[2] = MGI_PROP_NCP_VERSION;
mg_rw612_request(f, 3, MGI_RSP_TIMEOUT_MS);
MG_INFO(("RCP: %s", s->version));
if (!mg_rw612_set(MGI_PROP_PHY_ENABLED, &one, 1)) {
return mg_rw612_fail("PHY enable failed");
}
pan[0] = (uint8_t) MG_RADIO_NETWORK;
pan[1] = (uint8_t) (MG_RADIO_NETWORK >> 8);
addr[0] = (uint8_t) address;
addr[1] = (uint8_t) (address >> 8);
if (!mg_rw612_set(MGI_PROP_PHY_CHAN, &channel, 1) ||
!mg_rw612_set(MGI_PROP_PANID, pan, 2) ||
!mg_rw612_set(MGI_PROP_SADDR, addr, 2) ||
!mg_rw612_set(MGI_PROP_PROMISCUOUS, &zero, 1)) {
return mg_rw612_fail("Channel, PAN ID or address set failed");
}
if (!mg_rw612_set(MGI_PROP_RAW_STREAM, &one, 1)) {
return mg_rw612_fail("Raw stream enable failed");
}
return true;
}
static bool mgi_rw612w_radio_poll(struct mg_tcpip_if *ifp) {
bool was_sending = s_rw612.txing;
(void) ifp;
mg_rw612_poll_imu();
if (s_rw612.txing &&
(s_rw612.rsp || mg_millis() > s_rw612.txstart + MGI_TX_TIMEOUT_MS)) {
if (!s_rw612.rsp) MG_ERROR(("TX timeout"));
s_rw612.txing = false;
}
return was_sending && !s_rw612.txing;
}
// The MAC comes from the chip's unique ID
static bool mgi_rw612w_init(struct mg_tcpip_if *ifp) {
uint8_t uid[FSL_OCOTP_UID_LENGTH] = {0}, digest[32];
uint32_t uid_len = sizeof(uid);
OCOTP_ReadUniqueID(uid, &uid_len);
mg_sha256(digest, uid, sizeof(uid));
memcpy(ifp->mac, digest, 6);
ifp->mac[0] = 0x02;
return mg_radio_init(ifp, mgi_rw612w_radio_init, mgi_rw612w_radio_poll,
mgi_rw612w_radio_tx);
}
struct mg_tcpip_driver mg_tcpip_driver_rw612w = {mgi_rw612w_init, mg_radio_tx,
mg_radio_rx, mg_radio_poll};
#endif
+27
View File
@@ -0,0 +1,27 @@
// Copyright (c) 2026 Cesanta Software Limited
// All rights reserved
#pragma once
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_RW612W) && \
MG_ENABLE_DRIVER_RW612W
extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
#define MG_TCPIP_DRIVER_RW612W_INIT(mgr) \
do { \
static struct mg_tcpip_if mif_; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.driver = &mg_tcpip_driver_rw612w; \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_RW612W_INIT(x)
#endif
#endif
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && \ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_SAME54) && \
MG_ENABLE_DRIVER_SAME54 MG_ENABLE_DRIVER_SAME54
+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
+2
View File
@@ -1,4 +1,6 @@
#include "log.h"
#include "sdio.h" #include "sdio.h"
#include "util.h"
#if MG_ENABLE_TCPIP && \ #if MG_ENABLE_TCPIP && \
(defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO) (defined(MG_ENABLE_DRIVER_CYW_SDIO) && MG_ENABLE_DRIVER_CYW_SDIO)
+6 -3
View File
@@ -1,9 +1,13 @@
#include "st67w6.h" #include "net_builtin.h"
#include "net.h" #include "net.h"
#include "printf.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ST67W6) && \ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ST67W6) && \
MG_ENABLE_DRIVER_ST67W6 MG_ENABLE_DRIVER_ST67W6
bool mg_to_size_t(struct mg_str str, size_t *val);
static struct mg_tcpip_if *s_ifp; static struct mg_tcpip_if *s_ifp;
static uint32_t s_ip, s_mask; static uint32_t s_ip, s_mask;
static bool s_link = false, s_connecting = false; static bool s_link = false, s_connecting = false;
@@ -344,7 +348,6 @@ static bool st67w6_at_cmd(char *cmd, size_t len) {
} }
static bool st67w6_spi_init(void); static bool st67w6_spi_init(void);
bool mg_to_size_t(struct mg_str str, size_t *val);
static bool st67w6_init(uint8_t *mac) { static bool st67w6_init(uint8_t *mac) {
// struct mg_tcpip_driver_st67w6_data *d = (struct // struct mg_tcpip_driver_st67w6_data *d = (struct
@@ -365,7 +368,7 @@ static bool st67w6_init(uint8_t *mac) {
} }
// set clock, who cares ??? // set clock, who cares ???
if (!st67w6_at_cmd("AT+GET_CLOCK\r\n", 14)) return false; if (!st67w6_at_cmd("AT+GET_CLOCK\r\n", 14)) return false;
MG_DEBUG(("%.*s", s_at_resp_len, at_resp)); // TODO(scaprile): --> VERBOSE MG_VERBOSE(("%.*s", s_at_resp_len, at_resp));
// BT-ENABLED DEPENDENCY // BT-ENABLED DEPENDENCY
// MODULE DEPENDENCY // MODULE DEPENDENCY
+10 -2
View File
@@ -3,6 +3,8 @@
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ST67W6) && \ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_ST67W6) && \
MG_ENABLE_DRIVER_ST67W6 MG_ENABLE_DRIVER_ST67W6
#include "wifi.h"
struct mg_tcpip_driver_st67w6_data { struct mg_tcpip_driver_st67w6_data {
struct mg_wifi_data wifi; struct mg_wifi_data wifi;
void *spi; void *spi;
@@ -10,7 +12,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 +26,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
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \ #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_STM32F) && \
MG_ENABLE_DRIVER_STM32F MG_ENABLE_DRIVER_STM32F
+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 -3
View File
@@ -1,7 +1,10 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "util.h"
#if MG_ENABLE_TCPIP && (MG_ENABLE_DRIVER_STM32H || MG_ENABLE_DRIVER_MCXN || \ #if MG_ENABLE_TCPIP && (MG_ENABLE_DRIVER_STM32H || MG_ENABLE_DRIVER_MCXN || \
MG_ENABLE_DRIVER_STM32N) MG_ENABLE_DRIVER_STM32N)
// STM32C: vendor modded single-queue Synopsys v5.4, same settings as STM32H
// STM32H: vendor modded single-queue Synopsys v4.2 // STM32H: vendor modded single-queue Synopsys v4.2
// STM32N: dual-queue GbE Synopsys v5.2 with no hash table option, 64-bit AXI // STM32N: dual-queue GbE Synopsys v5.2 with no hash table option, 64-bit AXI
// MCXNx4x: dual-queue Synopsys v5.2 with no hash table option // MCXNx4x: dual-queue Synopsys v5.2 with no hash table option
@@ -310,7 +313,7 @@ static uint32_t s_rxno;
#if MG_ENABLE_DRIVER_MCXN #if MG_ENABLE_DRIVER_MCXN
void ETHERNET_IRQHandler(void); void ETHERNET_IRQHandler(void);
void ETHERNET_IRQHandler(void) { void ETHERNET_IRQHandler(void) {
#elif MG_ENABLE_DRIVER_STM32H #elif MG_ENABLE_DRIVER_STM32H && !MG_ENABLE_DRIVER_STM32C
void ETH_IRQHandler(void); void ETH_IRQHandler(void);
void ETH_IRQHandler(void) { void ETH_IRQHandler(void) {
#else #else
@@ -339,8 +342,10 @@ void ETH1_IRQHandler(void) {
} }
ETH->DMACSR = ETH->DMACSR =
MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing MG_BIT(7) | MG_BIT(8); // Clear possible RBU RPS while processing
ETH->DMACRDTPR = // Resume RX: tail is the last descriptor given back to DMA. It must differ
(uint32_t) (uintptr_t) &s_rxdesc[ETH_DESC_CNT - 1]; // and resume RX // from the DMA current descriptor, or some DMAs, e.g. STM32C5, stay suspended
ETH->DMACRDTPR = (uint32_t) (uintptr_t) &s_rxdesc[(s_rxno + ETH_DESC_CNT - 1) %
ETH_DESC_CNT];
} }
struct mg_tcpip_driver mg_tcpip_driver_stm32h = { struct mg_tcpip_driver mg_tcpip_driver_stm32h = {
+21 -4
View File
@@ -4,6 +4,13 @@
#if !defined(MG_ENABLE_DRIVER_STM32H) #if !defined(MG_ENABLE_DRIVER_STM32H)
#define MG_ENABLE_DRIVER_STM32H 0 #define MG_ENABLE_DRIVER_STM32H 0
#endif #endif
#if !defined(MG_ENABLE_DRIVER_STM32C)
#define MG_ENABLE_DRIVER_STM32C 0
#endif
#if MG_ENABLE_DRIVER_STM32C // STM32C5: STM32H5 MAC, the IRQ is ETH1
#undef MG_ENABLE_DRIVER_STM32H
#define MG_ENABLE_DRIVER_STM32H 1
#endif
#if !defined(MG_ENABLE_DRIVER_MCXN) #if !defined(MG_ENABLE_DRIVER_MCXN)
#define MG_ENABLE_DRIVER_MCXN 0 #define MG_ENABLE_DRIVER_MCXN 0
#endif #endif
@@ -12,6 +19,8 @@
#endif #endif
#if MG_ENABLE_DRIVER_STM32H || MG_ENABLE_DRIVER_MCXN || MG_ENABLE_DRIVER_STM32N #if MG_ENABLE_DRIVER_STM32H || MG_ENABLE_DRIVER_MCXN || MG_ENABLE_DRIVER_STM32N
#include "phy.h"
struct mg_tcpip_driver_stm32h_data { struct mg_tcpip_driver_stm32h_data {
// MDC clock divider. MDC clock is derived from HCLK, must not exceed 2.5MHz // MDC clock divider. MDC clock is derived from HCLK, must not exceed 2.5MHz
// HCLK range DIVIDER mdc_cr VALUE // HCLK range DIVIDER mdc_cr VALUE
@@ -43,9 +52,11 @@ struct mg_tcpip_driver_stm32h_data {
#define MG_DRIVER_MDC_CR 4 #define MG_DRIVER_MDC_CR 4
#endif #endif
#if MG_ENABLE_DRIVER_STM32H && MG_ARCH == MG_ARCH_CUBE && !defined(MG_ENABLE_ETH_IRQ) #if MG_ENABLE_DRIVER_STM32H && !MG_ENABLE_DRIVER_STM32C && \
MG_ARCH == MG_ARCH_CUBE && !defined(MG_ENABLE_ETH_IRQ)
#define MG_ENABLE_ETH_IRQ() NVIC_EnableIRQ(ETH_IRQn) #define MG_ENABLE_ETH_IRQ() NVIC_EnableIRQ(ETH_IRQn)
#elif MG_ENABLE_DRIVER_STM32N && MG_ARCH == MG_ARCH_CUBE && !defined(MG_ENABLE_ETH_IRQ) #elif (MG_ENABLE_DRIVER_STM32N || MG_ENABLE_DRIVER_STM32C) && \
MG_ARCH == MG_ARCH_CUBE && !defined(MG_ENABLE_ETH_IRQ)
#define MG_ENABLE_ETH_IRQ() NVIC_EnableIRQ(ETH1_IRQn) #define MG_ENABLE_ETH_IRQ() NVIC_EnableIRQ(ETH1_IRQn)
#elif !defined(MG_ENABLE_ETH_IRQ) #elif !defined(MG_ENABLE_ETH_IRQ)
#define MG_ENABLE_ETH_IRQ() #define MG_ENABLE_ETH_IRQ()
@@ -63,7 +74,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_; \
@@ -77,10 +90,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
+2
View File
@@ -1,4 +1,6 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TM4C) && MG_ENABLE_DRIVER_TM4C
struct tm4c_emac { struct tm4c_emac {
+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
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TMS570) && MG_ENABLE_DRIVER_TMS570 #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_TMS570) && MG_ENABLE_DRIVER_TMS570
struct tms570_emac_ctrl { struct tms570_emac_ctrl {
+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
+512
View File
@@ -0,0 +1,512 @@
#include "net_builtin.h"
#include "drivers/usb.h"
#include "log.h"
#include "printf.h"
#include "util.h"
// USB Ethernet needs the TCP/IP stack, the serial console does not
#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \
(MG_ENABLE_DRIVER_USB_RP || MG_ENABLE_DRIVER_USB_NRF52 || \
MG_ENABLE_DRIVER_USB_DWC2) && \
(MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL)
// Interfaces: ACM control and data 0/1 if enabled, then NCM control and data.
// The serial port comes first, so that its name on macOS does not depend on
// Ethernet: /dev/cu.usbmodem...01
#define MGI_USB_ETH_IF (MG_USB_IF_ETH_DATA - 1)
#define MGI_USB_NUM_IFS (2 * MG_ENABLE_USB_ETHERNET + 2 * MG_ENABLE_USB_SERIAL)
#define MGI_USB_CONFIG_LEN \
(9 + 85 * MG_ENABLE_USB_ETHERNET + 66 * MG_ENABLE_USB_SERIAL)
#if MG_ENABLE_USB_ETHERNET
#define MGI_USB_PRODUCT "MongooseUsbEthernet"
#else
#define MGI_USB_PRODUCT "MongooseUsbSerial"
#endif
// VID 0xadde, PID 0x40e4: an example, for development only
static const uint8_t s_device_desc[] = {
18, 1, 1, 2, 0xef, 2, 1, 64, 0xde, 0xad, 0xe4, 0x40, 0, 1, 1, 2, 3, 1};
// NCM: endpoints 0x81, 0x02/0x82. ACM: endpoints 0x83, 0x04/0x84
// clang-format off
static const uint8_t s_config_desc[] = {
9, 2, MGI_USB_CONFIG_LEN, 0, MGI_USB_NUM_IFS, 1, 0, 0x80,
50, // Config
#if MG_ENABLE_USB_SERIAL
8, 11, 0, 2, 2, 2, 1, 6, // ACM association
9, 4, 0, 0, 1, 2, 2, 1, 6, // ACM control interface
5, 0x24, 0, 0x20, 1, // CDC header
5, 0x24, 1, 0, 1, // Call management
4, 0x24, 2, 2, // ACM
5, 0x24, 6, 0, 1, // Union
7, 5, 0x83, 3, 16, 0, 16, // Notification endpoint
9, 4, 1, 0, 2, 10, 0, 0, 0, // Data interface
7, 5, 0x04, 2, 64, 0, 0, // Data OUT
7, 5, 0x84, 2, 64, 0, 0, // Data IN
#endif
#if MG_ENABLE_USB_ETHERNET
8, 11, MGI_USB_ETH_IF, 2, 2, 13, 0, 4, // NCM association
9, 4, MGI_USB_ETH_IF, 0, 1, 2, 13, 0, 4, // NCM control interface
5, 0x24, 0, 0x20, 1, // CDC header
5, 0x24, 6, MGI_USB_ETH_IF, MGI_USB_ETH_IF + 1, // Union
13, 0x24, 15, 5, 0, 0, 0, 0, 0xea,
5, 0, 0, 0, // Eth, 1514 bytes
6, 0x24, 0x1a, 0, 1, 0x21, // NCM 1.0
7, 5, 0x81, 3, 16, 0, 16, // Notification endpoint
9, 4, MGI_USB_ETH_IF + 1, 0, 0, 10, 0, 1, 0, // Data interface, off
9, 4, MGI_USB_ETH_IF + 1, 1, 2, 10, 0, 1, 0, // Data interface, on
7, 5, 0x02, 2, 64, 0, 0, // Data OUT
7, 5, 0x82, 2, 64, 0, 0, // Data IN
#endif
};
// clang-format on
// Endpoint addresses, for CLEAR_FEATURE(ENDPOINT_HALT)
static const uint8_t s_endpoints[] = {
#if MG_ENABLE_USB_ETHERNET
0x81, 0x02, 0x82,
#endif
#if MG_ENABLE_USB_SERIAL
0x83, 0x04, 0x84,
#endif
};
#if MG_ENABLE_USB_ETHERNET
// Windows 11 binds its NCM driver through a Microsoft OS 2.0 compatible ID
// clang-format off
static const uint8_t s_ms_os_desc[] = {
10, 0, 0, 0, 0, 0, 3, 6, 46, 0, // Set header, Windows 8.1+
8, 0, 1, 0, 0, 0, 36, 0, // Configuration subset
8, 0, 2, 0, MGI_USB_ETH_IF, 0, 28, 0, // Function subset, NCM
20, 0, 3, 0, 'W', 'I', 'N', 'N', 'C', 'M', // Compatible ID
0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// clang-format on
static const uint8_t s_bos_desc[] = {
5, 15, 33, 0, 1, 28, 16, 5, 0, 0xdf,
0x60, 0xdd, 0xd8, 0x89, 0x45, 0xc7, 0x4c, 0x9c, 0xd2, 0x65,
0x9d, 0x9e, 0x64, 0x8a, 0x9f, 0, 0, 3, 6, sizeof(s_ms_os_desc),
0, 1, 0};
// GET_NTB_PARAMETERS reply: NTB16 only, same limits both ways
static const uint8_t s_ntb_params[] = {
28, 0, 1, 0, MG_USB_NTB_SIZE & 255, MG_USB_NTB_SIZE >> 8, 0, 0, 4, 0, 0, 0,
4, 0, 0, 0, MG_USB_NTB_SIZE & 255, MG_USB_NTB_SIZE >> 8, 0, 0, 4, 0, 0, 0,
4, 0, 16, 0};
// Link notifications: speed 12 Mbit/s both ways, connected, disconnected
static const uint8_t s_speed[] = {0xa1, 0x2a, 0, 0, 0, 0, 8, 0,
0, 0x1b, 0xb7, 0, 0, 0x1b, 0xb7, 0};
static const uint8_t s_up[] = {0xa1, 0, 1, 0, 0, 0, 0, 0};
static const uint8_t s_down[] = {0xa1, 0, 0, 0, 0, 0, 0, 0};
// Transfer block header for one frame: NTH16, NDP16 with one datagram at
// offset 30, so that the IP header after the 14-byte Ethernet header lands
// on a 4-byte boundary
static const uint8_t s_nth[30] = {'N', 'C', 'M', 'H', 12, 0, 0, 0, 0, 0,
12, 0, 'N', 'C', 'M', '0', 16, 0, 0, 0,
30, 0, 0, 0, 0, 0, 0, 0, 0, 0};
#endif
// An IN transfer on an endpoint, sent a packet at a time
struct mgi_usb_in {
const uint8_t *data; // Bytes still to send
size_t left; // How many
unsigned packets; // Packets still to send: a short or empty one ends it
bool busy; // A packet is waiting for the host
};
// The USB device. There is one
static struct mgi_usb {
const struct mg_usb_hw *hw; // Controller, NULL until mg_usb_init()
struct mgi_usb_in in[5]; // IN transfers, by endpoint
char serial[17]; // Serial number, from the controller
bool configured; // Host has set the configuration
uint8_t buf[66]; // Generated control replies
#if MG_ENABLE_USB_ETHERNET
struct mg_tcpip_if *ifp; // Ethernet interface, NULL: serial only
bool alt; // Ethernet open: data interface setting 1
uint16_t filter, sequence; // Host packet filter, next IN block number
uint32_t input_size; // Largest IN block the host accepts
uint8_t notify; // Pending link notifications
struct mg_queue txq; // Transfer blocks for the host, see tx
char txq_buf[MG_USB_TX_SIZE]; // Its storage
uint8_t rx[MG_USB_NTB_SIZE]; // OUT transfer block being received
size_t rxlen; // How much of it arrived
bool discard; // It is too long: drop it
#endif
#if MG_ENABLE_USB_SERIAL
bool dtr; // Terminal open
uint64_t reboot; // mg_millis() to enter the bootloader, or 0
uint8_t line[7]; // Serial line coding
char log[MG_USB_LOG_SIZE]; // Log ring
unsigned head, tail; // Log ring write and read counters
char out[64]; // Log output being sent
#endif
} s_usb;
// Send the next packet of the IN transfer on ep. False if it is over
static bool mgi_usb_in_next(unsigned ep) {
struct mgi_usb_in *e = &s_usb.in[ep];
size_t n = e->left > 64 ? 64 : e->left;
if (e->packets == 0) return false;
s_usb.hw->in((enum mg_usb_ep) ep, e->data, n);
e->data += n, e->left -= n, e->packets--;
return true;
}
// Start an IN transfer. zlp: end a multiple of 64 bytes with an empty packet
static void mgi_usb_in_start(unsigned ep, const void *data, size_t len,
bool zlp) {
struct mgi_usb_in *e = &s_usb.in[ep];
e->data = (const uint8_t *) data, e->left = len;
e->packets = (unsigned) (len / 64 + (len % 64 || len == 0 || zlp));
e->busy = mgi_usb_in_next(ep);
}
// Cancel the transfers on ep
static void mgi_usb_idle(unsigned ep) {
memset(&s_usb.in[ep], 0, sizeof(s_usb.in[ep]));
#if MG_ENABLE_USB_ETHERNET
if (ep == MG_USB_EP_ETH_DATA) s_usb.rxlen = 0, s_usb.discard = false;
#endif
}
// Unconfigured, on start, bus reset and SET_CONFIGURATION. Keeps the log
static void mgi_usb_unconfigure(void) {
#if MG_ENABLE_USB_SERIAL
static const uint8_t line[7] = {0, 0xc2, 1, 0, 0, 0, 8}; // 115200 8N1
s_usb.dtr = false;
memcpy(s_usb.line, line, sizeof(line));
#endif
#if MG_ENABLE_USB_ETHERNET
s_usb.alt = false, s_usb.filter = s_usb.sequence = 0, s_usb.notify = 0;
s_usb.input_size = MG_USB_NTB_SIZE;
#endif
s_usb.configured = false;
}
// Build string descriptor i in s_usb.buf. Returns its length, 0 if none
static int mgi_usb_string(unsigned i) {
static const char *strings[] = {NULL, "Mongoose", MGI_USB_PRODUCT,
NULL, "USB Ethernet", NULL,
"USB Serial"};
const char *s = i < 7 ? strings[i] : NULL;
char tmp[33]; // Built strings: product name, host MAC
uint8_t *b = s_usb.buf;
size_t k, n;
if (i == 0) return b[0] = 4, b[1] = 3, b[2] = 9, b[3] = 4;
if (i == 2) { // Serial's last 4 digits: tell devices apart
size_t len = strlen(s_usb.serial);
mg_snprintf(tmp, sizeof(tmp), "%s_%s", MGI_USB_PRODUCT,
s_usb.serial + (len > 4 ? len - 4 : 0));
s = tmp;
}
if (i == 3) s = s_usb.serial;
#if MG_ENABLE_USB_ETHERNET
if (i == 5 && s_usb.ifp != NULL) { // Host end: our MAC, first byte changed
uint8_t *m = s_usb.ifp->mac;
mg_snprintf(tmp, sizeof(tmp), "%02X%02X%02X%02X%02X%02X",
((m[0] ^ 4) | 2) & ~1, m[1], m[2], m[3], m[4], m[5]);
s = tmp;
}
#endif
if (s == NULL) return 0;
n = strlen(s) > 32 ? 32 : strlen(s);
memset(b, 0, sizeof(s_usb.buf));
for (k = 0; k < n; k++) b[2 + k * 2] = (uint8_t) s[k];
b[0] = (uint8_t) (2 + n * 2), b[1] = 3;
return b[0];
}
// Answer a control request r, its OUT data at r + 8. Returns -1 to stall,
// else the IN reply length in *reply, 0 for status only
static int mgi_usb_request(const uint8_t *r, const void **reply) {
unsigned value = MG_LOAD_LE16(r + 2), index = MG_LOAD_LE16(r + 4);
unsigned wlen = MG_LOAD_LE16(r + 6), i;
const void *d = s_usb.buf;
int n = 0;
switch ((r[0] << 8) | r[1]) {
case 0x8006: // GET_DESCRIPTOR
if (value >> 8 == 1) d = s_device_desc, n = sizeof(s_device_desc);
if (value >> 8 == 2) d = s_config_desc, n = sizeof(s_config_desc);
#if MG_ENABLE_USB_ETHERNET
if (value >> 8 == 15) d = s_bos_desc, n = sizeof(s_bos_desc);
#endif
if (value >> 8 == 3) n = mgi_usb_string(value & 255);
if (n == 0) return -1;
break;
case 0x0005: // SET_ADDRESS, applied by the controller
if (value > 127) return -1;
break;
case 0x0009: // SET_CONFIGURATION
if (value > 1) return -1;
mgi_usb_unconfigure();
for (i = 1; i < 5; i++) mgi_usb_idle(i);
s_usb.configured = value == 1;
break;
case 0x8008: // GET_CONFIGURATION
s_usb.buf[0] = s_usb.configured, n = 1;
break;
case 0x010b: // SET_INTERFACE: only the Ethernet data interface has 1
if (index >= MGI_USB_NUM_IFS ||
value > (unsigned) (MG_ENABLE_USB_ETHERNET &&
index == MG_USB_IF_ETH_DATA))
return -1;
#if MG_ENABLE_USB_ETHERNET
if (index == MG_USB_IF_ETH_DATA) {
s_usb.alt = value == 1, s_usb.notify = 1;
mgi_usb_idle(MG_USB_EP_ETH_DATA);
}
#endif
break;
case 0x810a: // GET_INTERFACE
s_usb.buf[0] = 0, n = 1;
#if MG_ENABLE_USB_ETHERNET
if (index == MG_USB_IF_ETH_DATA) s_usb.buf[0] = s_usb.alt;
#endif
break;
#if MG_ENABLE_USB_ETHERNET
case 0xa183: // GET_NTB_FORMAT: NTB16
#endif
case 0x8000: // GET_STATUS: device, interface, endpoint
case 0x8100:
case 0x8200:
s_usb.buf[0] = s_usb.buf[1] = 0, n = 2;
break;
case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT), applied by the controller
if (value || index > 255 ||
!memchr(s_endpoints, (int) index, sizeof(s_endpoints)))
return -1;
break;
#if MG_ENABLE_USB_ETHERNET
case 0xc001: // Microsoft OS 2.0 descriptor set
if (index != 7) return -1;
d = s_ms_os_desc, n = sizeof(s_ms_os_desc);
break;
case 0x2143: // SET_ETHERNET_PACKET_FILTER
s_usb.filter = (uint16_t) value;
break;
case 0xa180: // GET_NTB_PARAMETERS
d = s_ntb_params, n = sizeof(s_ntb_params);
break;
case 0x2184: // SET_NTB_FORMAT: NTB16 only
if (value) return -1;
break;
case 0xa185: // GET_NTB_INPUT_SIZE, one datagram per block
memset(s_usb.buf, 0, 8);
MG_STORE_LE32(s_usb.buf, s_usb.input_size);
s_usb.buf[4] = 1, n = 8;
break;
case 0x2186: // SET_NTB_INPUT_SIZE
if ((wlen != 4 && wlen != 8) || MG_LOAD_LE32(r + 8) < 2048 ||
MG_LOAD_LE32(r + 8) > 65535)
return -1;
s_usb.input_size = MG_LOAD_LE32(r + 8);
if (s_usb.input_size > MG_USB_NTB_SIZE)
s_usb.input_size = MG_USB_NTB_SIZE;
break;
#endif
#if MG_ENABLE_USB_SERIAL
case 0xa121: // GET_LINE_CODING
d = s_usb.line, n = sizeof(s_usb.line);
break;
case 0x2120: // SET_LINE_CODING
if (wlen != sizeof(s_usb.line)) return -1;
memcpy(s_usb.line, r + 8, sizeof(s_usb.line));
break;
case 0x2122: // SET_CONTROL_LINE_STATE. Closed at 1200 baud: bootloader,
s_usb.dtr = value & 1; // after a delay that lets this request complete
if (!s_usb.dtr && MG_LOAD_LE32(s_usb.line) == 1200)
s_usb.reboot = mg_millis() + 100;
break;
case 0x2123: // SEND_BREAK
break;
#endif
default:
return -1;
}
*reply = d;
return n > (int) wlen ? (int) wlen : n;
}
#if MG_ENABLE_USB_ETHERNET
// Queue the frames of a received transfer block to the TCP/IP stack.
// Offsets come from the host: bound every datagram by the block, and follow
// at most 16 datagram tables so that a cyclic chain cannot loop forever
static void mgi_usb_decode(const uint8_t *p, size_t len) {
size_t block, ndp, end, i, ofs, n, tables = 0;
if (s_usb.ifp == NULL || len < 12 || MG_LOAD_LE32(p) != 0x484d434e) return;
block = MG_LOAD_LE16(p + 8), ndp = MG_LOAD_LE16(p + 10);
if (block > len) return;
while (ndp && tables++ < 16 && ndp + 16 <= block &&
MG_LOAD_LE32(p + ndp) == 0x304d434e) { // "NCM0"
end = ndp + MG_LOAD_LE16(p + ndp + 4);
for (i = ndp + 8; i + 4 <= end && end <= block; i += 4) {
ofs = MG_LOAD_LE16(p + i), n = MG_LOAD_LE16(p + i + 2);
if (ofs == 0 || n == 0) break;
if (n >= 14 && n <= 1514 && ofs + n <= block)
mg_tcpip_qwrite((void *) (p + ofs), n, s_usb.ifp);
}
ndp = MG_LOAD_LE16(p + ndp + 6);
}
}
// If the Ethernet IN endpoint is idle, start sending the first queued
// transfer block. It stays queued until sent. Drop blocks the host cannot
// take now: the link closed, or it lowered its block size
static void mgi_usb_tx_next(void) {
char *block;
size_t len;
while (!s_usb.in[MG_USB_EP_ETH_DATA].busy &&
(len = mg_queue_next(&s_usb.txq, &block)) > 0) {
if (s_usb.alt && s_usb.filter && len <= s_usb.input_size) {
mgi_usb_in_start(MG_USB_EP_ETH_DATA, block, len, len < s_usb.input_size);
} else {
mg_queue_del(&s_usb.txq, len);
}
}
}
#endif
#if MG_ENABLE_USB_SERIAL
// Log output function: keep the latest MG_USB_LOG_SIZE characters
static void mgi_usb_log(char ch, void *arg) {
if (s_usb.head - s_usb.tail >= MG_USB_LOG_SIZE) s_usb.tail++;
s_usb.log[s_usb.head++ % MG_USB_LOG_SIZE] = ch;
(void) arg;
}
#endif
// Controller events, see enum mg_usb_ev
static int mgi_usb_event(enum mg_usb_ev ev, enum mg_usb_ep ep, void *buf,
size_t len) {
const uint8_t *p = (const uint8_t *) buf;
unsigned i;
if (ev == MG_USB_EV_RESET) {
mgi_usb_unconfigure();
for (i = 0; i < 5; i++) mgi_usb_idle(i);
} else if (ev == MG_USB_EV_SETUP) {
const void *reply;
unsigned wlen = len < 8 ? 0 : MG_LOAD_LE16(p + 6);
int n;
mgi_usb_idle(MG_USB_EP_CTL); // A SETUP ends the previous transfer
if (len < 8 || (!(p[0] & 0x80) && len < 8 + wlen)) return -1;
if ((n = mgi_usb_request(p, &reply)) < 0) return -1;
if (!(p[0] & 0x80) || wlen == 0) return 0;
mgi_usb_in_start(MG_USB_EP_CTL, reply, (size_t) n, n < (int) wlen);
return 1;
} else if (ev == MG_USB_EV_IN && s_usb.in[ep].busy) {
s_usb.in[ep].busy = mgi_usb_in_next(ep);
#if MG_ENABLE_USB_ETHERNET
if (ep == MG_USB_EP_ETH_DATA && !s_usb.in[ep].busy) {
mg_queue_del(&s_usb.txq, mg_queue_next(&s_usb.txq, NULL)); // Sent
mgi_usb_tx_next();
}
#endif
return s_usb.in[ep].busy;
#if MG_ENABLE_USB_ETHERNET
} else if (ev == MG_USB_EV_OUT && ep == MG_USB_EP_ETH_DATA) {
// Add the packet to the transfer block. At the advertised maximum OUT
// size, the host need not send a ZLP. Other blocks end with a short
// packet, possibly empty
if (!s_usb.discard && s_usb.rxlen + len <= sizeof(s_usb.rx)) {
memcpy(s_usb.rx + s_usb.rxlen, buf, len);
s_usb.rxlen += len;
} else {
s_usb.discard = true;
}
if (len < 64 || s_usb.rxlen == sizeof(s_usb.rx)) {
if (!s_usb.discard) mgi_usb_decode(s_usb.rx, s_usb.rxlen);
s_usb.rxlen = 0, s_usb.discard = false;
}
#endif
}
return 0;
}
bool mg_usb_init(struct mg_tcpip_if *ifp, const struct mg_usb_hw *hw) {
if (s_usb.hw == NULL) {
s_usb.hw = hw;
mgi_usb_unconfigure();
#if MG_ENABLE_USB_ETHERNET
mg_queue_init(&s_usb.txq, s_usb.txq_buf, sizeof(s_usb.txq_buf));
#endif
#if MG_ENABLE_USB_SERIAL
mg_log_set_fn(mgi_usb_log, NULL); // Log to the USB serial port
#endif
hw->init(s_usb.serial);
}
#if MG_ENABLE_USB_ETHERNET
if (ifp != NULL) s_usb.ifp = ifp;
#else
(void) ifp;
#endif
return true;
}
size_t mg_usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp) {
#if MG_ENABLE_USB_ETHERNET
// Queue the frame wrapped in its transfer block, ready to send
size_t n = sizeof(s_nth) + len;
char *p;
if (!s_usb.alt || !s_usb.filter || len < 14 || len > 1514) return 0;
if (mg_queue_next(&s_usb.txq, NULL) == 0) {
mg_queue_init(&s_usb.txq, s_usb.txq.buf, s_usb.txq.size); // Unwrap
}
if (mg_queue_book(&s_usb.txq, &p, n) < n) {
ifp->nerr++; // Queue full: the host is not reading
return 0;
}
memcpy(p, s_nth, sizeof(s_nth));
MG_STORE_LE16(p + 6, s_usb.sequence);
s_usb.sequence++;
MG_STORE_LE16(p + 8, n);
MG_STORE_LE16(p + 22, len);
memcpy(p + sizeof(s_nth), buf, len);
mg_queue_add(&s_usb.txq, n);
mgi_usb_tx_next();
return len;
#else
(void) ifp, (void) buf, (void) len;
return 0;
#endif
}
bool mg_usb_poll(struct mg_tcpip_if *ifp, bool s1) {
(void) ifp;
if (s_usb.hw == NULL) return false; // mg_usb_init() not called yet
s_usb.hw->poll(mgi_usb_event);
#if MG_ENABLE_USB_SERIAL
if (s_usb.reboot && mg_millis() > s_usb.reboot) {
s_usb.reboot = 0;
MG_USB_REBOOT();
}
if (s_usb.configured && s_usb.dtr && !s_usb.in[MG_USB_EP_SER_DATA].busy) {
size_t n = 0;
while (n < sizeof(s_usb.out) && s_usb.tail != s_usb.head) {
s_usb.out[n++] = s_usb.log[s_usb.tail++ % MG_USB_LOG_SIZE];
}
if (n > 0) mgi_usb_in_start(MG_USB_EP_SER_DATA, s_usb.out, n, true);
}
#endif
#if MG_ENABLE_USB_ETHERNET
if (s_usb.notify && !s_usb.in[MG_USB_EP_ETH_EV].busy) {
// Link notifications: the speed first if the link is up, then the state
if (s_usb.notify == 1 && s_usb.alt) {
s_usb.notify = 2;
mgi_usb_in_start(MG_USB_EP_ETH_EV, s_speed, sizeof(s_speed), false);
} else {
s_usb.notify = 0;
mgi_usb_in_start(MG_USB_EP_ETH_EV, s_usb.alt ? s_up : s_down,
sizeof(s_up), false);
}
}
mgi_usb_tx_next();
return s1 && s_usb.alt && s_usb.filter;
#else
(void) s1;
return false;
#endif
}
#endif
+67
View File
@@ -0,0 +1,67 @@
#pragma once
// USB device: a CDC-NCM Ethernet interface, enabled by MG_ENABLE_USB_ETHERNET,
// and a CDC-ACM serial port for logs, enabled by MG_ENABLE_USB_SERIAL.
#ifndef MG_USB_NTB_SIZE
#define MG_USB_NTB_SIZE 2048 // Transfer block, each direction, >= 2048
#endif
#ifndef MG_USB_TX_SIZE
#define MG_USB_TX_SIZE 4096 // Ethernet frames waiting to go to the host
#endif
#ifndef MG_USB_QUEUE_SIZE
#define MG_USB_QUEUE_SIZE 4096 // Ethernet frames from the host
#endif
#ifndef MG_USB_LOG_SIZE
#define MG_USB_LOG_SIZE 1024 // Serial log ring
#endif
// Restart into the board's bootloader when the host opens the serial port at
// 1200 baud and closes it, the "1200 baud touch" that flashing tools use
#ifndef MG_USB_REBOOT
#define MG_USB_REBOOT() (void) 0
#endif
// Endpoints, numbered as in the configuration descriptor
enum mg_usb_ep {
MG_USB_EP_CTL, // control
MG_USB_EP_ETH_EV, // Ethernet link notifications, IN
MG_USB_EP_ETH_DATA, // Ethernet data, IN and OUT
MG_USB_EP_SER_EV, // serial notifications, IN, unused
MG_USB_EP_SER_DATA, // serial data, IN and OUT
};
// Interfaces: the serial port's control and data first, then Ethernet's. The
// Ethernet data interface has setting 1: Ethernet open
#define MG_USB_IF_ETH_DATA (2 * MG_ENABLE_USB_SERIAL + 1)
// Controller events, reported by mg_usb_hw::poll() to its fn. What fn returns
enum mg_usb_ev {
MG_USB_EV_RESET, // Bus reset or detach. Returns 0
MG_USB_EV_SETUP, // Control request, buf: the SETUP packet, then its OUT
// data. Returns -1: stall, 0: no IN data stage, send
// the status stage, 1: IN data stage started on ep 0
MG_USB_EV_IN, // An IN packet on ep went out. Returns 1: next packet
// sent, 0: transfer done
MG_USB_EV_OUT // An OUT packet arrived on ep, buf and len. Returns 0
};
// A USB device controller, implemented by its driver. Packets: up to 64 bytes
struct mg_usb_hw {
void (*init)(char serial[17]); // Start, write the serial number
void (*poll)(int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *buf, size_t));
void (*in)(enum mg_usb_ep, const void *buf, size_t len); // Write IN packet
};
struct mg_tcpip_if; // Without MG_ENABLE_TCPIP: serial console only
// Start the controller hw, and attach ifp: NULL for the serial console only.
// Call again to attach ifp later; the first call's hw stays in use
bool mg_usb_init(struct mg_tcpip_if *ifp, const struct mg_usb_hw *hw);
// Queue an Ethernet frame for the host. The controller driver's tx
size_t mg_usb_tx(const void *buf, size_t len, struct mg_tcpip_if *ifp);
// Run the controller. The controller driver's poll; returns true when the
// host has the Ethernet interface open and s1 is true. Serial only: ifp NULL
bool mg_usb_poll(struct mg_tcpip_if *ifp, bool s1);
+365
View File
@@ -0,0 +1,365 @@
#include "net_builtin.h"
#include "drivers/usb.h"
#include "drivers/usb_dwc2.h"
#include "printf.h"
#include "util.h"
#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \
MG_ENABLE_DRIVER_USB_DWC2 && \
(MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL)
// DWC2 device controller, polled: no interrupt handler, no DMA. Received
// packets come through one shared RX FIFO, each IN endpoint has a TX FIFO of
// its own. Register layout: STM32 reference manuals, OTG chapter.
#ifndef MG_USB_DWC2_BASE
#error "MG_ENABLE_DRIVER_USB_DWC2 needs MG_USB_DWC2_BASE, the core's address"
#endif
#ifndef MG_USB_DWC2_ULPI
#define MG_USB_DWC2_ULPI 0
#endif
#ifndef MG_USB_DWC2_UTMI
#define MG_USB_DWC2_UTMI 0
#endif
#if MG_USB_DWC2_ULPI && MG_USB_DWC2_UTMI
#error "MG_USB_DWC2_ULPI and MG_USB_DWC2_UTMI: choose one PHY"
#endif
#define MGI_DWC2_HS_PHY (MG_USB_DWC2_ULPI || MG_USB_DWC2_UTMI) // At full speed
// Register at offset off
#define MGI_DWC2(off) \
(*(volatile uint32_t *) ((uintptr_t) (MG_USB_DWC2_BASE) + (off)))
#define MGI_DWC2_GOTGCTL MGI_DWC2(0x000)
#define MGI_DWC2_GUSBCFG MGI_DWC2(0x00c)
#define MGI_DWC2_GRSTCTL MGI_DWC2(0x010)
#define MGI_DWC2_GINTSTS MGI_DWC2(0x014)
#define MGI_DWC2_GRXSTSP MGI_DWC2(0x020)
#define MGI_DWC2_GRXFSIZ MGI_DWC2(0x024)
#define MGI_DWC2_DIEPTXF0 MGI_DWC2(0x028)
#define MGI_DWC2_GCCFG MGI_DWC2(0x038)
#define MGI_DWC2_GSNPSID MGI_DWC2(0x040)
#define MGI_DWC2_DIEPTXF(n) MGI_DWC2(0x100 + 4 * (n)) // n: 1..
#define MGI_DWC2_DCFG MGI_DWC2(0x800)
#define MGI_DWC2_DCTL MGI_DWC2(0x804)
#define MGI_DWC2_DIEPMSK MGI_DWC2(0x810)
#define MGI_DWC2_DOEPMSK MGI_DWC2(0x814)
#define MGI_DWC2_DAINT MGI_DWC2(0x818)
#define MGI_DWC2_DAINTMSK MGI_DWC2(0x81c)
#define MGI_DWC2_DIEPCTL(n) MGI_DWC2(0x900 + 0x20 * (n))
#define MGI_DWC2_DIEPINT(n) MGI_DWC2(0x908 + 0x20 * (n))
#define MGI_DWC2_DIEPTSIZ(n) MGI_DWC2(0x910 + 0x20 * (n))
#define MGI_DWC2_DOEPCTL(n) MGI_DWC2(0xb00 + 0x20 * (n))
#define MGI_DWC2_DOEPINT(n) MGI_DWC2(0xb08 + 0x20 * (n))
#define MGI_DWC2_DOEPTSIZ(n) MGI_DWC2(0xb10 + 0x20 * (n))
#define MGI_DWC2_PCGCCTL MGI_DWC2(0xe00)
#define MGI_DWC2_FIFO(n) MGI_DWC2(0x1000 * ((n) + 1))
// Endpoint control bits, DIEPCTL and DOEPCTL
#define MGI_DWC2_USBAEP MG_BIT(15) // Active
#define MGI_DWC2_STALL MG_BIT(21)
#define MGI_DWC2_CNAK MG_BIT(26)
#define MGI_DWC2_SNAK MG_BIT(27)
#define MGI_DWC2_SD0PID MG_BIT(28) // Next packet is DATA0
#define MGI_DWC2_EPDIS MG_BIT(30)
#define MGI_DWC2_EPENA MG_BIT(31)
// FIFOs, in 32-bit words: RX first, then a packet's room per IN endpoint.
// 208 words in all, so it fits a full-speed core's 320
#define MGI_DWC2_RX_WORDS 128
// usb.c's event handler, see mg_usb_hw::poll()
#define MGI_DWC2_FN int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t)
static uint32_t s_mgi_dwc2_pkt[64 / 4]; // A received packet
static uint8_t s_mgi_dwc2_req[16]; // SETUP packet, then its OUT data
static size_t s_mgi_dwc2_req_len; // OUT data received so far
static bool s_mgi_dwc2_req_out; // Waiting for that OUT data stage
// Wait until the mask bits of reg are set, or clear. Bounded
static void mgi_dwc2_wait(volatile uint32_t *reg, uint32_t mask, bool set) {
unsigned i;
for (i = 0; ((*reg & mask) != 0) != set && i < 1000000; i++) (void) 0;
}
// Flush the TX FIFO of endpoint n, 0x10: all of them
static void mgi_dwc2_flush_tx(unsigned n) {
MGI_DWC2_GRSTCTL = MG_BIT(5) | (n << 6); // TXFFLSH, TXFNUM
mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(5), false);
}
// mg_usb_hw::in(): load one packet, then let the endpoint send it
static void mgi_dwc2_in(enum mg_usb_ep ep, const void *buf, size_t len) {
const uint8_t *p = (const uint8_t *) buf;
size_t i, k;
MGI_DWC2_DIEPTSIZ(ep) = MG_BIT(19) | (uint32_t) len; // One packet
MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_CNAK | MGI_DWC2_EPENA;
for (i = 0; i < len; i += 4) {
uint32_t w = 0;
for (k = 0; k < 4 && i + k < len; k++) w |= (uint32_t) p[i + k] << (8 * k);
MGI_DWC2_FIFO(ep) = w;
}
}
// Stop an IN transfer on endpoint ep, and empty its TX FIFO
static void mgi_dwc2_in_stop(unsigned ep) {
if (MGI_DWC2_DIEPCTL(ep) & MGI_DWC2_EPENA) {
MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_SNAK;
mgi_dwc2_wait(&MGI_DWC2_DIEPINT(ep), MG_BIT(6), true); // INEPNE
MGI_DWC2_DIEPCTL(ep) |= MGI_DWC2_EPDIS;
mgi_dwc2_wait(&MGI_DWC2_DIEPINT(ep), MG_BIT(1), true); // EPDISD
MGI_DWC2_DIEPINT(ep) = MG_BIT(1);
}
mgi_dwc2_flush_tx(ep);
}
// Let OUT endpoint ep take one packet. Endpoint 0 also takes SETUPs
static void mgi_dwc2_arm(unsigned ep) {
MGI_DWC2_DOEPTSIZ(ep) = (ep == 0 ? 3UL << 29 : 0) | MG_BIT(19) | 64;
MGI_DWC2_DOEPCTL(ep) |= MGI_DWC2_CNAK | MGI_DWC2_EPENA;
}
// Endpoint ep active, idle, DATA0 next. type: 2 bulk, 3 interrupt. out:
// also its OUT direction, ready to receive
static void mgi_dwc2_open(unsigned ep, uint32_t type, bool out) {
uint32_t ctl = 64 | MGI_DWC2_USBAEP | (type << 18) | MGI_DWC2_SD0PID;
mgi_dwc2_in_stop(ep);
MGI_DWC2_DIEPCTL(ep) = ctl | (ep << 22) | MGI_DWC2_SNAK; // Own TX FIFO
if (out) {
MGI_DWC2_DOEPCTL(ep) = ctl;
mgi_dwc2_arm(ep);
}
}
// Stall endpoint 0, until the next SETUP
static void mgi_dwc2_stall(void) {
MGI_DWC2_DIEPCTL(0) |= MGI_DWC2_STALL;
MGI_DWC2_DOEPCTL(0) |= MGI_DWC2_STALL;
}
// USB reset: address 0, endpoints off, FIFOs laid out again
static void mgi_dwc2_bus_reset(void) {
unsigned ep;
for (ep = 0; ep < 5; ep++) {
MGI_DWC2_DOEPCTL(ep) |= MGI_DWC2_SNAK;
if (ep > 0) MGI_DWC2_DOEPCTL(ep) &= ~MGI_DWC2_USBAEP;
if (ep > 0) MGI_DWC2_DIEPCTL(ep) &= ~MGI_DWC2_USBAEP;
mgi_dwc2_in_stop(ep);
}
MGI_DWC2_DAINTMSK = 0x1f; // IN endpoints 0-4: transfer complete
MGI_DWC2_DIEPMSK = MG_BIT(0); // XFRC
MGI_DWC2_DOEPMSK = MG_BIT(3) | 1U; // STUP, XFRC
MGI_DWC2_GRSTCTL = MG_BIT(4); // RXFFLSH
mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(4), false);
MGI_DWC2_GRXFSIZ = MGI_DWC2_RX_WORDS;
MGI_DWC2_DIEPTXF0 = (16UL << 16) | MGI_DWC2_RX_WORDS;
for (ep = 1; ep < 5; ep++) {
MGI_DWC2_DIEPTXF(ep) = (16UL << 16) | (MGI_DWC2_RX_WORDS + 16 * ep);
}
MGI_DWC2_DCFG &= ~(0x7fUL << 4); // Address 0
MGI_DWC2_DIEPCTL(0) &= ~3UL; // Endpoint 0: 64-byte packets
MGI_DWC2_DOEPCTL(0) &= ~3UL;
MGI_DWC2_DOEPTSIZ(0) = 3UL << 29; // Up to 3 SETUPs in a row
s_mgi_dwc2_req_out = false;
}
// A complete control request: usb.c answers it, then the controller follows
static void mgi_dwc2_request(MGI_DWC2_FN) {
uint8_t *r = s_mgi_dwc2_req;
size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage
int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out);
if (res < 0) {
mgi_dwc2_stall();
return;
}
switch ((r[0] << 8) | r[1]) {
case 0x0005: // SET_ADDRESS: the new address goes before the status stage
MGI_DWC2_DCFG =
(MGI_DWC2_DCFG & ~(0x7fUL << 4)) | ((uint32_t) (r[2] & 0x7f) << 4);
break;
case 0x0009: // SET_CONFIGURATION
if (r[2] != 1) break;
#if MG_ENABLE_USB_ETHERNET
mgi_dwc2_open(MG_USB_EP_ETH_EV, 3, false);
mgi_dwc2_open(MG_USB_EP_ETH_DATA, 2, true);
#endif
#if MG_ENABLE_USB_SERIAL
mgi_dwc2_open(MG_USB_EP_SER_EV, 3, false);
mgi_dwc2_open(MG_USB_EP_SER_DATA, 2, true);
#endif
break;
#if MG_ENABLE_USB_ETHERNET
case 0x010b: // SET_INTERFACE: Ethernet data endpoints back to DATA0
if (r[4] == MG_USB_IF_ETH_DATA) {
mgi_dwc2_open(MG_USB_EP_ETH_DATA, 2, r[2] == 1);
}
break;
#endif
case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT)
if (r[4] & 0x80) {
MGI_DWC2_DIEPCTL(r[4] & 15) =
(MGI_DWC2_DIEPCTL(r[4] & 15) & ~MGI_DWC2_STALL) | MGI_DWC2_SD0PID;
} else {
MGI_DWC2_DOEPCTL(r[4] & 15) =
(MGI_DWC2_DOEPCTL(r[4] & 15) & ~MGI_DWC2_STALL) | MGI_DWC2_SD0PID;
}
break;
}
if (res == 0) mgi_dwc2_in(MG_USB_EP_CTL, NULL, 0); // Status stage
}
// A SETUP packet: run it, or first receive its OUT data stage
static void mgi_dwc2_setup(MGI_DWC2_FN) {
uint8_t *r = s_mgi_dwc2_req;
unsigned wlen = MG_LOAD_LE16(r + 6);
mgi_dwc2_in_stop(0); // A SETUP ends the previous control transfer
s_mgi_dwc2_req_out = false;
if ((r[0] & 0x80) || wlen == 0) {
mgi_dwc2_request(fn);
} else if (wlen > sizeof(s_mgi_dwc2_req) - 8) {
mgi_dwc2_stall();
} else {
s_mgi_dwc2_req_out = true, s_mgi_dwc2_req_len = 0;
mgi_dwc2_arm(0);
}
}
// One entry of the RX FIFO: a SETUP, OUT data, or the end of either
static void mgi_dwc2_rx(MGI_DWC2_FN) {
uint32_t st = MGI_DWC2_GRXSTSP, i;
unsigned ep = st & 15, kind = (st >> 17) & 15;
size_t n = (st >> 4) & 0x7ff;
uint8_t *r = s_mgi_dwc2_req;
for (i = 0; i < (n + 3) / 4; i++) { // Take the packet off the FIFO
uint32_t w = MGI_DWC2_FIFO(0);
if (i < sizeof(s_mgi_dwc2_pkt) / 4) s_mgi_dwc2_pkt[i] = w;
}
if (n > sizeof(s_mgi_dwc2_pkt)) n = sizeof(s_mgi_dwc2_pkt);
if (kind == 6) { // SETUP packet
memcpy(r, s_mgi_dwc2_pkt, 8);
} else if (kind == 4) { // SETUP stage done
MGI_DWC2_DOEPTSIZ(0) |= 3UL << 29;
MGI_DWC2_DOEPINT(0) = MG_BIT(3); // STUP
mgi_dwc2_setup(fn);
} else if (kind == 2 && ep == 0 && s_mgi_dwc2_req_out) { // Control OUT
size_t room = sizeof(s_mgi_dwc2_req) - 8 - s_mgi_dwc2_req_len;
memcpy(r + 8 + s_mgi_dwc2_req_len, s_mgi_dwc2_pkt, n < room ? n : room);
s_mgi_dwc2_req_len += n;
#if MG_ENABLE_USB_ETHERNET
} else if (kind == 2 && ep == MG_USB_EP_ETH_DATA) {
fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, s_mgi_dwc2_pkt, n);
#endif
} else if (kind == 3 && ep == 0 && s_mgi_dwc2_req_out) { // OUT stage done
s_mgi_dwc2_req_out = false;
if (s_mgi_dwc2_req_len != MG_LOAD_LE16(r + 6)) {
mgi_dwc2_stall();
} else {
mgi_dwc2_request(fn);
}
} else if (kind == 3 && ep != 0) { // An OUT packet taken: take the next
mgi_dwc2_arm(ep); // Serial input is dropped
}
}
// mg_usb_hw::poll()
static void mgi_dwc2_poll(MGI_DWC2_FN) {
uint32_t sts = MGI_DWC2_GINTSTS;
if (sts & MG_BIT(12)) { // USBRST
MGI_DWC2_GINTSTS = MG_BIT(12);
mgi_dwc2_bus_reset();
fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0);
}
if (sts & MG_BIT(13)) MGI_DWC2_GINTSTS = MG_BIT(13); // ENUMDNE
while (MGI_DWC2_GINTSTS & MG_BIT(4)) mgi_dwc2_rx(fn); // RXFLVL
if (sts & MG_BIT(18)) { // IEPINT
uint32_t daint = MGI_DWC2_DAINT;
unsigned ep;
for (ep = 0; ep < 5; ep++) {
uint32_t ints;
if (!(daint & MG_BIT(ep))) continue;
ints = MGI_DWC2_DIEPINT(ep);
MGI_DWC2_DIEPINT(ep) = ints;
if (!(ints & 1U)) continue; // XFRC: the packet went out
if (!fn(MG_USB_EV_IN, (enum mg_usb_ep) ep, NULL, 0) && ep == 0 &&
(s_mgi_dwc2_req[0] & 0x80) && MG_LOAD_LE16(s_mgi_dwc2_req + 6)) {
mgi_dwc2_arm(0); // IN data stage over: the host's OUT status stage
}
}
}
}
// Core soft reset. From core v4.20a, the reset done bit says when it is over
static void mgi_dwc2_core_reset(void) {
bool done_bit = (MGI_DWC2_GSNPSID & 0xffff) >= 0x420a;
mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(31), true); // AHBIDL
MGI_DWC2_GRSTCTL |= 1U; // CSRST
if (done_bit) {
mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(29), true);
MGI_DWC2_GRSTCTL = (MGI_DWC2_GRSTCTL & ~1U) | MG_BIT(29);
} else {
mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, 1U, false);
}
mgi_dwc2_wait(&MGI_DWC2_GRSTCTL, MG_BIT(31), true);
}
// mg_usb_hw::init(): the serial number, the core as a full-speed device,
// then attach
static void mgi_dwc2_start(char serial[17]) {
#if defined(UID_BASE) // STM32: from the 96-bit unique ID
const volatile uint32_t *uid = (const volatile uint32_t *) UID_BASE;
uint32_t id[2] = {uid[0] ^ uid[2], uid[1]};
mg_snprintf(serial, 17, "%M", mg_print_hex, (int) sizeof(id), (uint8_t *) id);
#else
mg_snprintf(serial, 17, "%s", "0000000000000000");
#endif
#if MG_USB_DWC2_ULPI // 8-bit single data rate, internal VBUS indicator
MGI_DWC2_GUSBCFG =
(MGI_DWC2_GUSBCFG & ~(MG_BIT(3) | MG_BIT(6) | MG_BIT(7) | MG_BIT(17) |
MG_BIT(19) | MG_BIT(20) | MG_BIT(21))) |
MG_BIT(4); // ULPI
#elif MG_USB_DWC2_UTMI
// The core's own high-speed PHY: UTMI, not ULPI or full-speed; no TSDPS
MGI_DWC2_GUSBCFG &= ~(MG_BIT(4) | MG_BIT(6) | MG_BIT(22));
#else
MGI_DWC2_GUSBCFG |= MG_BIT(6); // The core's own full-speed PHY
#endif
#ifdef MG_USB_DWC2_GCCFG
MGI_DWC2_GCCFG = MG_USB_DWC2_GCCFG;
#endif
mgi_dwc2_core_reset();
#ifdef MG_USB_DWC2_GCCFG
MGI_DWC2_GCCFG = MG_USB_DWC2_GCCFG;
#endif
// Turnaround time: 9 for a high-speed PHY, 6 for a fast AHB otherwise.
// Timeout calibration: the maximum. Then device mode, which takes a while
MGI_DWC2_GUSBCFG = (MGI_DWC2_GUSBCFG & ~((0xfUL << 10) | 7U | MG_BIT(29))) |
((MGI_DWC2_HS_PHY ? 9UL : 6UL) << 10) | 7U | MG_BIT(30);
mgi_dwc2_wait(&MGI_DWC2_GINTSTS, 1U, false); // CMOD: device mode
MGI_DWC2_PCGCCTL = 0; // PHY clock on
// Full speed, on a high-speed PHY (DSPD 1) or the core's own full-speed
// one (DSPD 3). Stall a non-empty status stage. XCVRDLY: some ULPI PHYs
// need it to chirp
MGI_DWC2_DCFG = (MGI_DWC2_DCFG & ~3U) | MG_BIT(2) |
(MGI_DWC2_HS_PHY ? 1U : 3U) |
(MG_USB_DWC2_ULPI ? MG_BIT(14) : 0U);
MGI_DWC2_DCTL |= MG_BIT(1); // SDIS: detached while setting up
// No VBUS sensing: B-session valid, always
MGI_DWC2_GOTGCTL = (MGI_DWC2_GOTGCTL & ~MG_BIT(4)) | MG_BIT(6) | MG_BIT(7);
MGI_DWC2_GINTSTS = 0xffffffff;
mgi_dwc2_flush_tx(0x10);
mgi_dwc2_bus_reset();
MGI_DWC2_DCTL &= ~MG_BIT(1); // Attach
}
const struct mg_usb_hw mg_usb_hw_dwc2 = {mgi_dwc2_start, mgi_dwc2_poll,
mgi_dwc2_in};
#if MG_ENABLE_USB_ETHERNET
static bool mgi_dwc2_init(struct mg_tcpip_if *ifp) {
return mg_usb_init(ifp, &mg_usb_hw_dwc2);
}
struct mg_tcpip_driver mg_tcpip_driver_usb_dwc2 = {mgi_dwc2_init, mg_usb_tx,
NULL, mg_usb_poll};
#endif
#endif
+57
View File
@@ -0,0 +1,57 @@
#pragma once
// Synopsys DesignWare USB 2.0 OTG controller, "DWC2", as a device, see usb.h:
// CDC-NCM Ethernet and a CDC-ACM serial log console. Polled, no DMA, full
// speed. STM32 OTG_FS and OTG_HS (F2, F4, F7, H7, L4+, U5) are DWC2. Set in
// mongoose_config.h:
// - MG_USB_DWC2_BASE: the core's address, e.g. USB1_OTG_HS_PERIPH_BASE. The
// application enables its clocks, power and pins
// - MG_USB_DWC2_ULPI 1: an external ULPI PHY, run at full speed. Default: the
// core's own full-speed PHY
// - MG_USB_DWC2_UTMI 1: the core's own high-speed PHY (UTMI), run at full
// speed, e.g. STM32U59x/U5Ax OTG_HS. The application powers and clocks it
// - MG_USB_DWC2_GCCFG: optional, written to the STM32 GCCFG register, e.g.
// its PWRDWN bit to power the core's own full-speed PHY
// On STM32, include the device header in mongoose_config.h: the USB serial
// number is then the chip's unique ID. Examples:
// tutorials/stm32/portenta-h7/minimal-usb (ULPI),
// tutorials/stm32/nucleo-u5a5zj-q/minimal-usb (UTMI)
#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \
MG_ENABLE_DRIVER_USB_DWC2 && \
(MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL)
// The controller. Without USB Ethernet, run the serial console from main():
// mg_usb_init(NULL, &mg_usb_hw_dwc2) once, mg_usb_poll(NULL, false) in
// the main loop
extern const struct mg_usb_hw mg_usb_hw_dwc2;
#endif
#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_DWC2 && MG_ENABLE_USB_ETHERNET
extern struct mg_tcpip_driver mg_tcpip_driver_usb_dwc2;
// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the
// USB host. Leave it unset to get an address over DHCP, e.g. from macOS
// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if
// it is not set; the host end of the link gets a MAC derived from it
#define MG_TCPIP_DRIVER_USB_DWC2_INIT(mgr) \
do { \
static struct mg_tcpip_if mif_; \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.enable_dhcp_server = mif_.ip != 0; \
mif_.driver = &mg_tcpip_driver_usb_dwc2; \
mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \
MG_INFO(("Driver: usb_dwc2, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_DWC2_INIT(mgr)
#endif
#endif
+257
View File
@@ -0,0 +1,257 @@
#include "net_builtin.h"
#include "drivers/usb.h"
#include "drivers/usb_nrf52.h"
#include "printf.h"
#include "util.h"
#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \
MG_ENABLE_DRIVER_USB_NRF52 && \
(MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL)
#include <nrf.h>
// nRF52840 USB device controller, polled, full speed. Endpoint buffers are
// inside the controller: EasyDMA moves each packet between them and RAM,
// and reads RAM only, so every packet goes through s_mgi_usb_nrf52_pkt. The
// controller handles SET_ADDRESS by itself. Errata workarounds follow
// Nordic's nrfx_usbd.c: 171, 187 when enabling, 199 around each DMA
#define MGI_USB_NRF52_ERRATA_199 (*(volatile uint32_t *) 0x40027c1c)
// usb.c's event handler, see mg_usb_hw::poll()
#define MGI_USB_NRF52_FN \
int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t)
static uint32_t s_mgi_usb_nrf52_pkt[64 / 4]; // One packet in RAM
static uint8_t s_mgi_usb_nrf52_req[16]; // SETUP packet, then its OUT data
// Write an undocumented register the way Nordic's errata workarounds do
static void mgi_usb_nrf52_errata(uint32_t addr, uint32_t value) {
volatile uint32_t *unlock = (volatile uint32_t *) 0x4006ec00;
bool locked = *unlock == 0;
if (locked) *unlock = 0x9375;
*(volatile uint32_t *) addr = value;
if (locked) *unlock = 0x9375;
}
// Run one EasyDMA transfer and wait for its end event
static void mgi_usb_nrf52_dma(volatile uint32_t *task, volatile uint32_t *end) {
unsigned i;
*end = 0;
MGI_USB_NRF52_ERRATA_199 = 0x82;
*task = 1;
for (i = 0; *end == 0 && i < 100000; i++) (void) 0; // Microseconds
*end = 0;
MGI_USB_NRF52_ERRATA_199 = 0;
}
// Data toggle of endpoint address ep back to DATA0
static void mgi_usb_nrf52_dtoggle(unsigned ep) {
NRF_USBD->DTOGGLE = ep; // Select the endpoint, then set its toggle
NRF_USBD->DTOGGLE = (USBD_DTOGGLE_VALUE_Data0 << USBD_DTOGGLE_VALUE_Pos) | ep;
}
// mg_usb_hw::in(): copy the packet to RAM, then into the endpoint
static void mgi_usb_nrf52_in(enum mg_usb_ep ep, const void *buf, size_t len) {
if (len > 0) memcpy(s_mgi_usb_nrf52_pkt, buf, len);
NRF_USBD->EPIN[ep].PTR = (uint32_t) (uintptr_t) s_mgi_usb_nrf52_pkt;
NRF_USBD->EPIN[ep].MAXCNT = (uint32_t) len;
mgi_usb_nrf52_dma(&NRF_USBD->TASKS_STARTEPIN[ep],
&NRF_USBD->EVENTS_ENDEPIN[ep]);
}
// Move the packet on OUT endpoint ep to RAM, which also lets the endpoint
// accept the next one. Returns its length
static size_t mgi_usb_nrf52_out(unsigned ep) {
size_t n = NRF_USBD->SIZE.EPOUT[ep];
if (n == 0) {
NRF_USBD->SIZE.EPOUT[ep] = 0; // Nothing to move: accept the next
} else {
NRF_USBD->EPOUT[ep].PTR = (uint32_t) (uintptr_t) s_mgi_usb_nrf52_pkt;
NRF_USBD->EPOUT[ep].MAXCNT = (uint32_t) n;
mgi_usb_nrf52_dma(&NRF_USBD->TASKS_STARTEPOUT[ep],
&NRF_USBD->EVENTS_ENDEPOUT[ep]);
}
return n;
}
#if MG_ENABLE_USB_ETHERNET
// Ethernet data endpoints back to DATA0, OUT ready to receive
static void mgi_usb_nrf52_data_reset(void) {
mgi_usb_nrf52_dtoggle(0x02), mgi_usb_nrf52_dtoggle(0x82);
NRF_USBD->SIZE.EPOUT[2] = 0;
}
#endif
// Endpoints 1-4 on and idle if configured, else off
static void mgi_usb_nrf52_endpoints(bool on) {
NRF_USBD->EPINEN = 1, NRF_USBD->EPOUTEN = 1;
if (!on) return;
#if MG_ENABLE_USB_ETHERNET
NRF_USBD->EPINEN |= MG_BIT(1) | MG_BIT(2), NRF_USBD->EPOUTEN |= MG_BIT(2);
mgi_usb_nrf52_dtoggle(0x81);
mgi_usb_nrf52_data_reset();
#endif
#if MG_ENABLE_USB_SERIAL
NRF_USBD->EPINEN |= MG_BIT(3) | MG_BIT(4), NRF_USBD->EPOUTEN |= MG_BIT(4);
mgi_usb_nrf52_dtoggle(0x83), mgi_usb_nrf52_dtoggle(0x04);
mgi_usb_nrf52_dtoggle(0x84);
NRF_USBD->SIZE.EPOUT[4] = 0;
#endif
}
// A complete control request: usb.c answers it, then the controller follows
static void mgi_usb_nrf52_request(MGI_USB_NRF52_FN) {
uint8_t *r = s_mgi_usb_nrf52_req;
size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage
int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out);
if (res < 0) {
NRF_USBD->TASKS_EP0STALL = 1;
return;
}
switch ((r[0] << 8) | r[1]) {
case 0x0009: // SET_CONFIGURATION
mgi_usb_nrf52_endpoints(r[2] == 1);
break;
#if MG_ENABLE_USB_ETHERNET
case 0x010b: // SET_INTERFACE
if (r[4] == MG_USB_IF_ETH_DATA) mgi_usb_nrf52_data_reset();
break;
#endif
case 0x0201: // CLEAR_FEATURE(ENDPOINT_HALT)
mgi_usb_nrf52_dtoggle(r[4]);
NRF_USBD->EPSTALL =
(USBD_EPSTALL_STALL_UnStall << USBD_EPSTALL_STALL_Pos) | r[4];
if (!(r[4] & 0x80)) NRF_USBD->SIZE.EPOUT[r[4] & 15] = 0;
break;
}
if (res == 0) NRF_USBD->TASKS_EP0STATUS = 1; // No IN data stage
}
// A SETUP packet: run it, or first receive its OUT data stage
static void mgi_usb_nrf52_setup(MGI_USB_NRF52_FN) {
const volatile uint32_t *regs = &NRF_USBD->BMREQUESTTYPE;
uint8_t *r = s_mgi_usb_nrf52_req;
unsigned i, wlen;
for (i = 0; i < 8; i++) r[i] = (uint8_t) regs[i];
wlen = MG_LOAD_LE16(r + 6);
if (r[0] == 0 && r[1] == 5) return; // SET_ADDRESS: the controller's
if ((r[0] & 0x80) || wlen == 0) {
mgi_usb_nrf52_request(fn);
} else if (wlen > sizeof(s_mgi_usb_nrf52_req) - 8) {
NRF_USBD->TASKS_EP0STALL = 1;
} else {
NRF_USBD->TASKS_EP0RCVOUT = 1; // Accept the OUT data stage
}
}
// A control data stage packet: an IN one acknowledged, or an OUT one arrived
static void mgi_usb_nrf52_ep0_data(MGI_USB_NRF52_FN) {
uint8_t *r = s_mgi_usb_nrf52_req;
size_t n = NRF_USBD->SIZE.EPOUT[0];
if (r[0] & 0x80) {
if (!fn(MG_USB_EV_IN, MG_USB_EP_CTL, NULL, 0)) {
NRF_USBD->TASKS_EP0STATUS = 1;
}
} else if (n != MG_LOAD_LE16(r + 6)) {
NRF_USBD->TASKS_EP0STALL = 1;
} else {
mgi_usb_nrf52_out(0);
memcpy(r + 8, s_mgi_usb_nrf52_pkt, n);
mgi_usb_nrf52_request(fn);
}
}
// Follow USB power: enable the controller when VBUS appears, attach to the
// bus once both are ready, and detach when VBUS goes. True while attached
static bool mgi_usb_nrf52_attach(MGI_USB_NRF52_FN) {
uint32_t power = NRF_POWER->USBREGSTATUS;
if (!(power & POWER_USBREGSTATUS_VBUSDETECT_Msk)) {
if (NRF_USBD->ENABLE) {
NRF_USBD->USBPULLUP = 0, NRF_USBD->ENABLE = 0;
fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0);
}
return false;
}
if (!NRF_USBD->ENABLE) {
mgi_usb_nrf52_errata(0x4006ed14, 3); // Errata 187
mgi_usb_nrf52_errata(0x4006ec14, 0xc0); // Errata 171
NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk;
NRF_USBD->ENABLE = 1;
}
if (NRF_USBD->USBPULLUP) return true;
if (!(NRF_USBD->EVENTCAUSE & USBD_EVENTCAUSE_READY_Msk) ||
!(power & POWER_USBREGSTATUS_OUTPUTRDY_Msk))
return false;
NRF_USBD->EVENTCAUSE = USBD_EVENTCAUSE_READY_Msk;
mgi_usb_nrf52_errata(0x4006ec14, 0);
mgi_usb_nrf52_errata(0x4006ed14, 0);
NRF_USBD->USBPULLUP = 1;
return true;
}
// mg_usb_hw::poll()
static void mgi_usb_nrf52_poll(MGI_USB_NRF52_FN) {
if (!mgi_usb_nrf52_attach(fn)) return;
if (NRF_USBD->EVENTS_USBRESET) {
NRF_USBD->EVENTS_USBRESET = 0;
NRF_USBD->EVENTS_EP0DATADONE = NRF_USBD->EVENTS_EPDATA = 0;
NRF_USBD->EPDATASTATUS = NRF_USBD->EPDATASTATUS;
fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0);
mgi_usb_nrf52_endpoints(false);
return;
}
if (NRF_USBD->EVENTS_EP0DATADONE) { // Before a new SETUP replaces req
NRF_USBD->EVENTS_EP0DATADONE = 0;
mgi_usb_nrf52_ep0_data(fn);
}
if (NRF_USBD->EVENTS_EP0SETUP) {
NRF_USBD->EVENTS_EP0SETUP = 0;
mgi_usb_nrf52_setup(fn);
}
if (NRF_USBD->EVENTS_EPDATA) { // Bit n: IN n acknowledged, 16+n: OUT n
uint32_t done = NRF_USBD->EPDATASTATUS;
unsigned i;
NRF_USBD->EVENTS_EPDATA = 0;
NRF_USBD->EPDATASTATUS = done;
for (i = 1; i < 5; i++) {
if (done & MG_BIT(i)) fn(MG_USB_EV_IN, (enum mg_usb_ep) i, NULL, 0);
}
#if MG_ENABLE_USB_ETHERNET
if (done & MG_BIT(16 + MG_USB_EP_ETH_DATA)) {
size_t n = mgi_usb_nrf52_out(MG_USB_EP_ETH_DATA);
fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, s_mgi_usb_nrf52_pkt, n);
}
#endif
#if MG_ENABLE_USB_SERIAL
if (done & MG_BIT(16 + MG_USB_EP_SER_DATA)) {
NRF_USBD->SIZE.EPOUT[MG_USB_EP_SER_DATA] = 0; // Serial input: dropped
}
#endif
}
}
// mg_usb_hw::init(): the serial number, and the crystal that USB needs. The
// controller itself starts in poll, once USB power is there
static void mgi_usb_nrf52_start(char serial[17]) {
uint32_t id[2], xtal = CLOCK_HFCLKSTAT_SRC_Msk | CLOCK_HFCLKSTAT_STATE_Msk;
id[0] = NRF_FICR->DEVICEID[0], id[1] = NRF_FICR->DEVICEID[1];
mg_snprintf(serial, 17, "%M", mg_print_hex, (int) sizeof(id), (uint8_t *) id);
if ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) {
NRF_CLOCK->TASKS_HFCLKSTART = 1;
while ((NRF_CLOCK->HFCLKSTAT & xtal) != xtal) (void) 0;
}
}
const struct mg_usb_hw mg_usb_hw_nrf52 = {
mgi_usb_nrf52_start, mgi_usb_nrf52_poll, mgi_usb_nrf52_in};
#if MG_ENABLE_USB_ETHERNET
static bool mgi_usb_nrf52_init(struct mg_tcpip_if *ifp) {
return mg_usb_init(ifp, &mg_usb_hw_nrf52);
}
struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52 = {
mgi_usb_nrf52_init, mg_usb_tx, NULL, mg_usb_poll};
#endif
#endif
+45
View File
@@ -0,0 +1,45 @@
#pragma once
// nRF52840 USB device controller, see usb.h: CDC-NCM Ethernet and a CDC-ACM
// serial log console. No TinyUSB, polled. Needs the nRF52840 device headers
// from nrfx/mdk on the include path. Example: tutorials/nordic/xiao-nrf52840
#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && \
MG_ENABLE_DRIVER_USB_NRF52 && \
(MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL)
// The controller. Without USB Ethernet, run the serial console from main():
// mg_usb_init(NULL, &mg_usb_hw_nrf52) once, mg_usb_poll(NULL, false) in
// the main loop
extern const struct mg_usb_hw mg_usb_hw_nrf52;
#endif
#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_NRF52 && MG_ENABLE_USB_ETHERNET
extern struct mg_tcpip_driver mg_tcpip_driver_usb_nrf52;
// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the
// USB host. Leave it unset to get an address over DHCP, e.g. from macOS
// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if
// it is not set; the host end of the link gets a MAC derived from it
#define MG_TCPIP_DRIVER_USB_NRF52_INIT(mgr) \
do { \
static struct mg_tcpip_if mif_; \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.enable_dhcp_server = mif_.ip != 0; \
mif_.driver = &mg_tcpip_driver_usb_nrf52; \
mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \
MG_INFO(("Driver: usb_nrf52, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
// Like nrf52.h: both nRF52 drivers can be enabled at once, e.g. in a bridge
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_NRF52_INIT(mgr)
#endif
#endif
+235
View File
@@ -0,0 +1,235 @@
#include "net_builtin.h"
#include "drivers/usb.h"
#include "drivers/usb_rp.h"
#include "util.h"
#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && MG_ENABLE_DRIVER_USB_RP && \
(MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL)
// RP2040 / RP2350 USB device controller: single core, polled, full speed,
// 64-byte single-buffered endpoints in USB DPRAM
// usb.c's event handler, see mg_usb_hw::poll()
#define MGI_USB_RP_FN int (*fn)(enum mg_usb_ev, enum mg_usb_ep, void *, size_t)
struct mgi_usb_rp_ep {
uint8_t *buf; // Endpoint buffer in USB DPRAM
io_rw_32 *ctrl; // Buffer control register
uint8_t pid; // Next DATA PID, 0 or 1
};
static struct mgi_usb_rp_ep s_mgi_usb_rp_ep[5][2]; // Endpoint, OUT=0 IN=1
static uint8_t s_mgi_usb_rp_req[16]; // SETUP packet, then its OUT data
static bool s_mgi_usb_rp_req_out; // Waiting for that OUT data stage
static uint8_t s_mgi_usb_rp_address; // Address to set after the status stage
// Hand one packet buffer to the controller. OUT: accept up to len bytes
static void mgi_usb_rp_packet(unsigned ep, bool in, const void *data,
unsigned len) {
struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in];
uint32_t v = len | (e->pid ? USB_BUF_CTRL_DATA1_PID : 0) |
(in ? USB_BUF_CTRL_FULL : 0);
if (in && len) memcpy(e->buf, data, len);
e->pid ^= 1;
*e->ctrl = v;
// RP2040 datasheet: allow at least 12 cycles between writing buffer
// metadata and handing ownership to the controller through AVAIL
busy_wait_at_least_cycles(12);
*e->ctrl = v | USB_BUF_CTRL_AVAIL;
}
// mg_usb_hw::in()
static void mgi_usb_rp_in(enum mg_usb_ep ep, const void *buf, size_t len) {
mgi_usb_rp_packet(ep, true, buf, (unsigned) len);
}
// Set up endpoint ep, direction in, idle. Endpoints 1 and 3 are interrupt,
// 2 and 4 bulk, each with a 64-byte DPRAM buffer of its own
static void mgi_usb_rp_ep_init(unsigned ep, bool in) {
struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in];
e->ctrl =
in ? &usb_dpram->ep_buf_ctrl[ep].in : &usb_dpram->ep_buf_ctrl[ep].out;
e->buf = ep ? &usb_dpram->epx_data[(ep * 2 + in) * 64] : usb_dpram->ep0_buf_a;
e->pid = 0;
*e->ctrl = 0;
if (ep) {
io_rw_32 *ctrl =
in ? &usb_dpram->ep_ctrl[ep - 1].in : &usb_dpram->ep_ctrl[ep - 1].out;
*ctrl = EP_CTRL_ENABLE_BITS | EP_CTRL_INTERRUPT_PER_BUFFER |
((ep & 1 ? 3U : 2U) << EP_CTRL_BUFFER_TYPE_LSB) |
(uint32_t) ((uintptr_t) e->buf - (uintptr_t) usb_dpram);
}
}
#if MG_ENABLE_USB_ETHERNET
// Ethernet data endpoints idle, OUT armed to receive if Ethernet is open
static void mgi_usb_rp_data_reset(bool open) {
mgi_usb_rp_ep_init(2, false), mgi_usb_rp_ep_init(2, true);
if (open) mgi_usb_rp_packet(2, false, NULL, 64);
}
#endif
// Endpoints 1-4 idle. If configured, the serial port armed to receive
static void mgi_usb_rp_endpoints(bool on) {
#if MG_ENABLE_USB_ETHERNET
mgi_usb_rp_ep_init(1, true);
mgi_usb_rp_data_reset(false);
#endif
#if MG_ENABLE_USB_SERIAL
mgi_usb_rp_ep_init(3, true);
mgi_usb_rp_ep_init(4, false), mgi_usb_rp_ep_init(4, true);
if (on) mgi_usb_rp_packet(4, false, NULL, 64);
#endif
(void) on;
}
// Stall endpoint 0 until the next SETUP
static void mgi_usb_rp_stall(void) {
usb_hw->ep_stall_arm =
USB_EP_STALL_ARM_EP0_IN_BITS | USB_EP_STALL_ARM_EP0_OUT_BITS;
*s_mgi_usb_rp_ep[0][1].ctrl = USB_BUF_CTRL_STALL;
*s_mgi_usb_rp_ep[0][0].ctrl = USB_BUF_CTRL_STALL;
}
// A complete control request: usb.c answers it, then the controller follows
static void mgi_usb_rp_request(MGI_USB_RP_FN) {
uint8_t *r = s_mgi_usb_rp_req;
size_t out = (r[0] & 0x80) ? 0 : MG_LOAD_LE16(r + 6); // OUT data stage
int res = fn(MG_USB_EV_SETUP, MG_USB_EP_CTL, r, 8 + out);
if (res < 0) {
mgi_usb_rp_stall();
return;
}
switch ((r[0] << 8) | r[1]) {
case 0x0005: // SET_ADDRESS, set after the status stage
s_mgi_usb_rp_address = r[2];
break;
case 0x0009: // SET_CONFIGURATION
mgi_usb_rp_endpoints(r[2] == 1);
break;
#if MG_ENABLE_USB_ETHERNET
case 0x010b: // SET_INTERFACE
if (r[4] == MG_USB_IF_ETH_DATA) mgi_usb_rp_data_reset(r[2] == 1);
break;
#endif
case 0x0201: { // CLEAR_FEATURE(ENDPOINT_HALT)
struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[r[4] & 15][r[4] >> 7];
*e->ctrl &= ~USB_BUF_CTRL_STALL, e->pid = 0;
break;
}
}
if (res == 0) mgi_usb_rp_packet(0, true, NULL, 0); // Status stage, DATA1
}
// A SETUP packet: run it, or first receive its OUT data stage
static void mgi_usb_rp_setup(MGI_USB_RP_FN) {
uint8_t *r = s_mgi_usb_rp_req;
unsigned wlen;
memcpy(r, (const void *) usb_dpram->setup_packet, 8);
wlen = MG_LOAD_LE16(r + 6);
// A SETUP cancels the preceding control transfer. Both its data and
// status stages start with DATA1
mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true);
s_mgi_usb_rp_ep[0][0].pid = s_mgi_usb_rp_ep[0][1].pid = 1;
s_mgi_usb_rp_address = 0, s_mgi_usb_rp_req_out = false;
if ((r[0] & 0x80) || wlen == 0) {
mgi_usb_rp_request(fn);
} else if (wlen > sizeof(s_mgi_usb_rp_req) - 8) {
mgi_usb_rp_stall();
} else {
s_mgi_usb_rp_req_out = true;
mgi_usb_rp_packet(0, false, NULL, 64);
}
}
// A buffer the controller has finished with
static void mgi_usb_rp_complete(unsigned ep, bool in, MGI_USB_RP_FN) {
struct mgi_usb_rp_ep *e = &s_mgi_usb_rp_ep[ep][in];
uint8_t *r = s_mgi_usb_rp_req;
unsigned n = *e->ctrl & USB_BUF_CTRL_LEN_MASK;
if (in && fn(MG_USB_EV_IN, (enum mg_usb_ep) ep, NULL, 0)) return;
if (ep == 0 && in) { // Control IN data or status stage sent
if (s_mgi_usb_rp_address) {
usb_hw->dev_addr_ctrl = s_mgi_usb_rp_address, s_mgi_usb_rp_address = 0;
} else if ((r[0] & 0x80) && MG_LOAD_LE16(r + 6)) {
mgi_usb_rp_packet(0, false, NULL, 64); // Host's OUT status stage
}
} else if (ep == 0 && !in && s_mgi_usb_rp_req_out) { // OUT data stage
s_mgi_usb_rp_req_out = false;
if (n != MG_LOAD_LE16(r + 6)) {
mgi_usb_rp_stall();
} else {
memcpy(r + 8, e->buf, n);
mgi_usb_rp_request(fn);
}
#if MG_ENABLE_USB_ETHERNET
} else if (ep == MG_USB_EP_ETH_DATA && !in) {
fn(MG_USB_EV_OUT, MG_USB_EP_ETH_DATA, e->buf, n);
mgi_usb_rp_packet(ep, false, NULL, 64);
#endif
#if MG_ENABLE_USB_SERIAL
} else if (ep == MG_USB_EP_SER_DATA && !in) {
mgi_usb_rp_packet(ep, false, NULL, 64); // Serial input: dropped
#endif
}
}
// mg_usb_hw::poll()
static void mgi_usb_rp_poll(MGI_USB_RP_FN) {
uint32_t status = usb_hw->intr, done;
unsigned i;
if (status & USB_INTR_BUS_RESET_BITS) {
usb_hw->sie_status = USB_SIE_STATUS_BUS_RESET_BITS;
usb_hw->dev_addr_ctrl = 0;
usb_hw->buf_status = 0xffffffff;
fn(MG_USB_EV_RESET, MG_USB_EP_CTL, NULL, 0);
mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true);
mgi_usb_rp_endpoints(false);
return;
}
if (status & USB_INTR_SETUP_REQ_BITS) {
// Discard stale EP0 completions from an interrupted control transfer
usb_hw->buf_status = 3;
usb_hw->sie_status = USB_SIE_STATUS_SETUP_REC_BITS;
mgi_usb_rp_setup(fn);
}
done = usb_hw->buf_status;
for (i = 0; i < 10; i++) { // Bits: EP0 IN, EP0 OUT, EP1 IN, ...
if (!(done & (1U << i))) continue;
usb_hw->buf_status = 1U << i;
if (s_mgi_usb_rp_ep[i / 2][!(i & 1)].ctrl) {
mgi_usb_rp_complete(i / 2, !(i & 1), fn);
}
}
}
// mg_usb_hw::init(): the serial number, then the controller, attached
static void mgi_usb_rp_start(char serial[17]) {
pico_get_unique_board_id_string(serial, 17);
reset_block(RESETS_RESET_USBCTRL_BITS);
unreset_block_wait(RESETS_RESET_USBCTRL_BITS);
memset(usb_dpram, 0, sizeof(*usb_dpram));
usb_hw->muxing = USB_USB_MUXING_TO_PHY_BITS | USB_USB_MUXING_SOFTCON_BITS;
usb_hw->pwr =
USB_USB_PWR_VBUS_DETECT_BITS | USB_USB_PWR_VBUS_DETECT_OVERRIDE_EN_BITS;
usb_hw->main_ctrl = USB_MAIN_CTRL_CONTROLLER_EN_BITS;
usb_hw->sie_ctrl = USB_SIE_CTRL_EP0_INT_1BUF_BITS;
usb_hw->inte = 0; // Poll raw status instead of an interrupt handler
mgi_usb_rp_ep_init(0, false), mgi_usb_rp_ep_init(0, true);
mgi_usb_rp_endpoints(false);
hw_set_bits(&usb_hw->sie_ctrl, USB_SIE_CTRL_PULLUP_EN_BITS);
}
const struct mg_usb_hw mg_usb_hw_rp = {mgi_usb_rp_start, mgi_usb_rp_poll,
mgi_usb_rp_in};
#if MG_ENABLE_USB_ETHERNET
static bool mgi_usb_rp_init(struct mg_tcpip_if *ifp) {
return mg_usb_init(ifp, &mg_usb_hw_rp);
}
struct mg_tcpip_driver mg_tcpip_driver_usb_rp = {mgi_usb_rp_init, mg_usb_tx,
NULL, mg_usb_poll};
#endif
#endif
+42
View File
@@ -0,0 +1,42 @@
#pragma once
// RP2040 / RP2350 native USB controller, see usb.h: CDC-NCM Ethernet and
// a CDC-ACM serial log console. No TinyUSB, polled. Example: tutorials/rp/usb
#if (MG_ENABLE_TCPIP || !MG_ENABLE_USB_ETHERNET) && MG_ENABLE_DRIVER_USB_RP && \
(MG_ENABLE_USB_ETHERNET || MG_ENABLE_USB_SERIAL)
// The controller. Without USB Ethernet, run the serial console from main():
// mg_usb_init(NULL, &mg_usb_hw_rp) once, mg_usb_poll(NULL, false) in
// the main loop
extern const struct mg_usb_hw mg_usb_hw_rp;
#endif
#if MG_ENABLE_TCPIP && MG_ENABLE_DRIVER_USB_RP && MG_ENABLE_USB_ETHERNET
extern struct mg_tcpip_driver mg_tcpip_driver_usb_rp;
// Set MG_TCPIP_IP to give the device a static address and serve DHCP to the
// USB host. Leave it unset to get an address over DHCP, e.g. from macOS
// Internet Sharing. The device MAC comes from MG_SET_MAC_ADDRESS, random if
// it is not set; the host end of the link gets a MAC derived from it
#define MG_TCPIP_DRIVER_USB_RP_INIT(mgr) \
do { \
static struct mg_tcpip_if mif_; \
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.enable_dhcp_server = mif_.ip != 0; \
mif_.driver = &mg_tcpip_driver_usb_rp; \
mif_.recv_queue.size = MG_USB_QUEUE_SIZE; \
MG_SET_MAC_ADDRESS(mif_.mac); \
mg_tcpip_init(mgr, &mif_); \
MG_INFO(("Driver: usb_rp, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(mgr) MG_TCPIP_DRIVER_USB_RP_INIT(mgr)
#endif
#endif
+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
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#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
+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
+3
View File
@@ -1,4 +1,7 @@
#include "net_builtin.h" #include "net_builtin.h"
#include "log.h"
#include "phy.h"
#include "util.h"
#if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7 #if MG_ENABLE_TCPIP && defined(MG_ENABLE_DRIVER_XMC7) && MG_ENABLE_DRIVER_XMC7
+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
+4 -4
View File
@@ -2,9 +2,10 @@
#include "flash.h" #include "flash.h"
#include "log.h" #include "log.h"
#include "ota.h" #include "ota.h"
#include "util.h"
#ifdef MG_OTA_PUBLIC_KEY #ifdef MG_OTA_PUBLIC_KEY
#include "sha256.h" #include "sha256.h"
#include "tls_uecc.h" #include "tls_p256.h"
#endif #endif
#if MG_OTA != MG_OTA_NONE && MG_OTA != MG_OTA_CUSTOM #if MG_OTA != MG_OTA_NONE && MG_OTA != MG_OTA_CUSTOM
@@ -76,9 +77,8 @@ bool mg_ota_flash_end(struct mg_flash *flash) {
uint8_t hash[32]; uint8_t hash[32];
size_t fw_size = s_size - 68; // strip 64-byte sig + 4-byte magic size_t fw_size = s_size - 68; // strip 64-byte sig + 4-byte magic
mg_sha256(hash, (uint8_t *) base, fw_size); mg_sha256(hash, (uint8_t *) base, fw_size);
ok = mg_uecc_verify(s_pubkey, hash, sizeof(hash), ok = mg_p256_verify(s_pubkey, hash, sizeof(hash),
(uint8_t *) base + fw_size, (uint8_t *) base + fw_size) == 1;
mg_uecc_secp256r1()) == 1;
MG_INFO(("Signature: %s", ok ? "ok" : "fail")); MG_INFO(("Signature: %s", ok ? "ok" : "fail"));
} else { } else {
ok = false; ok = false;
+6 -1
View File
@@ -214,7 +214,12 @@ size_t mg_vxprintf(void (*out)(char, void *), void *param, const char *fmt,
n++; n++;
} else if (c == 's') { } else if (c == 's') {
char *p = va_arg(*ap, char *); char *p = va_arg(*ap, char *);
if (pr == ~0U) pr = p == NULL ? 0 : strlen(p); if (p != NULL && pr != ~0U) {
for (j = 0; j < pr && p[j] != '\0'; j++) ; // portable strnlen()
pr = j;
} else {
pr = p == NULL ? 0 : strlen(p);
}
for (j = 0; !minus && pr < w && j + pr < w; j++) for (j = 0; !minus && pr < w && j + pr < w; j++)
n += scpy(out, param, &pad, 1); n += scpy(out, param, &pad, 1);
n += scpy(out, param, p, pr); n += scpy(out, param, p, pr);
+288
View File
@@ -1,5 +1,293 @@
#include "arch.h"
#include "config.h"
#include "health.h" #include "health.h"
#if MG_ENABLE_HEALTH
#if !MG_ENABLE_CUSTOM_USAGE
#if MG_ARCH == MG_ARCH_ESP32
#include <esp_heap_caps.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#elif MG_ENABLE_FREERTOS && defined(__GNUC__) && defined(__ELF__)
// Some FreeRTOS allocators provide current free bytes but no low watermark.
extern size_t xPortGetMinimumEverFreeHeapSize(void) __attribute__((weak));
#endif
#if MG_ENABLE_FREERTOS && MG_ARCH == MG_ARCH_CUBE && \
configUSE_TRACE_FACILITY == 1 && configRECORD_STACK_HIGH_ADDRESS != 1
#warning \
"Set configRECORD_STACK_HIGH_ADDRESS to 1 in FreeRTOSConfig.h to report stack total and peak"
#endif
size_t mg_usage(int task, int metric) {
#if MG_ARCH == MG_ARCH_ESP32 || \
(MG_ENABLE_FREERTOS && defined(configTOTAL_HEAP_SIZE))
if (metric == MG_USAGE_HEAP_TOTAL || metric == MG_USAGE_HEAP_USED ||
metric == MG_USAGE_HEAP_PEAK) {
size_t total, available;
#if MG_ARCH == MG_ARCH_ESP32
total = heap_caps_get_total_size(MALLOC_CAP_DEFAULT);
if (metric == MG_USAGE_HEAP_TOTAL) return total;
available = metric == MG_USAGE_HEAP_USED
? heap_caps_get_free_size(MALLOC_CAP_DEFAULT)
: heap_caps_get_minimum_free_size(MALLOC_CAP_DEFAULT);
#else
total = configTOTAL_HEAP_SIZE;
if (metric == MG_USAGE_HEAP_TOTAL) return total;
if (metric == MG_USAGE_HEAP_USED) {
available = xPortGetFreeHeapSize();
} else {
#if defined(__GNUC__) && defined(__ELF__)
if (xPortGetMinimumEverFreeHeapSize == NULL) return 0;
available = xPortGetMinimumEverFreeHeapSize();
#else
return 0;
#endif
}
#endif
return available <= total ? total - available : 0;
}
#endif
#if MG_ENABLE_FREERTOS || MG_ARCH == MG_ARCH_ESP32
#if configUSE_TRACE_FACILITY == 1
UBaseType_t count = uxTaskGetNumberOfTasks();
if (metric == MG_USAGE_NUM_TASKS) return (size_t) count;
if (task >= 0 && (size_t) task < count) {
TaskStatus_t tasks[count];
if ((size_t) task >= uxTaskGetSystemState(tasks, count, NULL)) return 0;
TaskStatus_t *t = &tasks[task];
if (metric == MG_USAGE_TASK_NAME) return (size_t) t->pcTaskName;
#if (MG_ARCH == MG_ARCH_CUBE || MG_ARCH == MG_ARCH_ESP32) && \
configRECORD_STACK_HIGH_ADDRESS == 1
size_t total = 0;
uintptr_t tcb = (uintptr_t) t->xHandle;
uintptr_t base = (uintptr_t) t->pxStackBase;
if (tcb != 0 &&
t->pcTaskName == (const char *) (tcb + offsetof(StaticTask_t, ucDummy7))) {
StackType_t *end;
uintptr_t field = tcb + offsetof(StaticTask_t, pxDummy8);
memcpy(&end, (const void *) field, sizeof(end));
if (base != 0 && (uintptr_t) end >= base &&
(uintptr_t) end - base <= ((size_t) -1) - sizeof(*end))
total = (size_t) ((uintptr_t) end - base) + sizeof(*end);
}
if (metric == MG_USAGE_STACK_TOTAL) return total;
if (metric == MG_USAGE_STACK_PEAK) {
size_t available =
(size_t) t->usStackHighWaterMark * sizeof(StackType_t);
return available <= total ? total - available : 0;
}
#endif
}
#endif
#endif
(void) task, (void) metric;
return 0;
}
#endif
static size_t print_mem_stat(mg_pfn_t fn, void *arg, const char *name,
size_t total, size_t used, size_t peak) {
return mg_xprintf(fn, arg, "{%m:%m,%m:%zu,%m:%zu,%m:%zu}", MG_ESC("name"),
MG_ESC(name == NULL ? "" : name), MG_ESC("total"), total,
MG_ESC("used"), used, MG_ESC("peak"), peak);
}
size_t mg_print_mem_stats(mg_pfn_t fn, void *arg, va_list *ap) {
int i, count;
size_t heap_total = mg_usage(0, MG_USAGE_HEAP_TOTAL);
size_t heap_used = mg_usage(0, MG_USAGE_HEAP_USED);
size_t heap_peak = mg_usage(0, MG_USAGE_HEAP_PEAK);
size_t len = mg_xprintf(fn, arg, "[");
len += print_mem_stat(fn, arg, "heap", heap_total, heap_used, heap_peak);
count = (int) mg_usage(-1, MG_USAGE_NUM_TASKS);
for (i = 0; i < count; i++) {
const char *name = (const char *) mg_usage(i, MG_USAGE_TASK_NAME);
len += mg_xprintf(fn, arg, ",");
len += print_mem_stat(fn, arg, name, mg_usage(i, MG_USAGE_STACK_TOTAL),
mg_usage(i, MG_USAGE_STACK_USED),
mg_usage(i, MG_USAGE_STACK_PEAK));
}
(void) ap;
return len + mg_xprintf(fn, arg, "]");
}
#if MG_ARCH == MG_ARCH_ESP32
// reusable for other platforms, currently ESP32-only
struct mg_health_coredump {
const void *ptr;
size_t poffset;
size_t size;
};
static struct mg_health_coredump s_coredump;
#endif
bool mg_health_coredump_begin(size_t *size) {
#if MG_ARCH == MG_ARCH_ESP32 && CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
const esp_partition_t *p = esp_partition_find_first(
ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_COREDUMP, NULL);
size_t address = 0, len = 0;
esp_err_t err = esp_core_dump_image_get(&address, &len);
if (size == NULL || s_coredump.ptr != NULL || err != ESP_OK || p == NULL)
return false;
s_coredump.ptr = p;
s_coredump.poffset = address - p->address;
s_coredump.size = len;
*size = len;
return true;
#else
(void) size;
return false;
#endif
}
bool mg_health_coredump_read(size_t offset, void *buf, size_t *len) {
#if MG_ARCH == MG_ARCH_ESP32 && CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
const esp_partition_t *p = (const esp_partition_t *) s_coredump.ptr;
if (p == NULL || offset > s_coredump.size) return false;
if (*len > s_coredump.size - offset) *len = s_coredump.size - offset;
return esp_partition_read(p, s_coredump.poffset + offset, buf, *len) ==
ESP_OK;
#else
(void) offset, (void) buf, (void) len;
return false;
#endif
}
bool mg_health_coredump_end(void) {
#if MG_ARCH == MG_ARCH_ESP32 && CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
bool ok = s_coredump.ptr != NULL;
memset(&s_coredump, 0, sizeof(s_coredump));
return ok;
#else
return false;
#endif
}
// The one health record. Lives in RAM that survives a warm reset, see // The one health record. Lives in RAM that survives a warm reset, see
// MG_HEALTH_RAM and the .mg_health region in the linker script // MG_HEALTH_RAM and the .mg_health region in the linker script
struct mg_health mg_health_record MG_HEALTH_RAM; struct mg_health mg_health_record MG_HEALTH_RAM;
// STM32 H7, H5, C5 support. Needs the _estack symbol from the linker script
#if defined(STM32H7_DEV_ID) || defined(STM32H5) || defined(STM32C5)
// Fault handler body. Runs in exception context: no printf, no malloc, no
// blocking calls. Copies the unwind registers and raw stack into the health
// record, then resets.
// "used" keeps the linker from garbage-collecting this section: the only
// reference is the "b fault_c" branch in the naked handler below
__attribute__((used, noinline)) static void fault_c(uint32_t *frame,
uint32_t exc_return) {
extern uint32_t _estack;
uint32_t *stack = frame + 8 + ((exc_return & (1U << 4)) ? 0 : 18);
uint32_t *r = mg_health_record.data;
if (frame[7] & (1U << 9)) stack++; // Eight-byte stack alignment padding
r[0] = (uint32_t) (uintptr_t) stack; // SP
r[1] = frame[5]; // LR
r[2] = frame[6]; // PC
for (size_t i = 0; i < MG_HEALTH_DATA_SIZE - 3; i++) { // Raw stack
r[3 + i] = stack + i < &_estack ? stack[i] : 0;
}
mg_health_record.cpuid = SCB->CPUID;
mg_health_record.arch = MG_HEALTH_ARCH_ARM;
mg_health_record.reset_reason = MG_HEALTH_RESET_FAULT;
NVIC_SystemReset();
}
// Common fault entry. EXC_RETURN bit 2 tells which stack was in use:
// 0 = MSP, 1 = PSP. Load the faulting SP into r0 and hand it to fault_c()
__attribute__((naked)) void HardFault_Handler(void) {
__asm volatile(
"mov r1, lr\n\t"
"tst lr, #4\n\t"
"ite eq\n\t"
"mrseq r0, msp\n\t"
"mrsne r0, psp\n\t"
"b fault_c\n\t");
}
// Route the other fault types through the same entry point
void MemManage_Handler(void) __attribute__((alias("HardFault_Handler")));
void BusFault_Handler(void) __attribute__((alias("HardFault_Handler")));
void UsageFault_Handler(void) __attribute__((alias("HardFault_Handler")));
#endif
// Start a new boot: validate the record. Called by MG_HEALTH_INIT()
void mg_health_init(void) {
char magic[] = MG_HEALTH_MAGIC;
if (!mg_health_valid()) { // First boot, or RAM lost its contents
memset(&mg_health_record, 0, sizeof(mg_health_record));
memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic));
}
#if MG_ARCH == MG_ARCH_ESP32
#if CONFIG_IDF_TARGET_ARCH_XTENSA
mg_health_record.arch = MG_HEALTH_ARCH_XTENSA;
#elif CONFIG_IDF_TARGET_ARCH_RISCV
mg_health_record.arch = MG_HEALTH_ARCH_RISCV;
#endif
esp_reset_reason_t rr = esp_reset_reason();
mg_health_record.reset_reason = esp2mg(rr);
#if CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH == 0
MG_ERROR(("MG_HEALTH is enabled but CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH=n"));
#else
// After a crash, copy the backtrace from the core dump in flash: the same
// addresses the panic handler prints as "Backtrace: PC:SP PC:SP ...".
// The core dump stays in flash, so check the reset reason, otherwise an
// old crash is reported on every boot
esp_core_dump_summary_t s;
uint32_t *out = mg_health_record.data;
size_t n = 0;
memset(out, 0, sizeof(mg_health_record.data));
if ((rr != ESP_RST_PANIC && rr != ESP_RST_INT_WDT &&
rr != ESP_RST_TASK_WDT) ||
esp_core_dump_get_summary(&s) != ESP_OK) {
return; // If not panic, and if cannot get crash info, give up
}
out[n++] = s.exc_pc; // Crash PC
memcpy(&out[n], s.exc_task, 16), n += 4; // Crashed task name
#if CONFIG_IDF_TARGET_ARCH_XTENSA
out[n++] = s.ex_info.exc_a[0];
out[n++] = s.ex_info.exc_a[1];
size_t len = s.exc_bt_info.depth;
if (len > MG_HEALTH_DATA_SIZE - n) len = MG_HEALTH_DATA_SIZE - n;
memcpy(&out[n], s.exc_bt_info.bt, 4 * len);
#elif CONFIG_IDF_TARGET_ARCH_RISCV
out[n++] = s.ex_info.ra;
out[n++] = s.ex_info.sp;
size_t len = s.exc_bt_info.dump_size / 4;
if (len > MG_HEALTH_DATA_SIZE - n) len = MG_HEALTH_DATA_SIZE - n;
memcpy(&out[n], s.exc_bt_info.stackdump, 4 * len);
#endif
#endif // CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
#endif // MG_ARCH_ESP32
}
static size_t print_uint32(void (*fn)(char, void *), void *arg, va_list *ap) {
size_t n = va_arg(*ap, size_t);
uint32_t *p = va_arg(*ap, uint32_t *);
size_t len = 0;
while (n--) len += mg_xprintf(fn, arg, "%s%lu", len == 0 ? "" : ",", *p++);
return len;
}
size_t mg_print_crash_record(void (*fn)(char, void *), void *arg, va_list *ap) {
size_t len = 0;
if (mg_health_valid() &&
(mg_health_record.reset_reason == MG_HEALTH_RESET_FAULT ||
mg_health_record.reset_reason == MG_HEALTH_RESET_WATCHDOG)) {
size_t n = sizeof(mg_health_record.data) / sizeof(mg_health_record.data[0]);
len += mg_xprintf(fn, arg, "{%m:%hhu,%m:%lu,%m:%lu,%m:%u,%m:[%M]}", //
MG_ESC("version"), mg_health_record.magic[3], //
MG_ESC("arch"), mg_health_record.arch, //
MG_ESC("reason"), mg_health_record.reset_reason, //
MG_ESC("cpuid"), mg_health_record.cpuid, //
MG_ESC("data"), print_uint32, n, mg_health_record.data);
} else {
len += mg_xprintf(fn, arg, "{}");
}
(void) ap;
return len;
}
#endif
+117 -55
View File
@@ -1,43 +1,45 @@
// Device health monitoring // Device health monitoring
//
// Keeps a small record in a RAM region that survives a warm reset, so a device
// can tell why it restarted. The record holds a boot counter, the uptime this
// boot has reached, and the reset reason reported by the hardware. A crash
// loop, a hang loop and a marginal power supply each leave a different mark.
//
// Put MG_HEALTH_INIT() in main(), right after clock and memory init:
//
// ```c
// int main(void) {
// hal_clock_init();
// MG_HEALTH_INIT();
// ...
// }
// ```
//
// The record must live in RAM that startup code neither copies nor zeroes.
// See tutorials/stm32/nucleo-h723zg/minimal/link.ld for the .mg_health region,
// and tutorials/stm32/nucleo-h723zg/minimal/mongoose_config.h for the
// reset-reason hooks.
//
// On Cortex-M, a fault handler can record the crash: it sets reset_reason to
// MG_HEALTH_RESET_FAULT and walks the stack into backtrace[]. See
// tutorials/stm32/nucleo-h723zg/minimal/main.c for a sample HardFault_Handler.
#pragma once #pragma once
#include "arch.h" #include "arch.h"
#include "printf.h"
#if MG_ENABLE_HEALTH
#ifndef MG_HEALTH_MAGIC #ifndef MG_HEALTH_MAGIC
#define MG_HEALTH_MAGIC {'M', 'G', 'H', '3'} // '3' is the layout version #define MG_HEALTH_MAGIC {'M', 'G', 'H', '3'} // '3' is the layout version
#endif #endif
#if !defined(MG_HEALTH_RAM) && (defined(STM32H7_DEV_ID) || defined(STM32H5) || defined(STM32C5))
#define MG_HEALTH_RAM __attribute__((section(".mg_health")))
#endif
#ifndef MG_HEALTH_DATA_SIZE
#if (defined(STM32H7_DEV_ID) || defined(STM32H5)) || defined(STM32C5)
#define MG_HEALTH_DATA_SIZE 250
#elif MG_ARCH == MG_ARCH_ESP32 && CONFIG_IDF_TARGET_ARCH_XTENSA
#define MG_HEALTH_DATA_SIZE 23 // 7 header words + 16 backtrace PCs
#elif MG_ARCH == MG_ARCH_ESP32 && CONFIG_IDF_TARGET_ARCH_RISCV
#define MG_HEALTH_DATA_SIZE 7 // PC, task name, RA, SP
#else
#define MG_HEALTH_DATA_SIZE 10
#endif
#endif // MG_HEALTH_DATA_SIZE
// Places the record in RAM that survives a reset. Define in mongoose_config.h // Places the record in RAM that survives a reset. Define in mongoose_config.h
// to match the linker script, e.g. __attribute__((section(".mg_health"))) // to match the linker script, e.g. __attribute__((section(".mg_health")))
#ifndef MG_HEALTH_RAM #ifndef MG_HEALTH_RAM
#define MG_HEALTH_RAM #define MG_HEALTH_RAM
#endif #endif
// CPU core architecture
enum mg_health_arch {
MG_HEALTH_ARCH_ARM = 0,
MG_HEALTH_ARCH_XTENSA,
MG_HEALTH_ARCH_RISCV
};
// Why the device restarted. Hardware usually reports several flags at once, // Why the device restarted. Hardware usually reports several flags at once,
// so these are ordered by how much they tell you: the most specific cause a // so these are ordered by how much they tell you: the most specific cause a
// device reports wins // device reports wins
@@ -52,14 +54,12 @@ enum mg_health_reason {
MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack MG_HEALTH_RESET_FAULT // Fault handler ran, see regs[] and saved_stack
}; };
#ifndef MG_HEALTH_BACKTRACE struct mg_health { // NOTE: use 32-bit fields to avoid write issues
#define MG_HEALTH_BACKTRACE 20 // Return addresses in mg_health::backtrace
#endif
struct mg_health {
char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data char magic[4]; // MG_HEALTH_MAGIC when the record holds valid data
uint32_t reset_reason; // enum mg_health_reason that started this boot uint32_t reset_reason; // enum mg_health_reason that started this boot
uint32_t backtrace[MG_HEALTH_BACKTRACE]; // Crash backtrace, frame 0 first uint32_t arch; // enum mg_health_arch, core architecture (ARM, etc)
uint32_t cpuid; // ARM CPU ID
uint32_t data[MG_HEALTH_DATA_SIZE];
}; };
extern struct mg_health mg_health_record; // Defined in health.c extern struct mg_health mg_health_record; // Defined in health.c
@@ -90,34 +90,96 @@ static inline const char *mg_health_reason_str(int reason) {
} }
} }
// Start a new boot: validate the record, count the boot, store the reset #if MG_ARCH == MG_ARCH_ESP32
// reason. The current boot moves to prev_* slots first, so the previous #ifndef CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH
// boot's uptime and reason stay readable. Called by MG_HEALTH_INIT() #define CONFIG_ESP_COREDUMP_ENABLE_TO_FLASH 0
static inline void mg_health_init(void) { #endif
char magic[] = MG_HEALTH_MAGIC; #ifndef ESP_PARTITION_SUBTYPE_DATA_COREDUMP
// struct mg_health *h = mg_health_get(); #define ESP_PARTITION_SUBTYPE_DATA_COREDUMP 0x03
if (!mg_health_valid()) { // First boot, or RAM lost its contents #endif
memset(&mg_health_record, 0, sizeof(mg_health_record)); // clang-format off
memcpy(mg_health_record.magic, magic, sizeof(mg_health_record.magic)); static inline uint16_t esp2mg(esp_reset_reason_t rr) {
switch(rr) {
case ESP_RST_POWERON: return (uint16_t) MG_HEALTH_RESET_POWER;
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 2)
case ESP_RST_PWR_GLITCH:
#endif
case ESP_RST_BROWNOUT: return (uint16_t) MG_HEALTH_RESET_BROWNOUT;
case ESP_RST_EXT: return (uint16_t) MG_HEALTH_RESET_PIN;
case ESP_RST_SW: return (uint16_t) MG_HEALTH_RESET_SOFTWARE;
case ESP_RST_DEEPSLEEP: return (uint16_t) MG_HEALTH_RESET_LOWPOWER;
case ESP_RST_INT_WDT:
case ESP_RST_TASK_WDT:
case ESP_RST_WDT: return (uint16_t) MG_HEALTH_RESET_WATCHDOG;
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 2, 2)
case ESP_RST_CPU_LOCKUP:
#endif
case ESP_RST_PANIC: return (uint16_t) MG_HEALTH_RESET_FAULT;
default: break;
} }
// h->prev_uptime = h->uptime; return (uint16_t) MG_HEALTH_RESET_UNKNOWN;
// h->prev_reason = h->reason;
// h->counter++;
// h->uptime = 0;
// h->reason = mg_health_decode_reason();
// MG_HEALTH_RESET_CLEAR();
} }
// clang-format on
#endif
// // Record that the main loop is still alive. Called from mg_mgr_poll(), so a enum mg_usage_metric {
// // hung application leaves uptime frozen at the hang MG_USAGE_NUM_TASKS,
// extern uint64_t mg_health_next_ms; // Defined in health.c MG_USAGE_TASK_NAME,
MG_USAGE_STACK_TOTAL,
MG_USAGE_STACK_USED,
MG_USAGE_STACK_PEAK,
MG_USAGE_HEAP_TOTAL,
MG_USAGE_HEAP_USED,
MG_USAGE_HEAP_PEAK
};
// static inline void mg_health_uptime(uint64_t now_ms) { // Returns a task or heap metric. task is a zero-based index; NUM_TASKS and heap
// struct mg_health *h = mg_health_get(); // metrics ignore it. Sizes are in bytes, TASK_NAME returns const char * cast to
// if (now_ms >= mg_health_next_ms && mg_health_valid()) { // size_t
// mg_health_next_ms = now_ms + 1000; // Unsupported metrics return 0. PEAK is the maximum used since boot
// h->uptime++; // Set MG_ENABLE_CUSTOM_USAGE=1 and define mg_usage() in the application to
// } // provide custom measurements
// } size_t mg_usage(int task, int metric);
#define MG_HEALTH_INIT() mg_health_init() #define MG_HEALTH_INIT() mg_health_init()
extern size_t mg_print_crash_record(mg_pfn_t, void *, va_list *);
// JSON memory statistics via mg_usage(), suitable for %M: an array of
// {name, total, used, peak} entries, starting with "heap", then task stacks
// Unavailable metrics are reported as 0
extern size_t mg_print_mem_stats(mg_pfn_t, void *, va_list *);
extern void mg_health_init(void);
extern bool mg_health_coredump_begin(size_t *size);
extern bool mg_health_coredump_read(size_t offset, void *buf, size_t *len);
extern bool mg_health_coredump_end(void);
#else
#define MG_HEALTH_INIT()
static inline int mg_health_reason(void) {
return 0;
}
static inline const char *mg_health_reason_str(int reason) {
(void) reason;
return "unknown";
}
static inline size_t mg_print_crash_record(mg_pfn_t fn, void *arg,
va_list *ap) {
(void) ap;
return mg_xprintf(fn, arg, "{}");
}
static inline size_t mg_print_mem_stats(mg_pfn_t fn, void *arg, va_list *ap) {
(void) ap;
return mg_xprintf(fn, arg, "[]");
}
static inline bool mg_health_coredump_begin(size_t *size) {
(void) size;
return false;
}
static inline bool mg_health_coredump_read(size_t offset, void *buf,
size_t *len) {
(void) offset, (void) buf, (void) len;
return false;
}
static inline bool mg_health_coredump_end(void) {
return false;
}
#endif
+74 -51
View File
@@ -265,6 +265,12 @@ static bool mg_http_parse_headers(const char *s, const char *end,
// MG_INFO(("--HH [%.*s] [%.*s]", (int) k.len, k.buf, (int) v.len, v.buf)); // MG_INFO(("--HH [%.*s] [%.*s]", (int) k.len, k.buf, (int) v.len, v.buf));
h[i].name = k, h[i].value = v; // Success. Assign values h[i].name = k, h[i].value = v; // Success. Assign values
} }
if (i == max_hdrs &&
!(s < end &&
(s[0] == '\n' ||
(s[0] == '\r' && s + 1 < end && s[1] == '\n')))) {
return false;
}
return true; return true;
} }
@@ -358,7 +364,7 @@ static void mg_http_vprintf_chunk(struct mg_connection *c, const char *fmt,
if (c->send.len >= len + 10) { if (c->send.len >= len + 10) {
mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10); mg_snprintf((char *) c->send.buf + len, 9, "%08lx", c->send.len - len - 10);
c->send.buf[len + 8] = '\r'; c->send.buf[len + 8] = '\r';
if (c->send.len == len + 10) c->is_resp = 0; // Last chunk, reset marker if (c->send.len == len + 10) c->pfn_data = NULL; // Last chunk, done
} }
if (!mg_send(c, "\r\n", 2)) mg_error(c, "OOM"); if (!mg_send(c, "\r\n", 2)) mg_error(c, "OOM");
} }
@@ -373,7 +379,7 @@ void mg_http_printf_chunk(struct mg_connection *c, const char *fmt, ...) {
void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) { void mg_http_write_chunk(struct mg_connection *c, const char *buf, size_t len) {
mg_printf(c, "%lx\r\n", (unsigned long) len); mg_printf(c, "%lx\r\n", (unsigned long) len);
if (!mg_send(c, buf, len) || !mg_send(c, "\r\n", 2)) mg_error(c, "OOM"); if (!mg_send(c, buf, len) || !mg_send(c, "\r\n", 2)) mg_error(c, "OOM");
if (len == 0) c->is_resp = 0; if (len == 0) c->pfn_data = NULL; // Last chunk, response done
} }
// clang-format off // clang-format off
@@ -462,15 +468,14 @@ void mg_http_reply(struct mg_connection *c, int code, const char *headers,
(unsigned long) (c->send.len - len)); (unsigned long) (c->send.len - len));
c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space c->send.buf[len - 15 + n] = ' '; // Change ending 0 to space
} }
c->is_resp = 0; c->pfn_data = NULL; // Response done
} }
static void http_cb(struct mg_connection *, int, void *); static void http_cb(struct mg_connection *, int, void *);
static void restore_http_cb(struct mg_connection *c) { static void restore_http_cb(struct mg_connection *c) {
mg_fs_close((struct mg_fd *) c->pfn_data); mg_fs_close((struct mg_fd *) c->pfn_data);
c->pfn_data = NULL; c->pfn_data = NULL; // Response done
c->pfn = http_cb; c->pfn = http_cb;
c->is_resp = 0;
} }
char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime); char *mg_http_etag(char *buf, size_t len, size_t size, time_t mtime);
@@ -658,7 +663,7 @@ void mg_http_serve_file(struct mg_connection *c, struct mg_http_message *hm,
etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "", etag, (uint64_t) cl, gzip ? "Content-Encoding: gzip\r\n" : "",
range, hdrs); range, hdrs);
if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0 || c->is_closing) { if (mg_strcasecmp(hm->method, mg_str("HEAD")) == 0 || c->is_closing) {
c->is_resp = 0; c->pfn_data = NULL; // Response done
mg_fs_close(fd); mg_fs_close(fd);
} else { // start serving static content only if not closing, see #3354 } else { // start serving static content only if not closing, see #3354
// Track to-be-sent content length at the end of c->data, aligned // Track to-be-sent content length at the end of c->data, aligned
@@ -727,7 +732,7 @@ static void listdir(struct mg_connection *c, struct mg_http_message *hm,
n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off)); n = mg_snprintf(tmp, sizeof(tmp), "%lu", (unsigned long) (c->send.len - off));
if (n > sizeof(tmp)) n = 0; if (n > sizeof(tmp)) n = 0;
memcpy(c->send.buf + off - 12, tmp, n); // Set content length memcpy(c->send.buf + off - 12, tmp, n); // Set content length
c->is_resp = 0; // Mark response end c->pfn_data = NULL; // Response done
} }
// Map requested URI to the file path (buf,len). Use root directory r. // Map requested URI to the file path (buf,len). Use root directory r.
@@ -735,21 +740,27 @@ static void listdir(struct mg_connection *c, struct mg_http_message *hm,
static bool uri2path(const char *r, struct mg_str uri, char *buf, size_t len) { static bool uri2path(const char *r, struct mg_str uri, char *buf, size_t len) {
struct mg_str k, v, part, s = mg_str(r), u = {NULL, 0}, d = u; struct mg_str k, v, part, s = mg_str(r), u = {NULL, 0}, d = u;
size_t n; size_t n;
bool matched = false;
while (mg_span(s, &part, &s, ',')) { while (mg_span(s, &part, &s, ',')) {
if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0); if (!mg_span(part, &k, &v, '=')) k = part, v = mg_str_n(NULL, 0);
if (v.len == 0) v = k, k = mg_str("/"), u = k, d = v; if (v.len == 0) v = k, k = mg_str("/"), u = k, d = v;
if (uri.len < k.len) continue; if (uri.len < k.len) continue;
if (mg_strcmp(k, mg_str_n(uri.buf, k.len)) != 0) continue; if (mg_strcmp(k, mg_str_n(uri.buf, k.len)) != 0) continue;
u = k, d = v; u = k, d = v, matched = true;
} }
if (!matched) return false;
n = mg_snprintf(buf, len, "%.*s", (int) d.len, d.buf); n = mg_snprintf(buf, len, "%.*s", (int) d.len, d.buf);
if (len == 0 || n + 2 >= len) return false; // Path overflow if (len == 0 || n + 2 >= len) return false; // Path overflow
if (n > 0 && buf[n - 1] != '/') buf[n++] = '/', buf[n] = '\0'; // Add slash if (n > 0 && buf[n - 1] != '/') buf[n++] = '/', buf[n] = '\0'; // Add slash
if (mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0) < 0) { {
return false; int dn;
size_t p = n;
dn = mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0);
if (dn < 0) return false; // reject on malformed
buf[len - 1] = '\0'; // Double-check
n = strlen(buf);
if (n != p + (size_t) dn) return false; // reject on embedded NULs
} }
buf[len - 1] = '\0'; // Double-check
n = strlen(buf);
if (!mg_path_is_sane(mg_str_n(buf, n))) return false; if (!mg_path_is_sane(mg_str_n(buf, n))) return false;
while (n > 1 && buf[n - 1] == '/') buf[--n] = 0; // Trim trailing slashes while (n > 1 && buf[n - 1] == '/') buf[--n] = 0; // Trim trailing slashes
return true; return true;
@@ -781,7 +792,7 @@ static int uri_to_file_status(struct mg_connection *c,
"Content-Length: 0\r\n" "Content-Length: 0\r\n"
"\r\n", "\r\n",
(int) hm->uri.len, hm->uri.buf); (int) hm->uri.len, hm->uri.buf);
c->is_resp = 0; c->pfn_data = NULL; // Response done
flags = -1; flags = -1;
} else if (flags & MG_FS_DIR) { } else if (flags & MG_FS_DIR) {
if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 && if (((mg_snprintf(path + n, path_size - n, "/" MG_HTTP_INDEX) > 0 &&
@@ -880,8 +891,8 @@ void mg_http_serve_upload(struct mg_connection *c, struct mg_http_message *hm,
fs->rm(path); // MG_FS_WRITE appends, not truncates: drop any old file fs->rm(path); // MG_FS_WRITE appends, not truncates: drop any old file
if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) { if ((fd = mg_fs_open(fs, path, MG_FS_WRITE)) == NULL) {
MG_ERROR(("Cannot open %s for upload", path)); MG_ERROR(("Cannot open %s for upload", path));
} else if (!mg_http_stream_body(c, hm, serve_upload_cb, fd)) { } else {
mg_fs_close(fd); mg_http_stream_body(c, hm, serve_upload_cb, fd);
} }
} }
} }
@@ -1015,6 +1026,7 @@ struct mg_upload_state {
size_t received; // Number of body bytes received so far size_t received; // Number of body bytes received so far
void *user_data; // Passed to cb, free for cb to use void *user_data; // Passed to cb, free for cb to use
bool failed; // Set when cb returned false bool failed; // Set when cb returned false
bool finished; // End callback has been called
}; };
// Event handler installed by mg_http_stream_body(). Feeds the body to the // Event handler installed by mg_http_stream_body(). Feeds the body to the
@@ -1022,18 +1034,18 @@ struct mg_upload_state {
// handler: the connection is closed after the reply. // handler: the connection is closed after the reply.
static void mg_stream_handler(struct mg_connection *c, int ev, void *ev_data) { static void mg_stream_handler(struct mg_connection *c, int ev, void *ev_data) {
struct mg_upload_state *us = (struct mg_upload_state *) c->data; struct mg_upload_state *us = (struct mg_upload_state *) c->data;
bool (*fn)(struct mg_http_message *, struct mg_str *, void **) = bool (*fn)(struct mg_http_message *, struct mg_str *, void **) =
(bool (*)(struct mg_http_message *, struct mg_str *, void **)) (bool (*)(struct mg_http_message *, struct mg_str *, void **))
(ptrdiff_t) c->fn_data; (ptrdiff_t) c->fn_data;
(void) ev_data; (void) ev_data;
if (ev == MG_EV_CLOSE || ev == MG_EV_ERROR) { if (ev == MG_EV_CLOSE || ev == MG_EV_ERROR) {
if (us->received < us->expected) { if (!us->finished) {
// Connection dropped mid-upload. Let cb clean up, e.g. call mg_ota_end() // Connection dropped mid-upload. Let cb clean up, e.g. call mg_ota_end()
us->received = us->expected; // MG_EV_ERROR is followed by MG_EV_CLOSE us->finished = true; // MG_EV_ERROR is followed by MG_EV_CLOSE
fn(NULL, NULL, &us->user_data); fn(NULL, NULL, &us->user_data);
} }
} else if (ev == MG_EV_READ && !c->is_draining) { } else if (ev == MG_EV_READ && !c->is_draining && !us->finished) {
if (c->recv.len > 0 && us->received < us->expected) { if (!us->failed && c->recv.len > 0 && us->received < us->expected) {
// Got some uploaded data. Feed by 512-byte aligned chunks, for OTA // Got some uploaded data. Feed by 512-byte aligned chunks, for OTA
size_t left = us->expected - us->received, r = c->recv.len; size_t left = us->expected - us->received, r = c->recv.len;
size_t aligned = r < left ? MG_ROUND_DOWN(r, 512) : left; size_t aligned = r < left ? MG_ROUND_DOWN(r, 512) : left;
@@ -1044,10 +1056,13 @@ static void mg_stream_handler(struct mg_connection *c, int ev, void *ev_data) {
us->received += aligned; us->received += aligned;
mg_iobuf_del(&c->recv, 0, aligned); // Shift the unprocessed tail mg_iobuf_del(&c->recv, 0, aligned); // Shift the unprocessed tail
} }
if (us->received >= us->expected) { if (!us->finished && (us->failed || us->received >= us->expected)) {
// Finished upload. Always call cb, even after error, so it can clean up // Finished upload. Always call cb, even after error, so it can clean up
us->finished = true;
us->failed |= !fn(NULL, NULL, &us->user_data); us->failed |= !fn(NULL, NULL, &us->user_data);
if (!c->is_client) { if (c->is_client && us->failed) {
mg_error(c, "Body streaming failed");
} else if (!c->is_client) {
mg_http_reply(c, us->failed ? 500 : 200, NULL, "%zu %s\n", mg_http_reply(c, us->failed ? 500 : 200, NULL, "%zu %s\n",
us->received, us->failed ? "fail" : "ok"); us->received, us->failed ? "fail" : "ok");
} }
@@ -1056,48 +1071,54 @@ static void mg_stream_handler(struct mg_connection *c, int ev, void *ev_data) {
} }
} }
bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm, void mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
bool (*cb)(struct mg_http_message *, struct mg_str *, bool (*cb)(struct mg_http_message *, struct mg_str *,
void **user_data), void **),
void *user_data) { void *user_data) {
struct mg_upload_state *us = (struct mg_upload_state *) c->data; struct mg_upload_state *us = (struct mg_upload_state *) c->data;
struct mg_str *te = mg_http_get_header(hm, "Transfer-Encoding"); int code = 0;
bool handled = false; size_t head_len = hm->head.len;
// Catch upload requests early, without buffering whole body. Called on the // Catch upload requests early, without buffering whole body. Called on the
// MG_EV_HTTP_HDRS event: we've received all HTTP headers but not necessarily // MG_EV_HTTP_HDRS event: we've received all HTTP headers but not necessarily
// the full HTTP body // the full HTTP body
if (hm->body.len == (size_t) ~0 || if (!c->is_client && mg_strcmp(hm->method, mg_str("POST")) != 0 &&
(te != NULL && mg_strcasecmp(*te, mg_str("chunked")) == 0)) { mg_strcmp(hm->method, mg_str("PUT")) != 0) {
// Unknown length or chunked, cannot stream. Leave it to the caller code = 405;
} else if (!c->is_client && } else if (mg_http_get_header(hm, "Transfer-Encoding") != NULL) {
mg_strcmp(hm->method, mg_str("POST")) != 0 && code = 400;
mg_strcmp(hm->method, mg_str("PUT")) != 0) { } else if (hm->body.len == (size_t) ~0 ||
// Not an upload request. Leave it to the caller (!c->is_client && mg_http_get_header(hm, "Content-Length") == NULL)) {
code = 411;
} else if (sizeof(*us) > sizeof(c->data)) { } else if (sizeof(*us) > sizeof(c->data)) {
if (!c->is_client) { // Nobody to reply to on a client connection code = 500;
c->pfn = NULL; }
mg_http_reply(c, 500, NULL, "data too small\n"); c->pfn = NULL; // Take ownership even when validation fails
c->is_draining = 1; if (code != 0) {
cb(NULL, NULL, &user_data); // Let cb release user_data, start skipped c->fn = NULL;
handled = true; c->fn_data = NULL;
mg_iobuf_del(&c->recv, 0, c->recv.len);
cb(NULL, NULL, &user_data); // Release resources even if start was skipped
if (c->is_client) {
mg_error(c, "%s", mg_http_status_code_str(code));
} else {
mg_http_reply(c, code, code == 405 ? "Allow: POST, PUT\r\n" : NULL, "");
} }
c->is_draining = 1;
} else { } else {
c->pfn = NULL; // Silence HTTP protocol handler
memset(us, 0, sizeof(*us)); memset(us, 0, sizeof(*us));
us->expected = hm->body.len; // Store number of bytes we expect us->expected = hm->body.len; // Store number of bytes we expect
us->user_data = user_data; us->user_data = user_data;
c->fn = mg_stream_handler;
c->fn_data = (void *) (ptrdiff_t) cb;
us->failed = !cb(hm, NULL, &us->user_data); // Call before deleting headers us->failed = !cb(hm, NULL, &us->user_data); // Call before deleting headers
if (mg_http_get_header(hm, "Expect") != NULL) { if (!c->is_client && !us->failed && !us->finished &&
mg_http_get_header(hm, "Expect") != NULL) {
mg_http_reply(c, 100, NULL, ""); // If curl expects, we continue mg_http_reply(c, 100, NULL, ""); // If curl expects, we continue
} }
mg_iobuf_del(&c->recv, 0, hm->head.len); // Delete HTTP headers mg_iobuf_del(&c->recv, 0, head_len); // Delete HTTP headers
c->fn = mg_stream_handler; // We own the connection from now
c->fn_data = (void *) (ptrdiff_t) cb;
mg_call(c, MG_EV_READ, &c->recv.len); // Process the body bytes we have mg_call(c, MG_EV_READ, &c->recv.len); // Process the body bytes we have
handled = true;
} }
return handled;
} }
static bool is_hex_digit(int c) { static bool is_hex_digit(int c) {
@@ -1126,7 +1147,9 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
c->recv.len > 0)) { // see #2796 c->recv.len > 0)) { // see #2796
struct mg_http_message hm; struct mg_http_message hm;
size_t ofs = 0; // Parsing offset size_t ofs = 0; // Parsing offset
while (c->is_resp == 0 && ofs < c->recv.len) { // c->pfn_data is the "response generation in progress" marker. While it
// is set, don't parse the next pipelined request, to keep responses in order
while (c->pfn_data == NULL && ofs < c->recv.len) {
const char *buf = (char *) c->recv.buf + ofs; const char *buf = (char *) c->recv.buf + ofs;
int n = mg_http_parse(buf, c->recv.len - ofs, &hm); int n = mg_http_parse(buf, c->recv.len - ofs, &hm);
struct mg_str *te; // Transfer - encoding header struct mg_str *te; // Transfer - encoding header
@@ -1174,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;
@@ -1219,9 +1242,9 @@ static void http_cb(struct mg_connection *c, int ev, void *ev_data) {
ofs += (size_t) n + hm.body.len; ofs += (size_t) n + hm.body.len;
} }
if (c->is_accepted) c->is_resp = 1; // Start generating response if (c->is_accepted) c->pfn_data = c; // Response started
mg_call(c, MG_EV_HTTP_MSG, &hm); // User handler can clear is_resp mg_call(c, MG_EV_HTTP_MSG, &hm); // Handler sets pfn_data NULL when done
if (c->is_accepted && !c->is_resp) { if (c->is_accepted && c->pfn_data == NULL) {
struct mg_str *cc = mg_http_get_header(&hm, "Connection"); struct mg_str *cc = mg_http_get_header(&hm, "Connection");
if (cc != NULL && mg_strcasecmp(*cc, mg_str("close")) == 0) { if (cc != NULL && mg_strcasecmp(*cc, mg_str("close")) == 0) {
c->is_draining = 1; // honor "Connection: close" c->is_draining = 1; // honor "Connection: close"
+14 -11
View File
@@ -205,29 +205,32 @@ int mg_http_status(const struct mg_http_message *hm);
// Streams a POST/PUT body to a callback as it arrives, without buffering it. // Streams a POST/PUT body to a callback as it arrives, without buffering it.
// Call it from an MG_EV_HTTP_HDRS handler, after matching the request, e.g. // Call it from an MG_EV_HTTP_HDRS handler, after matching the request, e.g.
// with mg_match(). Returns true if it took over the connection, false if the // with mg_match(). Always takes over the connection. Invalid requests receive
// request is not POST/PUT, is chunked, or has no Content-Length. // an HTTP error; client-side failures call mg_error(). Replies and connection
// draining are handled internally, including callback failures.
// //
// Callback upload_fn(hm, data, user_data) is called: // Callback upload_fn(hm, data, user_data) is called:
// - at start: hm is set. Open the file, set *user_data. // - at start: hm is set. Open the file, set *user_data.
// - per chunk: data is set, 512 byte aligned except the last. Not called // - per chunk: data is set, 512 byte aligned except the last. Not called
// again after a failure. // again after a failure.
// - at end: both NULL. Always called once, also when the connection drops // - at end: both NULL. Always called exactly once, including validation
// early, so release resources here. A truncated body looks like a complete // failures before start and connections that drop early. Release resources
// one: validate before committing. // here. A truncated body looks like a complete one: validate before
// Return true on success, false on error. // committing.
// The callback returns true on success, false on error. A failure stops
// streaming immediately and calls the end callback before closing.
// Example: // Example:
// if (ev == MG_EV_HTTP_HDRS && mg_match(hm->uri, mg_str("/fs/*"), NULL) { // if (ev == MG_EV_HTTP_HDRS && mg_match(hm->uri, mg_str("/fs/*"), NULL)) {
// mg_http_stream_body(c, hm, upload, NULL)); // mg_http_stream_body(c, hm, upload, NULL);
// } // }
// Full example: // Full example:
// tutorials/http/file-upload-single-post // tutorials/http/file-upload-single-post
// Related APIs: // Related APIs:
// mg_http_listen(), mg_http_next_multipart() // mg_http_listen(), mg_http_next_multipart()
// Notes: // Notes:
// After it returns true, this function hijacks the connection. Existing event // The existing event handler is no longer called. hm is invalid after this
// handler not called, hm is invalid, c->data and c->fn_data are modified // call; c->data and c->fn_data are reserved for streaming state.
bool mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm, void mg_http_stream_body(struct mg_connection *c, struct mg_http_message *hm,
bool (*upload_fn)(struct mg_http_message *, bool (*upload_fn)(struct mg_http_message *,
struct mg_str *, void **user_data), struct mg_str *, void **user_data),
void *user_data); void *user_data);
+4 -30
View File
@@ -7,7 +7,7 @@
#include "util.h" #include "util.h"
#if MG_TLS == MG_TLS_BUILTIN #if MG_TLS == MG_TLS_BUILTIN
#include "tls_uecc.h" #include "tls_p256.h"
#endif #endif
static size_t jwt_split(struct mg_str jwt, struct mg_str *h, struct mg_str *p, static size_t jwt_split(struct mg_str jwt, struct mg_str *h, struct mg_str *p,
@@ -95,39 +95,14 @@ size_t mg_jwt_verify_hs256(struct mg_str jwt, const struct mg_jwt_opts *opts,
} }
#if MG_TLS == MG_TLS_BUILTIN #if MG_TLS == MG_TLS_BUILTIN
typedef struct {
MG_UECC_HashContext uECC;
mg_sha256_ctx sha256;
} jwt_hash_ctx;
static void jwt_hash_init(const MG_UECC_HashContext *ctx) {
jwt_hash_ctx *c = (jwt_hash_ctx *) ctx;
mg_sha256_init(&c->sha256);
}
static void jwt_hash_update(const MG_UECC_HashContext *ctx, const uint8_t *msg,
unsigned len) {
jwt_hash_ctx *c = (jwt_hash_ctx *) ctx;
mg_sha256_update(&c->sha256, msg, len);
}
static void jwt_hash_finish(const MG_UECC_HashContext *ctx, uint8_t *hash) {
jwt_hash_ctx *c = (jwt_hash_ctx *) ctx;
mg_sha256_final(hash, &c->sha256);
}
size_t mg_jwt_sign_es256(const struct mg_jwt_opts *opts, char *buf, size_t mg_jwt_sign_es256(const struct mg_jwt_opts *opts, char *buf,
size_t len) { size_t len) {
uint8_t hash[32], sig[64], tmp[2 * 32 + 64]; uint8_t hash[32], sig[64];
jwt_hash_ctx ctx = {
{jwt_hash_init, jwt_hash_update, jwt_hash_finish, 64, 32, tmp},
{{0}, 0, 0, {0}}};
size_t n = jwt_header_payload("ES256", opts, buf, len); size_t n = jwt_header_payload("ES256", opts, buf, len);
size_t m; size_t m;
if (n == 0 || n + 1 >= len) return 0; if (n == 0 || n + 1 >= len) return 0;
mg_sha256(hash, (uint8_t *) buf, n); mg_sha256(hash, (uint8_t *) buf, n);
if (mg_uecc_sign_deterministic(opts->private_key, hash, sizeof(hash), if (mg_p256_sign(opts->private_key, hash, sizeof(hash), sig) != 1)
&ctx.uECC, sig, mg_uecc_secp256r1()) != 1)
return 0; return 0;
buf[n++] = '.'; buf[n++] = '.';
m = mg_base64url_encode(sig, sizeof(sig), buf + n, len - n); m = mg_base64url_encode(sig, sizeof(sig), buf + n, len - n);
@@ -143,8 +118,7 @@ size_t mg_jwt_verify_es256(struct mg_str jwt, const struct mg_jwt_opts *opts,
if (mg_base64url_decode(s.buf, s.len, (char *) sig, sizeof(sig)) != 64) if (mg_base64url_decode(s.buf, s.len, (char *) sig, sizeof(sig)) != 64)
return 0; return 0;
mg_sha256(hash, (uint8_t *) jwt.buf, n); mg_sha256(hash, (uint8_t *) jwt.buf, n);
if (mg_uecc_verify(opts->public_key, hash, sizeof(hash), sig, if (mg_p256_verify(opts->public_key, hash, sizeof(hash), sig) != 1)
mg_uecc_secp256r1()) != 1)
return 0; return 0;
return mg_base64url_decode(p.buf, p.len, buf, len); return mg_base64url_decode(p.buf, p.len, buf, len);
} }
-7
View File
@@ -94,13 +94,6 @@ size_t mg_l2_eth_trailer(struct mg_tcpip_if *ifp, size_t len, uint8_t *cur) {
struct mg_l2addr *mg_l2_eth_mapip(enum mg_l2addrtype addrtype, struct mg_l2addr *mg_l2_eth_mapip(enum mg_l2addrtype addrtype,
struct mg_addr *addr); struct mg_addr *addr);
// Read an unaligned little-endian value from byte pointer p into a native integer.
// Safe on architectures that forbid unaligned access (e.g. Cortex-M0).
#define MG_LOAD_LE32(p) \
((uint32_t) (((uint32_t) MG_U8P(p)[3] << 24U) | \
((uint32_t) MG_U8P(p)[2] << 16U) | \
((uint32_t) MG_U8P(p)[1] << 8U) | MG_U8P(p)[0]))
bool mg_l2_eth_rx(struct mg_tcpip_if *ifp, enum mg_l2proto *proto, bool mg_l2_eth_rx(struct mg_tcpip_if *ifp, enum mg_l2proto *proto,
struct mg_str *pay, struct mg_str *raw) { struct mg_str *pay, struct mg_str *raw) {
struct eth *eth = (struct eth *) raw->buf; struct eth *eth = (struct eth *) raw->buf;
+74 -35
View File
@@ -55,7 +55,10 @@ static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
// c->is_hexdumping = true; // c->is_hexdumping = true;
if (mg_url_is_ssl(MG_MDASH_URL)) { if (mg_url_is_ssl(MG_MDASH_URL)) {
struct mg_str host = mg_url_host(MG_MDASH_URL); struct mg_str host = mg_url_host(MG_MDASH_URL);
struct mg_tls_opts opts = {.ca = mg_str(mg_mdash_ca_pem), .name = host}; struct mg_tls_opts opts;
memset(&opts, 0, sizeof(struct mg_tls_opts));
opts.ca = mg_str(mg_mdash_ca_pem);
opts.name = host;
mg_tls_init(c, &opts); mg_tls_init(c, &opts);
} }
} }
@@ -65,16 +68,18 @@ static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
// mDashTriggerEvent(s_mDashState, NULL); // mDashTriggerEvent(s_mDashState, NULL);
} else if (ev == MG_EV_WS_MSG) { } else if (ev == MG_EV_WS_MSG) {
struct mg_iobuf io = {0, 0, 0, 512}; struct mg_iobuf io = {0, 0, 0, 512};
struct mg_ws_message *wm = ev_data; struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
struct mg_str s = wm->data; struct mg_str s = wm->data;
struct mg_rpc_req r;
while (s.len > 0 && isspace((uint8_t) s.buf[s.len - 1])) s.len--; while (s.len > 0 && isspace((uint8_t) s.buf[s.len - 1])) s.len--;
MG_INFO(("RPC: %.*s", (int) s.len, s.buf)); MG_INFO(("RPC: %.*s", (int) s.len, s.buf));
struct mg_rpc_req r = {.head = &c->mgr->rpcs, memset(&r, 0, sizeof(struct mg_rpc_req));
.rpc = NULL, r.head = &c->mgr->rpcs;
.pfn = mg_pfn_iobuf, r.rpc = NULL;
.pfn_data = &io, r.pfn = mg_pfn_iobuf;
.req_data = NULL, r.pfn_data = &io;
.frame = s}; r.req_data = NULL;
r.frame = s;
mg_rpc_process(&r); mg_rpc_process(&r);
if (io.buf != NULL) { if (io.buf != NULL) {
MG_INFO((" %s", io.buf)); MG_INFO((" %s", io.buf));
@@ -84,6 +89,7 @@ static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
} }
mg_iobuf_free(&io); mg_iobuf_free(&io);
} else if (ev == MG_EV_CLOSE) { } else if (ev == MG_EV_CLOSE) {
mg_health_coredump_end();
mg_mdash_conn = NULL; mg_mdash_conn = NULL;
MG_INFO(("disconnected, ram %lu", 0)); MG_INFO(("disconnected, ram %lu", 0));
} }
@@ -91,31 +97,17 @@ static void mg_mdash_fn(struct mg_connection *c, int ev, void *ev_data) {
} }
static void mg_mdash_rpc_get_info(struct mg_rpc_req *r) { static void mg_mdash_rpc_get_info(struct mg_rpc_req *r) {
if (mg_health_valid()) { const char *reset_reason = mg_health_reason_str(mg_health_reason());
uint32_t *data = mg_health_record.backtrace; mg_rpc_ok(r, "{%m:%m,%m:%llu,%m:%m,%m:\"mws.%d\",%m:%M}", //
mg_rpc_ok(r, MG_ESC("fw_version"), MG_ESC(MG_FIRMWARE_VERSION), //
"{%m:%m,%m:%llu,%m:%m,%m:\"mws.%d\",%m:{%m:true," MG_ESC("uptime"), (uint64_t) (mg_millis() / 1000), //
"%m:{%m:\"0x%08lx\",%m:\"0x%08lx\",%m:\"0x%08lx\"}," MG_ESC("reboot_reason"), MG_ESC(reset_reason), //
"%m:{%m:\"0x%08lx\",%m:%m}}}", MG_ESC("arch"), MG_ARCH, //
MG_ESC("fw_version"), MG_ESC(MG_MDASH_FIRMWARE_VERSION), MG_ESC("crash"), mg_print_crash_record);
MG_ESC("uptime"), (uint64_t) (mg_millis() / 1000), }
MG_ESC("reboot_reason"),
MG_ESC(mg_health_reason_str(mg_health_reason())), MG_ESC("arch"), static void mg_mdash_rpc_mem_stats(struct mg_rpc_req *r) {
MG_ARCH, MG_ESC("report"), MG_ESC("valid"), MG_ESC("regs"), mg_rpc_ok(r, "%M", mg_print_mem_stats);
MG_ESC("sp"), (unsigned long) data[0], MG_ESC("lr"),
(unsigned long) data[1], MG_ESC("pc"), (unsigned long) data[2],
MG_ESC("stack"), MG_ESC("addr"), (unsigned long) data[0],
MG_ESC("data"), mg_print_base64,
(int) ((MG_HEALTH_BACKTRACE - 3) * sizeof(data[0])),
(uint8_t *) &data[3]);
} else {
mg_rpc_ok(r, "{%m:%m,%m:%llu,%m:%m,%m:\"mws.%d\",%m:{%m:false}}",
MG_ESC("fw_version"), MG_ESC(MG_MDASH_FIRMWARE_VERSION),
MG_ESC("uptime"), (uint64_t) (mg_millis() / 1000),
MG_ESC("reboot_reason"),
MG_ESC(mg_health_reason_str(mg_health_reason())), MG_ESC("arch"),
MG_ARCH, MG_ESC("report"), MG_ESC("valid"));
}
} }
static void mg_mdash_rpc_ota_begin(struct mg_rpc_req *r) { static void mg_mdash_rpc_ota_begin(struct mg_rpc_req *r) {
@@ -134,7 +126,7 @@ static void mg_mdash_rpc_ota_write(struct mg_rpc_req *r) {
mg_rpc_err(r, 500, "%m", MG_ESC("data required")); mg_rpc_err(r, 500, "%m", MG_ESC("data required"));
} else { } else {
struct mg_str s = mg_str_n(&r->frame.buf[ofs] + 1, (size_t) (len - 2)); struct mg_str s = mg_str_n(&r->frame.buf[ofs] + 1, (size_t) (len - 2));
size_t n = mg_base64_decode(s.buf, s.len, s.buf, s.len); // Decode in-place size_t n = mg_base64_decode(s.buf, s.len, s.buf, s.len); // Decode in-place
if (n == 0) { if (n == 0) {
mg_rpc_ok(r, "%m", MG_ESC("finished")); mg_rpc_ok(r, "%m", MG_ESC("finished"));
mg_ota_end(); mg_ota_end();
@@ -159,24 +151,68 @@ static void mg_mdash_rpc_ota_end(struct mg_rpc_req *r) {
// MG_ESC("percent")); // MG_ESC("percent"));
} }
static void rpc_coredump_begin(struct mg_rpc_req *r) {
size_t size = 0;
if (mg_health_coredump_begin(&size)) {
mg_rpc_ok(r, "{%m:%llu}", MG_ESC("size"), (uint64_t) size);
} else {
mg_rpc_err(r, 500, "%m", MG_ESC("failed"));
}
}
static void rpc_coredump_read(struct mg_rpc_req *r) {
uint8_t buf[768];
size_t len = sizeof(buf);
size_t offset = (size_t) mg_json_get_long(r->frame, "$.params.offset", -1);
if (mg_health_coredump_read(offset, buf, &len)) {
mg_rpc_ok(r, "{%m:\"%M\"}", MG_ESC("data"), mg_print_base64,
(int) len, buf);
} else {
mg_rpc_err(r, 500, "%m", MG_ESC("failed"));
}
}
static void rpc_coredump_end(struct mg_rpc_req *r) {
if (mg_health_coredump_end()) {
mg_rpc_ok(r, "true");
} else {
mg_rpc_err(r, 500, "%m", MG_ESC("failed"));
}
}
void mg_mdash_init(struct mg_mgr *mgr) { void mg_mdash_init(struct mg_mgr *mgr) {
MG_INFO(("Initialising mdash agent, key [%s]", MG_MDASH_KEY)); MG_INFO(("Initialising mdash agent, key [%s]", MG_MDASH_KEY));
mg_rpc_add(&mgr->rpcs, mg_str("RPC.List"), mg_rpc_list, NULL); mg_rpc_add(&mgr->rpcs, mg_str("RPC.List"), mg_rpc_list, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("Sys.GetInfo"), mg_mdash_rpc_get_info, NULL); mg_rpc_add(&mgr->rpcs, mg_str("Sys.GetInfo"), mg_mdash_rpc_get_info, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("Sys.MemStats"), mg_mdash_rpc_mem_stats, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("OTA.Begin"), mg_mdash_rpc_ota_begin, NULL); mg_rpc_add(&mgr->rpcs, mg_str("OTA.Begin"), mg_mdash_rpc_ota_begin, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("OTA.Write"), mg_mdash_rpc_ota_write, NULL); mg_rpc_add(&mgr->rpcs, mg_str("OTA.Write"), mg_mdash_rpc_ota_write, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("OTA.End"), mg_mdash_rpc_ota_end, NULL); mg_rpc_add(&mgr->rpcs, mg_str("OTA.End"), mg_mdash_rpc_ota_end, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("CoreDump.Begin"), rpc_coredump_begin, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("CoreDump.Read"), rpc_coredump_read, NULL);
mg_rpc_add(&mgr->rpcs, mg_str("CoreDump.End"), rpc_coredump_end, NULL);
} }
void mg_mdash_poll(struct mg_mgr *mgr) { void mg_mdash_poll(struct mg_mgr *mgr) {
#if MG_TLS == MG_TLS_NONE
(void) mgr, (void) mg_mdash_fn; // mdash needs wss://, nothing to do
#else
static uint64_t timer = 0; static uint64_t timer = 0;
if (mg_mdash_conn == NULL && mg_timer_expired(&timer, 1000, mg_millis())) { // No RPC handlers means mdash was never set up, or mg_mdash_free() ran.
// No key means mdash would reject us, so do not connect at all
if (mg_mdash_conn == NULL && mgr->rpcs != NULL && MG_MDASH_KEY[0] != '\0' &&
mg_timer_expired(&timer, 1000, mg_millis())) {
MG_INFO(("Connecting to %s", MG_MDASH_URL)); MG_INFO(("Connecting to %s", MG_MDASH_URL));
mg_mdash_conn = mg_ws_connect(mgr, MG_MDASH_URL, mg_mdash_fn, NULL, mg_mdash_conn = mg_ws_connect(mgr, MG_MDASH_URL, mg_mdash_fn, NULL,
"Origin: %s\r\n" "Origin: %s\r\n"
"Authorization: Bearer %s\r\n", "Authorization: Bearer %s\r\n",
MG_MDASH_URL, MG_MDASH_KEY); MG_MDASH_URL, MG_MDASH_KEY);
} }
#endif
}
void mg_mdash_free(struct mg_mgr *mgr) {
mg_rpc_del(&mgr->rpcs, NULL);
} }
#else #else
@@ -186,4 +222,7 @@ void mg_mdash_init(struct mg_mgr *mgr) {
void mg_mdash_poll(struct mg_mgr *mgr) { void mg_mdash_poll(struct mg_mgr *mgr) {
(void) mgr; (void) mgr;
} }
void mg_mdash_free(struct mg_mgr *mgr) {
(void) mgr;
}
#endif #endif
+1 -4
View File
@@ -12,13 +12,10 @@
#define MG_MDASH_KEY "" #define MG_MDASH_KEY ""
#endif #endif
#ifndef MG_MDASH_FIRMWARE_VERSION
#define MG_MDASH_FIRMWARE_VERSION "1.0.0"
#endif
#ifndef MG_ENABLE_MDASH #ifndef MG_ENABLE_MDASH
#define MG_ENABLE_MDASH 0 #define MG_ENABLE_MDASH 0
#endif #endif
void mg_mdash_init(struct mg_mgr *); void mg_mdash_init(struct mg_mgr *);
void mg_mdash_poll(struct mg_mgr *); void mg_mdash_poll(struct mg_mgr *);
void mg_mdash_free(struct mg_mgr *);
Loaded 100 of 925 files, more files were not shown because too many files have changed in this diff. Show more