Skip to content
Projets

À propos

A Constrained Application Protocol(CoAP) library implemented in Rust.

Outils de développement

Comment ces chiffres sont mesurés

Progression mesurée des étoiles

in 24h
0
in 7 days
0
in 15 days
Historique en cours
in 1 month
Historique en cours

Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.

README.md

Original

coap-rs

CircleCI Windows Build Status Downloads Coverage Status MIT licensed

A fast and stable Constrained Application Protocol(CoAP) library implemented in Rust.

Features:

Documentation

Installation

First add this to your Cargo.toml:

[dependencies]
coap = "0.29"
coap-lite = "0.13.3"
tokio = {version = "^1.32", features = ["full"]}

Example

Server:

use coap::{
    router::{
        extract::{Json, Path, Query, State},
        get, post, Router,
    },
    Server,
};
use serde::Deserialize;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::Mutex;

#[derive(Debug, Clone, Default)]
pub struct RoomState {
    rooms: HashMap<String, f64>,
}

pub type RoomMutex = Arc<Mutex<RoomState>>;

#[derive(Debug, Deserialize)]
pub struct QueryArgs {
    room: String,
}

async fn get_temperature(
    Query(QueryArgs { room }): Query<QueryArgs>,
    state: State<RoomMutex>,
) -> String {
    let state = state.lock().await;
    if let Some(temp) = state.rooms.get(&room) {
        format!("Temperature in {room}: {temp}")
    } else {
        format!("Room {} not found", room)
    }
}

async fn set_temperature(
    Path(room): Path<String>,
    Json(temp): Json<f64>,
    State(state): State<RoomMutex>,
) -> String {
    let mut state = state.lock().await;
    state.rooms.insert(room, temp);
    "OK".to_string()
}

#[tokio::main]
async fn main() {
    let addr = "127.0.0.1:5683";

    let state = Arc::new(Mutex::new(RoomState {
        rooms: HashMap::new(),
    }));

    let router = Router::new()
        .route("/temperature", get(get_temperature))
        .route("/temperature/{room}", post(set_temperature))
        .with_state(state);

    let server = Server::new_udp(addr).unwrap();
    println!("Server up on {addr}");

    server.serve(router).await.unwrap();
}

Client:

use coap::UdpCoAPClient;

#[tokio::main]
async fn main() {
    let url = "coap://127.0.0.1:5683/temperature?room=kitchen";
    println!("Client request: {}", url);

    let response = UdpCoAPClient::get(url).await.unwrap();
    println!("Server reply: {}", String::from_utf8(response.message.payload).unwrap());
}

Confirmable requests are sent once and retried up to four times by default. Use set_transport_retries to change the number of retries after the initial attempt; setting it to zero disables retries. Non-confirmable requests are never retried.

Resource Discovery:

Resource discovery at /.well-known/core is disabled by default. Enable it on the router and optionally add link attributes to routes:

let router = Router::new()
    .route(
        "/temperature",
        get(get_temperature).link_attribute(LINK_ATTR_RESOURCE_TYPE, "temperature"),
    )
    .enable_discovery(true);

Discover the resources with the client:

use coap::UdpCoAPClient;

#[tokio::main]
async fn main() {
    let url = "coap://127.0.0.1:5683?rt=temperature";
    println!("Client request: {}", url);

    let links = UdpCoAPClient::discover(url).await.unwrap();
    for link in links {
        println!("Server resource: {} {:?}", link.href, link.attributes);
    }
}

Benchmark

$ cargo bench

Explorer des projets similaires

Chargement…