use crate::axdr::{Data, DateTime};
use crate::codec::{Encode, Error, ErrorKind, Result, SliceWriter, Writer};
use crate::security::wrap::{Outgoing, protect_apdu};
use crate::security::{CryptoProvider, InvocationCounter, Protector, SecurityPolicy, SystemTitle};
use crate::xdlms::{Apdu, DataNotification, LongInvokeId, OptionalDateTime};
#[derive(Debug)]
pub struct PushSender<P, const N: usize = 512> {
protector: Protector<P>,
system_title: SystemTitle,
invocation_counter: InvocationCounter,
long_invoke_id: u32,
scratch: [u8; N],
}
impl<P: CryptoProvider, const N: usize> PushSender<P, N> {
pub fn new(
provider: P,
system_title: SystemTitle,
policy: SecurityPolicy,
invocation_counter: u32,
) -> Self {
Self {
protector: Protector::new(provider, policy.global()),
system_title,
invocation_counter: InvocationCounter::new(invocation_counter),
long_invoke_id: 0,
scratch: [0; N],
}
}
#[must_use]
pub const fn invocation_counter(&self) -> u32 {
self.invocation_counter.get()
}
#[must_use]
pub const fn system_title(&self) -> SystemTitle {
self.system_title
}
pub fn notify(
&mut self,
captured_at: Option<DateTime>,
body: &Data<'_>,
out: &mut [u8],
) -> Result<usize> {
let long_invoke_id = self.next_long_invoke_id();
let notification =
DataNotification { long_invoke_id, date_time: OptionalDateTime(captured_at), body: *body };
let mut w = SliceWriter::new(&mut self.scratch);
Apdu::DataNotification(notification).encode(&mut w)?;
let plain_len = w.written();
if self.protector.policy().is_none() {
let mut w = SliceWriter::new(out);
w.write_bytes(self.scratch.get(..plain_len).unwrap_or(&[]))?;
return Ok(w.written());
}
let ctx = Outgoing {
system_title: self.system_title,
invocation_counter: self.invocation_counter.next()?,
auth_key: self.protector.auth_key(),
policy: self.protector.policy(),
general_allowed: true,
};
let plain = self.scratch.get(..plain_len).unwrap_or(&[]);
protect_apdu(&self.protector, &ctx, plain, out)
}
fn next_long_invoke_id(&mut self) -> LongInvokeId {
self.long_invoke_id = self.long_invoke_id.wrapping_add(1) & 0x00FF_FFFF;
LongInvokeId::new(self.long_invoke_id)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PushDestination<'a> {
Wrapper(&'a str),
Local(&'a str),
Other(&'a str),
}
impl<'a> PushDestination<'a> {
#[must_use]
pub const fn as_str(&self) -> &'a str {
match self {
Self::Wrapper(s) | Self::Local(s) | Self::Other(s) => s,
}
}
}
pub fn check_body_fits(body: &Data<'_>, max_pdu_size: u16) -> Result<()> {
const OVERHEAD: usize = 1 + 4 + 13 + (1 + 9 + 5 + 1 + 4 + 12);
let needed = body.encoded_len().saturating_add(OVERHEAD);
if needed > usize::from(max_pdu_size) {
return Err(Error::new(ErrorKind::BufferTooSmall { needed: needed - usize::from(max_pdu_size) }, 0));
}
Ok(())
}