1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
use embedded_nal::UdpFullStack;

use log::info;

// This function works on *any* UdpFullStack, including embedded ones -- only main() is what makes
// this use POSIX sockets.
//
// There *is* still a bit of a std dependency in that the code can't know when the next request is
// here, so right now it's using std::thread::sleep to stay idle, but that's not realted to how
// coap-message us used here.
fn run<S>(stack: &mut S)
where
    S: UdpFullStack,
{
    let mut sock = stack.socket().expect("Can't create a socket");

    let log = Some(coap_message_demos::log::Log::start_once());

    let mut handler = coap_message_demos::full_application_tree(log);

    stack.bind(&mut sock, 5683).expect("Can't bind to port");
    info!("Server is ready.");

    loop {
        match embedded_nal_minimal_coapserver::poll(stack, &mut sock, &mut handler) {
            Err(embedded_nal::nb::Error::WouldBlock) => {
                // See <https://github.com/rust-embedded-community/embedded-nal/issues/47>
                std::thread::sleep(std::time::Duration::from_millis(50));
            }
            e => e.expect("UDP error during send/receive"),
        }
    }
}

fn main() {
    let mut stack = std_embedded_nal::Stack::default();

    run(&mut stack);
}