1use std::collections::BTreeMap;
13use std::path::Path;
14
15use serde_json::{Map, Value, json};
16
17pub mod recording;
18pub mod table;
19pub mod timing;
20
21pub const FORMAT: &str = "openfrenz-session/1";
23
24#[derive(Debug, thiserror::Error)]
26pub enum Error {
27 #[error("recording: {0}")]
29 Sqlite(#[from] rusqlite::Error),
30 #[error("io: {0}")]
32 Io(#[from] std::io::Error),
33 #[error("arrow: {0}")]
35 Arrow(#[from] arrow_schema::ArrowError),
36 #[error("parquet: {0}")]
38 Parquet(#[from] parquet::errors::ParquetError),
39 #[error("json: {0}")]
41 Json(#[from] serde_json::Error),
42 #[error("invalid input: {0}")]
44 Invalid(String),
45}
46
47#[derive(Debug, Clone)]
49pub struct Session {
50 pub meta: Map<String, Value>,
52 pub tables: BTreeMap<&'static str, table::Table>,
54}
55
56impl Session {
57 fn new(source: Value) -> Self {
58 let mut meta = Map::new();
59 meta.insert("format".into(), json!(FORMAT));
60 meta.insert(
61 "exporter".into(),
62 json!(format!("openfrenz frenz-export {}", env!("CARGO_PKG_VERSION"))),
63 );
64 meta.insert("source".into(), source);
65 Self {
66 meta,
67 tables: BTreeMap::new(),
68 }
69 }
70
71 pub fn write(&self, dir: &Path) -> Result<(), Error> {
73 std::fs::create_dir_all(dir)?;
74 let mut files = Map::new();
75 for (name, table) in &self.tables {
76 table.write_parquet(&dir.join(format!("{name}.parquet")))?;
77 files.insert(
78 (*name).to_owned(),
79 json!({"file": format!("{name}.parquet"), "rows": table.rows()}),
80 );
81 }
82 let mut meta = self.meta.clone();
83 meta.insert("tables".into(), Value::Object(files));
84 std::fs::write(
85 dir.join("session.json"),
86 serde_json::to_string_pretty(&Value::Object(meta))?,
87 )?;
88 Ok(())
89 }
90}
91
92pub fn read(input: &Path) -> Result<Session, Error> {
94 if input.extension().is_some_and(|e| e == "sqlite") {
95 recording::from_recording(input)
96 } else {
97 Err(Error::Invalid(format!("{}: not a .sqlite recording", input.display())))
98 }
99}
100
101pub(crate) fn eeg_channel_json() -> Value {
103 json!({
104 "forehead_right": "slot 0: right forehead pad, beside the optical sensor",
105 "comb_left": "slot 1: left side comb (shows eyes-closed alpha)",
106 "forehead_left": "slot 3: left forehead pad (strongest blink/EMG)",
107 "comb_right": "slot 4: right side comb (shows eyes-closed alpha)",
108 "reference": "centre forehead pad (inferred)",
109 })
110}
111
112pub(crate) fn motion_json(accel: bool) -> Value {
114 json!({
115 "nominal_rate_hz": 50.0,
116 "units": "raw signed 16-bit counts",
117 "frame": "+x down (toward chin when worn), +y wearer's left, +z forward; y/z rotated ~30° about x",
118 "scale": if accel { json!({"counts_per_g_nominal": 16384, "note": "per-unit calibration: see docs/HARDWARE.md"}) } else { json!("unknown") },
119 })
120}