use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::{device::DataSchema, operation::CommandCode};
pub const DEFAULT_MAXIMUM_CATALOG_PROFILES: usize = 4096;
pub const DEFAULT_MAXIMUM_CATALOG_JSON_BYTES: usize = 8 * 1024 * 1024;
pub const MAXIMUM_CATALOG_PROFILES: usize = 65_536;
pub const MAXIMUM_CATALOG_JSON_BYTES: usize = 64 * 1024 * 1024;
pub const MAXIMUM_PROFILE_TEXT_BYTES: usize = 1024;
pub const MAXIMUM_PROFILE_COMMANDS: usize = 4096;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CatalogLimits {
pub profiles: usize,
pub json_bytes: usize,
}
impl Default for CatalogLimits {
fn default() -> Self {
Self {
profiles: DEFAULT_MAXIMUM_CATALOG_PROFILES,
json_bytes: DEFAULT_MAXIMUM_CATALOG_JSON_BYTES,
}
}
}
impl CatalogLimits {
pub const fn with_profiles(mut self, profiles: usize) -> Self {
self.profiles = profiles;
self
}
pub const fn with_json_bytes(mut self, json_bytes: usize) -> Self {
self.json_bytes = json_bytes;
self
}
pub const fn validate(self) -> Result<(), CatalogLoadError> {
if self.profiles == 0 || self.json_bytes == 0 {
return Err(CatalogLoadError::ZeroLimit);
}
if self.profiles > MAXIMUM_CATALOG_PROFILES {
return Err(CatalogLoadError::ProfileConfigurationLimit(self.profiles));
}
if self.json_bytes > MAXIMUM_CATALOG_JSON_BYTES {
return Err(CatalogLoadError::JsonConfigurationLimit(self.json_bytes));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct DeviceKey {
pub expanded_type: u16,
pub device_revision: u8,
}
impl DeviceKey {
pub const fn new(
expanded_type: u16,
device_revision: u8,
) -> Result<Self, crate::device::SchemaError> {
if expanded_type > 0x3fff {
return Err(crate::device::SchemaError::ExpandedDeviceType(
expanded_type,
));
}
Ok(Self {
expanded_type,
device_revision,
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ResponseCodeStatus {
Success,
Warning,
Error,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResponseCodeDefinition {
pub status: ResponseCodeStatus,
pub description: String,
}
impl ResponseCodeDefinition {
pub fn new(status: ResponseCodeStatus, description: impl Into<String>) -> Self {
Self {
status,
description: description.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DeviceProfile {
pub key: DeviceKey,
pub display_name: String,
pub source_revision: String,
pub responses: BTreeMap<u16, DataSchema>,
#[serde(default)]
pub response_codes: BTreeMap<u16, BTreeMap<u8, ResponseCodeDefinition>>,
}
impl DeviceProfile {
pub fn new(
key: DeviceKey,
display_name: impl Into<String>,
source_revision: impl Into<String>,
) -> Self {
Self {
key,
display_name: display_name.into(),
source_revision: source_revision.into(),
responses: BTreeMap::new(),
response_codes: BTreeMap::new(),
}
}
pub fn with_response(mut self, command: impl Into<CommandCode>, schema: DataSchema) -> Self {
self.responses.insert(command.into().get(), schema);
self
}
pub fn with_response_code(
mut self,
command: impl Into<CommandCode>,
code: u8,
definition: ResponseCodeDefinition,
) -> Self {
self.response_codes
.entry(command.into().get())
.or_default()
.insert(code, definition);
self
}
pub fn response(&self, command: CommandCode) -> Option<&DataSchema> {
self.responses.get(&command.get())
}
pub fn response_code(&self, command: CommandCode, code: u8) -> Option<&ResponseCodeDefinition> {
self.response_codes.get(&command.get())?.get(&code)
}
pub fn warning_codes(&self, command: CommandCode) -> Vec<u8> {
self.response_codes
.get(&command.get())
.into_iter()
.flat_map(|codes| codes.iter())
.filter_map(|(code, definition)| {
(definition.status == ResponseCodeStatus::Warning).then_some(*code)
})
.collect()
}
pub fn validate(&self) -> Result<(), crate::device::SchemaError> {
if self.key.expanded_type > 0x3fff {
return Err(crate::device::SchemaError::ExpandedDeviceType(
self.key.expanded_type,
));
}
if self.display_name.trim().is_empty() {
return Err(crate::device::SchemaError::EmptyProfileName);
}
if self.source_revision.trim().is_empty() {
return Err(crate::device::SchemaError::MissingSourceRevision);
}
if self.display_name.len() > MAXIMUM_PROFILE_TEXT_BYTES {
return Err(crate::device::SchemaError::ProfileTextTooLong(
"display_name",
self.display_name.len(),
));
}
if self.source_revision.len() > MAXIMUM_PROFILE_TEXT_BYTES {
return Err(crate::device::SchemaError::ProfileTextTooLong(
"source_revision",
self.source_revision.len(),
));
}
if self.responses.len() > MAXIMUM_PROFILE_COMMANDS
|| self.response_codes.len() > MAXIMUM_PROFILE_COMMANDS
{
return Err(crate::device::SchemaError::TooManyProfileCommands(
self.responses.len().max(self.response_codes.len()),
));
}
for schema in self.responses.values() {
schema.validate()?;
}
for codes in self.response_codes.values() {
for (code, definition) in codes {
if code & 0x80 != 0 {
return Err(crate::device::SchemaError::ResponseCode(*code));
}
if definition.description.trim().is_empty() {
return Err(crate::device::SchemaError::EmptyResponseCodeDescription(
*code,
));
}
if definition.description.len() > MAXIMUM_PROFILE_TEXT_BYTES {
return Err(crate::device::SchemaError::ProfileTextTooLong(
"response code description",
definition.description.len(),
));
}
}
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct DeviceCatalog {
profiles: BTreeMap<DeviceKey, DeviceProfile>,
limits: CatalogLimits,
}
impl Default for DeviceCatalog {
fn default() -> Self {
Self::new()
}
}
impl DeviceCatalog {
pub const fn new() -> Self {
Self {
profiles: BTreeMap::new(),
limits: CatalogLimits {
profiles: DEFAULT_MAXIMUM_CATALOG_PROFILES,
json_bytes: DEFAULT_MAXIMUM_CATALOG_JSON_BYTES,
},
}
}
pub fn with_limits(limits: CatalogLimits) -> Result<Self, CatalogLoadError> {
limits.validate()?;
Ok(Self {
profiles: BTreeMap::new(),
limits,
})
}
pub fn insert(
&mut self,
profile: DeviceProfile,
) -> Result<Option<DeviceProfile>, crate::device::SchemaError> {
profile.validate()?;
if !self.profiles.contains_key(&profile.key) && self.profiles.len() >= self.limits.profiles
{
return Err(crate::device::SchemaError::CatalogProfileLimit(
self.limits.profiles,
));
}
Ok(self.profiles.insert(profile.key, profile))
}
pub fn resolve(&self, key: DeviceKey) -> Option<&DeviceProfile> {
self.profiles.get(&key)
}
pub fn load_json(&mut self, bytes: &[u8]) -> Result<DeviceKey, CatalogLoadError> {
if bytes.len() > self.limits.json_bytes {
return Err(CatalogLoadError::JsonLimit {
actual: bytes.len(),
maximum: self.limits.json_bytes,
});
}
let profile: DeviceProfile = serde_json::from_slice(bytes)?;
let key = profile.key;
self.insert(profile)?;
Ok(key)
}
pub fn len(&self) -> usize {
self.profiles.len()
}
pub fn is_empty(&self) -> bool {
self.profiles.is_empty()
}
pub const fn limits(&self) -> CatalogLimits {
self.limits
}
}
#[derive(Debug, thiserror::Error)]
pub enum CatalogLoadError {
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error(transparent)]
Schema(#[from] crate::device::SchemaError),
#[error("catalog limits must be greater than zero")]
ZeroLimit,
#[error("catalog profile limit {0} exceeds the supported limit")]
ProfileConfigurationLimit(usize),
#[error("catalog JSON limit {0} exceeds the supported limit")]
JsonConfigurationLimit(usize),
#[error("JSON input contains {actual} bytes and exceeds the {maximum}-byte limit")]
JsonLimit {
actual: usize,
maximum: usize,
},
}