matc 0.1.3

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

#![allow(clippy::too_many_arguments)]

use crate::tlv;
use anyhow;
use serde_json;


// 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: Option<u16>,
    pub location: Option<String>,
    pub requestor_can_consent: Option<bool>,
    pub metadata_for_provider: Option<Vec<u8>>,
}

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

// Command listing

pub fn get_command_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x00, "QueryImage"),
        (0x02, "ApplyUpdateRequest"),
        (0x04, "NotifyUpdateApplied"),
    ]
}

pub fn get_command_name(cmd_id: u32) -> Option<&'static str> {
    match cmd_id {
        0x00 => Some("QueryImage"),
        0x02 => Some("ApplyUpdateRequest"),
        0x04 => Some("NotifyUpdateApplied"),
        _ => None,
    }
}

pub fn get_command_schema(cmd_id: u32) -> Option<Vec<crate::clusters::codec::CommandField>> {
    match cmd_id {
        0x00 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "vendor_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "product_id", kind: crate::clusters::codec::FieldKind::U16, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 2, name: "software_version", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 3, name: "protocols_supported", kind: crate::clusters::codec::FieldKind::List { entry_type: "DownloadProtocolEnum" }, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 4, name: "hardware_version", kind: crate::clusters::codec::FieldKind::U16, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 5, name: "location", kind: crate::clusters::codec::FieldKind::String, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 6, name: "requestor_can_consent", kind: crate::clusters::codec::FieldKind::Bool, optional: true, nullable: false },
            crate::clusters::codec::CommandField { tag: 7, name: "metadata_for_provider", kind: crate::clusters::codec::FieldKind::OctetString, optional: true, nullable: false },
        ]),
        0x02 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "update_token", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "new_version", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        0x04 => Some(vec![
            crate::clusters::codec::CommandField { tag: 0, name: "update_token", kind: crate::clusters::codec::FieldKind::OctetString, optional: false, nullable: false },
            crate::clusters::codec::CommandField { tag: 1, name: "software_version", kind: crate::clusters::codec::FieldKind::U32, optional: false, nullable: false },
        ]),
        _ => None,
    }
}

pub fn encode_command_json(cmd_id: u32, args: &serde_json::Value) -> anyhow::Result<Vec<u8>> {
    match cmd_id {
        0x00 => Err(anyhow::anyhow!("command \"QueryImage\" has complex args: use raw mode")),
        0x02 => {
        let update_token = crate::clusters::codec::json_util::get_octstr(args, "update_token")?;
        let new_version = crate::clusters::codec::json_util::get_u32(args, "new_version")?;
        encode_apply_update_request(update_token, new_version)
        }
        0x04 => {
        let update_token = crate::clusters::codec::json_util::get_octstr(args, "update_token")?;
        let software_version = crate::clusters::codec::json_util::get_u32(args, "software_version")?;
        encode_notify_update_applied(update_token, software_version)
        }
        _ => Err(anyhow::anyhow!("unknown command ID: 0x{:02X}", cmd_id)),
    }
}

#[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"))
    }
}

// Typed facade (invokes + reads)

/// Invoke `QueryImage` command on cluster `OTA Software Update Provider`.
pub async fn query_image(conn: &crate::controller::Connection, endpoint: u16, params: QueryImageParams) -> anyhow::Result<QueryImageResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_PROVIDER, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_PROVIDER_CMD_ID_QUERYIMAGE, &encode_query_image(params)?).await?;
    decode_query_image_response(&tlv)
}

/// Invoke `ApplyUpdateRequest` command on cluster `OTA Software Update Provider`.
pub async fn apply_update_request(conn: &crate::controller::Connection, endpoint: u16, update_token: Vec<u8>, new_version: u32) -> anyhow::Result<ApplyUpdateResponse> {
    let tlv = conn.invoke_request2(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_PROVIDER, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_PROVIDER_CMD_ID_APPLYUPDATEREQUEST, &encode_apply_update_request(update_token, new_version)?).await?;
    decode_apply_update_response(&tlv)
}

/// Invoke `NotifyUpdateApplied` command on cluster `OTA Software Update Provider`.
pub async fn notify_update_applied(conn: &crate::controller::Connection, endpoint: u16, update_token: Vec<u8>, software_version: u32) -> anyhow::Result<()> {
    conn.invoke_request(endpoint, crate::clusters::defs::CLUSTER_ID_OTA_SOFTWARE_UPDATE_PROVIDER, crate::clusters::defs::CLUSTER_OTA_SOFTWARE_UPDATE_PROVIDER_CMD_ID_NOTIFYUPDATEAPPLIED, &encode_notify_update_applied(update_token, software_version)?).await?;
    Ok(())
}