coap_crate/
coap_crate.rs

1extern crate coap;
2
3use coap::Server;
4use tokio::runtime::Runtime;
5
6use log::info;
7
8fn main() {
9    let addr = "localhost:5683";
10
11    let log = coap_message_demos::log::Log::start_once();
12
13    Runtime::new().unwrap().block_on(async move {
14        let server = Server::new_udp(addr).unwrap();
15        println!("Server up on {}", addr);
16        info!("Server up on {}", addr);
17
18        use coap_handler::Handler;
19
20        // Unlike in coap 0.11, the run closure is now Fn, so we can't have an exclusive reference
21        // to a handler but need to fan out. To avoid the need for a mutex, we just use a handler
22        // factory.
23        //
24        // Note that this may have "funny" effects w/rt the CBOR editable items, which are shared
25        // only across handlers spawned from a single full_application_tree call.
26        let handler = || coap_message_demos::full_application_tree(Some(log));
27
28        server
29            .run(
30                move |mut request: Box<coap_lite::CoapRequest<std::net::SocketAddr>>| {
31                    let mut handler = handler();
32
33                    // We can just unwrap because the tokio based surver unwinds crashing handlers.
34                    // We could still choose to rather render the errors, because a) it'd provide
35                    // concrete information to the client and b) it sends a response instead of
36                    // leaving the client hanging -- see the coap-lite example for how that is
37                    // done.
38
39                    let extracted = handler.extract_request_data(&request.message).unwrap();
40
41                    if let Some(r) = request.response.as_mut() {
42                        handler.build_response(&mut r.message, extracted).unwrap();
43                    }
44
45                    async { request }
46                },
47            )
48            .await
49            .unwrap();
50    });
51}