|
| 1 | +// Copyright (c) 2025 Witekio |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +#![no_std] |
| 5 | +#![allow(unexpected_cfgs)] |
| 6 | + |
| 7 | +use log::{error, info, warn}; |
| 8 | +use static_cell::ConstStaticCell; |
| 9 | +use zephyr::error::Result; |
| 10 | +use zephyr::net::udp::UdpSocket; |
| 11 | + |
| 12 | +#[no_mangle] |
| 13 | +extern "C" fn rust_main() { |
| 14 | + unsafe { |
| 15 | + zephyr::set_logger().unwrap(); |
| 16 | + } |
| 17 | + |
| 18 | + let res = run_echo(); |
| 19 | + |
| 20 | + if let Err(e) = res { |
| 21 | + error!("Echo server terminated with error {}", e); |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +fn run_echo() -> Result<()> { |
| 26 | + // Don't allocate the large RX buffer on the stack |
| 27 | + static RX_BUF: ConstStaticCell<[u8; 2048]> = ConstStaticCell::new([0; 2048]); |
| 28 | + let rx_buf = RX_BUF.take(); |
| 29 | + |
| 30 | + let sockaddr = "0.0.0.0:4242".parse().unwrap(); |
| 31 | + let sock = UdpSocket::bind(&sockaddr)?; |
| 32 | + |
| 33 | + info!("Waiting for UDP packets on port 4242"); |
| 34 | + |
| 35 | + loop { |
| 36 | + let (n, peer) = sock.recv_from(rx_buf)?; |
| 37 | + |
| 38 | + // Note that being able to set the MSG_TRUNC sockopt is not implemented yet so it should |
| 39 | + // not be possible to get n > rx_buf.len(), but it's probably still worth including the |
| 40 | + // check for when this sockopt is implemented. |
| 41 | + let n_trunc = n.min(rx_buf.len()); |
| 42 | + if n != n_trunc { |
| 43 | + warn!("Data truncated, got {} / {} bytes", n_trunc, n); |
| 44 | + } |
| 45 | + |
| 46 | + info!("Echoing {} bytes back to peer address {:?}", n_trunc, peer); |
| 47 | + let _ = sock.send_to(&rx_buf[0..n_trunc], &peer)?; |
| 48 | + } |
| 49 | +} |
0 commit comments