use crate::error::DateTimeError;
use chrono::prelude::*;
use core::fmt;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy)]
pub struct PositionLLA {
pub lon: f64,
pub lat: f64,
pub alt: f64,
}
pub(crate) trait ToLLA {
fn to_lla(&self) -> PositionLLA;
}
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy)]
pub struct PositionECEF {
pub x: f64,
pub y: f64,
pub z: f64,
}
pub(crate) trait ToECEF {
fn to_ecef(&self) -> PositionECEF;
}
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Velocity {
pub speed: f64,
pub heading: f64,
}
pub(crate) trait ToVelocity {
fn to_velocity(&self) -> Velocity;
}
impl<T> From<&T> for PositionLLA
where
T: ToLLA,
{
fn from(packet: &T) -> Self {
packet.to_lla()
}
}
impl<T> From<&T> for Velocity
where
T: ToVelocity,
{
fn from(packet: &T) -> Self {
packet.to_velocity()
}
}
impl<T> From<&T> for PositionECEF
where
T: ToECEF,
{
fn from(packet: &T) -> Self {
packet.to_ecef()
}
}
pub(crate) trait ToDateTime {
fn to_datetime(&self) -> Result<DateTime<Utc>, DateTimeError>;
}
pub(crate) fn datetime_from_components(
year: u16,
month: u8,
day: u8,
hour: u8,
min: u8,
sec: u8,
nanos: i32,
) -> Result<DateTime<Utc>, DateTimeError> {
let date = NaiveDate::from_ymd_opt(i32::from(year), u32::from(month), u32::from(day))
.ok_or(DateTimeError::InvalidDate)?;
let time = NaiveTime::from_hms_opt(u32::from(hour), u32::from(min), u32::from(sec))
.ok_or(DateTimeError::InvalidTime)?;
const NANOS_LIM: u32 = 1_000_000_000;
if (nanos.wrapping_abs() as u32) >= NANOS_LIM {
return Err(DateTimeError::InvalidNanoseconds);
}
let dt = NaiveDateTime::new(date, time) + chrono::Duration::nanoseconds(i64::from(nanos));
Ok(DateTime::from_naive_utc_and_offset(dt, Utc))
}
#[allow(dead_code, reason = "It is only dead code in some feature sets")]
pub(crate) struct FieldIter<I>(pub(crate) I);
impl<I> fmt::Debug for FieldIter<I>
where
I: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(feature = "serde")]
impl<I> serde::Serialize for FieldIter<I>
where
I: Iterator + Clone,
I::Item: serde::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_seq(self.0.clone())
}
}