Something went wrong. Try again.
Unofficial implementation of analysis for activPAL™ data
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321// Copyright (C) 2026 Jannik Schürg <jannik.schuerg@posteo.de>//// SPDX-License-Identifier: Apache-2.0// SPDX-License-Identifier: MIT
//! Parser for activPAL .datx files.
use chrono::{NaiveDate, NaiveDateTime, NaiveTime};use thiserror::Error;
mod raw_sample;
pub use raw_sample::NumRawSamples;
#[derive(Debug, Error)]pub enum DatxParseError { #[error("invalid magic number")] InvalidMagic, #[error("missing tail")] NoTail, #[error("too short")] TooShort, #[error("invalid date: {0}")] InvalidDate(String), #[error("invalid range: {0}")] InvalidRange(u8),}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Resolution { Bits8, Bits10,}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RangeG { G2, G4, G8,}
pub struct DatxFile { pub firmware: u16, pub sample_rate: u8, pub recording_setup_number: u16, pub start_time: Option<NaiveDateTime>, pub stop_time: NaiveDateTime, /// Resolution in bits. pub resolution: Resolution, /// Range in g: 2, 4, or 8. pub range: RangeG, /// Whether the body contains run markers. compression: bool, bad_start_time: u8, tail: Vec<u8>, body: Vec<u8>, header: Vec<u8>,}
impl DatxFile { pub fn parse(data: &[u8]) -> Result<Self, DatxParseError> { if !data.starts_with(b"header") { return Err(DatxParseError::InvalidMagic); }
let (header, rest) = data .split_at_checked(1024) .ok_or(DatxParseError::TooShort)?; if &header[0x3f4..=0x3fd] != b"header end" { return Err(DatxParseError::InvalidMagic); } let firmware = header[0x11] as u16 | ((header[0x27] as u16) << 8); let sample_rate = header[0x23]; let recording_setup_number = u16::from_le_bytes([header[0x2d], header[0x2e]]); let compression = header[0x24] == 1; let bad_start_time = header[0x30]; let start_time = (bad_start_time == 0) .then(|| read_dt(header, 0x100)) .transpose()?; let stop_time = read_dt(header, 0x106)?; // let start_condition = header[0x10c]; // let stop_condition = header[0x113]; let (resolution, range) = { let mode = header[0x26]; let resolution = if mode < 128 { Resolution::Bits8 } else { Resolution::Bits10 }; let range = if mode < 128 { mode } else { mode - 128 }; let range = match range { 0 => RangeG::G2, 1 => RangeG::G4, 2 => RangeG::G8, _ => return Err(DatxParseError::InvalidRange(range)), }; (resolution, range) };
let (body, tail) = rsplit_once(rest, b"tail").ok_or(DatxParseError::NoTail)?;
let chunk_size = match resolution { Resolution::Bits8 => 3, Resolution::Bits10 => 4, }; let body = trim_trailing_fill(body, chunk_size);
Ok(Self { firmware, sample_rate, recording_setup_number, start_time, stop_time, compression, bad_start_time, resolution, range, tail: tail.to_vec(), body: body.to_vec(), header: header.to_vec(), }) }
pub fn body(&self) -> &[u8] { &self.body }
pub fn contains_run_markers(&self) -> bool { self.compression }
pub fn device_tag(&self) -> Option<&str> { ascii(&self.header[0x12..=0x22]) }
pub fn file_code(&self) -> Option<&str> { ascii(&self.header[0x200..=0x207]) }
pub fn analysis_software(&self) -> Option<&str> { ascii(&self.header[0x208..=0x217]) }
pub fn download_software(&self) -> Option<&str> { ascii(&self.header[0x28d..=0x29c]) }
pub fn bad_start_time(&self) -> Option<u8> { (self.bad_start_time != 0).then_some(self.bad_start_time) }
pub fn secondary(&self) -> &[u8] { &self.header[0x114..=0x1a4] }
pub fn metadata(&self) -> &[u8] { &self.header[0x2e8..=0x2ef] }
pub fn battery_log(&self) -> Result<impl Iterator<Item = BatteryReadout> + '_, DatxParseError> { let len = self.tail.len(); if !len.is_multiple_of(7) { return Err(DatxParseError::TooShort); } Ok(BatteryLogIterator { data: &self.tail }) }
pub fn has_magnetometry(&self) -> bool { let pack = self.header[0x3c]; match pack { 0 => self.header[0x2b] != 0, 1 | 2 | 4 => true, _ => false, } }
pub fn has_barometry(&self) -> bool { let pack = self.header[0x3c]; match pack { 0 => self.header[0x2b] != 0, 1..=3 => true, _ => false, } }
pub fn body_coding(&self) -> Option<BodyCoding> { if self.sample_rate != 20 { // out of scope return None; } let coding = match self.resolution { Resolution::Bits8 => BodyCoding::LegacyByte, Resolution::Bits10 if self.has_magnetometry() && matches!(self.firmware, 960..=999) => { let halved_mode = matches!(self.firmware, 979..=999) || self.sample_rate == 50; if halved_mode { // out of scope, left sample_rate check for clarity but it is redundant return None; } BodyCoding::MagInterleaved } Resolution::Bits10 => BodyCoding::PackedWord, }; Some(coding) }}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum BodyCoding { PackedWord, MagInterleaved, LegacyByte,}
pub struct BatteryReadout { start: u32, end: u32, reading: u8,}
#[derive(Debug, Error)]pub enum BatteryReadoutError { #[error("invalid reading, 0x00 or 0xff")] InvalidReading, #[error("device fault, {0} > 0xD2")] DeviceFault(u8),}
impl BatteryReadout { pub fn start(&self) -> NumRawSamples { NumRawSamples(self.start * 64) }
pub fn end(&self) -> NumRawSamples { NumRawSamples(self.end * 64) }
pub fn voltage(&self) -> Result<f32, BatteryReadoutError> { // A reading of 0x00 or 0xff is invalid and above 0xd2 is a device fault; match self.reading { 0x00 | 0xff => Err(BatteryReadoutError::InvalidReading), r if r > 0xd2 => Err(BatteryReadoutError::DeviceFault(r)), r => Ok(r as f32 / 46.3), } }}
struct BatteryLogIterator<'a> { data: &'a [u8],}
impl<'a> Iterator for BatteryLogIterator<'a> { type Item = BatteryReadout;
fn next(&mut self) -> Option<Self::Item> { if self.data.is_empty() { return None; } // The first record is considered 6 bytes long with implicit zero in the first bytes. // We abuse the zero byte after the tail marker for this. let start = u32::from_be_bytes([0, self.data[0], self.data[1], self.data[2]]); let end = u32::from_be_bytes([0, self.data[3], self.data[4], self.data[5]]); let reading = self.data[6]; self.data = &self.data[7..]; Some(BatteryReadout { start, end, reading, }) }}
#[inline]fn rsplit_once<'a>(haystack: &'a [u8], needle: &[u8]) -> Option<(&'a [u8], &'a [u8])> { memchr::memmem::rfind(haystack, needle) .map(|pos| (&haystack[..pos], &haystack[pos + needle.len()..]))}
fn read_dt(header: &[u8], offset: usize) -> Result<NaiveDateTime, DatxParseError> { let hour = header[offset]; let minute = header[offset + 1]; let second = header[offset + 2]; let day = header[offset + 3] as u32; let month = header[offset + 4] as u32; let year = 2000 + header[offset + 5] as u16;
let date = NaiveDate::from_ymd_opt(year.into(), month, day); let time = NaiveTime::from_hms_opt(hour.into(), minute.into(), second.into()); match (date, time) { (Some(date), Some(time)) => Ok(NaiveDateTime::new(date, time)), _ => { let date = format!("{year}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}"); Err(DatxParseError::InvalidDate(date)) } }}
#[inline]fn ascii(data: &[u8]) -> Option<&str> { let data = &data[..memchr::memchr(0, data).unwrap_or(data.len())]; data.is_ascii() .then(|| unsafe { std::str::from_utf8_unchecked(data) })}
/// Trim trailing fill bytes from the body.////// The returned slice is _not_ guaranteed to be a multiple of `sample_size`.fn trim_trailing_fill(payload: &[u8], sample_size: usize) -> &[u8] { let mut run = 0; for (i, &b) in payload.iter().enumerate().rev() { if b == 0xff { run = 0; } else { run += 1; if run == sample_size { return &payload[..i + sample_size]; } } } payload}