1#[cfg(feature="tof-liftof")]
7pub mod ipbus;
8pub mod parsers;
9pub mod serialization;
10pub use serialization::Serialization;
11pub mod caraspace;
12#[cfg(feature="root")]
13pub mod root_reader;
14#[cfg(feature="root")]
15pub use root_reader::read_example;
16pub mod tof_reader;
17pub use tof_reader::TofPacketReader;
18pub mod tof_writer;
19pub use tof_writer::TofPacketWriter;
20pub mod telemetry_reader;
21pub use telemetry_reader::TelemetryPacketReader;
22pub mod telemetry_writer;
23pub use telemetry_writer::TelemetryPacketWriter;
24pub mod data_source;
25pub use data_source::DataSource;
26pub mod streamers;
27pub use streamers::*;
28
29
30#[cfg(feature="pybindings")]
31use std::path::PathBuf;
32
33use flate2::Compression;
34use flate2::write::GzEncoder;
35use flate2::read::GzDecoder;
36use diffy::{
37 apply_bytes,
38 Patch,
39 create_patch
40};
41use crate::prelude::*;
42
43#[derive(Debug, Clone)]
47pub enum FileType {
48 Unknown,
49 CalibrationFile(u8),
51 RunFile(u32),
53 SummaryFile(String),
56}
57
58fn sort_by_time_and_subrun(entries : &mut Vec<(u32, u32, u64, String)>) {
66 entries.sort_by(|a, b| (a.0, a.1, a.2, &a.3).cmp(&(b.0, b.1, b.2, &b.3)));
67}
68
69pub fn list_path_contents_sorted(input: &str, pattern: Option<Regex>) -> Result<Vec<String>, io::Error> {
80 let path = Path::new(input);
81 match fs::metadata(path) {
82 Ok(metadata) => {
83 if metadata.is_file() {
84 let fname = String::from(input);
85 return Ok(vec![fname]);
86 }
87 if metadata.is_dir() {
88 let re : Regex;
89 match pattern {
90 None => {
91 re = Regex::new(GENERIC_ONLINE_FILE_PATTERN).unwrap();
94 }
95 Some(_re) => {
96 re = _re;
97 }
98 }
99 let re_subrun = Regex::new(r"Run\d+_(\d+)\.").unwrap();
102 let mut entries: Vec<(u32, u32, u64, String)> = fs::read_dir(path)?
103 .filter_map(Result::ok) .filter_map(|entry| {
105 let basename = entry.file_name().into_string().ok()?;
106 let filename = format!("{}/{}", path.display(), basename);
107 re.captures(&filename.clone()).map(|caps| {
108 let date = caps.get(1)?.as_str().parse::<u32>().ok()?;
109 let time = caps.get(2)?.as_str().parse::<u32>().ok()?;
110 let subrun = re_subrun.captures(&basename)
112 .and_then(|c| c.get(1)?.as_str().parse::<u64>().ok())
113 .unwrap_or(0);
114 Some((date, time, subrun, filename))
115 })?
116 })
117 .collect();
118
119 sort_by_time_and_subrun(&mut entries);
120 return Ok(entries.into_iter().map(|(_, _, _, name)| name).collect());
122 }
123 Err(io::Error::new(io::ErrorKind::Other, "Path exists but is neither a file nor a directory"))
124 }
125 Err(e) => Err(e),
126 }
127}
128
129#[cfg(feature="pybindings")]
142#[pyfunction]
143#[pyo3(name="list_path_contents_sorted")]
144#[pyo3(signature = ( input, pattern = None ))]
145pub fn list_path_contents_sorted_py(input: &str, pattern: Option<String>) -> PyResult<Option<Vec<String>>> {
146 let mut regex_pattern : Option<Regex> = None;
147 if let Some(pat_str) = pattern {
148 match Regex::new(&pat_str) {
149 Err(err) => {
150 let msg = format!("Unable to compile regex {}! {}. Check your regex syntax! Also try a raw string.", &pat_str, err);
151 return Err(PyValueError::new_err(msg));
152 }
153 Ok(re) => {
154 regex_pattern = Some(re);
155 }
156 }
157 }
158 match list_path_contents_sorted(input, regex_pattern) {
159 Err(err) => {
160 error!("Unable to get files! {err}");
161 return Err(PyValueError::new_err(err.to_string()));
162 }
163 Ok(files) => {
164 return Ok(Some(files));
165 }
166 }
167}
168
169#[cfg_attr(feature="pybindings", pyfunction)]
173pub fn get_utc_timestamp() -> String {
174 let now: DateTime<Utc> = Utc::now();
175 let timestamp_str = now.format(HUMAN_TIMESTAMP_FORMAT).to_string();
177 timestamp_str
178}
179
180#[cfg_attr(feature="pybindings", pyfunction)]
184pub fn get_utc_timestamp_from_unix(unix_time : f64) -> Option<String> {
185 let seconds = unix_time.trunc() as i64;
187 let nanoseconds = (unix_time.fract() * 1_000_000_000.0) as u32;
188
189 if let Some(dt) = Utc.timestamp_opt(seconds, nanoseconds).single() {
192 Some(dt.format("%y%m%d_%H%M%S").to_string())
193 } else {
194 None
195 }
196}
197
198#[cfg_attr(feature="pybindings", pyfunction)]
202pub fn get_unix_timestamp_from_telemetry(fname : &str) -> Option<u64> {
203 let tformat_re = Regex::new(GENERIC_TELEMETRY_FILE_PATTERN_CAPTURE).unwrap();
204 let res = tformat_re.captures(fname).and_then(|caps| {
205 let map : HashMap<String, String> = tformat_re.capture_names()
206 .filter_map(|name| name)
207 .filter_map(|name| {
208 caps.name(name).map(|m| (name.to_string(), m.as_str().to_string()))
210 })
211 .collect();
212 Some(map)
213 });
214 return get_unix_timestamp(&res.unwrap()["utctime"], None);
215}
216
217#[cfg_attr(feature="pybindings", pyfunction)]
221pub fn get_utc_date() -> String {
222 let now: DateTime<Utc> = Utc::now();
223 let timestamp_str = now.format("%y%m%d").to_string();
225 timestamp_str
226}
227
228#[cfg_attr(feature="pybindings", pyfunction)]
241pub fn get_califilename(rb_id : u8, latest : bool) -> String {
242 let ts = get_utc_timestamp();
243 if latest {
244 format!("RB{rb_id:02}_latest.cali.tof.gaps")
245 } else {
246 format!("RB{rb_id:02}_{ts}.cali.tof.gaps")
247 }
248}
249
250#[cfg_attr(feature="pybindings", pyfunction)]
266pub fn get_runfilename(run : u32, subrun : u64, rb_id : Option<u8>, timestamp : Option<String>, tof_only : bool) -> String {
267 let ts : String;
268 match timestamp {
269 Some(_ts) => {
270 ts = _ts;
271 }
272 None => {
273 ts = get_utc_timestamp();
274 }
275 }
276 let fname : String;
277 match rb_id {
278 None => {
279 if tof_only {
280 fname = format!("Run{run}_{subrun}.{ts}.tof.gaps");
281 } else {
282 fname = format!("Run{run}_{subrun}.{ts}.gaps");
283 }
284 }
285 Some(rbid) => {
286 fname = format!("Run{run}_{subrun}.{ts}.RB{rbid:02}.tof.gaps");
287 }
288 }
289 fname
290}
291
292#[cfg_attr(feature="pybindings", pyfunction)]
299#[cfg_attr(feature="pybindings", pyo3(signature = (fname , pattern = None)))]
300pub fn get_rundata_from_file(fname : &str, pattern : Option<String>) -> Option<HashMap<String,String>> {
301 let regex_pattern : Regex;
302 if let Some(pat_str) = pattern {
303 match Regex::new(&pat_str) {
304 Err(err) => {
305 let msg = format!("Unable to compile regex {}! {}. Check your regex syntax! Also try a raw string.", &pat_str, err);
306 error!("{}",msg);
309 return None;
310 }
311 Ok(re) => {
312 regex_pattern = re;
313 }
314 }
315 } else {
316 regex_pattern = Regex::new(GENERIC_ONLINE_FILE_PATTERN_CAPTURE).unwrap();
317 }
318 let res : Option<HashMap<String,String>>;
319 res = regex_pattern.captures(fname).and_then(|caps| {
320 let map : HashMap<String, String> = regex_pattern.capture_names()
321 .filter_map(|name| name)
322 .filter_map(|name| {
323 caps.name(name).map(|m| (name.to_string(), m.as_str().to_string()))
325 })
326 .collect();
327 Some(map)
328 });
329 res
335}
336
337#[cfg_attr(feature="pybindings", pyfunction)]
349#[cfg_attr(feature="pybindings", pyo3(signature = (input , tformat = None )))]
350pub fn get_datetime(input : &str, tformat : Option<String>) -> Option<DateTime<Utc>> {
351 let mut date_time_format = String::from("%y%m%d_%H%M%S");
353 if let Some(tform) = tformat {
354 date_time_format = tform.to_string();
355 }
356 if let Ok(ndtime) = NaiveDateTime::parse_from_str(input, &date_time_format) {
357 let dt_utc : DateTime<Utc> = DateTime::<Utc>::from_naive_utc_and_offset(ndtime, Utc);
359 return Some(dt_utc);
360 } else {
361 error!("Unable to parse {} for format {}! You can specify formats trhough the tformat keyword", input, date_time_format);
362 return None;
363 }
364}
365
366#[cfg_attr(feature="pybindings", pyfunction)]
378#[cfg_attr(feature="pybindings", pyo3(signature = (input , tformat = None )))]
379pub fn get_unix_timestamp(input : &str, tformat : Option<String>) -> Option<u64> {
380 let dt = get_datetime(input, tformat);
381 if let Some(dt_) = dt {
382 return Some(dt_.timestamp() as u64);
385 } else {
386 return None;
387 }
388}
389
390#[derive(Debug, Copy, Clone, PartialEq,FromRepr, AsRefStr, EnumIter)]
394#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
395#[repr(u8)]
396pub enum DataSourceKind {
397 Unknown = 0,
398 TofFiles = 10,
401 TofStream = 11,
403 TelemetryFiles = 20,
406 TelemetryStream = 21,
409 CaraspaceFiles = 30,
413 CaraspaceStream = 31,
416 ROOTFiles = 40,
418}
419
420expand_and_test_enum!(DataSourceKind, test_datasourcekind_repr);
421
422#[cfg(feature = "pybindings")]
428#[pymethods]
429impl DataSourceKind {
430
431 #[getter]
432 fn __hash__(&self) -> usize {
433 (*self as u8) as usize
434 }
435}
436
437#[cfg(feature="pybindings")]
438pythonize_display!(DataSourceKind);
439
440#[macro_export]
445macro_rules! reader {
446 ($struct_name:ident, $element_type:ident) => {
447
448 use crate::io::DataReader;
449 use crate::io::Serialization;
450
451 impl Iterator for $struct_name {
452 type Item = $element_type;
453 fn next(&mut self) -> Option<Self::Item> {
454 self.read_next()
455 }
456 }
457
458 impl DataReader<$element_type> for $struct_name {
459 fn get_header0(&self) -> u8 {
460 ($element_type::HEAD & 0x1) as u8
461 }
462
463 fn get_header1(&self) -> u8 {
464 ($element_type::HEAD & 0x2) as u8
465 }
466
467 fn get_file_idx(&self) -> usize {
468 self.file_idx }
470
471 fn set_file_idx(&mut self, file_idx : usize) {
472 self.file_idx = file_idx;
473 }
474
475 fn get_filenames(&self) -> &Vec<String> {
476 &self.filenames
477 }
478
479 fn set_cursor(&mut self, pos : usize) {
480 self.cursor = pos;
481 }
482
483 fn set_file_reader(&mut self, reader : BufReader<File>) {
484 self.file_reader = reader;
485 }
486
487 fn read_next(&mut self) -> Option<$element_type> {
488 self.read_next_item()
489 }
490
491 fn prime_next_file(&mut self) -> Option<usize> {
493 if self.file_idx == self.filenames.len() -1 {
494 return None;
495 } else {
496 self.file_idx += 1;
497 let nextfilename : &str = self.filenames[self.file_idx].as_str();
498 let nextfile = OpenOptions::new().create(false).append(false).read(true).open(nextfilename).expect("Unable to open file {nextfilename}");
499 self.file_reader = BufReader::new(nextfile);
500 self.cursor = 0;
501 return Some(self.file_idx);
502 }
503 }
504 }
505 }
506}
507
508pub trait DataReader<T>
511 where T : Default + Serialization {
512 fn get_header0(&self) -> u8;
518 fn get_header1(&self) -> u8;
519
520 fn get_filenames(&self) -> &Vec<String>;
522
523 fn get_file_idx(&self) -> usize;
526
527 fn set_file_idx(&mut self, idx : usize);
530
531 fn set_file_reader(&mut self, freader : BufReader<File>);
533
534 fn prime_next_file(&mut self) -> Option<usize>;
536
537 fn get_current_filename(&self) -> Option<&str> {
540 if self.get_filenames().len() <= self.get_file_idx() {
542 return None;
543 }
544 Some(self.get_filenames()[self.get_file_idx()].as_str())
545 }
546
547 fn set_cursor(&mut self, pos : usize);
549
550 fn read_next(&mut self) -> Option<T>;
553
554 fn first(&mut self) -> Option<T> {
557 match self.rewind() {
558 Err(err) => {
559 error!("Error when rewinding files! {err}");
560 return None;
561 }
562 Ok(_) => ()
563 }
564 let pack = self.read_next();
565 match self.rewind() {
566 Err(err) => {
567 error!("Error when rewinding files! {err}");
568 }
569 Ok(_) => ()
570 }
571 return pack;
572 }
573
574 fn last(&mut self) -> Option<T> {
577 self.set_file_idx(self.get_filenames().len() - 1);
578 let lastfilename = self.get_filenames()[self.get_file_idx()].as_str();
579 let lastfile = OpenOptions::new().create(false).append(false).read(true).open(lastfilename).expect("Unable to open file {nextfilename}");
580 self.set_file_reader(BufReader::new(lastfile));
581 self.set_cursor(0);
582 let mut tp = T::default();
583 let mut idx = 0;
584 loop {
585 match self.read_next() {
586 None => {
587 match self.rewind() {
588 Err(err) => {
589 error!("Error when rewinding files! {err}");
590 }
591 Ok(_) => ()
592 }
593 if idx == 0 {
594 return None;
595 } else {
596 return Some(tp);
597 }
598 }
599 Some(pack) => {
600 idx += 1;
601 tp = pack;
602 continue;
603 }
604 }
605 }
606 }
607
608 fn rewind(&mut self) -> io::Result<()> {
612 let firstfile = &self.get_filenames()[0];
613 let file = OpenOptions::new().create(false).append(false).read(true).open(&firstfile)?;
614 self.set_file_reader(BufReader::new(file));
615 self.set_cursor(0);
616 self.set_file_idx(0);
617 Ok(())
618 }
619}
620
621pub fn compress_toml(file_path: &Path) -> Result<Vec<u8>, io::Error> {
624 let mut input_file = File::open(file_path)?;
625 let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
626 io::copy(&mut input_file, &mut encoder)?;
627 encoder.finish()
628}
629
630#[cfg(feature="pybindings")]
633#[pyfunction]
634#[pyo3(name="compress_toml")]
635pub fn compress_toml_py(file_path: String) -> Result<Vec<u8>, io::Error> {
636 let path_buff = PathBuf::from(file_path);
637 compress_toml(&path_buff)
638}
639
640pub fn decompress_toml(compressed_data: &[u8], output_path: &Path) -> Result<(), io::Error> {
642 let mut decoder = GzDecoder::new(compressed_data);
643 let mut output_file = File::create(output_path)?;
644 io::copy(&mut decoder, &mut output_file)?;
645 Ok(())
646}
647
648#[cfg(feature="pybindings")]
650#[pyfunction]
651#[pyo3(name="decompress_toml")]
652pub fn decompress_toml_py(compressed_data: &[u8], output_path: String) -> Result<(), io::Error> {
653 let path_buff = PathBuf::from(output_path);
654 decompress_toml(compressed_data, &path_buff)
655}
656
657
658pub fn create_compressed_diff(old_path: &Path, new_path: &Path) -> Result<Vec<u8>, io::Error> {
664 let old_text = fs::read_to_string(old_path)?;
665 let new_text = fs::read_to_string(new_path)?;
666 let diff = create_patch(&old_text, &new_text);
667 let diff_bytes = diff.to_bytes();
668 let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
669 io::copy(&mut diff_bytes.as_slice(), &mut encoder)?;
670 encoder.finish()
671}
672
673#[cfg(feature="pybindings")]
679#[pyfunction]
680#[pyo3(name="create_compressed_diff")]
681pub fn create_compressed_diff_py(old_path: String, new_path: String) -> Result<Vec<u8>, io::Error> {
682 let old_file = PathBuf::from(old_path);
683 let new_file = PathBuf::from(new_path);
684 create_compressed_diff(&old_file, &new_file)
685}
686
687
688pub fn apply_diff_to_file(compressed_bytes : Vec<u8>, original_file_path: &str) -> io::Result<()> {
698 let mut decoder = GzDecoder::new(&compressed_bytes[..]);
699 let mut uncompressed_data = Vec::new();
700 match decoder.read_to_end(&mut uncompressed_data) {
701 Ok(_) => (),
702 Err(e) => {
703 error!("Unable to decompress the received bytes!");
704 return Err(e);
705 }
706 }
707
708 let mut original_file = fs::File::open(original_file_path)?;
710 let mut original_content = String::new();
711 original_file.read_to_string(&mut original_content)?;
712 match Patch::from_bytes(&uncompressed_data.as_slice()) {
713 Ok(patch) => {
714 info!("Got patch {:?}", patch);
715 match apply_bytes(&original_content.as_bytes(), &patch) {
716 Ok(modified_content) => {
717 let mut output_file = fs::File::create(original_file_path)?;
718 output_file.write_all(&modified_content.as_slice())?;
719 }
720 Err(err) => {
721 error!("Unable to apply the patch {err}");
722 }
723 }
724 }
725 Err(err) => {
726 error!("Unable to apply the patch! {err}");
727 }
728 }
729 Ok(())
730}
731
732#[cfg(feature="pybindings")]
742#[pyfunction]
743#[pyo3(name="apply_diff_to_file")]
744pub fn apply_diff_to_file_py(compressed_bytes : Vec<u8>, original_file_path: &str) -> io::Result<()> {
745 apply_diff_to_file(compressed_bytes, original_file_path)
746}
747#[test]
757fn sort_files_with_the_same_timestamp_by_subrun() {
758 let mut entries = vec![(231114, 221320, 10, String::from("Run42_10")),
760 (231114, 221320, 2, String::from("Run42_2")),
761 (231114, 221321, 0, String::from("Run42_0_later")),
762 (231114, 221320, 1, String::from("Run42_1")),
763 (231113, 235959, 7, String::from("Run42_7_earlier"))];
764 sort_by_time_and_subrun(&mut entries);
765 let names : Vec<&str> = entries.iter().map(|e| e.3.as_str()).collect();
766 assert_eq!(names, vec!["Run42_7_earlier", "Run42_1", "Run42_2", "Run42_10", "Run42_0_later"]);
767}
768
769#[test]
770fn list_path_contents_sorted_by_subrun() {
771 let dir = tempfile::tempdir().unwrap();
772 let names = ["Run42_10.231114_221320.gaps",
775 "Run42_2.231114_221320.gaps",
776 "Run42_1.231114_221320.gaps",
777 "Run42_0.231114_221319.gaps",
778 "Run42_11.231114_221321.gaps",
779 "NotARunFile.txt"];
780 for n in names {
781 fs::write(dir.path().join(n), b"").unwrap();
782 }
783 let files : Vec<String> = list_path_contents_sorted(dir.path().to_str().unwrap(), None).unwrap()
784 .iter().map(|f| Path::new(f).file_name().unwrap().to_str().unwrap().to_string()).collect();
785 assert_eq!(files, vec!["Run42_0.231114_221319.gaps",
786 "Run42_1.231114_221320.gaps",
787 "Run42_2.231114_221320.gaps",
788 "Run42_10.231114_221320.gaps",
789 "Run42_11.231114_221321.gaps"]);
790}