coap-zero 0.3.0

CoAP protocol implementation for no_std without alloc
Documentation
// Copyright Open Logistics Foundation
//
// Licensed under the Open Logistics Foundation License 1.3.
// For details on the licensing terms, see the LICENSE file.
// SPDX-License-Identifier: OLFL-1.3

use bondrewd::{BitfieldEnum, Bitfields};

use super::{
    codes::{Code, EncodedCode},
    token::TokenLength,
    Error, Type,
};

/// 4 byte Header of a CoAP Message
#[derive(Bitfields, Debug, PartialEq, Eq)]
#[bondrewd(enforce_bytes = 4)]
pub(crate) struct MessageHeader {
    #[bondrewd(bit_length = 2)]
    version: u8,
    #[bondrewd(bit_length = 2, enum_primitive = "u8")]
    message_type: Type,
    #[bondrewd(bit_length = 4)]
    token_length: u8,
    #[bondrewd(struct_size = 1)]
    code: EncodedCode,
    #[bondrewd(endianness = "big")]
    message_id: u16,
}

impl MessageHeader {
    /// Creates a new Message Header
    pub(crate) fn new(
        version: u8,
        message_type: Type,
        token_length: TokenLength,
        code: EncodedCode,
        message_id: u16,
    ) -> Self {
        Self {
            version,
            message_type,
            token_length: token_length as u8,
            code,
            message_id,
        }
    }

    /// CoAP Protocol Version
    pub(crate) fn version(&self) -> u8 {
        self.version
    }

    /// Type of the message
    pub(crate) fn message_type(&self) -> Type {
        self.message_type
    }

    /// Length of Token
    pub(crate) fn token_length(&self) -> Result<TokenLength, Error> {
        self.token_length.try_into()
    }

    /// Code of the message
    pub(crate) fn code(&self) -> Result<Code, Error> {
        self.code.try_into()
    }

    /// Id of the message
    pub(crate) fn message_id(&self) -> u16 {
        self.message_id
    }
}