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
40
41
42
43
44
45
#![feature(async_closure)]

extern crate coap;

use coap::Server;
use tokio::runtime::Runtime;

use log::info;

fn main() {
    let addr = "localhost:5683";

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

    Runtime::new().unwrap().block_on(async move {
        let mut server = Server::new(addr).unwrap();
        println!("Server up on {}", addr);
        info!("Server up on {}", addr);

        use coap_handler::Handler;

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

        server
            .run(move |mut request| {
                // Having a shared reference to a single handler works for this server because it
                // allows the handler to be FnMut and not Sync -- essentially, because the server
                // promises not to become multithreaded.

                let extracted = handler.extract_request_data(&request.message);

                if let Some(r) = request.response.as_mut() {
                    handler.build_response(&mut r.message, extracted);
                }

                // By running all the processing in the sync part of the function (because the
                // coap-handler doesn't cater for async right now), the &mut handler reference we use
                // does not need to live across possible await points, and is thus usable.

                async { request.response }
            })
            .await
            .unwrap();
    });
}