matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for OTA Software Update Provider Cluster
//! Cluster ID: 0x0029
//!
//! This file is automatically generated from OTAProvider.xml

use crate::tlv;
use anyhow;


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex};

// Enum definitions

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum ApplyUpdateAction {
    /// Apply the update.
    Proceed = 0,
    /// Wait at least the given delay time.
    Awaitnextaction = 1,
    /// The OTA Provider is conveying a desire to rescind a previously provided Software Image.
    Discontinue = 2,
}

impl ApplyUpdateAction {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(ApplyUpdateAction::Proceed),
            1 => Some(ApplyUpdateAction::Awaitnextaction),
            2 => Some(ApplyUpdateAction::Discontinue),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<ApplyUpdateAction> for u8 {
    fn from(val: ApplyUpdateAction) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum DownloadProtocol {
    /// Indicates support for synchronous BDX.
    Bdxsynchronous = 0,
    /// Indicates support for asynchronous BDX.
    Bdxasynchronous = 1,
    /// Indicates support for HTTPS.
    Https = 2,
    /// Indicates support for vendor specific protocol.
    Vendorspecific = 3,
}

impl DownloadProtocol {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(DownloadProtocol::Bdxsynchronous),
            1 => Some(DownloadProtocol::Bdxasynchronous),
            2 => Some(DownloadProtocol::Https),
            3 => Some(DownloadProtocol::Vendorspecific),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<DownloadProtocol> for u8 {
    fn from(val: DownloadProtocol) -> Self {
        val as u8
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[repr(u8)]
pub enum Status {
    /// Indicates that the OTA Provider has an update available.
    Updateavailable = 0,
    /// Indicates OTA Provider may have an update, but it is not ready yet.
    Busy = 1,
    /// Indicates that there is definitely no update currently available from the OTA Provider.
    Notavailable = 2,
    /// Indicates that the requested download protocol is not supported by the OTA Provider.
    Downloadprotocolnotsupported = 3,
}

impl Status {
    /// Convert from u8 value
    pub fn from_u8(value: u8) -> Option<Self> {
        match value {
            0 => Some(Status::Updateavailable),
            1 => Some(Status::Busy),
            2 => Some(Status::Notavailable),
            3 => Some(Status::Downloadprotocolnotsupported),
            _ => None,
        }
    }

    /// Convert to u8 value
    pub fn to_u8(self) -> u8 {
        self as u8
    }
}

impl From<Status> for u8 {
    fn from(val: Status) -> Self {
        val as u8
    }
}

// Command encoders

/// Parameters for QueryImage command
pub struct QueryImageParams {
    pub vendor_id: u16,
    pub product_id: u16,
    pub software_version: u32,
    pub protocols_supported: Vec<DownloadProtocol>,
    pub hardware_version: u16,
    pub location: String,
    pub requestor_can_consent: bool,
    pub metadata_for_provider: Vec<u8>,
}

/// Encode QueryImage command (0x00)
pub fn encode_query_image(params: QueryImageParams) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt16(params.vendor_id)).into(),
        (1, tlv::TlvItemValueEnc::UInt16(params.product_id)).into(),
        (2, tlv::TlvItemValueEnc::UInt32(params.software_version)).into(),
        (3, tlv::TlvItemValueEnc::StructAnon(params.protocols_supported.into_iter().map(|v| (0, tlv::TlvItemValueEnc::UInt8(v.to_u8())).into()).collect())).into(),
        (4, tlv::TlvItemValueEnc::UInt16(params.hardware_version)).into(),
        (5, tlv::TlvItemValueEnc::String(params.location)).into(),
        (6, tlv::TlvItemValueEnc::Bool(params.requestor_can_consent)).into(),
        (7, tlv::TlvItemValueEnc::OctetString(params.metadata_for_provider)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode ApplyUpdateRequest command (0x02)
pub fn encode_apply_update_request(update_token: Vec<u8>, new_version: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(update_token)).into(),
        (1, tlv::TlvItemValueEnc::UInt32(new_version)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode NotifyUpdateApplied command (0x04)
pub fn encode_notify_update_applied(update_token: Vec<u8>, software_version: u32) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(update_token)).into(),
        (1, tlv::TlvItemValueEnc::UInt32(software_version)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

#[derive(Debug, serde::Serialize)]
pub struct QueryImageResponse {
    pub status: Option<Status>,
    pub delayed_action_time: Option<u32>,
    pub image_uri: Option<String>,
    pub software_version: Option<u32>,
    pub software_version_string: Option<String>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub update_token: Option<Vec<u8>>,
    pub user_consent_needed: Option<bool>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub metadata_for_requestor: Option<Vec<u8>>,
}

#[derive(Debug, serde::Serialize)]
pub struct ApplyUpdateResponse {
    pub action: Option<ApplyUpdateAction>,
    pub delayed_action_time: Option<u32>,
}

// Command response decoders

/// Decode QueryImageResponse command response (01)
pub fn decode_query_image_response(inp: &tlv::TlvItemValue) -> anyhow::Result<QueryImageResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(QueryImageResponse {
                status: item.get_int(&[0]).and_then(|v| Status::from_u8(v as u8)),
                delayed_action_time: item.get_int(&[1]).map(|v| v as u32),
                image_uri: item.get_string_owned(&[2]),
                software_version: item.get_int(&[3]).map(|v| v as u32),
                software_version_string: item.get_string_owned(&[4]),
                update_token: item.get_octet_string_owned(&[5]),
                user_consent_needed: item.get_bool(&[6]),
                metadata_for_requestor: item.get_octet_string_owned(&[7]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ApplyUpdateResponse command response (03)
pub fn decode_apply_update_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ApplyUpdateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ApplyUpdateResponse {
                action: item.get_int(&[0]).and_then(|v| ApplyUpdateAction::from_u8(v as u8)),
                delayed_action_time: item.get_int(&[1]).map(|v| v as u32),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}