use crate::wifi::{elements, ELEMENT_VENDOR};
use crate::{
BasicId, Error, HeightType, IdType, Location, Message, OperatorLocationType, Status, System,
UaType,
};
pub const PAYLOAD_LEN: usize = 91;
pub const WIFI_OUI: [u8; 3] = [0x26, 0x37, 0x12];
pub const SUBCOMMAND_FLIGHT_INFO: u8 = 0x10;
pub const SUBCOMMAND_FLIGHT_PURPOSE: u8 = 0x11;
pub const CRC_INIT: u16 = 0x3692;
pub fn crc16(data: &[u8]) -> u16 {
let mut crc = CRC_INIT;
for &b in data {
crc ^= b as u16;
for _ in 0..8 {
crc = if crc & 1 != 0 {
(crc >> 1) ^ 0x8408
} else {
crc >> 1
};
}
}
crc
}
const PRODUCTS: &[(u8, &str)] = &[
(1, "Inspire 1"),
(2, "Phantom 3 Series"),
(3, "Phantom 3 Series"),
(4, "Phantom 3 Std"),
(5, "M100"),
(6, "ACEONE"),
(7, "WKM"),
(8, "NAZA"),
(9, "A2"),
(10, "A3"),
(11, "Phantom 4"),
(12, "MG1"),
(14, "M600"),
(15, "Phantom 3 4k"),
(16, "Mavic Pro"),
(17, "Inspire 2"),
(18, "Phantom 4 Pro"),
(20, "N2"),
(21, "Spark"),
(23, "M600 Pro"),
(24, "Mavic Air"),
(25, "M200"),
(26, "Phantom 4 Series"),
(27, "Phantom 4 Adv"),
(28, "M210"),
(30, "M210RTK"),
(31, "A3_AG"),
(32, "MG2"),
(34, "MG1A"),
(35, "Phantom 4 RTK"),
(36, "Phantom 4 Pro V2.0"),
(38, "MG1P"),
(40, "MG1P-RTK"),
(41, "Mavic 2"),
(44, "M200 V2 Series"),
(51, "Mavic 2 Enterprise"),
(53, "Mavic Mini"),
(58, "Mavic Air 2"),
(59, "P4M"),
(60, "M300 RTK"),
(61, "DJI FPV"),
(63, "Mini 2"),
(64, "AGRAS T10"),
(65, "AGRAS T30"),
(66, "Air 2S"),
(67, "M30"),
(68, "DJI Mavic 3"),
(69, "Mavic 2 Enterprise Advanced"),
(70, "Mini SE"),
];
pub fn product_name(code: u8) -> Option<&'static str> {
PRODUCTS.iter().find(|(c, _)| *c == code).map(|(_, n)| *n)
}
pub fn raw_to_degrees(raw: i32) -> f64 {
(raw as f64 / 1e7).to_degrees()
}
fn pair(lat_raw: i32, lon_raw: i32) -> Option<(f64, f64)> {
if lat_raw == 0 && lon_raw == 0 {
None
} else {
Some((raw_to_degrees(lat_raw), raw_to_degrees(lon_raw)))
}
}
fn text(bytes: &[u8]) -> Option<&str> {
let end = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
let s = &bytes[..end];
if !s.is_empty() && s.iter().all(|b| (0x20..0x7f).contains(b)) {
core::str::from_utf8(s).ok()
} else {
None
}
}
struct Reader<'a> {
b: &'a [u8],
at: usize,
}
impl<'a> Reader<'a> {
fn take<const N: usize>(&mut self) -> [u8; N] {
let mut out = [0u8; N];
out.copy_from_slice(&self.b[self.at..self.at + N]);
self.at += N;
out
}
fn u8(&mut self) -> u8 {
self.take::<1>()[0]
}
fn u16(&mut self) -> u16 {
u16::from_le_bytes(self.take())
}
fn i16(&mut self) -> i16 {
i16::from_le_bytes(self.take())
}
fn i32(&mut self) -> i32 {
i32::from_le_bytes(self.take())
}
fn u64(&mut self) -> u64 {
u64::from_le_bytes(self.take())
}
}
const RECORD_V2_LEN: usize = 87;
const RECORD_V1_LEN: usize = 75;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FlightInfo {
pub version: u8,
pub sequence: u16,
pub state_info: u16,
pub serial: [u8; 16],
pub longitude_raw: i32,
pub latitude_raw: i32,
pub altitude_raw: i16,
pub height_raw: i16,
pub v_north: i16,
pub v_east: i16,
pub v_up: i16,
pub pitch_roll_raw: Option<(i16, i16)>,
pub yaw_raw: i16,
pub gps_time_ms: Option<u64>,
pub app_latitude_raw: Option<i32>,
pub app_longitude_raw: Option<i32>,
pub home_longitude_raw: i32,
pub home_latitude_raw: i32,
pub product_type: u8,
pub uuid_len: u8,
pub uuid: [u8; 20],
}
impl FlightInfo {
pub fn decode(payload: &[u8]) -> Result<Self, Error> {
if payload.len() < PAYLOAD_LEN {
return Err(Error::TooShort {
need: PAYLOAD_LEN,
got: payload.len(),
});
}
let computed = crc16(&payload[..PAYLOAD_LEN - 2]);
let found = u16::from_le_bytes([payload[PAYLOAD_LEN - 2], payload[PAYLOAD_LEN - 1]]);
if computed != found {
return Err(Error::ChecksumMismatch { computed, found });
}
Self::decode_unchecked(payload)
}
pub fn decode_unchecked(payload: &[u8]) -> Result<Self, Error> {
let need = 2 + RECORD_V2_LEN;
if payload.len() < need {
return Err(Error::TooShort {
need,
got: payload.len(),
});
}
if payload[1] != SUBCOMMAND_FLIGHT_INFO {
return Err(Error::NotRemoteId);
}
Self::decode_record(&payload[2..])
}
pub fn decode_record(record: &[u8]) -> Result<Self, Error> {
let version = *record.first().ok_or(Error::TooShort { need: 1, got: 0 })?;
let need = if version == 1 {
RECORD_V1_LEN
} else {
RECORD_V2_LEN
};
if record.len() < need {
return Err(Error::TooShort {
need,
got: record.len(),
});
}
let mut r = Reader { b: record, at: 1 };
let sequence = r.u16();
let state_info = r.u16();
let serial = r.take::<16>();
let longitude_raw = r.i32();
let latitude_raw = r.i32();
let altitude_raw = r.i16();
let height_raw = r.i16();
let v_north = r.i16();
let v_east = r.i16();
let v_up = r.i16();
let (pitch_roll_raw, yaw_raw, gps_time_ms, app_latitude_raw, app_longitude_raw) =
if version == 1 {
let pitch = r.i16();
let roll = r.i16();
(Some((pitch, roll)), r.i16(), None, None, None)
} else {
let yaw = r.i16();
let t = r.u64();
let alat = r.i32();
let alon = r.i32();
(None, yaw, Some(t), Some(alat), Some(alon))
};
let home_longitude_raw = r.i32();
let home_latitude_raw = r.i32();
let product_type = r.u8();
let uuid_len = r.u8();
let uuid = r.take::<20>();
Ok(FlightInfo {
version,
sequence,
state_info,
serial,
longitude_raw,
latitude_raw,
altitude_raw,
height_raw,
v_north,
v_east,
v_up,
pitch_roll_raw,
yaw_raw,
gps_time_ms,
app_latitude_raw,
app_longitude_raw,
home_longitude_raw,
home_latitude_raw,
product_type,
uuid_len,
uuid,
})
}
pub fn serial_str(&self) -> Option<&str> {
text(&self.serial)
}
pub fn uuid_str(&self) -> Option<&str> {
let n = (self.uuid_len as usize).min(self.uuid.len());
text(&self.uuid[..n])
}
pub fn position(&self) -> Option<(f64, f64)> {
pair(self.latitude_raw, self.longitude_raw)
}
pub fn home_position(&self) -> Option<(f64, f64)> {
pair(self.home_latitude_raw, self.home_longitude_raw)
}
pub fn pilot_position(&self) -> Option<(f64, f64)> {
pair(self.app_latitude_raw?, self.app_longitude_raw?)
}
pub fn yaw_deg(&self) -> f32 {
self.yaw_raw as f32 / 100.0
}
pub fn key(&self) -> u64 {
self.serial.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &b| {
(h ^ b as u64).wrapping_mul(0x0000_0100_0000_01b3)
})
}
pub fn product_name(&self) -> Option<&'static str> {
product_name(self.product_type)
}
pub fn altitude_m(&self) -> f32 {
self.altitude_raw as f32 * 0.3048
}
pub fn height_m(&self) -> f32 {
self.height_raw as f32 * 0.3048
}
pub fn messages(&self) -> impl Iterator<Item = Message> {
let basic = self.serial_str().and_then(|s| {
BasicId::new(IdType::SerialNumber, UaType::HelicopterOrMultirotor, s)
.ok()
.map(Message::BasicId)
});
let location = self.position().map(|(lat, lon)| {
Message::Location(Location {
status: Status::Undeclared,
height_type: HeightType::AboveTakeoff,
latitude: lat,
longitude: lon,
timestamp: self
.gps_time_ms
.map(|t| ((t % 3_600_000) / 100) as f32 / 10.0),
..Location::default()
})
});
let system = self.pilot_position().map(|(lat, lon)| {
Message::System(System {
operator_location_type: OperatorLocationType::LiveGnss,
operator_latitude: lat,
operator_longitude: lon,
timestamp: self
.gps_time_ms
.map(|t| (t / 1000).saturating_sub(SYSTEM_EPOCH_UNIX))
.and_then(|s| u32::try_from(s).ok())
.unwrap_or(0),
..System::default()
})
});
basic.into_iter().chain(location).chain(system)
}
}
const SYSTEM_EPOCH_UNIX: u64 = 1_546_300_800;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FlightPurpose<'a> {
pub serial: [u8; 16],
pub drone_id: &'a [u8],
pub purpose: &'a [u8],
}
impl<'a> FlightPurpose<'a> {
pub fn decode(record: &'a [u8]) -> Result<Self, Error> {
let need = 16 + 1 + 10 + 1;
if record.len() < need {
return Err(Error::TooShort {
need,
got: record.len(),
});
}
let mut serial = [0u8; 16];
serial.copy_from_slice(&record[..16]);
let id_len = (record[16] as usize).min(10);
let drone_id = &record[17..17 + id_len];
let purpose_len = record[27] as usize;
let rest = &record[28..];
let purpose = &rest[..purpose_len.min(rest.len())];
Ok(FlightPurpose {
serial,
drone_id,
purpose,
})
}
pub fn serial_str(&self) -> Option<&str> {
text(&self.serial)
}
pub fn drone_id_str(&self) -> Option<&str> {
text(self.drone_id)
}
pub fn purpose_str(&self) -> Option<&str> {
text(self.purpose)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum WifiDroneId<'a> {
FlightInfo(FlightInfo),
FlightPurpose(FlightPurpose<'a>),
Other {
subcommand: u8,
record: &'a [u8],
},
}
pub fn parse_vendor_element(info: &[u8]) -> Result<WifiDroneId<'_>, Error> {
if info.len() < 3 || info[..3] != WIFI_OUI {
return Err(Error::NotRemoteId);
}
if info.len() < 7 {
return Err(Error::TooShort {
need: 7,
got: info.len(),
});
}
let subcommand = info[6];
let record = &info[7..];
match subcommand {
SUBCOMMAND_FLIGHT_INFO => FlightInfo::decode_record(record).map(WifiDroneId::FlightInfo),
SUBCOMMAND_FLIGHT_PURPOSE => FlightPurpose::decode(record).map(WifiDroneId::FlightPurpose),
_ => Ok(WifiDroneId::Other { subcommand, record }),
}
}
pub fn find_in_elements(ies: &[u8]) -> Option<WifiDroneId<'_>> {
elements(ies)
.filter(|(id, _)| *id == ELEMENT_VENDOR)
.find_map(|(_, body)| parse_vendor_element(body).ok())
}
pub mod antsdr {
use crate::Error;
pub const HEADER_LEN: usize = 5;
pub const PACKET_DRONEID: u8 = 0x01;
pub const REPORT_LEN: usize = 64 + 64 + 1 + 12 * 8 + 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Frame<'a> {
pub header: u16,
pub packet_type: u8,
pub body: &'a [u8],
}
pub fn next_frame(buf: &[u8]) -> Result<(Frame<'_>, usize), Error> {
if buf.len() < HEADER_LEN {
return Err(Error::TooShort {
need: HEADER_LEN,
got: buf.len(),
});
}
let len = u16::from_le_bytes([buf[3], buf[4]]) as usize;
let total = HEADER_LEN + len;
if buf.len() < total {
return Err(Error::TooShort {
need: total,
got: buf.len(),
});
}
Ok((
Frame {
header: u16::from_le_bytes([buf[0], buf[1]]),
packet_type: buf[2],
body: &buf[HEADER_LEN..total],
},
total,
))
}
#[derive(Debug, Clone, PartialEq)]
pub struct Report {
pub serial: [u8; 64],
pub device_type: [u8; 64],
pub device_type_code: u8,
pub app_latitude: f64,
pub app_longitude: f64,
pub drone_latitude: f64,
pub drone_longitude: f64,
pub height: f64,
pub altitude: f64,
pub home_latitude: f64,
pub home_longitude: f64,
pub frequency: f64,
pub speed_east: f64,
pub speed_north: f64,
pub speed_up: f64,
pub rssi: u32,
}
impl Report {
pub fn decode(body: &[u8]) -> Result<Self, Error> {
if body.len() < REPORT_LEN {
return Err(Error::TooShort {
need: REPORT_LEN,
got: body.len(),
});
}
let mut serial = [0u8; 64];
serial.copy_from_slice(&body[..64]);
let mut device_type = [0u8; 64];
device_type.copy_from_slice(&body[64..128]);
let f = |i: usize| {
let at = 129 + i * 8;
let mut b = [0u8; 8];
b.copy_from_slice(&body[at..at + 8]);
f64::from_le_bytes(b)
};
let at = 129 + 12 * 8;
Ok(Report {
serial,
device_type,
device_type_code: body[128],
app_latitude: f(0),
app_longitude: f(1),
drone_latitude: f(2),
drone_longitude: f(3),
height: f(4),
altitude: f(5),
home_latitude: f(6),
home_longitude: f(7),
frequency: f(8),
speed_east: f(9),
speed_north: f(10),
speed_up: f(11),
rssi: u32::from_le_bytes([body[at], body[at + 1], body[at + 2], body[at + 3]]),
})
}
pub fn from_frame(frame: &Frame<'_>) -> Result<Self, Error> {
if frame.packet_type != PACKET_DRONEID {
return Err(Error::NotRemoteId);
}
Self::decode(frame.body)
}
pub fn serial_str(&self) -> Option<&str> {
super::text(&self.serial)
}
pub fn device_type_str(&self) -> Option<&str> {
super::text(&self.device_type)
}
}
}