Skip to main content

gondola_core/
database.rs

1//! Database access & entities for gaps-online-software
2//!
3//! A local .sqlite database is shipped with gaps-online-software,
4//! pre-populated with relevant meta data for the GAPS experiment.
5// This file is part of gaps-online-software and published 
6// under the GPLv3 license
7
8use crate::prelude::*;
9
10use std::fs::File;
11use std::io::{self, BufRead, BufReader};
12use std::path::Path;
13
14use diesel::prelude::*;
15use diesel::FromSqlRow;
16use diesel::AsExpression;
17use diesel::serialize;
18use diesel::deserialize;
19use diesel::sqlite::Sqlite;
20use diesel::deserialize::FromSql;
21use diesel::serialize::Output;
22use diesel::sql_types::Integer;
23use diesel::serialize::ToSql;
24use diesel::backend::Backend;
25
26mod schema;    
27
28mod tracker_mask;
29pub use tracker_mask::{
30  TrackerStripMask,
31  create_trk_mask_table
32};
33
34mod tracker_pedestal;
35pub use tracker_pedestal::create_trk_pedestal_table;
36
37mod tracker_transfer_fn;
38pub use tracker_transfer_fn::{
39  TrackerStripTransferFunction,
40  create_trk_transfer_fn_table
41};
42
43mod tracker_gain;
44pub use tracker_gain::{
45  TrackerStripGain,
46  create_trk_gain_table
47};
48
49mod tracker_pulse;
50pub use tracker_pulse::{
51  TrackerStripPulse,
52  create_trk_pulse_table
53};
54
55mod tracker_cali_times; 
56pub use tracker_cali_times::{
57  TrackerCaliTimeWindow,
58  is_in_tracker_cali_window,
59  create_trk_cali_tw_table,
60};
61
62mod tof_paddle_temps;
63pub use tof_paddle_temps::{
64  TofPaddleTemp,
65  TofPaddleTempDataSeries,
66  create_tof_paddle_temp_table
67};
68
69/// Low gain/LTB connections to paddle ID 
70pub type DsiJChPidMapping = HashMap<u8, HashMap<u8, HashMap<u8, (u8, u8)>>>;
71/// Low gain/LTB connections to rb ID 
72pub type DsiJChRbMapping = HashMap<u8, HashMap<u8, HashMap<u8, u8>>>;
73/// RB ID and RB Ch to paddle ID mapping 
74pub type RbChPidMapping = HashMap<u8, HashMap<u8, u8>>;
75
76//--------------------------------------------------------------
77
78/// Describe the contents of a byte sequence ("packet") typicially 
79/// crafted for telemetry. The numbers are defined by the 'bfsw'
80/// software package.
81#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy, FromRepr, AsRefStr, EnumIter,AsExpression, FromSqlRow)]
82#[cfg_attr(feature = "pybindings", pyclass(eq, eq_int))]
83#[diesel(sql_type = Integer)]
84pub enum TrackerCalibrationFileType {
85  Unknown        = 0,
86  Pedestal       = 200,
87  TransferFn     = 201,
88  ChannelMask    = 202,
89  PulsedChannels = 203,
90  Gains          = 204,
91  Any            = 255,
92}
93
94impl ToSql<Integer, Sqlite> for TrackerCalibrationFileType {
95  fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, Sqlite>) -> serialize::Result {
96    out.set_value(*self as i32);
97    Ok(serialize::IsNull::No)
98  }
99}
100
101impl FromSql<Integer, Sqlite> for TrackerCalibrationFileType {
102  fn from_sql(bytes: <Sqlite as Backend>::RawValue<'_>) -> deserialize::Result<Self> {
103    let v = i32::from_sql(bytes)?;
104    match v {
105      0   => Ok(TrackerCalibrationFileType::Unknown),
106      200 => Ok(TrackerCalibrationFileType::Pedestal),
107      201 => Ok(TrackerCalibrationFileType::TransferFn),
108      202 => Ok(TrackerCalibrationFileType::ChannelMask),
109      203 => Ok(TrackerCalibrationFileType::PulsedChannels),
110      204 => Ok(TrackerCalibrationFileType::Gains),
111      255 => Ok(TrackerCalibrationFileType::Any),
112      _ => {
113        error!("Unable to understand type {v}");
114        return Err("Unrecognized calibration file type".into());
115      }
116    }
117  }
118}
119
120impl fmt::Display for TrackerCalibrationFileType {
121  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
122    let mut repr = String::from("<TrackerCalFileType::");
123    match self {
124      Self::Unknown        => { repr += "Unknown>";}
125      Self::Pedestal       => { repr += "Pedestal>";}
126      Self::TransferFn     => { repr += "TransferFn>";}
127      Self::ChannelMask    => { repr += "ChannelMask>";}
128      Self::PulsedChannels => { repr += "PulsedChannels>";}
129      Self::Gains          => { repr += "Gains>";}
130      Self::Any            => { repr += "Any>";}
131    }
132    write!(f, "{}", repr)
133  }
134}
135
136//expand_and_test_enum!(TrackerCalibrationFileType, test_telemetrypackettype_repr);
137
138//--------------------------------------------------------------
139
140/// This loads the calbration DB for SimpleDet as provided by Elena 
141/// and INFN. 
142///
143/// This calibration db is basically a list of files and timestamps
144/// Exitence of these paths is not guaranteed.
145#[cfg_attr(feature="pybindings", pyfunction)]
146#[cfg_attr(feature="pybindings", pyo3(signature = (db_path, cali_ftype = TrackerCalibrationFileType::Any)))]
147pub fn load_calibration_db_elena(db_path : &str, cali_ftype : TrackerCalibrationFileType) -> Option<Vec<TrackerCalibrationFile>> {
148  use schema::calibration_files::dsl::*;
149  info!("Will load SD calibration DB from {}", db_path);
150  let mut conn = SqliteConnection::establish(db_path).ok()?;
151  match calibration_files.load::<TrackerCalibrationFile>(&mut conn) {
152    Err(err) => {
153      error!("Unable to load tracker calibration files from db! {err}");
154      return None;
155    }
156    Ok(mut files) => {
157      match cali_ftype {
158        TrackerCalibrationFileType::Any => {
159          return Some(files);
160        }
161        _ => {
162          files.retain(|x| x.file_type == cali_ftype);            
163          return Some(files);
164        }
165      }
166    }
167  }
168}
169
170//--------------------------------------------------------------
171
172
173/// Connect to a database at a given location
174pub fn connect_to_db_path(db_path : &str) -> Result<diesel::SqliteConnection, ConnectionError> {
175  info!("Will set GONDOLA_DB_URL to {}", db_path);
176  warn!("Setting environment variables is not thread safe!");
177  check_db_file(db_path)?;
178  unsafe {
179    //env::set_var("GONDOLA_DB_URL", db_path);
180    env::set_var("GONDOLA_DB_URL", db_path);
181  }
182  SqliteConnection::establish(db_path)
183}
184
185//---------------------------------------------------------------------
186
187/// Make sure the database file exists before connecting to it.
188///
189/// SQLite would otherwise silently create an empty database at a
190/// wrong path and all queries would return nothing. SQLite URIs
191/// ("file:...") and in-memory databases are passed through.
192fn check_db_file(db_path : &str) -> Result<(), ConnectionError> {
193  if db_path.starts_with("file:") || db_path == ":memory:" {
194    return Ok(());
195  }
196  if !Path::new(db_path).is_file() {
197    let msg = format!("No database file at '{}'!", db_path);
198    error!("{}", msg);
199    return Err(ConnectionError::BadConnection(msg));
200  }
201  Ok(())
202}
203
204//---------------------------------------------------------------------
205
206/// Connect to the default database at the standard location
207pub fn connect_to_db() -> Result<diesel::SqliteConnection, ConnectionError>  {
208  let db_path  = env::var("GONDOLA_DB_URL").unwrap_or_else(|_| "".to_string());
209  if db_path == "" {
210    error!("Empty GONDOLA_DB_URL. Did you forget to load the gaps-online-software setup-env.sh shell?");
211  }
212  check_db_file(&db_path)?;
213  SqliteConnection::establish(&db_path)
214}
215
216//---------------------------------------------------------------------
217
218/// Create a mapping of DSI/J(LTB) -> PaddleID
219///
220/// This will basically tell you for a given LTB hit which paddle has 
221/// triggered.
222pub fn get_dsi_j_ch_pid_map(paddles : &Vec<TofPaddle>) -> DsiJChPidMapping {
223  let mut mapping = DsiJChPidMapping::new();
224  for dsi in 1..6 {
225    let mut jmap = HashMap::<u8, HashMap<u8, (u8, u8)>>::new();
226    for j in 1..6 {
227      let mut rbidch_map : HashMap<u8, (u8,u8)> = HashMap::new();
228      for ch in 1..17 {
229        let rbidch = (0,0);
230        rbidch_map.insert(ch,rbidch);
231        //map[dsi] = 
232      }
233      jmap.insert(j,rbidch_map);
234    }
235    mapping.insert(dsi,jmap);
236  }
237  for pdl in paddles {
238    let dsi  = pdl.dsi as u8;
239    let   j  = pdl.j_ltb   as u8;
240    let ch_a = pdl.ltb_chA as u8;
241    let ch_b = pdl.ltb_chB as u8;
242    let pid  = pdl.paddle_id as u8;
243    let panel_id = pdl.panel_id as u8;
244    mapping.get_mut(&dsi).unwrap().get_mut(&j).unwrap().insert(ch_a,(pid, panel_id));
245    mapping.get_mut(&dsi).unwrap().get_mut(&j).unwrap().insert(ch_b,(pid, panel_id));
246  }
247  return mapping;
248}
249
250//---------------------------------------------------------------------
251
252/// Create a mapping of DSI/J(LTB) -> RBID
253///
254/// This will basically tell you for a given LTB hit which rb has 
255/// triggered.
256pub fn get_dsi_j_ch_rb_map(paddles : &Vec<TofPaddle>) -> DsiJChRbMapping {
257  let mut mapping = DsiJChRbMapping::new();
258  for dsi in 1..6 {
259    let mut jmap = HashMap::<u8, HashMap<u8, u8>>::new();
260    for j in 1..6 {
261      let mut rbidch_map : HashMap<u8, u8> = HashMap::new();
262      for ch in 1..17 {
263        let rbidch = 0u8;
264        rbidch_map.insert(ch,rbidch);
265        //map[dsi] = 
266      }
267      jmap.insert(j,rbidch_map);
268    }
269    mapping.insert(dsi,jmap);
270  }
271  for pdl in paddles {
272    let dsi    = pdl.dsi as u8;
273    let   j    = pdl.j_ltb   as u8;
274    let ch_a   = pdl.ltb_chA as u8;
275    let ch_b   = pdl.ltb_chB as u8;
276    let rb_id  = pdl.paddle_id as u8;
277    mapping.get_mut(&dsi).unwrap().get_mut(&j).unwrap().insert(ch_a,rb_id);
278    mapping.get_mut(&dsi).unwrap().get_mut(&j).unwrap().insert(ch_b,rb_id);
279  }
280  return mapping;
281}
282
283//---------------------------------------------------------------------
284
285/// Get a mapping of which pb controls paddles connected to which RB
286#[cfg_attr(feature="pybindings", pyfunction)]
287pub fn get_rbids_for_pbid(pbid : u8) -> Option<(u8, u8)> {
288  let rats = RAT::all()?;
289  for rat in rats {
290    if rat.pb_id as u8 == pbid {
291      return Some((rat.rb1_id as u8, rat.rb2_id as u8));
292    }
293  }
294  None
295}
296
297pub fn get_rbid_pbchannel_pid_map(paddles : &Vec<TofPaddle>) -> Option<(RbChPidMapping, RbChPidMapping)> {
298  let mut map_a    = RbChPidMapping::new();
299  let mut map_b    = RbChPidMapping::new();
300 
301  let rats = RAT::all().unwrap();
302  let mut rb1rb2map = HashMap::<u8,u8>::new();
303  let mut rb2rb1map = HashMap::<u8,u8>::new();
304  for r in rats {
305    // these vectors are sorted now
306    // the index is the smae for each rat
307    rb1rb2map.insert(r.rb1_id as u8, r.rb2_id as u8);
308    rb2rb1map.insert(r.rb2_id as u8, r.rb1_id as u8);
309  }
310  // for the map, what we want is that for 
311  // BOTH rbs in the rat, we have the SAME 
312  // PB channels/pids 
313  // For the PB, we don't care to which 
314  // RB the data channels are connected to
315  // The rb here is a stand-in for the 
316  // "any rb in that RAT"
317  for pdl in paddles {
318    let rb_id   = pdl.rb_id as u8;
319    let pb_ch_a = pdl.pb_chA as u8;
320    let pb_ch_b = pdl.pb_chB as u8;
321    let pid     = pdl.paddle_id as u8;
322    // chheck if it is rb1 or 2 
323    let other_rb : u8;
324    if rb1rb2map.contains_key(&rb_id) { 
325      other_rb = *rb1rb2map.get(&rb_id).unwrap(); 
326    } else { 
327      other_rb = *rb2rb1map.get(&rb_id).unwrap();   
328    }
329   
330    for rid in [rb_id,other_rb] {
331      if map_a.contains_key(&rid) {
332        map_a.get_mut(&rid).unwrap().insert(pb_ch_a, pid);
333      } else {
334        let mut ch_map = HashMap::<u8,u8>::new();
335        ch_map.insert(pb_ch_a, pid);
336        map_a.insert(rid , ch_map);
337      }
338      if map_b.contains_key(&rid) {
339        map_b.get_mut(&rid).unwrap().insert(pb_ch_b, pid);
340      } else{
341        let mut ch_map = HashMap::<u8,u8>::new();
342        ch_map.insert(pb_ch_b, pid);
343        map_b.insert(rid , ch_map);
344      }
345    }
346  }
347  Some((map_a, map_b))
348}
349
350//---------------------------------------------------------------------
351
352/// Create a mapping of DSI/J(LTB) -> RBID
353///
354/// This will basically tell you for a given LTB hit which rb has 
355/// triggered.
356#[cfg(feature="pybindings")]
357#[pyfunction]
358#[pyo3(name="get_dsi_j_ch_rb_map")]
359pub fn get_dsi_j_ch_rb_map_py() -> Option<DsiJChRbMapping> {
360  if let Some(paddles) = TofPaddle::all() {
361    return Some(get_dsi_j_ch_rb_map(&paddles));
362  } else {
363    return None;
364  }
365}
366
367
368
369
370//---------------------------------------------------------------------
371
372/// Create a mapping of RB/PB Channel -> PaddleID
373///
374/// Find out to which paddle ends the sipms are connected 
375/// on the powerboard. 
376/// Per each RAT, there is one RB which controls the 
377/// PB (powerboard). For a given RB id, find out which 
378/// PB is in the same RAT and return the connected 
379/// paddle id
380///
381/// # Returns:
382///   * tuple(dict (rb_id, dict(pb_ch, pid)),..) 
383///     The returned tuple contains two dictionaries. 
384///     The first is for paddle end A, the second for 
385///     paddle end B
386#[cfg(feature="pybindings")]
387#[pyfunction]
388#[pyo3(name="get_rbid_pbchannel_pid_map")]
389pub fn get_rbid_pbchannel_pid_map_py() -> Option<(RbChPidMapping, RbChPidMapping)> {
390  if let Some(paddles) = TofPaddle::all() {
391    return Some(get_rbid_pbchannel_pid_map(&paddles).unwrap());
392  } else {
393    return None;
394  }
395}
396
397//---------------------------------------------------------------------
398
399/// Create a mapping of DSI/J(LTB) -> PaddleID
400///
401/// This will basically tell you for a given LTB hit which paddle has 
402/// triggered.
403#[cfg(feature="pybindings")]
404#[pyfunction]
405#[pyo3(name="get_dsi_j_ch_pid_map")]
406pub fn get_dsi_j_ch_pid_map_py() -> Option<DsiJChPidMapping> {
407  if let Some(paddles) = TofPaddle::all() {
408    return Some(get_dsi_j_ch_pid_map(&paddles));
409  } else {
410    return None;
411  }
412}
413
414//---------------------------------------------------------------------
415
416/// Map the detector ids ("hardware" ids) to volume ids as used in the 
417/// simulation 
418///
419/// Get the map first and then query it 
420/// 
421/// ```python
422/// m = gondola.db.get_hid_vid_maps() 
423/// print (m[0][160]) # volume id for paddle 160
424/// ```  
425/// 
426/// # Returns: 
427///   * tuple (dict,dict) : Two maps, the first for the tof, the second 
428///                         for the tracker 
429#[cfg_attr(feature="pybindings", pyfunction)]
430pub fn get_hid_vid_maps() -> Option<(HashMap<u32, u64>, HashMap<u32, u64>)> {
431  // FIXME - error catching
432  let pdls   = TofPaddle::all_as_dict().unwrap(); 
433  let strips = TrackerStrip::all_as_dict().unwrap();
434  let mut hid_vid_map_tof = HashMap::<u32, u64>::new();
435  let mut hid_vid_map_trk = HashMap::<u32, u64>::new();  
436  for k in pdls.keys() {
437    hid_vid_map_tof.insert(*k as u32, pdls[k].volume_id as u64);
438  }
439  for k in strips.keys() {
440    hid_vid_map_trk.insert(*k as u32,strips[k].volume_id as u64);
441  }
442  Some((hid_vid_map_tof, hid_vid_map_trk))
443}
444
445//---------------------------------------------------------------------
446
447/// Map the volume id as it is used in the simulation to the actual 
448/// ("hardware") detector ids
449///
450/// Get the map first and then query it 
451/// ```python
452/// m = gondola.db.get_vid_hid_maps() 
453/// print (m[0][100000000]) # tof paddle 1
454/// ```  
455/// 
456/// # Returns: 
457///   * tuple (dict,dict) : Two maps, the first for the tof, the second 
458///                         for the tracker 
459#[cfg_attr(feature="pybindings", pyfunction)]
460pub fn get_vid_hid_maps() -> Option<(HashMap<u64, u32>, HashMap<u64,u32>)> {
461  // FIXME - error catching
462  let pdls   = TofPaddle::all_as_dict().unwrap(); 
463  let strips = TrackerStrip::all_as_dict().unwrap();
464  let mut vid_hid_map_tof = HashMap::<u64, u32>::new();
465  let mut vid_hid_map_trk = HashMap::<u64, u32>::new();
466  for k in pdls.keys() {
467    vid_hid_map_tof.insert(pdls[k].volume_id as u64, *k as u32);
468  }
469  for k in strips.keys() {
470    vid_hid_map_trk.insert(strips[k].volume_id as u64, *k);
471  }
472  Some((vid_hid_map_tof, vid_hid_map_trk))
473}
474
475//---------------------------------------------------------------------
476
477/// Create a mapping of mtb link ids to rb ids
478//#[cfg_attr(feature="pybindings", pyfunction)]
479pub fn get_linkid_rbid_map(rbs : &Vec<ReadoutBoard>) -> HashMap<u8, u8>{
480  let mut mapping = HashMap::<u8, u8>::new();
481  for rb in rbs {
482    mapping.insert(rb.mtb_link_id, rb.rb_id);
483  }
484  mapping
485}
486
487//---------------------------------------------------------------------
488
489/// Create a map for rbid, ch -> paddle id. This is only for the A 
490/// side and will not have an entry in case the given RB channel
491/// is connected to the B side of the paddle
492pub fn get_rb_ch_pid_a_map() -> Option<RbChPidMapping> {
493  let paddles = TofPaddle::all()?;
494  let mut mapping = RbChPidMapping::new();
495  for rbid  in 1..51 {
496    let mut chmap = HashMap::<u8, u8>::new();
497    for ch in 1..9 {
498      chmap.insert(ch,0);
499    }
500    mapping.insert(rbid,chmap);
501  }
502  for pdl in paddles {
503    let rb_id = pdl.rb_id  as u8;
504    let ch_a  = pdl.rb_chA as u8;
505    let pid   = pdl.paddle_id as u8;
506    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_a).unwrap() = pid;
507  }
508  Some(mapping)
509}
510
511//---------------------------------------------------------------------
512
513/// Create a map for rbid, ch -> paddle id. This is only for the B 
514/// side and will not have an entry in case the given RB channel
515/// is connected to the A side of the paddle
516pub fn get_rb_ch_pid_b_map() -> Option<RbChPidMapping> {
517  let mut mapping = RbChPidMapping::new();
518  let paddles = TofPaddle::all()?;
519  for rbid  in 1..51 {
520    let mut chmap = HashMap::<u8, u8>::new();
521    for ch in 1..9 {
522      chmap.insert(ch,0);
523    }
524    mapping.insert(rbid,chmap);
525  }
526
527  for pdl in paddles {
528    let rb_id = pdl.rb_id  as u8;
529    let ch_b  = pdl.rb_chB as u8;
530    let pid   = pdl.paddle_id as u8;
531    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_b).unwrap() = pid;
532  }
533  Some(mapping)
534}
535
536//---------------------------------------------------------------------
537
538/// Create a map for rbid, ch -> paddle id. 
539///
540/// This version is oblivious to the paddle ends 
541pub fn get_rb_ch_pid() -> Option<RbChPidMapping> {
542  let paddles = TofPaddle::all()?;
543  let mut mapping = RbChPidMapping::new();
544  for rbid  in 1..51 {
545    let mut chmap = HashMap::<u8, u8>::new();
546    for ch in 1..9 {
547      chmap.insert(ch,0);
548    }
549    mapping.insert(rbid,chmap);
550  }
551  for pdl in paddles {
552    let rb_id = pdl.rb_id  as u8;
553    let ch_a  = pdl.rb_chA as u8;
554    let ch_b  = pdl.rb_chB as u8;
555    let pid   = pdl.paddle_id as u8;
556    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_a).unwrap() = pid;
557    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_b).unwrap() = pid;
558  }
559  Some(mapping)
560}
561
562//---------------------------------------------------------------------
563
564/// Get all rb ids from paddles which are stored in the 
565/// database
566#[cfg_attr(feature="pybindings", pyfunction)]
567pub fn get_all_rbids_in_db() -> Option<Vec<u8>> {
568  match TofPaddle::all() {
569    None => {
570      error!("Can not load paddles from DB! Did you load the setup-env.sh shell?");
571      return None;
572    }
573    Some(paddles) => {
574      let mut rbids : Vec<u8> = paddles.iter().map(|p| p.rb_id as u8).collect();
575      rbids.sort();
576      rbids.dedup();
577      return Some(rbids);
578    }
579  }
580}
581
582//---------------------------------------------------------------------
583
584#[cfg_attr(feature="pybindings", pyfunction)]
585pub fn get_all_pbids_in_db() -> Option<Vec<u8>> {
586  match TofPaddle::all() {
587    None => {
588      error!("Can not load paddles from DB! Did you load the setup-env.sh shell?");
589      return None;
590    }
591    Some(paddles) => {
592      let mut rbids : Vec<u8> = paddles.iter().map(|p| p.pb_id as u8).collect();
593      rbids.sort();
594      rbids.dedup();
595      return Some(rbids);
596    }
597  }
598}
599
600//---------------------------------------------------------------------
601
602/// A single TOF paddle with 2 ends comnected
603#[derive(Debug,PartialEq, Clone, Queryable, Selectable, Insertable, serde::Serialize, serde::Deserialize)]
604#[diesel(table_name = schema::tof_db_paddle)]
605#[diesel(primary_key(paddle_id))]
606#[allow(non_snake_case)]
607#[cfg_attr(feature="pybindings", pyclass)]
608pub struct TofPaddle {
609  pub paddle_id         : i16, 
610  pub volume_id         : i64, 
611  pub panel_id          : i16, 
612  pub mtb_link_id       : i16, 
613  pub rb_id             : i16, 
614  pub rb_chA            : i16, 
615  pub rb_chB            : i16, 
616  pub ltb_id            : i16, 
617  pub ltb_chA           : i16, 
618  pub ltb_chB           : i16, 
619  pub pb_id             : i16, 
620  pub pb_chA            : i16, 
621  pub pb_chB            : i16, 
622  pub cable_len         : f32, 
623  pub dsi               : i16, 
624  pub j_rb              : i16, 
625  pub j_ltb             : i16, 
626  pub height            : f32, 
627  pub width             : f32, 
628  pub length            : f32, 
629  pub normal_x          : f32,
630  pub normal_y          : f32,
631  pub normal_z          : f32,
632  pub global_pos_x_l0   : f32, 
633  pub global_pos_y_l0   : f32, 
634  pub global_pos_z_l0   : f32, 
635  pub global_pos_x_l0_A : f32, 
636  pub global_pos_y_l0_A : f32, 
637  pub global_pos_z_l0_A : f32, 
638  pub global_pos_x_l0_B : f32, 
639  pub global_pos_y_l0_B : f32, 
640  pub global_pos_z_l0_B : f32, 
641  pub coax_cable_time   : f32,
642  pub harting_cable_time: f32,
643}
644
645impl TofPaddle {
646  pub fn new() -> Self {
647    Self {
648      paddle_id         : 0, 
649      volume_id         : 0, 
650      panel_id          : 0, 
651      mtb_link_id       : 0, 
652      rb_id             : 0, 
653      rb_chA            : 0, 
654      rb_chB            : 0, 
655      ltb_id            : 0, 
656      ltb_chA           : 0, 
657      ltb_chB           : 0, 
658      pb_id             : 0, 
659      pb_chA            : 0, 
660      pb_chB            : 0, 
661      cable_len         : 0.0, 
662      dsi               : 0, 
663      j_rb              : 0, 
664      j_ltb             : 0, 
665      height            : 0.0, 
666      width             : 0.0, 
667      length            : 0.0, 
668      normal_x          : 0.0,
669      normal_y          : 0.0,
670      normal_z          : 0.0,
671      global_pos_x_l0   : 0.0, 
672      global_pos_y_l0   : 0.0, 
673      global_pos_z_l0   : 0.0, 
674      global_pos_x_l0_A : 0.0, 
675      global_pos_y_l0_A : 0.0, 
676      global_pos_z_l0_A : 0.0, 
677      global_pos_x_l0_B : 0.0, 
678      global_pos_y_l0_B : 0.0, 
679      global_pos_z_l0_B : 0.0,
680      coax_cable_time   : 0.0, 
681      harting_cable_time: 0.0
682    }
683  }
684
685  /// Save myself to the database
686  pub fn save(&self) {
687    use schema::tof_db_paddle::dsl::*;
688    //let conn = connect_to_db().unwrap();
689    let _ = diesel::insert_into(tof_db_paddle)
690      .values(self);
691  }
692
693  /// Return the lowest channel number (either A or B)
694  /// to be able to sort the paddles into RBs
695  pub fn get_lowest_rb_ch(&self) -> u8 {
696    if self.rb_chA < self.rb_chB {
697      return self.rb_chA as u8;
698    }
699    else {
700      return self.rb_chB as u8;
701    }
702  }
703
704  /// Get all TofPaddles which are connected to a certain
705  /// Readoutboard
706  ///
707  /// # Arguments:
708  ///   * rbid : The RB id identifier (1-50)
709  pub fn by_rbid(rbid : u8) -> Option<Vec<TofPaddle>> {
710    if rbid > 50 {
711      error!("We don't have any RBs with an ID > 50!");
712      return None
713    }
714    use schema::tof_db_paddle::dsl::*;
715    let mut conn = connect_to_db().ok()?;
716    let rbid_tmp = rbid as i16;
717
718    let paddles = tof_db_paddle.filter(rb_id.eq(rbid_tmp))
719                  .load::<TofPaddle>(&mut conn);
720
721    match paddles {
722      Err(err) => {
723        error!("Unable to load paddles from db! {err}");
724        return None;
725      }
726      Ok(pdls) => {
727        return Some(pdls);
728      }
729    } 
730  }
731
732  /// Retrieve all 160 paddles from the database 
733  pub fn all() -> Option<Vec<TofPaddle>> {
734    use schema::tof_db_paddle::dsl::*;
735    let mut conn = connect_to_db().ok()?;
736    match tof_db_paddle.load::<TofPaddle>(&mut conn) {
737      Err(err) => {
738        error!("Unable to load paddles from db! {err}");
739        return None;
740      }
741      Ok(pdls) => {
742        return Some(pdls);
743      }
744    }
745  }
746  
747  /// Retrive all paddles from the database, but return a 
748  /// HashMap <paddle_id, TofPaddle>
749  pub fn all_as_dict() -> Result<HashMap<u8,Self>, ConnectionError> {
750    let mut paddles = HashMap::<u8, Self>::new();
751    match Self::all() {
752      None => {
753        error!("We can't find any paddles in the database!");
754        return Ok(paddles);
755      }
756      Some(pdls) => {
757        for p in pdls {
758          paddles.insert(p.paddle_id as u8, p.clone());
759        }
760      }
761    }
762    return Ok(paddles);
763  }
764  
765  /// The principal is the direction along the longest
766  /// dimension from A -> B
767  pub fn principal(&self) -> (f32,f32,f32) {
768    let mut pr = (self.global_pos_x_l0_B - self.global_pos_x_l0_A,
769                  self.global_pos_y_l0_B - self.global_pos_y_l0_A,
770                  self.global_pos_z_l0_B - self.global_pos_z_l0_A);
771    let length = f32::sqrt(pr.0.powf(2.0) + pr.1.powf(2.0) + pr.2.powf(2.0)); 
772    pr = (pr.0/length, pr.1/length, pr.2/length);
773    return pr;
774  }
775
776  /// Normal vector of the paddle 
777  pub fn normal(&self) -> (f32, f32, f32) {
778    (self.normal_x, self.normal_y, self.normal_z)
779  }
780
781  pub fn center_pos(&self) -> (f32,f32,f32) {
782    (self.global_pos_x_l0, self.global_pos_y_l0, self.global_pos_z_l0)
783  }
784
785  #[allow(non_snake_case)]
786  pub fn sideA_pos(&self) -> (f32,f32,f32) {
787    (self.global_pos_x_l0_A, self.global_pos_y_l0_A, self.global_pos_z_l0_A)
788  }
789  
790  #[allow(non_snake_case)]
791  pub fn sideB_pos(&self) -> (f32,f32,f32) {
792    (self.global_pos_x_l0_B, self.global_pos_y_l0_B, self.global_pos_z_l0_B)
793  }
794
795  ///Convert DSI and J connection to the actual 
796  ///slot they are plugged in on the MTB (0-24)
797  pub fn rb_slot(&self) -> i16 {
798    (self.dsi-1)*5 + self.j_rb - 1
799  }
800  
801  /// Convert DSI and J connection to the actual 
802  /// slot they are plugged in on the MTB (0-24)
803  pub fn lt_slot(&self) -> i16 {
804    (self.dsi-1)*5 + self.j_ltb - 1
805  }
806} 
807
808#[cfg(feature="pybindings")]
809#[pymethods]
810impl TofPaddle {
811 
812  /// Get the (numerically) lower of the two 
813  /// RB channels the TOF paddle is connected with 
814  /// to its associate ReadoutBoard 
815  #[getter]
816  fn get_lowest_rb_ch_py(&self) -> u8 {
817    self.get_lowest_rb_ch() 
818  }
819
820  /// The paddle id of the paddle in range [1,160]
821  #[getter]
822  fn get_paddle_id   (&self) -> i16 {  
823    self.paddle_id
824  }
825
826  /// Retrieve the volume id. The volume id is 
827  /// assigned by the simulation 
828  #[getter]
829  fn get_volume_id   (&self) -> i64 {  
830    self.volume_id
831  }
832
833  /// Retrieve the panel id.
834  ///
835  /// Panel 1-6  : Cube 
836  /// Panel 7-14 : Umbrella 
837  /// Panel > 14 : Cortina 
838  #[getter]
839  fn get_panel_id    (&self) -> i16 {  
840    self.panel_id
841  }
842
843  /// The MTB link id is an internal number
844  /// used by the MTB to identify ReadoutBoards 
845  #[getter]
846  fn get_mtb_link_id (&self) -> i16 {  
847    self.mtb_link_id
848  }
849
850  /// Retrieve the Readoutboard id for the 
851  /// Readoutboard the paddle is connected to 
852  #[getter]
853  fn get_rb_id       (&self) -> i16 {  
854    self.rb_id
855  } 
856
857  /// Get the ReadoutBoard channel to which 
858  /// the A-side of the Paddle is connected 
859  #[getter]
860  #[allow(non_snake_case)]
861  fn get_rb_chA      (&self) -> i16 {  
862    self.rb_chA
863  }
864  
865  /// Get the ReadoutBoard channel to which 
866  /// the b-side of the Paddle is connected 
867  #[getter]
868  #[allow(non_snake_case)]
869  fn get_rb_chB      (&self) -> i16 {  
870    self.rb_chB
871  }
872
873  /// Get the LTB id the low-gain channels 
874  /// of this paddle are connected to
875  #[getter]
876  fn get_ltb_id      (&self) -> i16 {  
877    self.ltb_id
878  }
879
880  /// Get the LTB channel the A-side of this 
881  /// paddle is connected to 
882  #[getter]
883  #[allow(non_snake_case)]
884  fn get_ltb_chA     (&self) -> i16 {  
885    self.ltb_chA
886  }
887  
888  /// Get the LTB channel the B-side of this 
889  /// paddle is connected to 
890  #[getter]
891  #[allow(non_snake_case)]
892  fn get_ltb_chB     (&self) -> i16 {  
893    self.ltb_chB
894  }
895
896  /// Get the powerboard id for the respective
897  /// powerboard which provides the driving 
898  /// voltage for this paddle
899  #[getter]
900  fn get_pb_id       (&self) -> i16 {  
901    self.pb_id
902  }
903
904  /// Get the channel on the powerboard 
905  /// the paddle A-side is connected to 
906  #[getter]
907  #[allow(non_snake_case)]
908  fn get_pb_chA      (&self) -> i16 {  
909    self.pb_chA
910  }
911  
912  /// Get the channel on the powerboard 
913  /// the paddle b-side is connected to 
914  #[getter]
915  #[allow(non_snake_case)]
916  fn get_pb_chB      (&self) -> i16 {  
917    self.pb_chB
918  }
919
920  /// DEPRECATED - the length of the Harting
921  /// cable connected to this paddle 
922  #[getter]
923  fn get_cable_len   (&self) -> f32 {  
924    self.cable_len
925  }
926
927  /// Retrive the DSI connector this paddle
928  /// is connected through the RB/LTB to 
929  /// the MTB 
930  #[getter]
931  fn get_dsi         (&self) -> i16 {  
932    self.dsi
933  }
934
935  /// Retrieve the j address of the DSI connector 
936  /// this paddle is connected through the RB
937  /// to the MTB 
938  #[getter]
939  fn get_j_rb        (&self) -> i16 {  
940    self.j_rb
941  }
942  
943  /// Retrieve the j address of the DSI connector 
944  /// this paddle is connected through the LTB
945  /// to the MTB 
946  #[getter]
947  fn get_j_ltb       (&self) -> i16 {  
948    self.j_ltb
949  }
950
951  /// Get the (local) height of the paddle 
952  #[getter]
953  fn get_height      (&self) -> f32 {  
954    self.height
955  }
956
957  /// Get the (local) width of the paddle 
958  #[getter]
959  fn get_width       (&self) -> f32 {  
960    self.width
961  }
962
963  /// Get the (local) length of the paddle 
964  #[getter]
965  fn get_length      (&self) -> f32 {  
966    self.length
967  }
968  
969  /// Retrieve all 160 paddles from the database 
970  #[staticmethod]
971  #[pyo3(name="all")]
972  pub fn all_py() -> Option<Vec<Self>> {
973    TofPaddle::all()
974  } 
975
976  /// Retrieve all paddles connected to a certain 
977  /// ReadoutBoard from the database 
978  ///
979  /// # Arguments 
980  ///   * rbid   : RB id of the desired ReadoutBoard (typically < 50) 
981  #[staticmethod]
982  #[pyo3(name="by_rbid")]
983  pub fn by_rbid_py(rbid : u8) -> Option<Vec<Self>> {
984    TofPaddle::by_rbid(rbid)
985  }
986
987  /// Retrieve all paddles from the database and return 
988  /// a dictionary as dict([rbid, TofPaddle]) 
989  // FIXME use PyResult
990  #[staticmethod]
991  #[pyo3(name="all_as_dict")]
992  pub fn all_as_dict_py() -> Option<HashMap<u8,Self>> {
993    match TofPaddle::all_as_dict() {
994      Err(err) => {
995        error!("Unable to retrieve paddle dictionary. {err}. Did you laod the setup-env.sh shell?");
996        return None;
997      }
998      Ok(_paddles) => {
999        return Some(_paddles);
1000      }
1001    }
1002  } 
1003  
1004  /// The principal is the direction along the longest
1005  /// dimension from A -> B
1006  #[getter]
1007  #[pyo3(name="principal")]
1008  pub fn principal_py(&self) -> (f32,f32,f32) {
1009    let mut pr = (self.global_pos_x_l0_B - self.global_pos_x_l0_A,
1010                  self.global_pos_y_l0_B - self.global_pos_y_l0_A,
1011                  self.global_pos_z_l0_B - self.global_pos_z_l0_A);
1012    let length = f32::sqrt(pr.0.powf(2.0) + pr.1.powf(2.0) + pr.2.powf(2.0)); 
1013    pr = (pr.0/length, pr.1/length, pr.2/length);
1014    return pr;
1015  }
1016
1017  /// Return normal axis - that is orthogonal to the principal and
1018  /// to the axis of "width", so parallel to the axis of "height"
1019  /// (the thickness of the paddle). E.g. the paddles of the cube
1020  /// top (panel 1) have the normal (0, 0, 1)
1021  #[getter]
1022  #[pyo3(name="normal")]
1023  pub fn normal_py(&self) -> (f32, f32, f32) {
1024    self.normal()
1025  }
1026
1027  /// The center position of the paddle (middle of all 3 local dimensions)
1028  #[getter]
1029  #[pyo3(name="center_pos")]
1030  pub fn center_pos_py(&self) -> (f32,f32,f32) {
1031    (self.global_pos_x_l0, self.global_pos_y_l0, self.global_pos_z_l0)
1032  }
1033
1034  /// The position of the SiPm at the A-side 
1035  #[getter]
1036  #[pyo3(name="sideA_pos")]
1037  #[allow(non_snake_case)]
1038  pub fn sideA_pos_py(&self) -> (f32,f32,f32) {
1039    (self.global_pos_x_l0_A, self.global_pos_y_l0_A, self.global_pos_z_l0_A)
1040  }
1041  
1042  /// The position of the SiPm at the B-side 
1043  #[getter]
1044  #[pyo3(name="sideB_pos")]
1045  #[allow(non_snake_case)]
1046  pub fn sideB_pos_py(&self) -> (f32,f32,f32) {
1047    (self.global_pos_x_l0_B, self.global_pos_y_l0_B, self.global_pos_z_l0_B)
1048  }
1049
1050  ///Convert DSI and J connection to the actual 
1051  ///slot they are plugged in on the MTB (0-24)
1052  #[getter]
1053  #[pyo3(name="rb_slot")]
1054  pub fn rb_slot_py(&self) -> i16 {
1055    self.rb_slot()
1056  }
1057  
1058  /// Convert DSI and J connection to the actual 
1059  /// slot they are plugged in on the MTB (0-24)
1060  #[getter]
1061  #[pyo3(name="lt_slot")]
1062  pub fn lt_slot_py(&self) -> i16 {
1063    self.lt_slot()
1064  }
1065  
1066  /// The x-coordinate of the center position of the paddle  
1067  #[getter]
1068  #[pyo3(name="global_pos_x_l0")]
1069  fn get_global_pos_x_l0(&self) -> f32 {
1070    self.global_pos_x_l0 
1071  }
1072  
1073  /// The y-coordinate of the center position of the paddle  
1074  #[getter]
1075  #[pyo3(name="global_pos_y_l0")]
1076  fn get_global_pos_y_l0(&self) -> f32 {
1077    self.global_pos_y_l0
1078  }
1079  
1080  /// The z-coordinate of the center position of the paddle  
1081  #[getter]
1082  #[pyo3(name="global_pos_z_l0")]
1083  fn get_global_pos_z_l0(&self) -> f32 {
1084    self.global_pos_z_l0
1085  }
1086}
1087
1088
1089#[cfg_attr(feature="pybindings", pymethods)]
1090impl TofPaddle {
1091}
1092
1093//---------------------------------------------------------------------
1094
1095impl fmt::Display for TofPaddle {
1096  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1097    let mut repr = String::from("<TofPaddle:");
1098    repr += "\n** identifiers **";
1099    repr += &(format!("\n   pid                : {}", self.paddle_id));     
1100    repr += &(format!("\n   vid                : {}", self.volume_id));
1101    repr += &(format!("\n   panel id           : {}", self.panel_id));
1102    repr += "\n  ** connedtions **";
1103    repr += &(format!("\n   DSI/J/CH (LG) [A]  : {}  | {} | {:02}", self.dsi, self.j_ltb, self.ltb_chA));
1104    repr += &(format!("\n   DSI/J/CH (HG) [A]  : {}  | {} | {:02}", self.dsi, self.j_rb, self.rb_chA));
1105    repr += &(format!("\n   DSI/J/CH (LG) [B]  : {}  | {} | {:02}", self.dsi, self.j_ltb, self.ltb_chB));
1106    repr += &(format!("\n   DSI/J/CH (HG) [B]  : {}  | {} | {:02}", self.dsi, self.j_rb, self.rb_chB));
1107    repr += &(format!("\n   RB/CH         [A]  : {:02} | {}", self.rb_id, self.rb_chA));
1108    repr += &(format!("\n   RB/CH         [B]  : {:02} | {}", self.rb_id, self.rb_chB));
1109    repr += &(format!("\n   LTB/CH        [A]  : {:02} | {}", self.ltb_id, self.ltb_chA));
1110    repr += &(format!("\n   LTB/CH        [B]  : {:02} | {}", self.ltb_id, self.ltb_chB));
1111    repr += &(format!("\n   PB/CH         [A]  : {:02} | {}", self.pb_id, self.pb_chA));
1112    repr += &(format!("\n   PB/CH         [B]  : {:02} | {}", self.pb_id, self.pb_chB));
1113    repr += &(format!("\n   MTB Link ID        : {:02}", self.mtb_link_id));
1114    repr += "\n   cable len [cm] :";
1115    repr += &(format!("\n    \u{21B3} {:.2}", self.cable_len));
1116    repr += "\n    (Harting -> RB)";
1117    repr += "\n   cable times [ns] (JAZ) :";
1118    repr += &(format!("\n    \u{21B3} {:.2} {:.2}", self.coax_cable_time, self.harting_cable_time));
1119    repr += "\n  ** Coordinates (L0) & dimensions **";
1120    repr += "\n   length, width, height [mm]";
1121    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]", self.length, self.width, self.height));
1122    repr += "\n   center [mm]:";
1123    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]", self.global_pos_x_l0, self.global_pos_y_l0, self.global_pos_z_l0));
1124    repr += "\n   normal vector:";
1125    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]", self.normal_x, self.normal_y, self.normal_z));
1126    repr += "\n   A-side [mm]:";
1127    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]>", self.global_pos_x_l0_A, self.global_pos_y_l0_A, self.global_pos_z_l0_A));
1128    repr += "\n   B-side [mm]:";
1129    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]>", self.global_pos_x_l0_B, self.global_pos_y_l0_B, self.global_pos_z_l0_B));
1130    write!(f, "{}", repr)
1131  }
1132}
1133
1134//---------------------------------------------------------------------
1135
1136#[cfg(feature="pybindings")]
1137pythonize!(TofPaddle);
1138
1139//---------------------------------------------------------------------
1140
1141/// A Readoutboard with paddles connected
1142#[derive(Debug, Clone)]
1143#[allow(non_snake_case)]
1144#[cfg_attr(feature="pybindings", pyclass)]
1145pub struct ReadoutBoard {
1146  pub rb_id           : u8, 
1147  pub dsi             : u8, 
1148  pub j               : u8, 
1149  pub mtb_link_id     : u8, 
1150  pub paddle12        : TofPaddle,
1151  //pub paddle12_chA    : u8,
1152  pub paddle34        : TofPaddle,
1153  //pub paddle34_chA    : u8,
1154  pub paddle56        : TofPaddle,
1155  //pub paddle56_chA    : u8,
1156  pub paddle78        : TofPaddle,
1157  //pub paddle78_chA    : u8,
1158  // extra stuff, not from the db
1159  // or maybe in the future?
1160  pub calib_file_path : String,
1161  pub calibration     : RBCalibrations,       
1162}
1163  
1164impl ReadoutBoard {
1165  
1166  pub fn new() -> Self {
1167    Self {
1168      rb_id           : 0, 
1169      dsi             : 0, 
1170      j               : 0, 
1171      mtb_link_id     : 0, 
1172      paddle12        : TofPaddle::new(),
1173      //paddle12_chA    : 0,
1174      paddle34        : TofPaddle::new(),
1175      //paddle34_chA    : 0,
1176      paddle56        : TofPaddle::new(),
1177      //paddle56_chA    : 0,
1178      paddle78        : TofPaddle::new(),
1179      //paddle78_chA    : 0,
1180      calib_file_path : String::from(""),
1181      calibration     : RBCalibrations::new(0),
1182    }
1183  }
1184
1185  #[allow(non_snake_case)]
1186  pub fn get_paddle12_chA(&self) -> u8 {
1187    self.paddle12.rb_chA as u8 
1188  }
1189  
1190  #[allow(non_snake_case)]
1191  pub fn get_paddle34_chA(&self) -> u8 {
1192    self.paddle34.rb_chA as u8 
1193  }
1194  
1195  #[allow(non_snake_case)]
1196  pub fn get_paddle56_chA(&self) -> u8 {
1197    self.paddle56.rb_chA as u8 
1198  }
1199  
1200  #[allow(non_snake_case)]
1201  pub fn get_paddle78_chA(&self) -> u8 {
1202    self.paddle78.rb_chA as u8 
1203  }
1204
1205  pub fn by_rbid(rbid : u8) -> Option<Self> {
1206    let paddles = TofPaddle::by_rbid(rbid);
1207    if paddles.is_none() {
1208      return None;
1209    }
1210    let mut rb_paddles = paddles.unwrap();   
1211    if rb_paddles.len() != 4 {
1212      panic!("Found more than 4 paddles for this RB! DB inconsistency! Abort!");
1213    }
1214    rb_paddles.sort_by_key(|paddle| paddle.get_lowest_rb_ch());
1215    // we ensured earlier that the vector is of len 4
1216    let paddle78 = rb_paddles.pop().unwrap();
1217    let paddle56 = rb_paddles.pop().unwrap();
1218    let paddle34 = rb_paddles.pop().unwrap();
1219    let paddle12 = rb_paddles.pop().unwrap();
1220
1221    Some(ReadoutBoard {
1222      rb_id           : rbid, 
1223      dsi             : paddle12.dsi as u8, 
1224      j               : paddle12.j_rb as u8, 
1225      mtb_link_id     : paddle12.mtb_link_id as u8, 
1226      paddle12        : paddle12,
1227      //paddle12_chA    : paddle12,
1228      paddle34        : paddle34,
1229      //paddle34_chA    : 0,
1230      paddle56        : paddle56,
1231      //paddle56_chA    : 0,
1232      paddle78        : paddle78,
1233      //paddle78_chA    : 0,
1234      calib_file_path : String::from(""),
1235      calibration     : RBCalibrations::new(0),
1236    })
1237  }
1238
1239  /// Returns the ip address following a convention
1240  ///
1241  /// This does NOT GUARANTEE that the address is correct!
1242  pub fn guess_address(&self) -> String {
1243    format!("tcp://10.0.1.1{:02}:42000", self.rb_id)
1244  }
1245 
1246  pub fn get_paddle_ids(&self) -> [u8;4] {
1247    let pid0 = self.paddle12.paddle_id as u8;
1248    let pid1 = self.paddle34.paddle_id as u8;
1249    let pid2 = self.paddle56.paddle_id as u8;
1250    let pid3 = self.paddle78.paddle_id as u8;
1251    [pid0, pid1, pid2, pid3]
1252  }
1253
1254  #[allow(non_snake_case)]
1255  pub fn get_A_sides(&self) -> [u8;4] {
1256    let pa_0 = self.get_paddle12_chA();
1257    let pa_1 = self.get_paddle34_chA();
1258    let pa_2 = self.get_paddle56_chA();
1259    let pa_3 = self.get_paddle78_chA();
1260    [pa_0, pa_1, pa_2, pa_3]
1261  }
1262
1263  #[allow(non_snake_case)]
1264  pub fn get_pid_rbchA(&self, pid : u8) -> Option<u8> {
1265    if self.paddle12.paddle_id as u8 == pid {
1266      let rv = self.paddle12.rb_chA as u8;
1267      return Some(rv);
1268    } else if self.paddle34.paddle_id as u8 == pid {
1269      let rv = self.paddle34.rb_chA as u8;
1270      return Some(rv);
1271    } else if self.paddle56.paddle_id as u8 == pid {
1272      let rv = self.paddle56.rb_chA as u8;
1273      return Some(rv);
1274    } else if self.paddle78.paddle_id as u8== pid {
1275      let rv = self.paddle78.rb_chA as u8;
1276      return Some(rv);
1277    } else {
1278      return None;
1279    }
1280  }
1281  
1282  #[allow(non_snake_case)]
1283  pub fn get_pid_rbchB(&self, pid : u8) -> Option<u8> {
1284    if self.paddle12.paddle_id as u8 == pid {
1285      let rv = self.paddle12.rb_chB as u8;
1286      return Some(rv);
1287    } else if self.paddle34.paddle_id as u8== pid {
1288      let rv = self.paddle34.rb_chB as u8;
1289      return Some(rv);
1290    } else if self.paddle56.paddle_id as u8== pid {
1291      let rv = self.paddle56.rb_chB as u8;
1292      return Some(rv);
1293    } else if self.paddle78.paddle_id as u8 == pid {
1294      let rv = self.paddle78.rb_chB as u8;
1295      return Some(rv);
1296    } else {
1297      return None;
1298    }
1299  }
1300
1301  pub fn get_paddle_length(&self, pid : u8) -> Option<f32> {
1302    if self.paddle12.paddle_id as u8 == pid {
1303      let rv = self.paddle12.length;
1304      return Some(rv);
1305    } else if self.paddle34.paddle_id as u8== pid {
1306      let rv = self.paddle34.length;
1307      return Some(rv);
1308    } else if self.paddle56.paddle_id as u8== pid {
1309      let rv = self.paddle56.length;
1310      return Some(rv);
1311    } else if self.paddle78.paddle_id as u8 == pid {
1312      let rv = self.paddle78.length;
1313      return Some(rv);
1314    } else {
1315      return None;
1316    }
1317  }
1318  
1319  pub fn all() -> Option<Vec<Self>> {
1320    let all_rbs = get_all_rbids_in_db();
1321    match all_rbs {
1322      None => {
1323        error!("Can not get TofPaddle information from DB, and thus can't construct ReadoutBoard instances. Did you load the setup-env.sh shell?");
1324        return None;
1325      }
1326      Some(all_rbids) => {
1327        let mut rbs = Vec::<Self>::new();
1328        for k in all_rbids {
1329          rbs.push(ReadoutBoard::by_rbid(k)?);
1330        }
1331        return Some(rbs);
1332      }
1333    }
1334  }
1335  
1336  /// Get all Readoutboards from the database
1337  ///
1338  /// # Returns:
1339  ///   * dict [rbid->Readoutboard]
1340  pub fn all_as_dict() -> Result<HashMap<u8,Self>, ConnectionError> {
1341    let mut rbs = HashMap::<u8, Self>::new();
1342    match Self::all() {
1343      None => {
1344        error!("We can't find any readoutboards in the database!");
1345        return Ok(rbs);
1346      }
1347      Some(rbs_) => {
1348        for rb in rbs_ {
1349          rbs.insert(rb.rb_id, rb );
1350        }
1351      }
1352    }
1353    return Ok(rbs);
1354  }
1355  
1356  pub fn to_summary_str(&self) -> String {
1357    let mut repr  = String::from("<ReadoutBoard:");
1358    repr += &(format!("\n  Board id    : {}",self.rb_id));            
1359    repr += &(format!("\n  MTB Link ID : {}",self.mtb_link_id));
1360    repr += &(format!("\n  RAT         : {}",self.paddle12.ltb_id));
1361    repr += &(format!("\n  DSI/J       : {}/{}",self.dsi,self.j));
1362    repr += "\n **Connected paddles**";
1363    repr += &(format!("\n  Channel 1/2 : {:02} (panel {:01})", self.paddle12.paddle_id, self.paddle12.panel_id));
1364    repr += &(format!("\n  Channel 3/4 : {:02} (panel {:01})", self.paddle34.paddle_id, self.paddle34.panel_id));
1365    repr += &(format!("\n  Channel 5/6 : {:02} (panel {:01})", self.paddle56.paddle_id, self.paddle56.panel_id));
1366    repr += &(format!("\n  Channel 7/8 : {:02} (panel {:01})", self.paddle78.paddle_id, self.paddle78.panel_id));
1367    repr
1368  }
1369
1370  /// Load the newest calibration from the calibration file path
1371  pub fn load_latest_calibration(&mut self) -> Result<(), Box<dyn std::error::Error>> {
1372    //  files look like RB20_2024_01_26-08_15_54.cali.tof.gaps
1373    //let re = Regex::new(r"(\d{4}_\d{2}_\d{2}-\d{2}_\d{2}_\d{2})")?;
1374    let re = Regex::new(r"(\d{6}_\d{6})")?;
1375    // Define your file pattern (e.g., "logs/*.log" for all .log files in the logs directory)
1376    let pattern = format!("{}/RB{:02}_*", self.calib_file_path, self.rb_id); // Adjust this pattern to your files' naming convention
1377    let timestamp = DateTime::<Utc>::from_timestamp(0,0).unwrap(); // I am not sure what to do here
1378                                                                   // otherwise than unwrap. How is
1379                                                                   // this allowed to fail?
1380    //let mut newest_file = (String::from(""), NaiveDateTime::from_timestamp(0, 0));
1381    let mut newest_file = (String::from(""), timestamp);
1382
1383    // Iterate over files that match the pattern
1384    let mut filename : String;
1385    for entry in glob(&pattern)? {
1386      if let Ok(path) = entry {
1387        // Get the filename as a string
1388        //let cpath = path.clone();
1389        match path.file_name() {
1390          None => continue,
1391          Some(fname) => {
1392              // the expect might be ok, since this is something done during initialization
1393              filename = fname.to_os_string().into_string().expect("Unwrapping filename failed!");
1394          }
1395        }
1396        if let Some(caps) = re.captures(&filename) {
1397          if let Some(timestamp_str) = caps.get(0).map(|m| m.as_str()) {
1398            //println!("timestamp_str {}, {}",timestamp_str, HUMAN_TIMESTAMP_FORMAT);
1399            //let timestamp = NaiveDateTime::parse_from_str(timestamp_str, "%Y_%m_%d-%H_%M_%S")?;
1400            //let timestamp = DateTime::<Utc>::parse_from_str(timestamp_str, "%Y_%m_%d-%H_%M_%S")?;
1401            let footzstring = format!("{}+0000", timestamp_str);
1402            let timestamp = DateTime::parse_from_str(&footzstring, "%y%m%d_%H%M%S%z")?;
1403            //let timestamp = DateTime::parse_from_str(&footzstring, HUMAN_TIMESTAMP_FORMAT)?;
1404            //println!("parse successful");
1405            //let _timestamp = DateTime
1406            if timestamp > newest_file.1 {
1407              // FIXME - into might panic?
1408              newest_file.1 = timestamp.into();
1409              newest_file.0 = filename.clone();
1410            }
1411          }
1412        }
1413      }
1414    }
1415    
1416    if newest_file.0.is_empty() {
1417      error!("No matching calibration available for board {}!", self.rb_id);
1418    } else {
1419      let file_to_load = format!("{}/{}", self.calib_file_path, newest_file.0);
1420      info!("Loading calibration from file: {}", file_to_load);
1421      self.calibration = RBCalibrations::from_file(file_to_load, true)?;
1422    }
1423    Ok(())
1424  }
1425}
1426
1427impl fmt::Display for ReadoutBoard {
1428  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1429    let mut repr  = String::from("<ReadoutBoard:");
1430    repr += &(format!("\n  Board id    : {}",self.rb_id));            
1431    repr += &(format!("\n  MTB Link ID : {}",self.mtb_link_id));
1432    repr += &(format!("\n  DSI/J       : {}/{}",self.dsi,self.j));
1433    repr += "\n **Connected paddles**";
1434    repr += &(format!("\n  Ch0/1(1/2)  : {}",self.paddle12)); 
1435    repr += &(format!("\n    A-side    : {}", self.get_paddle12_chA()));
1436    repr += &(format!("\n  Ch1/2(2/3)  : {}",self.paddle34));         
1437    repr += &(format!("\n    A-side    : {}", self.get_paddle34_chA()));
1438    repr += &(format!("\n  Ch2/3(3/4)  : {}",self.paddle56));         
1439    repr += &(format!("\n    A-side    : {}", self.get_paddle56_chA()));
1440    repr += &(format!("\n  Ch3/4(4/5)  : {}>",self.paddle78));         
1441    repr += &(format!("\n    A-side    : {}", self.get_paddle78_chA()));
1442    repr += "** calibration will be loaded from this path:";
1443    repr += &(format!("\n      \u{021B3} {}", self.calib_file_path));
1444    repr += &(format!("\n  calibration : {}>", self.calibration));
1445    write!(f, "{}", repr)
1446  }
1447}
1448
1449//---------------------------------------------------------------------
1450
1451#[cfg(feature="pybindings")]
1452#[pymethods]
1453impl ReadoutBoard {
1454
1455  #[getter]
1456  fn get_rb_id(&self) -> u8 {
1457    self.rb_id
1458  }
1459
1460  #[getter]
1461  fn get_dsi(&self) -> u8 {
1462    self.dsi
1463  }
1464
1465  #[getter]
1466  fn get_j(&self) -> u8 {
1467    self.j
1468  }
1469
1470  #[getter]
1471  fn get_mtb_link_id(&self) -> u8 {
1472    self.mtb_link_id
1473  }
1474
1475  #[getter]
1476  fn get_paddle12(&self) -> TofPaddle { 
1477    self.paddle12.clone() 
1478  }
1479  
1480  #[getter]
1481  fn get_paddle34(&self) -> TofPaddle { 
1482    self.paddle34.clone() 
1483  }
1484  
1485  #[getter]
1486  fn get_paddle56(&self) -> TofPaddle { 
1487    self.paddle56.clone() 
1488  }
1489  
1490  #[getter]
1491  fn get_paddle78(&self) -> TofPaddle { 
1492    self.paddle78.clone() 
1493  }
1494
1495  #[staticmethod]
1496  #[pyo3(name="all")]
1497  pub fn all_py() -> Option<Vec<Self>> {
1498    Self::all()
1499  } 
1500
1501  /// Load a calibration file for this specific Readoutboard
1502  #[pyo3(name="load_calibration")]
1503  pub fn load_calibration_py(&mut self, path : &Bound<'_,PyAny>) -> PyResult<()> {
1504    let mut string_value = String::from("foo");
1505    if let Ok(s) = path.extract::<String>() {
1506       string_value = s;
1507    } //else if let Ok(p) = filename_or_directory.extract::<&Path>() {
1508    if let Ok(fspath_method) = path.getattr("__fspath__") {
1509      if let Ok(fspath_result) = fspath_method.call0() {
1510        if let Ok(py_string) = fspath_result.extract::<String>() {
1511          string_value = py_string;
1512        }
1513      }
1514    }
1515    self.calib_file_path = string_value;
1516    match self.load_latest_calibration() {
1517      Ok(_) => {
1518        return Ok(())
1519      }
1520      Err(err) => { 
1521        return Err(PyValueError::new_err(err.to_string()));
1522      }
1523    }
1524  }
1525
1526  #[staticmethod]
1527  #[pyo3(name="all_as_dict")]
1528  pub fn all_as_dict_py() -> Option<HashMap<u8,Self>> {
1529    match Self::all_as_dict() {
1530      Err(err) => {
1531        error!("Unable to retrieve RB dictionary. {err}. Did you laod the setup-env.sh shell?");
1532        return None;
1533      }
1534      Ok(_data) => {
1535        return Some(_data);
1536      }
1537    }
1538  } 
1539}
1540//paddle12        : TofPaddle::new(),
1541////paddle12_chA    : 0,
1542//paddle34        : TofPaddle::new(),
1543////paddle34_chA    : 0,
1544//paddle56        : TofPaddle::new(),
1545////paddle56_chA    : 0,
1546//paddle78        : TofPaddle::new(),
1547////paddle78_chA    : 0,
1548//calib_file_path : String::from(""),
1549//calibration     : RBCalibrations::new(0),
1550//}
1551
1552#[cfg(feature="pybindings")]
1553pythonize!(ReadoutBoard);
1554
1555//---------------------------------------------------------------------
1556
1557#[derive(Debug,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
1558#[diesel(table_name = schema::tof_db_rat)]
1559#[diesel(primary_key(rat_id))]
1560#[allow(non_snake_case)]
1561#[cfg_attr(feature="pybindings", pyclass)]
1562pub struct RAT {
1563  pub rat_id                    : i16, 
1564  pub pb_id                     : i16, 
1565  pub rb1_id                    : i16, 
1566  pub rb2_id                    : i16, 
1567  pub ltb_id                    : i16, 
1568  pub ltb_harting_cable_length  : i16, 
1569}
1570
1571impl RAT {
1572  pub fn new() -> Self {
1573    Self {
1574      rat_id                    : 0, 
1575      pb_id                     : 0, 
1576      rb1_id                    : 0, 
1577      rb2_id                    : 0, 
1578      ltb_id                    : 0, 
1579      ltb_harting_cable_length  : 0, 
1580    }
1581  }
1582  
1583  /// Get the RAT where rb2id matched the argument
1584  pub fn where_rb2id(rb2id : u8) -> Option<Vec<RAT>> {
1585
1586    let mut result = Vec::<RAT>::new();
1587    match RAT::all() {
1588      Some(rats) => {
1589        for rat in rats {
1590          if rat.rb2_id == rb2id as i16 {
1591            result.push(rat);
1592          }
1593        }
1594        return Some(result);
1595      }
1596      None => ()
1597    }
1598    Some(result)
1599  }
1600  
1601  /// Get the RAT where rb1id (the rb id of rb"1" in the RAT) matched the argument
1602  pub fn where_rb1id(rb2id : u8) -> Option<Vec<RAT>> {
1603    let mut result = Vec::<RAT>::new();
1604    match RAT::all() {
1605      Some(rats) => {
1606        for rat in rats {
1607          if rat.rb1_id == rb2id as i16 {
1608            result.push(rat);
1609          }
1610        }
1611        return Some(result);
1612      }
1613      None => ()
1614    }
1615    Some(result)
1616  }
1617
1618  pub fn all() -> Option<Vec<RAT>> {
1619    use schema::tof_db_rat::dsl::*;
1620    let mut conn = connect_to_db().ok()?;
1621    match tof_db_rat.load::<RAT>(&mut conn) {
1622      Err(err) => {
1623        error!("Unable to load RATs from db! {err}");
1624        return None;
1625      }
1626      Ok(rats) => {
1627        return Some(rats);
1628      }
1629    }
1630  }
1631
1632}
1633
1634impl fmt::Display for RAT {
1635  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1636    let mut repr = String::from("<RAT");
1637    repr += &(format!("\n  ID                : {}", self.rat_id));                   
1638    repr += &(format!("\n  PB                : {} ", self.pb_id));                    
1639    repr += &(format!("\n  RB1               : {}", self.rb1_id));                   
1640    repr += &(format!("\n  RB2               : {}", self.rb2_id));                   
1641    repr += &(format!("\n  LTB               : {}", self.ltb_id));                   
1642    repr += &(format!("\n  H. cable len [cm] : {}>", self.ltb_harting_cable_length)); 
1643    write!(f, "{}", repr)
1644  }
1645}
1646
1647///// Get all trackerstrips from the database
1648//pub fn get_trackerstrips() -> Result<HashMap<u32,TrackerStrip>, ConnectionError> {
1649//  let db_path  = env::var("GONDOLA_DB_URL").unwrap_or_else(|_| "".to_string());
1650//  let mut conn = connect_to_db(db_path)?;
1651//  let mut strips = HashMap::<u32, TrackerStrip>::new();
1652//  match TrackerStrip::all(&mut conn) {
1653//    None => {
1654//      error!("We can't find any tracker strips in the database!");
1655//      return Ok(strips);
1656//    }
1657//    Some(ts) => {
1658//      for s in ts {
1659//        strips.insert(s.get_stripid() as u32, s.clone());
1660//      }
1661//    }
1662//  }
1663//  return Ok(strips);
1664//}
1665//
1666///// Create a mapping of mtb link ids to rb ids
1667//pub fn get_linkid_rbid_map(rbs : &Vec<ReadoutBoard>) -> HashMap<u8, u8>{
1668//  let mut mapping = HashMap::<u8, u8>::new();
1669//  for rb in rbs {
1670//    mapping.insert(rb.mtb_link_id, rb.rb_id);
1671//  }
1672//  mapping
1673//}
1674//
1675///// Create a mapping of rb id to mtb link ids
1676//pub fn get_rbid_linkid_map(rbs : &Vec<ReadoutBoard>) -> HashMap<u8, u8> {
1677//  let mut mapping = HashMap::<u8, u8>::new();
1678//  for rb in rbs {
1679//    mapping.insert(rb.rb_id, rb.mtb_link_id);
1680//  }
1681//  mapping
1682//}
1683//
1684
1685
1686
1687
1688///// Create a map for rbid, ch -> paddle id. This is for both sides
1689///// and will always return a paddle id independent of A or B
1690//pub fn get_rb_ch_pid_map(paddles : &Vec<Paddle>) -> RbChPidMapping {
1691//  let mut mapping = RbChPidMapping::new();
1692//  for rbid  in 1..51 {
1693//    let mut chmap = HashMap::<u8, u8>::new();
1694//    for ch in 1..9 {
1695//      chmap.insert(ch,0);
1696//    }
1697//    mapping.insert(rbid,chmap);
1698//  }
1699//  for pdl in paddles {
1700//    let rb_id = pdl.rb_id  as u8;
1701//    let ch_a  = pdl.rb_chA as u8;
1702//    let ch_b  = pdl.rb_chB as u8;
1703//    let pid   = pdl.paddle_id as u8;
1704//    //println!("rb_id {rb_id}, chA {ch_a}, chB {ch_b}");
1705//    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_a).unwrap() = pid;
1706//    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_b).unwrap() = pid;
1707//  }
1708//  mapping
1709//}
1710//
1711///// Create a map for rbid, ch -> paddle id. This is only for the A 
1712///// side and will not have an entry in case the given RB channel
1713///// is connected to the B side of the paddle
1714//pub fn get_rb_ch_pid_a_map(paddles : &Vec<Paddle>) -> RbChPidMapping {
1715//  let mut mapping = RbChPidMapping::new();
1716//  for rbid  in 1..51 {
1717//    let mut chmap = HashMap::<u8, u8>::new();
1718//    for ch in 1..9 {
1719//      chmap.insert(ch,0);
1720//    }
1721//    mapping.insert(rbid,chmap);
1722//  }
1723//  for pdl in paddles {
1724//    let rb_id = pdl.rb_id  as u8;
1725//    let ch_a  = pdl.rb_chA as u8;
1726//    let pid   = pdl.paddle_id as u8;
1727//    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_a).unwrap() = pid;
1728//  }
1729//  mapping
1730//}
1731//
1732//
1733///// Create a map for rbid, ch -> paddle id. This is only for the B 
1734///// side and will not have an entry in case the given RB channel
1735///// is connected to the A side of the paddle
1736//pub fn get_rb_ch_pid_b_map(paddles : &Vec<Paddle>) -> RbChPidMapping {
1737//  let mut mapping = RbChPidMapping::new();
1738//  for rbid  in 1..51 {
1739//    let mut chmap = HashMap::<u8, u8>::new();
1740//    for ch in 1..9 {
1741//      chmap.insert(ch,0);
1742//    }
1743//    mapping.insert(rbid,chmap);
1744//  }
1745//  for pdl in paddles {
1746//    let rb_id = pdl.rb_id  as u8;
1747//    let ch_b  = pdl.rb_chB as u8;
1748//    let pid   = pdl.paddle_id as u8;
1749//    *mapping.get_mut(&rb_id).unwrap().get_mut(&ch_b).unwrap() = pid;
1750//  }
1751//  mapping
1752//}
1753//
1754///// A representation of a run 
1755//#[derive(Debug, Clone, Queryable,Insertable, Selectable, serde::Serialize, serde::Deserialize)]
1756//#[diesel(table_name = schema::tof_db_run)]
1757//#[diesel(primary_key(run_id))]
1758//pub struct Run {
1759//  pub run_id                    : i64,
1760//  pub runtime_secs              : Option<i64>,
1761//  pub calib_before              : Option<bool>,
1762//  pub shifter                   : Option<i16>,
1763//  pub run_type                  : Option<i16>,
1764//  pub run_path                  : Option<String>,
1765//}
1766//
1767//impl Run {
1768//  pub fn new() -> Self {
1769//    Self {
1770//      run_id        : 0, 
1771//      runtime_secs  : Some(0), 
1772//      calib_before  : Some(true), 
1773//      shifter       : Some(0), 
1774//      run_type      : Some(0), 
1775//      run_path      : Some(String::from("")), 
1776//    }
1777//  }
1778//
1779//  pub fn get_last_run(conn: &mut SqliteConnection) -> Option<u32> {
1780//    use schema::tof_db_run::dsl::*;
1781//    match tof_db_run.load::<Run>(conn) {
1782//      Err(err) => {
1783//        error!("Unable to load DSICards from db! {err}");
1784//        return None;
1785//      }
1786//      Ok(_runs) => {
1787//        //return Some(runs);
1788//      }
1789//    }
1790//    let _results = tof_db_run
1791//      //.filter(published.eq(true))
1792//      .limit(1)
1793//      //.select(Run::as_select())
1794//      .load::<Run>(conn)
1795//      .expect("Error loading posts");
1796//    None
1797//  }
1798//}
1799//
1800//impl fmt::Display for Run {
1801//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1802//    let mut repr = String::from("<Run");
1803//    repr += &(format!("\n  RunID         : {}", self.run_id));                   
1804//    repr += &(format!("\n  - auto cali   : {}", self.calib_before.unwrap_or(false)));
1805//    repr += &(format!("\n  runtime [sec] : {}", self.runtime_secs.unwrap_or(-1)));
1806//    repr += &(format!("\n  shifter       : {}", self.shifter.unwrap_or(-1)));
1807//    repr += &(format!("\n  run_type      : {}", self.run_type.unwrap_or(-1)));
1808//    repr += &(format!("\n  run_path      : {}", self.run_path.clone().unwrap_or(String::from(""))));
1809//    write!(f, "{}", repr)
1810//  }
1811//}
1812//
1813///// Representation of a local trigger board.
1814///// 
1815///// The individual LTB channels do not map directly to PaddleEnds. Rather two of them
1816///// map to a paddle and then the whole paddle should get read out.
1817///// To be more specific about this. The LTB has 16 channels, but we treat them as 8.
1818///// Each 2 LTB channels get "married" internally in the board and will then continue
1819///// on as 1 LTB channel, visible to the outside. The information about which end of 
1820///// the Paddle crossed which threshhold is lost.
1821///// How it works is that the two channels will be combined by the trigger logic:
1822///// - There are 4 states (2 bits)
1823/////   - 0 - no hit
1824/////   - 1 - Hit
1825/////   - 2 - Beta
1826/////   - 3 - Veto
1827///// 
1828///// Each defining an individual threshold. If that is crossed, the whole paddle
1829///// (ends A+B) will be read out by the ReadoutBoard
1830///// 
1831///// The LTB channels here are labeled 1-8. This is as it is in the TOF spreadsheet.
1832///// Also dsi is labeled as in the spreadsheet and will start from one.
1833///// 
1834///// It is NOT clear from this which ch on the rb is connected to which side, for that
1835///// the paddle/RB tables need to be consulted.
1836///// Again: rb_ch0 does NOT necessarily correspond to the A side!
1837///// 
1838//#[derive(Debug,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
1839//#[diesel(table_name = schema::tof_db_rat)]
1840//#[diesel(primary_key(rat_id))]
1841//pub struct RAT {
1842//  pub rat_id                    : i16, 
1843//  pub pb_id                     : i16, 
1844//  pub rb1_id                    : i16, 
1845//  pub rb2_id                    : i16, 
1846//  pub ltb_id                    : i16, 
1847//  pub ltb_harting_cable_length  : i16, 
1848//}
1849//
1850//impl RAT {
1851//  pub fn new() -> Self {
1852//    Self {
1853//      rat_id                    : 0, 
1854//      pb_id                     : 0, 
1855//      rb1_id                    : 0, 
1856//      rb2_id                    : 0, 
1857//      ltb_id                    : 0, 
1858//      ltb_harting_cable_length  : 0, 
1859//    }
1860//  }
1861//  
1862//  /// Get the RAT where rb2id matched the argument
1863//  pub fn where_rb2id(conn: &mut SqliteConnection, rb2id : u8) -> Option<Vec<RAT>> {
1864//    let mut result = Vec::<RAT>::new();
1865//    match RAT::all(conn) {
1866//      Some(rats) => {
1867//        for rat in rats {
1868//          if rat.rb2_id == rb2id as i16 {
1869//            result.push(rat);
1870//          }
1871//        }
1872//        return Some(result);
1873//      }
1874//      None => ()
1875//    }
1876//    Some(result)
1877//  }
1878//  
1879//  /// Get the RAT where rb1id (the rb id of rb"1" in the RAT) matched the argument
1880//  pub fn where_rb1id(conn: &mut SqliteConnection, rb2id : u8) -> Option<Vec<RAT>> {
1881//    let mut result = Vec::<RAT>::new();
1882//    match RAT::all(conn) {
1883//      Some(rats) => {
1884//        for rat in rats {
1885//          if rat.rb1_id == rb2id as i16 {
1886//            result.push(rat);
1887//          }
1888//        }
1889//        return Some(result);
1890//      }
1891//      None => ()
1892//    }
1893//    Some(result)
1894//  }
1895//
1896//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<RAT>> {
1897//    match tof_db_rat.load::<RAT>(conn) {
1898//      Err(err) => {
1899//        error!("Unable to load RATs from db! {err}");
1900//        return None;
1901//      }
1902//      Ok(rats) => {
1903//        return Some(rats);
1904//      }
1905//    }
1906//  }
1907//
1908//}
1909//
1910//impl fmt::Display for RAT {
1911//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1912//    let mut repr = String::from("<RAT");
1913//    repr += &(format!("\n  ID                : {}", self.rat_id));                   
1914//    repr += &(format!("\n  PB                : {} ", self.pb_id));                    
1915//    repr += &(format!("\n  RB1               : {}", self.rb1_id));                   
1916//    repr += &(format!("\n  RB2               : {}", self.rb2_id));                   
1917//    repr += &(format!("\n  LTB               : {}", self.ltb_id));                   
1918//    repr += &(format!("\n  H. cable len [cm] : {}>", self.ltb_harting_cable_length)); 
1919//    write!(f, "{}", repr)
1920//  }
1921//}
1922//
1923//
1924///// A DSI card which is plugged into one of five slots on the MTB
1925///// The DSI card provides the connection to RBs and LTBs and has 
1926///// a subdivision, which is called 'j'
1927//#[derive(Queryable, Selectable)]
1928//#[diesel(primary_key(dsi_id))]
1929//#[diesel(table_name = schema::tof_db_dsicard)]
1930//pub struct DSICard { 
1931//  pub dsi_id    : i16,
1932//  pub j1_rat_id : Option<i16>,
1933//  pub j2_rat_id : Option<i16>,
1934//  pub j3_rat_id : Option<i16>,
1935//  pub j4_rat_id : Option<i16>,
1936//  pub j5_rat_id : Option<i16>,
1937//}
1938// 
1939//
1940//impl DSICard {
1941//  pub fn new() -> Self {
1942//    Self {
1943//      dsi_id    : 0,
1944//      j1_rat_id : None,
1945//      j2_rat_id : None,
1946//      j3_rat_id : None,
1947//      j4_rat_id : None,
1948//      j5_rat_id : None,
1949//    }
1950//  }
1951//  
1952//  /// True if this RAT box is plugged in to any of the j 
1953//  /// connectors on this specific DSI card
1954//  pub fn has_rat(&self, r_id : u8) -> bool {
1955//    if let Some(rid) = self.j1_rat_id {
1956//      if rid as u8 == r_id {
1957//        return true;
1958//      }
1959//    }
1960//    if let Some(rid) = self.j2_rat_id {
1961//      if rid as u8 == r_id {
1962//        return true;
1963//      }
1964//    }
1965//    if let Some(rid) = self.j3_rat_id {
1966//      if rid as u8 == r_id {
1967//        return true;
1968//      }
1969//    }
1970//    if let Some(rid) = self.j4_rat_id {
1971//      if rid as u8 == r_id {
1972//        return true;
1973//      }
1974//    }
1975//    if let Some(rid) = self.j5_rat_id {
1976//      if rid as u8 == r_id {
1977//        return true;
1978//      }
1979//    }
1980//    return false;
1981//  }
1982//
1983//  /// Get the j connetor for this specific RAT
1984//  /// Raises ValueError if the RAT is not connected
1985//  pub fn get_j(&self, r_id : u8) -> Option<u8> {
1986//    if !self.has_rat(r_id) {
1987//      return None;
1988//    }
1989//    if let Some(rid) = self.j1_rat_id {
1990//      if rid as u8 == r_id {
1991//        let _j = self.j1_rat_id.unwrap() as u8;
1992//        return Some(_j);
1993//      }
1994//    }
1995//    if let Some(rid) = self.j2_rat_id {
1996//      if rid as u8 == r_id {
1997//        let _j = self.j2_rat_id.unwrap() as u8;
1998//        return Some(_j);
1999//      }
2000//    }
2001//    if let Some(rid) = self.j3_rat_id {
2002//      if rid as u8 == r_id {
2003//        let _j = self.j3_rat_id.unwrap() as u8;
2004//        return Some(_j);
2005//      }
2006//    }
2007//    if let Some(rid) = self.j4_rat_id {
2008//      if rid as u8 == r_id {
2009//        let _j = self.j4_rat_id.unwrap() as u8;
2010//        return Some(_j);
2011//      }
2012//    }
2013//    if let Some(rid) = self.j5_rat_id {
2014//      if rid as u8 == r_id {
2015//        let _j = self.j5_rat_id.unwrap() as u8;
2016//        return Some(_j);
2017//      }
2018//    }
2019//  None
2020//  }
2021//  
2022//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<DSICard>> {
2023//    match tof_db_dsicard.load::<DSICard>(conn) {
2024//      Err(err) => {
2025//        error!("Unable to load DSICards from db! {err}");
2026//        return None;
2027//      }
2028//      Ok(dsis) => {
2029//        return Some(dsis);
2030//      }
2031//    }
2032//  }
2033//}
2034//
2035//impl fmt::Display for DSICard {
2036//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2037//    let mut repr  = String::from("<DSI Card:");
2038//    repr += &(format!("\n  ID     : {}", self.dsi_id));     
2039//    repr += "\n  -- -- -- --";
2040//    if let Some(_j) = self.j1_rat_id {
2041//        repr += &(format!("\n  J1 RAT : {}",_j));
2042//    } else {
2043//        repr += "\n  J1 RAT : Not connected";
2044//    }
2045//    if let Some(_j) = self.j2_rat_id {
2046//        repr += &(format!("\n  J2 RAT : {}",_j));
2047//    } else {
2048//        repr += "\n  J2 RAT : Not connected";
2049//    }
2050//    if let Some(_j) = self.j3_rat_id {
2051//        repr += &(format!("\n  J3 RAT : {}",_j));
2052//    } else {
2053//        repr += "\n  J3 RAT : Not connected";
2054//    }
2055//    if let Some(_j) = self.j4_rat_id {
2056//        repr += &(format!("\n  J4 RAT : {}",_j));
2057//    } else {
2058//        repr += "\n  J4 RAT : Not connected";
2059//    }
2060//    if let Some(_j) = self.j5_rat_id {
2061//        repr += &(format!("\n  J5 RAT : {}>",_j));
2062//    } else {
2063//        repr += "\n  J5 RAT : Not connected>";
2064//    }
2065//    write!(f, "{}", repr)
2066//  }
2067//}
2068//
2069
2070/// A single Tracker strip
2071#[derive(Debug,PartialEq, Clone,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
2072#[diesel(table_name = schema::tof_db_trackerstrip)]
2073#[diesel(primary_key(strip_id))]
2074#[allow(non_snake_case)]
2075#[cfg_attr(feature="pybindings", pyclass)]
2076pub struct TrackerStrip {
2077  pub strip_id            : i32,
2078  pub layer               : i32, 
2079  pub row                 : i32, 
2080  pub module              : i32, 
2081  pub channel             : i32,  
2082  pub global_pos_x_l0     : f32,
2083  pub global_pos_y_l0     : f32,
2084  pub global_pos_z_l0     : f32,
2085  pub global_pos_x_det_l0 : f32,
2086  pub global_pos_y_det_l0 : f32,
2087  pub global_pos_z_det_l0 : f32,
2088  pub principal_x         : f32,
2089  pub principal_y         : f32,
2090  pub principal_z         : f32,
2091  pub volume_id           : i64,
2092}
2093
2094impl TrackerStrip {
2095  pub fn new() -> Self {
2096    Self {
2097      strip_id            : 0,
2098      layer               : 0, 
2099      row                 : 0, 
2100      module              : 0, 
2101      channel             : 0,  
2102      global_pos_x_l0     : 0.0,
2103      global_pos_y_l0     : 0.0,
2104      global_pos_z_l0     : 0.0,
2105      global_pos_x_det_l0 : 0.0,
2106      global_pos_y_det_l0 : 0.0,
2107      global_pos_z_det_l0 : 0.0,
2108      principal_x         : 0.0,
2109      principal_y         : 0.0,
2110      principal_z         : 0.0,
2111      volume_id           : 0,
2112    }
2113  }
2114  
2115  /// Factory method for the strip id following tracker convention
2116  pub fn create_stripid(layer : u8, row :u8, module : u8, channel : u8) -> u32 {
2117    channel as u32 + (module as u32)*100 + (row as u32)*10000 + (layer as u32)*100000
2118  }
2119
2120  /// FIXME - why use this at all and not just get the one from the db??
2121  pub fn get_stripid(&self) -> u32 {
2122    self.channel as u32 + (self.module as u32)*100 + (self.row as u32)*10000 + (self.layer as u32)*100000
2123  }
2124  
2125  /// Get all TRK strips from the database
2126  pub fn all_as_dict() -> Result<HashMap<u32,Self>, ConnectionError> {
2127    let mut strips = HashMap::<u32, Self>::new();
2128    match Self::all() {
2129      None => {
2130        error!("We can't find any tracker strips in the database!");
2131        return Ok(strips);
2132      }
2133      Some(strips_) => {
2134        for s in strips_ {
2135          strips.insert(s.strip_id as u32, s );
2136        }
2137      }
2138    }
2139    return Ok(strips);
2140  }
2141
2142  pub fn all() -> Option<Vec<Self>> {
2143    use schema::tof_db_trackerstrip::dsl::*;
2144    let mut conn = connect_to_db().ok()?;
2145    match tof_db_trackerstrip.load::<Self>(&mut conn) {
2146      Err(err) => {
2147        error!("Unable to load tracker strips from db! {err}");
2148        return None;
2149      }
2150      Ok(strips) => {
2151        return Some(strips);
2152      }
2153    }
2154  }
2155
2156  pub fn get_coordinates(&self) -> (f32, f32, f32) {
2157    (self.global_pos_x_l0, self.global_pos_y_l0, self.global_pos_z_l0)
2158  }
2159
2160  pub fn get_detcoordinates(&self) -> (f32, f32, f32) {
2161    (self.global_pos_x_det_l0, self.global_pos_y_det_l0, self.global_pos_z_det_l0)
2162  }
2163}
2164
2165impl fmt::Display for TrackerStrip {
2166  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2167    let mut repr = format!("<TrackerStrip [{}]:", self.strip_id);
2168    repr += &(format!("\n   vid                : {}", self.volume_id));
2169    repr += &(format!("\n   layer              : {}", self.layer));
2170    repr += &(format!("\n   row                : {}", self.row));
2171    repr += &(format!("\n   module             : {}", self.module));
2172    repr += &(format!("\n   channel            : {}", self.channel));
2173    repr += "\n   strip center [mm]:";
2174    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]", self.global_pos_x_l0, self.global_pos_y_l0, self.global_pos_z_l0));
2175    repr += "\n   detector (disk) center [mm]:";
2176    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]", self.global_pos_x_det_l0, self.global_pos_y_det_l0, self.global_pos_z_det_l0));
2177    repr += "\n   strip principal direction:";
2178    repr += &(format!("\n    \u{21B3} [{:.2}, {:.2}, {:.2}]", self.principal_x, self.principal_y, self.principal_z));
2179    write!(f, "{}", repr)
2180  }
2181}
2182
2183#[cfg(feature="pybindings")]
2184#[pymethods]
2185impl TrackerStrip {
2186  #[getter]
2187  fn get_strip_id           (&self) -> i32 {
2188    self.strip_id
2189  }
2190  
2191  #[getter]
2192  fn get_layer              (&self) -> i32 { 
2193    self.layer
2194  }
2195  
2196  #[getter]
2197  fn get_row                (&self) -> i32 { 
2198    self.row
2199  }
2200  
2201  #[getter]
2202  fn get_module             (&self) -> i32 { 
2203    self.module
2204  }
2205  
2206  #[getter]
2207  fn get_channel            (&self) -> i32 {  
2208    self.channel
2209  }
2210
2211  #[getter]
2212  fn get_global_pos_x_l0    (&self) -> f32 {
2213    self.global_pos_x_l0
2214  }
2215
2216  #[getter]
2217  fn get_global_pos_y_l0    (&self) -> f32 {
2218    self.global_pos_y_l0
2219  }
2220
2221  #[getter]
2222  fn get_global_pos_z_l0    (&self) -> f32 {
2223    self.global_pos_z_l0
2224  }
2225
2226  #[getter]
2227  fn get_global_pos_x_det_l0(&self) -> f32 {
2228    self.global_pos_x_det_l0
2229  }
2230
2231  #[getter]
2232  fn get_global_pos_y_det_l0(&self) -> f32 {
2233    self.global_pos_y_det_l0
2234  }
2235
2236  #[getter]
2237  fn get_global_pos_z_det_l0(&self) -> f32 {
2238    self.global_pos_z_det_l0
2239  }
2240
2241  #[getter]
2242  fn coordinates(&self) -> (f32, f32, f32) {
2243    self.get_coordinates()
2244  }
2245
2246  #[getter]
2247  fn detector_coordinates(&self) -> (f32, f32, f32) {
2248    self.get_detcoordinates() 
2249  }
2250
2251  #[getter]
2252  fn get_principal_x        (&self) -> f32 {
2253    self.principal_x
2254  }
2255  #[getter]
2256  fn get_principal_y        (&self) -> f32 {
2257    self.principal_y
2258  }
2259  #[getter]
2260  fn get_principal_z        (&self) -> f32 {
2261    self.principal_z
2262  }
2263  #[getter]
2264  fn get_volume_id          (&self) -> i64 {
2265    self.volume_id
2266  }
2267
2268  #[staticmethod]
2269  #[pyo3(name="all")]
2270  pub fn all_py() -> Option<Vec<Self>> {
2271    Self::all()
2272  } 
2273  
2274  #[staticmethod]
2275  #[pyo3(name="all_as_dict")]
2276  pub fn all_as_dict_py() -> Option<HashMap<u32,Self>> {
2277    match Self::all_as_dict() {
2278      Err(err) => {
2279        error!("Unable to retrieve tracker strip dictionary. {err}. Did you laod the setup-env.sh shell?");
2280        return None;
2281      }
2282      Ok(_data) => {
2283        return Some(_data);
2284      }
2285    }
2286  } 
2287}
2288
2289#[cfg(feature="pybindings")]
2290pythonize!(TrackerStrip);
2291
2292//------------------------------------------------
2293
2294/// Masking of unusable strips as curated by the tracker team 
2295#[derive(Debug,PartialEq, Clone,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
2296#[diesel(table_name = schema::tof_db_tofpaddletimingconstant)]
2297#[diesel(primary_key(data_id))]
2298#[allow(non_snake_case)]
2299#[cfg_attr(feature="pybindings", pyclass)]
2300pub struct TofPaddleTimingConstant {
2301  pub data_id             : i32,
2302  pub paddle_id           : i32,    
2303  pub volume_id           : i64,    
2304  pub utc_timestamp_start : i64,
2305  pub utc_timestamp_stop  : i64,
2306  pub name                : Option<String>, 
2307  pub version             : Option<i32>,   
2308  pub timing_constant     : f32,  
2309  pub paddle_constant     : f32, 
2310  pub panel_constant      : f32,
2311}
2312
2313impl TofPaddleTimingConstant {
2314
2315  pub fn new() -> Self {
2316    Self {
2317      data_id             : 0,
2318      paddle_id           : 0,    
2319      volume_id           : 0,    
2320      utc_timestamp_start : 0,  
2321      utc_timestamp_stop  : 0,
2322      name                : None, 
2323      version             : None,
2324      timing_constant     : 0.0,
2325      paddle_constant     : 0.0,
2326      panel_constant      : 0.0,
2327    }
2328  }
2329
2330  /// Retrieve the names under which the timing constants are 
2331  /// saved 
2332  pub fn all_names() -> Result<Vec<String>, ConnectionError> {
2333    let mut conn = connect_to_db()?;
2334    let mut names = Vec::<String>::new();
2335    let unique_names =
2336      schema::tof_db_tofpaddletimingconstant::table.select(
2337      schema::tof_db_tofpaddletimingconstant::name)
2338      .distinct()
2339      .load::<Option<String>>(&mut conn).expect("Error getting names from db!");
2340    for k in unique_names {
2341      if let Some(n) = k {
2342        names.push(n);
2343      }
2344    }
2345    Ok(names)
2346  }
2347
2348  /// Get Tof timing constants as associated with a distinct name 
2349  ///
2350  /// # Returns:
2351  ///   * HashMap<u32 \[paddle id\], Self> 
2352  pub fn as_dict_by_name(fname : &str) -> Result<HashMap<u8,Self>, ConnectionError> {
2353    use schema::tof_db_tofpaddletimingconstant::dsl::*;
2354    let mut paddles = HashMap::<u8, Self>::new();
2355    if fname == "" {
2356      match Self::all() {
2357        None => {
2358          error!("Unable to retrive ANY TofPaddleTimingConstant");
2359          return Ok(paddles);
2360        }
2361        Some(_paddles) => {
2362          for k in _paddles {
2363            paddles.insert(k.paddle_id as u8, k);
2364          }
2365          return Ok(paddles);
2366        }
2367      }
2368    }
2369    let mut conn = connect_to_db()?;
2370    match tof_db_tofpaddletimingconstant.filter(
2371      schema::tof_db_tofpaddletimingconstant::name.eq(fname)).load::<Self>(&mut conn) {
2372      Err(err) => {
2373        error!("We can't find any TOF paddle timing constants in the database! {err}");
2374        return Ok(paddles);
2375      }
2376      Ok(paddles_) => {
2377        for p in paddles_ {
2378          paddles.insert(p.paddle_id as u8, p );
2379        }
2380      }
2381    }
2382    return Ok(paddles);
2383  }
2384
2385  /// Get all timing calibration constants we have from the database
2386  /// - not recommended, this will be mixing different versions 
2387  ///
2388  /// # Returns:
2389  ///   * HashMap<u32 [strip id], TrackeStripMask> 
2390  pub fn all() -> Option<Vec<Self>> {
2391    use schema::tof_db_tofpaddletimingconstant::dsl::*;
2392    let mut conn = connect_to_db().ok()?;
2393    match tof_db_tofpaddletimingconstant.load::<Self>(&mut conn) {
2394      Err(err) => {
2395        error!("Unable to load TOF paddle timing constants from db! {err}");
2396        return None;
2397      }
2398      Ok(tc) => {
2399        return Some(tc);
2400      }
2401    }
2402  }
2403}
2404
2405impl Default for TofPaddleTimingConstant {
2406  fn default() -> Self {
2407    Self::new()
2408  }
2409}
2410
2411impl fmt::Display for TofPaddleTimingConstant {
2412  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2413    let mut repr = format!("<TofPaddleTimingConstant [paddle {}]:", self.paddle_id);
2414    repr += &(format!("\n   volume id        : {}", self.volume_id));
2415    repr += "\n   UTC Timestamps (Begin/End) :";
2416    repr += &(format!("\n   {}/{}", self.utc_timestamp_start, self.utc_timestamp_stop));    
2417    if self.name.is_some() {
2418      repr += &(format!("\n   name             : {}", self.name.clone().unwrap())); 
2419    }
2420    if self.version.is_some() {
2421      repr += &(format!("\n   version          : {}", self.version.unwrap())); 
2422    }
2423    repr += &(format!("\n   paddle const.    : {}", self.paddle_constant));   
2424    repr += &(format!("\n   panel  const.    : {}", self.panel_constant));   
2425    repr += &(format!("\n   timing const.    : {}", self.timing_constant));   
2426    write!(f, "{}", repr)
2427  }
2428}
2429
2430#[cfg(feature="pybindings")]
2431#[pymethods]
2432impl TofPaddleTimingConstant {
2433  
2434  #[staticmethod]
2435  #[pyo3(name="all")]
2436  pub fn all_py() -> Option<Vec<Self>> {
2437    Self::all()
2438  } 
2439  
2440  #[staticmethod]
2441  #[pyo3(name="all_names")]
2442  /// Get all names for registered datasets. These
2443  /// can be used in .as_dict_by_name() to query 
2444  /// the db for a set of values
2445  pub fn all_names_py() -> Option<Vec<String>> {
2446    match Self::all_names() {
2447      Err(_) => {
2448        return None;
2449      }
2450      Ok(names) => {
2451        return Some(names);
2452      }
2453    }
2454  }
2455 
2456  /// Get the TOF paddle timing constants as associated by a specific 
2457  /// name
2458  ///
2459  /// # Arguments 
2460  ///   * name : The name the constants are associated with 
2461  #[staticmethod]
2462  #[pyo3(name="as_dict_by_name")]
2463  pub fn all_as_dict_py(name : &str) -> Option<HashMap<u8,Self>> {
2464    match Self::as_dict_by_name(name) {
2465      Err(err) => {
2466        error!("Unable to retrieve TOF paddle timing constants dictionary. {err}. Did you laod the setup-env.sh shell?");
2467        return None;
2468      }
2469      Ok(_data) => {
2470        return Some(_data);
2471      }
2472    }
2473  } 
2474  
2475  #[getter]
2476  fn get_paddle_id     (&self) -> i32 {    
2477    self.paddle_id
2478  }
2479  
2480  #[getter]
2481  fn get_volume_id    (&self) -> i64 {    
2482    self.volume_id
2483  }
2484  
2485  #[getter]
2486  fn get_utc_timestamp_start(&self) -> i64 {
2487    self.utc_timestamp_start
2488  }
2489  
2490  #[getter]
2491  fn get_utc_timestamp_stop(&self) -> i64 {
2492    self.utc_timestamp_stop
2493  }
2494  
2495  #[getter]
2496  fn get_name    (&self) -> Option<String> {
2497    self.name.clone()
2498  }
2499 
2500  #[getter]
2501  fn get_version    (&self) -> Option<i32> {
2502    self.version.clone()
2503  }
2504  
2505  #[getter]
2506  fn get_timing_constant       (&self) -> f32 { 
2507    self.timing_constant
2508  }
2509  
2510  #[getter]
2511  fn get_paddle_constant       (&self) -> f32 { 
2512    self.paddle_constant
2513  }
2514  
2515  #[getter]
2516  fn get_panel_constant       (&self) -> f32 { 
2517    self.panel_constant
2518  }
2519
2520  /// Completely reset the timing constant and 
2521  /// NOT use the one from the db, but an own 
2522  fn set_timing_constan(&mut self, tc : f32) {
2523    self.timing_constant = tc;
2524  }
2525
2526}
2527
2528#[cfg(feature="pybindings")]
2529pythonize!(TofPaddleTimingConstant);
2530
2531//----------------------------------
2532
2533/// Measurement of tracker pedestal values for each strip
2534#[derive(Debug,PartialEq, Clone,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
2535#[diesel(table_name = schema::tof_db_trackerstrippedestal)]
2536#[diesel(primary_key(data_id))]
2537#[allow(non_snake_case)]
2538#[cfg_attr(feature="pybindings", pyclass)]
2539pub struct TrackerStripPedestal {
2540  pub data_id             : i32,  
2541  pub strip_id            : i32,    
2542  pub volume_id           : i64,    
2543  pub utc_timestamp_start : i64,
2544  pub utc_timestamp_stop  : i64,
2545  pub name                : Option<String>,
2546  pub pedestal_mean       : f32, 
2547  pub pedestal_sigma      : f32, 
2548  pub is_mean_value       : bool,
2549}
2550
2551impl TrackerStripPedestal {
2552
2553  pub fn new() -> Self {
2554    Self {
2555      data_id             : 0,
2556      strip_id            : 0,    
2557      volume_id           : 0,    
2558      utc_timestamp_start : 0,    
2559      utc_timestamp_stop  : 0,
2560      name                : None,
2561      pedestal_mean       : 0.0,
2562      pedestal_sigma      : 0.0,
2563      is_mean_value       : false
2564    }
2565  }
2566  
2567  /// Get Tracker strip pedestals for a certain dataset 
2568  ///
2569  /// # Returns:
2570  ///   * HashMap<u32 [strip id], TrackerStripMask> 
2571  pub fn as_dict_by_name(fname : &str) -> Result<HashMap<u32,Self>, ConnectionError> {
2572    use schema::tof_db_trackerstrippedestal::dsl::*;
2573    let mut strips = HashMap::<u32, Self>::new();
2574    if fname == "" {
2575      match Self::all() {
2576        None => {
2577          error!("Unable to retrive ANY TrackerStripPedestal");
2578          return Ok(strips);
2579        }
2580        Some(_strips) => {
2581          for k in _strips {
2582            strips.insert(k.strip_id as u32, k);
2583          }
2584          return Ok(strips);
2585        }
2586      }
2587    }
2588    let mut conn = connect_to_db()?;
2589    match tof_db_trackerstrippedestal.filter(
2590      schema::tof_db_trackerstrippedestal::name.eq(fname)).load::<Self>(&mut conn) {
2591      Err(err) => {
2592        error!("We can't find any tracker strip masks in the database! {err}");
2593        return Ok(strips);
2594      }
2595      Ok(peds_) => {
2596        for s in peds_ {
2597          strips.insert(s.strip_id as u32, s );
2598        }
2599      }
2600    }
2601    return Ok(strips);
2602  }
2603 
2604  // FIXME - this fails
2605  pub fn all_names() -> Result<Vec<String>, ConnectionError> {
2606    let mut conn = connect_to_db()?;
2607    let mut names = Vec::<String>::new();
2608    let unique_names =
2609      schema::tof_db_trackerstrippedestal::table.select(
2610      schema::tof_db_trackerstrippedestal::name)
2611      .distinct()
2612      .load::<Option<String>>(&mut conn).expect("Error getting names from db!");
2613    for k in unique_names {
2614      if let Some(n) = k {
2615        names.push(n);
2616      }
2617    }
2618    Ok(names)
2619  }
2620  
2621  /// Get all tracker strip mask from the database
2622  ///
2623  /// # Returns:
2624  ///   * HashMap<u32 [strip id], TrackeStripMask> 
2625  pub fn all() -> Option<Vec<Self>> {
2626    use schema::tof_db_trackerstrippedestal::dsl::*;
2627    let mut conn = connect_to_db().ok()?;
2628    match tof_db_trackerstrippedestal.load::<Self>(&mut conn) {
2629      Err(err) => {
2630        error!("Unable to load tracker strips pedestals from db! {err}");
2631        return None;
2632      }
2633      Ok(strips) => {
2634        return Some(strips);
2635      }
2636    }
2637  }
2638  
2639  ///
2640  pub fn parse_from_file<P: AsRef<Path>>(path: P) -> io::Result<Vec<Self>> {
2641    let file = File::open(path)?;
2642    let reader = BufReader::new(file);
2643    let mut pedestals = Vec::<Self>::new();
2644    let hid_vid_map = get_hid_vid_maps().unwrap().1;
2645    for line in reader.lines() {
2646      let line = line?;
2647      if line.starts_with("#") || line.starts_with("Layer") || line.starts_with("layer") {
2648        continue;
2649      }
2650      let mut ped = TrackerStripPedestal::new();
2651      let parts: Vec<&str> = line.split_whitespace().collect();
2652      if parts.len() == 6 {
2653        // Parse the first number as a standard decimal
2654        let layer   = parts[0].parse::<u8>()
2655          .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
2656        let row     = parts[1].parse::<u8>()
2657          .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
2658        let module   = parts[2].parse::<u8>()
2659          .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
2660        let channel  = parts[3].parse::<u8>()
2661          .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
2662        ped.strip_id  = TrackerStrip::create_stripid(layer, row, module, channel) as i32; 
2663        ped.volume_id = *hid_vid_map.get(&(ped.strip_id as u32)).unwrap() as i64; // critical error is good here,
2664                                                               // should alert the user
2665        ped.pedestal_mean  = parts[4].parse::<f32>()
2666          .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
2667        ped.pedestal_sigma = parts[5].parse::<f32>()
2668          .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
2669        pedestals.push(ped); 
2670      }
2671    }
2672    Ok(pedestals)
2673  }
2674}
2675
2676impl Default for TrackerStripPedestal {
2677  fn default() -> Self {
2678    Self::new()
2679  }
2680}
2681
2682impl fmt::Display for TrackerStripPedestal {
2683  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2684    let mut repr = format!("<TrackerStripPedestal [{}]:", self.strip_id);
2685    repr += &(format!("\n   vid            : {}", self.volume_id));
2686    repr += "\n   UTC Timestamps (Begin/End):";
2687    repr += &(format!("\n   {}/{}", self.utc_timestamp_start, self.utc_timestamp_stop));    
2688    if self.name.is_some() {
2689      repr += &(format!("\n   name : {}", self.name.clone().unwrap()));
2690    }
2691    repr += &(format!("\n   pedestal_mean  : {}", self.pedestal_mean));    
2692    repr += &(format!("\n   pedestal_sigma : {}", self.pedestal_sigma));    
2693    repr += &(format!("\n   is_mean_value  : {}", self.is_mean_value));    
2694    write!(f, "{}", repr)
2695  }
2696}
2697
2698#[cfg(feature="pybindings")]
2699#[pymethods]
2700impl TrackerStripPedestal {
2701  
2702  #[staticmethod]
2703  #[pyo3(name="parse_from_file")]
2704  fn parse_from_file_py(fname : &str) -> Option<Vec<Self>> {
2705    let result = Self::parse_from_file(fname);
2706    if result.is_ok() {
2707      return Some(result.unwrap());
2708    } else {
2709      error!("An error occured when parsing {} : '{}'", fname, result.unwrap_err());
2710      return None;
2711    }
2712  }
2713  
2714  #[staticmethod]
2715  #[pyo3(name="all")]
2716  pub fn all_py() -> Option<Vec<Self>> {
2717    Self::all()
2718  } 
2719  
2720  #[staticmethod]
2721  #[pyo3(name="all_names")]
2722  /// Get all names for registered datasets. These
2723  /// can be used in .as_dict_by_name() to query 
2724  /// the db for a set of values
2725  pub fn all_names_py() -> Option<Vec<String>> {
2726    match Self::all_names() {
2727      Err(_) => {
2728        return None;
2729      }
2730      Ok(names) => {
2731        return Some(names);
2732      }
2733    }
2734  }
2735  
2736  #[staticmethod]
2737  #[pyo3(name="as_dict_by_name")]
2738  pub fn all_as_dict_py(name : &str) -> Option<HashMap<u32,Self>> {
2739    match Self::as_dict_by_name(name) {
2740      Err(err) => {
2741        error!("Unable to retrieve tracker strip pedestal dictionary. {err}. Did you laod the setup-env.sh shell?");
2742        return None;
2743      }
2744      Ok(_data) => {
2745        return Some(_data);
2746      }
2747    }
2748  } 
2749 
2750  #[getter]
2751  #[pyo3(name="name")]
2752  fn get_name_py (&self) -> Option<String> {
2753    self.name.clone()
2754  }
2755  
2756  #[setter]
2757  #[pyo3(name="name")] 
2758  fn set_name_py(&mut self, value : String) {
2759    self.name = Some(value);
2760  }
2761
2762  #[getter]
2763  fn get_strip_id     (&self) -> i32 {    
2764    self.strip_id
2765  }
2766  
2767  #[getter]
2768  fn get_volume_id    (&self) -> i64 {    
2769    self.volume_id
2770  }
2771  
2772  #[getter]
2773  fn get_utc_timestamp_start(&self) -> i64 {
2774    self.utc_timestamp_start
2775  }
2776  
2777  #[getter]
2778  fn get_utc_timestamp_stop(&self) -> i64 {
2779    self.utc_timestamp_stop
2780  }
2781  
2782  #[setter]
2783  fn set_utc_timestamp_start(&mut self, value : i64) {
2784    self.utc_timestamp_start = value;
2785  }
2786  
2787  #[setter]
2788  fn set_utc_timestamp_stop(&mut self, value : i64) {
2789    self.utc_timestamp_stop = value;
2790  }
2791  
2792  #[getter]
2793  fn get_pedestal_mean    (&self) -> f32 {
2794    self.pedestal_mean
2795  }
2796  
2797  #[getter]
2798  fn get_pedestal_sigam   (&self) -> f32 { 
2799    self.pedestal_sigma
2800  }
2801  
2802  #[getter]
2803  fn get_is_mean_value   (&self) -> bool { 
2804    self.is_mean_value
2805  }
2806}
2807
2808#[cfg(feature="pybindings")]
2809pythonize!(TrackerStripPedestal);
2810
2811//-------------------------------------------------
2812
2813/// Common noise subtraction - pulse channels on the wafers and get the average adc. 
2814/// The gain is available as well. Data from Mengjiao's group 
2815#[derive(Debug,PartialEq, Clone,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
2816#[diesel(table_name = schema::tof_db_trackerstripcmnnoise)]
2817#[diesel(primary_key(data_id))]
2818#[allow(non_snake_case)]
2819#[cfg_attr(feature="pybindings", pyclass)]
2820pub struct TrackerStripCmnNoise {   
2821  pub data_id              : i32,
2822  pub strip_id             : i32,    
2823  pub volume_id            : i64,    
2824  pub utc_timestamp_start  : i64,    
2825  pub utc_timestamp_stop   : i64,    
2826  pub name                 : Option<String>, 
2827  pub gain                 : f32,
2828  pub pulse_chn            : i32,
2829  pub pulse_avg            : f32,
2830  pub gain_is_mean         : bool,
2831  pub pulse_is_mean        : bool,
2832} 
2833
2834impl TrackerStripCmnNoise {
2835
2836  pub fn new() -> Self {
2837    Self {
2838      data_id             : 0,
2839      strip_id            : 0,    
2840      volume_id           : 0,    
2841      utc_timestamp_start : 0,   
2842      utc_timestamp_stop  : 0,
2843      name                : None, 
2844      gain                : 0.0, 
2845      pulse_chn           : 0,
2846      pulse_avg           : 0.0,
2847      gain_is_mean        : false,
2848      pulse_is_mean       : false
2849    }
2850  }
2851  
2852  pub fn all_names() -> Result<Vec<String>, ConnectionError> {
2853    let mut conn = connect_to_db()?;
2854    let mut names = Vec::<String>::new();
2855    let unique_names =
2856      schema::tof_db_trackerstripcmnnoise::table.select(
2857      schema::tof_db_trackerstripcmnnoise::name)
2858      .distinct()
2859      .load::<Option<String>>(&mut conn).expect("Error getting names from db!");
2860    for k in unique_names {
2861      if let Some(n) = k {
2862        names.push(n);
2863      }
2864    }
2865    Ok(names)
2866  }
2867  
2868  /// Get Tracker strip cmn noise data for a certain dataset 
2869  ///
2870  /// # Returns:
2871  ///   * HashMap<u32 [strip id], TrackerStripTransferFn> 
2872  pub fn as_dict_by_name(fname : &str) -> Result<HashMap<u32,Self>, ConnectionError> {
2873    use schema::tof_db_trackerstripcmnnoise::dsl::*;
2874    let mut strips = HashMap::<u32, Self>::new();
2875    if fname == "" {
2876      match Self::all() {
2877        None => {
2878          error!("Unable to retrive ANY TrackerStripCMNNoise Data (pulser)");
2879          return Ok(strips);
2880        }
2881        Some(_strips) => {
2882          for k in _strips {
2883            strips.insert(k.strip_id as u32, k);
2884          }
2885          return Ok(strips);
2886        }
2887      }
2888    }
2889    let mut conn = connect_to_db()?;
2890    match tof_db_trackerstripcmnnoise.filter(
2891      schema::tof_db_trackerstripcmnnoise::name.eq(fname)).load::<Self>(&mut conn) {
2892      Err(err) => {
2893        error!("We can't find any tracker strip common noise information with that name in the database! {err}");
2894        return Ok(strips);
2895      }
2896      Ok(peds_) => {
2897        for s in peds_ {
2898          strips.insert(s.strip_id as u32, s );
2899        }
2900      }
2901    }
2902    return Ok(strips);
2903  }
2904
2905  /// Get all tracker strip transfer functions from the database
2906  ///
2907  /// # Returns:
2908  ///   * HashMap<u32 [strip id], TrackeStripTransferFunction> 
2909  pub fn all() -> Option<Vec<Self>> {
2910    use schema::tof_db_trackerstripcmnnoise::dsl::*;
2911    let mut conn = connect_to_db().ok()?;
2912    match tof_db_trackerstripcmnnoise.load::<Self>(&mut conn) {
2913      Err(err) => {
2914        error!("Unable to load tracker transfer functions from db! {err}");
2915        return None;
2916      }
2917      Ok(strips) => {
2918        return Some(strips);
2919      }
2920    }
2921  }
2922}
2923
2924impl fmt::Display for TrackerStripCmnNoise {
2925  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2926    let mut repr = format!("<TrackerStripCmnNoise [{}]:", self.strip_id);
2927    repr += &(format!("\n   vid              : {}", self.volume_id));
2928    repr += "\n   UTC Timestamps (Begin/End):";
2929    repr += &(format!("\n   {}/{}", self.utc_timestamp_start, self.utc_timestamp_stop));    
2930    if self.gain_is_mean {
2931      repr += &(String::from("\n -- Gain is mean value!"));
2932    }
2933    if self.pulse_is_mean {
2934      repr += &(String::from("\n -- Pulse is mean value!"));
2935    }
2936    if self.name.is_some() {
2937      repr += &(format!("\n   name     : {}", self.name.clone().unwrap())); 
2938    }
2939    repr += &(format!("\n   gain : {} pulse ch : {} pulse avg : {}>", self.gain, self.pulse_chn, self.pulse_avg));
2940    write!(f, "{}", repr)
2941  }
2942}
2943
2944
2945
2946#[cfg(feature="pybindings")]
2947#[pymethods]
2948impl TrackerStripCmnNoise {
2949  
2950  #[staticmethod]
2951  #[pyo3(name="all")]
2952  pub fn all_py() -> Option<Vec<Self>> {
2953    Self::all()
2954  } 
2955 
2956  #[staticmethod]
2957  #[pyo3(name="all_names")]
2958  /// Get all names for registered datasets. These
2959  /// can be used in .as_dict_by_name() to query 
2960  /// the db for a set of values
2961  pub fn all_names_py() -> Option<Vec<String>> {
2962    match Self::all_names() {
2963      Err(_) => {
2964        return None;
2965      }
2966      Ok(names) => {
2967        return Some(names);
2968      }
2969    }
2970  }
2971
2972  #[staticmethod]
2973  #[pyo3(name="as_dict_by_name")]
2974  pub fn all_as_dict_py(name : &str) -> Option<HashMap<u32,Self>> {
2975    match Self::as_dict_by_name(name) {
2976      Err(err) => {
2977        error!("Unable to retrieve tracker strip cmn noise dictionary. {err}. Did you laod the setup-env.sh shell?");
2978        return None;
2979      }
2980      Ok(_data) => {
2981        return Some(_data);
2982      }
2983    }
2984  } 
2985  
2986  #[getter]
2987  fn get_strip_id     (&self) -> i32 {    
2988    self.strip_id
2989  }
2990  
2991  #[getter]
2992  fn get_volume_id    (&self) -> i64 {    
2993    self.volume_id
2994  }
2995  
2996  #[getter]
2997  fn get_utc_timestamp_start(&self) -> i64 {
2998    self.utc_timestamp_start
2999  }
3000  
3001  #[getter]
3002  fn get_utc_timestamp_stop(&self) -> i64 {
3003    self.utc_timestamp_stop
3004  }
3005
3006  #[getter]
3007  fn get_name(&self) -> Option<String> {
3008    self.name.clone()
3009  }
3010      
3011  #[getter]
3012  fn get_gain(&self) -> f32 {
3013    self.gain
3014  }
3015  
3016  #[getter]
3017  fn get_pulse_cn(&self) -> u32 {
3018    self.pulse_chn as u32
3019  }
3020
3021  #[getter]
3022  fn get_gain_is_mean(&self) -> bool {
3023    self.gain_is_mean
3024  }
3025  
3026  #[getter]
3027  fn get_pulse_is_mean(&self) -> bool {
3028    self.pulse_is_mean
3029  }
3030
3031  #[getter]
3032  fn get_pulse_avg(&self) -> f32 {
3033    self.pulse_avg
3034  }
3035
3036  //fn get_common_level(&self, adc : f32) -> f32 {
3037  //  self.common_level(adc)
3038  //}
3039
3040}
3041
3042#[cfg(feature="pybindings")]
3043pythonize!(TrackerStripCmnNoise);
3044
3045//-------------------------------------------------
3046
3047#[derive(Debug, Queryable, Selectable)]
3048#[diesel(table_name = schema::calibration_files)]
3049#[diesel(primary_key(id))]
3050#[allow(non_snake_case)]
3051#[cfg_attr(feature="pybindings", pyclass)]
3052pub struct TrackerCalibrationFile {
3053  pub id                        : i32, 
3054  pub file_type                 : TrackerCalibrationFileType,
3055  pub path                      : String, 
3056  pub from_timestamp            : i64, 
3057  pub to_timestamp              : i64, 
3058}
3059
3060impl TrackerCalibrationFile {
3061  pub fn new() -> Self {
3062    Self {
3063      id             : 0,
3064      file_type      : TrackerCalibrationFileType::Unknown,
3065      path           : String::from(""),
3066      from_timestamp : 0,
3067      to_timestamp   : 0, 
3068    }
3069  }
3070}
3071
3072impl Default for TrackerCalibrationFile {
3073  fn default() -> Self {
3074    Self::new()
3075  }
3076}
3077
3078impl fmt::Display for TrackerCalibrationFile  {
3079  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3080    let mut repr = String::from("<TrackerCalibrationFile:");
3081    repr += &(format!("\n id        : {}", self.id));
3082    repr += &(format!("\n file_type : {}", self.file_type));
3083    repr += &(format!("\n path      : {}", self.path));
3084    repr += &(format!("\n from ts   : {} [{}]", self.from_timestamp, get_utc_timestamp_from_unix(self.from_timestamp as f64).unwrap()));
3085    repr += &(format!("\n to   ts   : {} [{}]", self.to_timestamp,   get_utc_timestamp_from_unix(self.to_timestamp as f64).unwrap()));
3086    write!(f, "{}", repr)
3087  }
3088}
3089
3090#[cfg(feature="pybindings")]
3091pythonize!(TrackerCalibrationFile);
3092
3093#[cfg(feature="pybindings")]
3094#[pymethods]
3095impl TrackerCalibrationFile {
3096      
3097  #[getter]
3098  fn get_id(&self) -> i32 {
3099    self.id
3100  }
3101
3102  #[getter]
3103  fn get_file_type(&self) -> TrackerCalibrationFileType {
3104    self.file_type
3105  }
3106
3107#[getter]
3108  fn get_path(&self) -> String {
3109    self.path.clone()
3110  }
3111
3112#[getter]
3113  fn get_from_timestamp(&self) -> i64 {
3114    self.from_timestamp
3115  }
3116
3117#[getter]
3118  fn get_to_timestamp(&self) -> i64 {
3119    self.to_timestamp
3120  }
3121}
3122
3123//-------------------------------------------------
3124
3125//
3126//
3127//
3128//    
3129//// Summary of DSI/J/LTBCH (0-319)
3130//// This is not "official" but provides a way of indexing all
3131//// the individual channels
3132//#[derive(Debug,PartialEq,Queryable, Selectable)]
3133//#[diesel(table_name = schema::tof_db_mtbchannel)]
3134//#[diesel(primary_key(mtb_ch))]
3135//#[allow(non_snake_case)]
3136//pub struct MTBChannel {
3137//  pub mtb_ch      : i64,         
3138//  pub dsi         : Option<i16>, 
3139//  pub j           : Option<i16>, 
3140//  pub ltb_id      : Option<i16>, 
3141//  pub ltb_ch      : Option<i16>, 
3142//  pub rb_id       : Option<i16>, 
3143//  pub rb_ch       : Option<i16>, 
3144//  pub mtb_link_id : Option<i16>, 
3145//  pub paddle_id   : Option<i16>, 
3146//  pub paddle_isA  : Option<bool>,
3147//  pub hg_ch       : Option<i16>, 
3148//  pub lg_ch       : Option<i16>, 
3149//}
3150//
3151//impl MTBChannel {
3152//
3153//  pub fn new() -> Self {
3154//    Self {
3155//      mtb_ch      : -1,         
3156//      dsi         : None, 
3157//      j           : None, 
3158//      ltb_id      : None, 
3159//      ltb_ch      : None, 
3160//      rb_id       : None, 
3161//      rb_ch       : None, 
3162//      mtb_link_id : None, 
3163//      paddle_id   : None, 
3164//      paddle_isA  : None,
3165//      hg_ch       : None, 
3166//      lg_ch       : None, 
3167//    }
3168//  }
3169//  
3170//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<MTBChannel>> {
3171//    use schema::tof_db_mtbchannel::dsl::*;
3172//    match tof_db_mtbchannel.load::<MTBChannel>(conn) {
3173//      Err(err) => {
3174//        error!("Unable to load RATs from db! {err}");
3175//        return None;
3176//      }
3177//      Ok(mtbch) => {
3178//        return Some(mtbch);
3179//      }
3180//    }
3181//  }
3182//}
3183//
3184//
3185//impl fmt::Display for MTBChannel {
3186//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3187//    let mut repr = String::from("<MTBChannel");
3188//    repr += &(format!("\n  Channel ID : {}", self.mtb_ch));
3189//    repr += &(format!("\n  DSI/J/     : {}/{}", self.dsi.unwrap_or(-1), self.j.unwrap_or(-1)));
3190//    repr += "\n  LTB ID/CH => RB ID/CH";
3191//    repr += &(format!("\n   |-> {}/{} => {}/{}", self.ltb_id.unwrap_or(-1), self.ltb_ch.unwrap_or(-1), self.rb_id.unwrap_or(-1), self.rb_ch.unwrap_or(-1)));
3192//    repr += &(format!("\n  MTB Link ID [RB] : {}", self.mtb_link_id.unwrap_or(-1)));
3193//    repr += "\n  LG CH => HG CH";
3194//    repr += &(format!("\n   |-> {} => {}", self.lg_ch.unwrap_or(-1), self.hg_ch.unwrap_or(-1)));
3195//    repr += &(format!("\n  Paddle Id: {}", self.paddle_id.unwrap_or(-1)));
3196//    let mut pend = "None";
3197//    if !self.paddle_isA.is_none() {
3198//      if self.paddle_isA.unwrap() {
3199//          pend = "A";
3200//      } else {
3201//          pend = "B";
3202//      }
3203//    }
3204//    repr += &(format!("\n  Paddle End: {}>", pend));
3205//    write!(f, "{}", repr)
3206//  }
3207//}
3208//
3209//
3210/////////////////////////////////////////////////////
3211////
3212//// The following models exceed a bit the capabilities
3213//// of Diesel, or my Diesel skill.
3214//// These models contain multiple ForeignKeys, in all
3215//// cases these link to the paddle table. 
3216////
3217//// For each of LocalTriggerBoard, ReadoutBoard, Panel
3218//// we have 2 structs:
3219//// One called DB<entity> and the other <entity>. The
3220//// first does have the ForeignKeys as SmallInt, and 
3221//// the latter looks them up and fills in the blanks
3222////
3223////
3224////
3225//
3226///// The DB wrapper for the LocalTriggerBoard, for 
3227///// easy implementation there are no joins, we do 
3228///// them manually in the public implementation 
3229///// of the LocaltriggerBoard
3230//#[derive(Queryable, Selectable, Identifiable, Associations)]
3231//#[diesel(table_name = schema::tof_db_localtriggerboard)]
3232//#[diesel(primary_key(board_id))]
3233//#[diesel(belongs_to(Paddle, foreign_key=paddle1_id))]
3234//pub struct DBLocalTriggerBoard {
3235//    pub board_id      : i16,    
3236//    pub dsi           : Option<i16>,
3237//    pub j             : Option<i16>,
3238//    pub rat           : Option<i16>,
3239//    pub ltb_id        : Option<i16>, 
3240//    pub cable_len     : f32,
3241//    pub paddle1_id    : Option<i16>,
3242//    pub paddle2_id    : Option<i16>,
3243//    pub paddle3_id    : Option<i16>,
3244//    pub paddle4_id    : Option<i16>,
3245//    pub paddle5_id    : Option<i16>,
3246//    pub paddle6_id    : Option<i16>,
3247//    pub paddle7_id    : Option<i16>,
3248//    pub paddle8_id    : Option<i16>,
3249//}
3250//
3251//impl DBLocalTriggerBoard {
3252//  
3253//  //pub fn new() -> Self {
3254//  //  Self {
3255//  //    board_id      : 0,    
3256//  //    dsi           : None,
3257//  //    j             : None,
3258//  //    rat           : None,
3259//  //    ltb_id        : None, 
3260//  //    cable_len     : 0.0,
3261//  //    paddle1_id    : None,
3262//  //    paddle2_id    : None,
3263//  //    paddle3_id    : None,
3264//  //    paddle4_id    : None,
3265//  //    paddle5_id    : None,
3266//  //    paddle6_id    : None,
3267//  //    paddle7_id    : None,
3268//  //    paddle8_id    : None,
3269//  //  }
3270//  //}
3271//
3272//  /// True if sane dsi and j values are 
3273//  /// assigned to this board
3274//  pub fn connected(&self) -> bool {
3275//    self.dsi != None && self.j != None
3276//  }
3277//
3278//  /// True if all fields are filled with 
3279//  /// reasonable values and not the default
3280//  pub fn valid(&self) -> bool {
3281//    self.board_id      > 0 &&    
3282//    self.dsi       .is_some() && 
3283//    self.j         .is_some() && 
3284//    self.rat       .is_some() && 
3285//    // right now, we explicitly don't care
3286//    // about the ltb_id
3287//    //self.ltb_id    .is_some() &&  
3288//    self.cable_len     > 0.0  &&
3289//    self.paddle1_id.is_some() &&
3290//    self.paddle2_id.is_some() &&
3291//    self.paddle3_id.is_some() &&
3292//    self.paddle4_id.is_some() &&
3293//    self.paddle5_id.is_some() &&
3294//    self.paddle6_id.is_some() &&
3295//    self.paddle7_id.is_some() &&
3296//    self.paddle8_id.is_some()
3297//  }
3298//  
3299//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<DBLocalTriggerBoard>> {
3300//    use schema::tof_db_localtriggerboard::dsl::*;
3301//    match tof_db_localtriggerboard
3302//        //.inner_join(tof_db_localtriggerboard.on(schema::tof_db_paddle::dsl::paddle_id.eq(schema::tof_db_localtriggerboard::dsl::paddle1_id)))
3303//        .load::<DBLocalTriggerBoard>(conn) {
3304//      Err(err) => {
3305//        error!("Unable to load LocalTriggerBoards from db! {err}");
3306//        return None;
3307//      }
3308//      Ok(ltbs) => {
3309//        return Some(ltbs);
3310//      }
3311//    }
3312//  }
3313//}
3314//
3315//impl fmt::Display for DBLocalTriggerBoard {
3316//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3317//    let mut repr : String;
3318//    if !self.connected() {
3319//      repr = format!("<DBLocalTriggerBoard: ID {}  - UNCONNECTED>", self.board_id);
3320//    } else {
3321//      repr = String::from("<DBLocalTriggerBoard:");
3322//      repr += &(format!("\n  LTB ID  : {}", self.board_id));             
3323//    }
3324//    repr += &(format!("\n  DSI/J   : {}/{}", self.dsi.unwrap(), self.j.unwrap()));     
3325//    repr += &(format!("\n  RAT ID  : {}", self.rat.unwrap()));
3326//    repr += "\n  H. cable len (MTB connection):";
3327//    repr += &(format!("\n    ->      {}", self.cable_len));
3328//    repr += "\n  -- -- -- -- -- -- -- -- -- -- -- -- -- --";
3329//    repr += "\n  Paddle IDs:";
3330//    repr += &(format!("\n    {:02}", self.paddle1_id.unwrap_or(-1))); 
3331//    repr += &(format!("\n    {:02}", self.paddle2_id.unwrap_or(-1)));  
3332//    repr += &(format!("\n    {:02}", self.paddle3_id.unwrap_or(-1)));  
3333//    repr += &(format!("\n    {:02}", self.paddle4_id.unwrap_or(-1)));  
3334//    repr += &(format!("\n    {:02}", self.paddle5_id.unwrap_or(-1))); 
3335//    repr += &(format!("\n    {:02}", self.paddle6_id.unwrap_or(-1))); 
3336//    repr += &(format!("\n    {:02}", self.paddle7_id.unwrap_or(-1))); 
3337//    repr += &(format!("\n    {:02}", self.paddle8_id.unwrap_or(-1))); 
3338//    write!(f, "{}", repr)
3339//  }
3340//}
3341//
3342//#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
3343//pub struct LocalTriggerBoard {
3344//    pub board_id      : u8,    
3345//    pub dsi           : u8,
3346//    pub j             : u8,
3347//    pub rat           : u8,
3348//    pub ltb_id        : u8, 
3349//    pub cable_len     : f32,
3350//    pub paddle1       : Paddle,
3351//    pub paddle2       : Paddle,
3352//    pub paddle3       : Paddle,
3353//    pub paddle4       : Paddle,
3354//    pub paddle5       : Paddle,
3355//    pub paddle6       : Paddle,
3356//    pub paddle7       : Paddle,
3357//    pub paddle8       : Paddle,
3358//}
3359//
3360//impl LocalTriggerBoard {
3361//  
3362//  pub fn new() -> Self {
3363//    Self {
3364//      board_id      : 0,    
3365//      dsi           : 0,
3366//      j             : 0,
3367//      rat           : 0,
3368//      ltb_id        : 0, 
3369//      cable_len     : 0.0,
3370//      paddle1       : Paddle::new(),
3371//      paddle2       : Paddle::new(),
3372//      paddle3       : Paddle::new(),
3373//      paddle4       : Paddle::new(),
3374//      paddle5       : Paddle::new(),
3375//      paddle6       : Paddle::new(),
3376//      paddle7       : Paddle::new(),
3377//      paddle8       : Paddle::new(),
3378//    }
3379//  }
3380//  
3381//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<LocalTriggerBoard>> {
3382//    use schema::tof_db_localtriggerboard::dsl::*;
3383//    let db_ltbs : Vec<DBLocalTriggerBoard>;
3384//    match tof_db_localtriggerboard
3385//        //.inner_join(tof_db_localtriggerboard.on(schema::tof_db_paddle::dsl::paddle_id.eq(schema::tof_db_localtriggerboard::dsl::paddle1_id)))
3386//        .load::<DBLocalTriggerBoard>(conn) {
3387//      Err(err) => {
3388//        error!("Unable to load LocalTriggerBoards from db! {err}");
3389//        return None;
3390//      }
3391//      Ok(ltbs) => {
3392//        db_ltbs = ltbs;
3393//      }
3394//    }
3395//    let paddles_op = Paddle::all(conn);
3396//    match paddles_op {
3397//      None => {
3398//        return None;
3399//      }
3400//      Some(_) => ()
3401//    }
3402//    let paddles = paddles_op.unwrap();
3403//    // This is not the best and fastest, but since our diesel skills 
3404//    // are a merely 3, we can't do it right now.
3405//    let mut ltbs = Vec::<LocalTriggerBoard>::new();
3406//    //println!("Iterating over {} ltbs in the DB!", db_ltbs.len());
3407//    for dbltb in db_ltbs {
3408//      let mut ltb  = LocalTriggerBoard::new();
3409//      for pdl in paddles.iter() {
3410//        // this call ensures that the following unwraps
3411//        // go through
3412//        if !dbltb.valid() {
3413//          error!("Got unpopulated LTB from DB for LTB {}", dbltb);
3414//          continue;
3415//        }
3416//        if pdl.paddle_id == dbltb.paddle1_id.unwrap() {
3417//          ltb.board_id  = dbltb.board_id as u8;        
3418//          ltb.dsi       = dbltb.dsi.unwrap_or(0) as u8;
3419//          ltb.j         = dbltb.j.unwrap_or(0) as u8;     
3420//          ltb.rat       = dbltb.rat.unwrap_or(0) as u8;     
3421//          ltb.ltb_id    = dbltb.ltb_id.unwrap_or(0) as u8;    
3422//          ltb.cable_len = dbltb.cable_len;    
3423//          ltb.paddle1   = pdl.clone();
3424//        }
3425//        if pdl.paddle_id == dbltb.paddle2_id.unwrap() {
3426//          ltb.paddle2   = pdl.clone();
3427//        }
3428//        if pdl.paddle_id == dbltb.paddle3_id.unwrap() {
3429//          ltb.paddle3   = pdl.clone();
3430//        }
3431//        if pdl.paddle_id == dbltb.paddle4_id.unwrap() {
3432//          ltb.paddle4   = pdl.clone();
3433//        }
3434//        if pdl.paddle_id == dbltb.paddle5_id.unwrap() {
3435//          ltb.paddle5   = pdl.clone();
3436//        }
3437//        if pdl.paddle_id == dbltb.paddle6_id.unwrap() {
3438//          ltb.paddle6   = pdl.clone();
3439//        }
3440//        if pdl.paddle_id == dbltb.paddle7_id.unwrap() {
3441//          ltb.paddle7   = pdl.clone();
3442//        }
3443//        if pdl.paddle_id == dbltb.paddle8_id.unwrap() {
3444//          ltb.paddle8   = pdl.clone();
3445//        }
3446//      }
3447//      ltbs.push(ltb);
3448//    }
3449//    Some(ltbs)
3450//  }
3451//}
3452//
3453//impl fmt::Display for LocalTriggerBoard {
3454//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3455//    let mut repr : String;
3456//    repr = String::from("<LocalTriggerBoard:");
3457//    repr += &(format!("\n  LTB ID  : {}", self.board_id));             
3458//    repr += &(format!("\n  DSI/J   : {}/{}", self.dsi, self.j));     
3459//    repr += &(format!("\n  RAT ID  : {}", self.rat));
3460//    repr += "\n  H. cable len (MTB connection):";
3461//    repr += &(format!("\n    ->      {}", self.cable_len));
3462//    repr += "\n  -- -- -- -- -- -- -- -- -- -- -- -- -- --";
3463//    repr += "\n  LTB Ch -> RB Id, RB chn, Pdl ID, Pan ID:";
3464//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}",  self.paddle1.rb_id, self.paddle1.rb_chA, self.paddle1.rb_chB, self.paddle1.paddle_id, self.paddle1.panel_id)); 
3465//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}",  self.paddle2.rb_id, self.paddle2.rb_chA, self.paddle2.rb_chB, self.paddle2.paddle_id, self.paddle2.panel_id));  
3466//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}",  self.paddle3.rb_id, self.paddle3.rb_chA, self.paddle3.rb_chB, self.paddle3.paddle_id, self.paddle3.panel_id));  
3467//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}",  self.paddle4.rb_id, self.paddle4.rb_chA, self.paddle4.rb_chB, self.paddle4.paddle_id, self.paddle4.panel_id));  
3468//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}",  self.paddle5.rb_id, self.paddle5.rb_chA, self.paddle5.rb_chB, self.paddle5.paddle_id, self.paddle5.panel_id)); 
3469//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}",  self.paddle6.rb_id, self.paddle6.rb_chA, self.paddle6.rb_chB, self.paddle6.paddle_id, self.paddle6.panel_id)); 
3470//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}",  self.paddle7.rb_id, self.paddle7.rb_chA, self.paddle7.rb_chB, self.paddle7.paddle_id, self.paddle7.panel_id)); 
3471//    repr += &(format!("\n            {:02}   |   {},{} |  {:03} | {:02}>", self.paddle8.rb_id, self.paddle8.rb_chA, self.paddle8.rb_chB, self.paddle8.paddle_id, self.paddle8.panel_id)); 
3472//    write!(f, "{}", repr)
3473//  }
3474//}
3475//
3476///// A Readoutboard with paddles connected
3477///// 
3478//#[derive(Debug,PartialEq, Clone,Queryable, Selectable, serde::Serialize, serde::Deserialize)]
3479//#[diesel(table_name = schema::tof_db_readoutboard)]
3480//#[diesel(primary_key(rb_id_id))]
3481//#[allow(non_snake_case)]
3482//pub struct DBReadoutBoard {
3483//  // FIXME - this HAS TO BE (MUST!) the same order
3484//  // as in schema.rs !!
3485//  pub rb_id        : i16, 
3486//  pub dsi          : i16, 
3487//  pub j            : i16, 
3488//  pub mtb_link_id  : i16, 
3489//  pub paddle12_chA : Option<i16>,
3490//  pub paddle34_chA : Option<i16>,
3491//  pub paddle56_chA : Option<i16>,
3492//  pub paddle78_chA : Option<i16>,
3493//  pub paddle12_id  : Option<i16>,
3494//  pub paddle34_id  : Option<i16>,
3495//  pub paddle56_id  : Option<i16>,
3496//  pub paddle78_id  : Option<i16>,
3497//}
3498//
3499//impl DBReadoutBoard {
3500//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<DBReadoutBoard>> {
3501//    use schema::tof_db_readoutboard::dsl::*;
3502//    match tof_db_readoutboard
3503//        //.inner_join(tof_db_localtriggerboard.on(schema::tof_db_paddle::dsl::paddle_id.eq(schema::tof_db_localtriggerboard::dsl::paddle1_id)))
3504//        .load::<DBReadoutBoard>(conn) {
3505//      Err(err) => {
3506//        error!("Unable to load ReadoutBoards from db! {err}");
3507//        return None;
3508//      }
3509//      Ok(rbs) => {
3510//        return Some(rbs);
3511//      }
3512//    }
3513//  }
3514//}
3515//
3516//impl fmt::Display for DBReadoutBoard {
3517//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3518//    let mut repr  = String::from("<ReadoutBoard:");
3519//    repr += &(format!("\n  Board id    : {}",self.rb_id));            
3520//    repr += &(format!("\n  MTB Link ID : {}",self.mtb_link_id));
3521//    repr += &(format!("\n  DSI/J       : {}/{}",self.dsi,self.j));
3522//    repr += "\n **Connected paddles**";
3523//    repr += &(format!("\n  Ch0/1(1/2)  : {}", self.paddle12_id.unwrap_or(-1)));         
3524//    repr += &(format!("\n  Ch1/2(2/3)  : {}", self.paddle34_id.unwrap_or(-1)));         
3525//    repr += &(format!("\n  Ch2/3(3/4)  : {}", self.paddle56_id.unwrap_or(-1)));         
3526//    repr += &(format!("\n  Ch3/4(4/5)  : {}>",self.paddle78_id.unwrap_or(-1)));         
3527//    write!(f, "{}", repr)
3528//  }
3529//}
3530//
3531///// A Readoutboard with paddles connected
3532//#[derive(Debug, Clone)]
3533//#[allow(non_snake_case)]
3534//pub struct ReadoutBoard {
3535//  pub rb_id           : u8, 
3536//  pub dsi             : u8, 
3537//  pub j               : u8, 
3538//  pub mtb_link_id     : u8, 
3539//  pub paddle12        : Paddle,
3540//  pub paddle12_chA    : u8,
3541//  pub paddle34        : Paddle,
3542//  pub paddle34_chA    : u8,
3543//  pub paddle56        : Paddle,
3544//  pub paddle56_chA    : u8,
3545//  pub paddle78        : Paddle,
3546//  pub paddle78_chA    : u8,
3547//  // extra stuff, not from the db
3548//  // or maybe in the future?
3549//  pub calib_file_path : String,
3550//  pub calibration     : RBCalibrations,       
3551//}
3552//
3553//impl ReadoutBoard {
3554//
3555//  pub fn new() -> Self {
3556//    Self {
3557//      rb_id           : 0, 
3558//      dsi             : 0, 
3559//      j               : 0, 
3560//      mtb_link_id     : 0, 
3561//      paddle12        : Paddle::new(),
3562//      paddle12_chA    : 0,
3563//      paddle34        : Paddle::new(),
3564//      paddle34_chA    : 0,
3565//      paddle56        : Paddle::new(),
3566//      paddle56_chA    : 0,
3567//      paddle78        : Paddle::new(),
3568//      paddle78_chA    : 0,
3569//      calib_file_path : String::from(""),
3570//      calibration     : RBCalibrations::new(0),
3571//    }
3572//  }
3573//
3574//  /// Returns the ip address following a convention
3575//  ///
3576//  /// This does NOT GUARANTEE that the address is correct!
3577//  pub fn guess_address(&self) -> String {
3578//    format!("tcp://10.0.1.1{:02}:42000", self.rb_id)
3579//  }
3580// 
3581//  pub fn get_paddle_ids(&self) -> [u8;4] {
3582//    let pid0 = self.paddle12.paddle_id as u8;
3583//    let pid1 = self.paddle34.paddle_id as u8;
3584//    let pid2 = self.paddle56.paddle_id as u8;
3585//    let pid3 = self.paddle78.paddle_id as u8;
3586//    [pid0, pid1, pid2, pid3]
3587//  }
3588//
3589//  #[allow(non_snake_case)]
3590//  pub fn get_A_sides(&self) -> [u8;4] {
3591//    let pa_0 = self.paddle12_chA;
3592//    let pa_1 = self.paddle34_chA;
3593//    let pa_2 = self.paddle56_chA;
3594//    let pa_3 = self.paddle78_chA;
3595//    [pa_0, pa_1, pa_2, pa_3]
3596//  }
3597//
3598//  #[allow(non_snake_case)]
3599//  pub fn get_pid_rbchA(&self, pid : u8) -> Option<u8> {
3600//    if self.paddle12.paddle_id as u8 == pid {
3601//      let rv = self.paddle12.rb_chA as u8;
3602//      return Some(rv);
3603//    } else if self.paddle34.paddle_id as u8 == pid {
3604//      let rv = self.paddle34.rb_chA as u8;
3605//      return Some(rv);
3606//    } else if self.paddle56.paddle_id as u8 == pid {
3607//      let rv = self.paddle56.rb_chA as u8;
3608//      return Some(rv);
3609//    } else if self.paddle78.paddle_id as u8== pid {
3610//      let rv = self.paddle78.rb_chA as u8;
3611//      return Some(rv);
3612//    } else {
3613//      return None;
3614//    }
3615//  }
3616//  
3617//  #[allow(non_snake_case)]
3618//  pub fn get_pid_rbchB(&self, pid : u8) -> Option<u8> {
3619//    if self.paddle12.paddle_id as u8 == pid {
3620//      let rv = self.paddle12.rb_chB as u8;
3621//      return Some(rv);
3622//    } else if self.paddle34.paddle_id as u8== pid {
3623//      let rv = self.paddle34.rb_chB as u8;
3624//      return Some(rv);
3625//    } else if self.paddle56.paddle_id as u8== pid {
3626//      let rv = self.paddle56.rb_chB as u8;
3627//      return Some(rv);
3628//    } else if self.paddle78.paddle_id as u8 == pid {
3629//      let rv = self.paddle78.rb_chB as u8;
3630//      return Some(rv);
3631//    } else {
3632//      return None;
3633//    }
3634//  }
3635//
3636//  pub fn get_paddle_length(&self, pid : u8) -> Option<f32> {
3637//    if self.paddle12.paddle_id as u8 == pid {
3638//      let rv = self.paddle12.length;
3639//      return Some(rv);
3640//    } else if self.paddle34.paddle_id as u8== pid {
3641//      let rv = self.paddle34.length;
3642//      return Some(rv);
3643//    } else if self.paddle56.paddle_id as u8== pid {
3644//      let rv = self.paddle56.length;
3645//      return Some(rv);
3646//    } else if self.paddle78.paddle_id as u8 == pid {
3647//      let rv = self.paddle78.length;
3648//      return Some(rv);
3649//    } else {
3650//      return None;
3651//    }
3652//  }
3653//
3654//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<ReadoutBoard>> {
3655//    use schema::tof_db_readoutboard::dsl::*;
3656//    let db_rbs : Vec<DBReadoutBoard>;
3657//    match tof_db_readoutboard
3658//        //.inner_join(tof_db_localtriggerboard.on(schema::tof_db_paddle::dsl::paddle_id.eq(schema::tof_db_localtriggerboard::dsl::paddle1_id)))
3659//        .load::<DBReadoutBoard>(conn) {
3660//      Err(err) => {
3661//        error!("Unable to load ReadoutBoards from db! {err}");
3662//        return None;
3663//      }
3664//      Ok(rbs) => {
3665//        db_rbs = rbs;
3666//      }
3667//    }
3668//    let paddles_op = Paddle::all(conn);
3669//    match paddles_op {
3670//      None => {
3671//        return None;
3672//      }
3673//      Some(_) => ()
3674//    }
3675//    let paddles = paddles_op.unwrap();
3676//    // This is not the best and fastest, but since our diesel skills 
3677//    // are a merely 3, we can't do it right now.
3678//    let mut rbs = Vec::<ReadoutBoard>::new();
3679//    //println!("Iterating over {} rbs in the DB!", db_rbs.len());
3680//    for dbrb in db_rbs {
3681//      let mut rb  = ReadoutBoard::new();
3682//      rb.rb_id        = dbrb.rb_id as u8;        
3683//      rb.dsi          = dbrb.dsi as u8;
3684//      rb.j            = dbrb.j  as u8;     
3685//      rb.mtb_link_id  = dbrb.mtb_link_id  as u8;    
3686//      rb.paddle12_chA = dbrb.paddle12_chA.unwrap() as u8;
3687//      rb.paddle34_chA = dbrb.paddle34_chA.unwrap() as u8;
3688//      rb.paddle56_chA = dbrb.paddle56_chA.unwrap() as u8;
3689//      rb.paddle78_chA = dbrb.paddle78_chA.unwrap() as u8;
3690//      for pdl in paddles.iter() {
3691//        // this call ensures that the following unwraps
3692//        // go through
3693//        //if !dbltb.valid() {
3694//        //  error!("Got unpopulated LTB from DB for LTB {}", dbltb);
3695//        //  continue;
3696//        //}
3697//        if pdl.paddle_id == dbrb.paddle12_id.unwrap_or(0) {
3698//          rb.paddle12     = pdl.clone();
3699//        }
3700//        if pdl.paddle_id == dbrb.paddle34_id.unwrap_or(0) {
3701//          rb.paddle34   = pdl.clone();
3702//        }
3703//        if pdl.paddle_id == dbrb.paddle56_id.unwrap_or(0) {
3704//          rb.paddle56   = pdl.clone();
3705//        }
3706//        if pdl.paddle_id == dbrb.paddle78_id.unwrap_or(0) {
3707//          rb.paddle78   = pdl.clone();
3708//        }
3709//      }
3710//      rbs.push(rb);
3711//    }
3712//    Some(rbs)
3713//  }
3714//  
3715//  // FIXME - better query
3716//  pub fn where_rbid(conn: &mut SqliteConnection, rb_id : u8) -> Option<ReadoutBoard> {
3717//    let all = ReadoutBoard::all(conn)?;
3718//    for rb in all {
3719//      if rb.rb_id == rb_id {
3720//        return Some(rb);
3721//      }
3722//    }
3723//    None
3724//  }
3725//
3726//  pub fn to_summary_str(&self) -> String {
3727//    let mut repr  = String::from("<ReadoutBoard:");
3728//    repr += &(format!("\n  Board id    : {}",self.rb_id));            
3729//    repr += &(format!("\n  MTB Link ID : {}",self.mtb_link_id));
3730//    repr += &(format!("\n  RAT         : {}",self.paddle12.ltb_id));
3731//    repr += &(format!("\n  DSI/J       : {}/{}",self.dsi,self.j));
3732//    repr += "\n **Connected paddles**";
3733//    repr += &(format!("\n  Channel 1/2 : {:02} (panel {:01})", self.paddle12.paddle_id, self.paddle12.panel_id));
3734//    repr += &(format!("\n  Channel 3/4 : {:02} (panel {:01})", self.paddle34.paddle_id, self.paddle34.panel_id));
3735//    repr += &(format!("\n  Channel 5/6 : {:02} (panel {:01})", self.paddle56.paddle_id, self.paddle56.panel_id));
3736//    repr += &(format!("\n  Channel 7/8 : {:02} (panel {:01})", self.paddle78.paddle_id, self.paddle78.panel_id));
3737//    repr
3738//  }
3739//
3740//  /// Load the newest calibration from the calibration file path
3741//  pub fn load_latest_calibration(&mut self) -> Result<(), Box<dyn std::error::Error>> {
3742//    //  files look like RB20_2024_01_26-08_15_54.cali.tof.gaps
3743//    //let re = Regex::new(r"(\d{4}_\d{2}_\d{2}-\d{2}_\d{2}_\d{2})")?;
3744//    let re = Regex::new(r"(\d{6}_\d{6})")?;
3745//    // Define your file pattern (e.g., "logs/*.log" for all .log files in the logs directory)
3746//    let pattern = format!("{}/RB{:02}_*", self.calib_file_path, self.rb_id); // Adjust this pattern to your files' naming convention
3747//    let timestamp = DateTime::<Utc>::from_timestamp(0,0).unwrap(); // I am not sure what to do here
3748//                                                                   // otherwise than unwrap. How is
3749//                                                                   // this allowed to fail?
3750//    //let mut newest_file = (String::from(""), NaiveDateTime::from_timestamp(0, 0));
3751//    let mut newest_file = (String::from(""), timestamp);
3752//
3753//    // Iterate over files that match the pattern
3754//    let mut filename : String;
3755//    for entry in glob(&pattern)? {
3756//      if let Ok(path) = entry {
3757//        // Get the filename as a string
3758//        //let cpath = path.clone();
3759//        match path.file_name() {
3760//          None => continue,
3761//          Some(fname) => {
3762//              // the expect might be ok, since this is something done during initialization
3763//              filename = fname.to_os_string().into_string().expect("Unwrapping filename failed!");
3764//          }
3765//        }
3766//        if let Some(caps) = re.captures(&filename) {
3767//          if let Some(timestamp_str) = caps.get(0).map(|m| m.as_str()) {
3768//            //println!("timestamp_str {}, {}",timestamp_str, HUMAN_TIMESTAMP_FORMAT);
3769//            //let timestamp = NaiveDateTime::parse_from_str(timestamp_str, "%Y_%m_%d-%H_%M_%S")?;
3770//            //let timestamp = DateTime::<Utc>::parse_from_str(timestamp_str, "%Y_%m_%d-%H_%M_%S")?;
3771//            let footzstring = format!("{}+0000", timestamp_str);
3772//            let timestamp = DateTime::parse_from_str(&footzstring, "%y%m%d_%H%M%S%z")?;
3773//            //let timestamp = DateTime::parse_from_str(&footzstring, HUMAN_TIMESTAMP_FORMAT)?;
3774//            //println!("parse successful");
3775//            //let _timestamp = DateTime
3776//            if timestamp > newest_file.1 {
3777//              // FIXME - into might panic?
3778//              newest_file.1 = timestamp.into();
3779//              newest_file.0 = filename.clone();
3780//            }
3781//          }
3782//        }
3783//      }
3784//    }
3785//    
3786//    if newest_file.0.is_empty() {
3787//      error!("No matching calibration available for board {}!", self.rb_id);
3788//    } else {
3789//      let file_to_load = format!("{}/{}", self.calib_file_path, newest_file.0);
3790//      info!("Loading calibration from file: {}", file_to_load);
3791//      self.calibration = RBCalibrations::from_file(file_to_load, true)?;
3792//    }
3793//    Ok(())
3794//  }
3795//}
3796//
3797//impl fmt::Display for ReadoutBoard {
3798//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3799//    let mut repr  = String::from("<ReadoutBoard:");
3800//    repr += &(format!("\n  Board id    : {}",self.rb_id));            
3801//    repr += &(format!("\n  MTB Link ID : {}",self.mtb_link_id));
3802//    repr += &(format!("\n  DSI/J       : {}/{}",self.dsi,self.j));
3803//    repr += "\n **Connected paddles**";
3804//    repr += &(format!("\n  Ch0/1(1/2)  : {}",self.paddle12)); 
3805//    repr += &(format!("\n    A-side    : {}", self.paddle12_chA));
3806//    repr += &(format!("\n  Ch1/2(2/3)  : {}",self.paddle34));         
3807//    repr += &(format!("\n    A-side    : {}", self.paddle34_chA));
3808//    repr += &(format!("\n  Ch2/3(3/4)  : {}",self.paddle56));         
3809//    repr += &(format!("\n    A-side    : {}", self.paddle56_chA));
3810//    repr += &(format!("\n  Ch3/4(4/5)  : {}>",self.paddle78));         
3811//    repr += &(format!("\n    A-side    : {}", self.paddle78_chA));
3812//    repr += "** calibration will be loaded from this path:";
3813//    repr += &(format!("\n      \u{021B3} {}", self.calib_file_path));
3814//    repr += &(format!("\n  calibration : {}>", self.calibration));
3815//    write!(f, "{}", repr)
3816//  }
3817//}
3818//
3819//
3820///// A TOF Panel is a larger unit of paddles next to each other
3821/////
3822///// TOF faces (e.g. Umbrella) can have multiple Panels
3823//#[derive(Debug, Clone,Queryable, Selectable)]
3824//#[diesel(table_name = schema::tof_db_panel)]
3825//#[diesel(primary_key(panel_id))]
3826//pub struct DBPanel {
3827//  // ORDER OF THESE FIELDS HAS TO BE THE SAME AS IN schema.rs!!
3828//  pub  panel_id    : i16        ,   
3829//  pub  description : String     ,   
3830//  pub  normal_x    : i16        ,   
3831//  pub  normal_y    : i16        ,   
3832//  pub  normal_z    : i16        ,   
3833//  pub  dw_paddle   : Option<i16>,   
3834//  pub  dh_paddle   : Option<i16>,   
3835//  pub  paddle0_id  : Option<i16>,   
3836//  pub  paddle1_id  : Option<i16>,   
3837//  pub  paddle10_id : Option<i16>,   
3838//  pub  paddle11_id : Option<i16>,   
3839//  pub  paddle2_id  : Option<i16>,   
3840//  pub  paddle3_id  : Option<i16>,   
3841//  pub  paddle4_id  : Option<i16>,   
3842//  pub  paddle5_id  : Option<i16>,   
3843//  pub  paddle6_id  : Option<i16>,   
3844//  pub  paddle7_id  : Option<i16>,   
3845//  pub  paddle8_id  : Option<i16>,   
3846//  pub  paddle9_id  : Option<i16>,   
3847//}
3848//
3849//impl DBPanel {
3850//
3851//  pub fn valid(&self) -> bool {
3852//    self.panel_id    > 0 &&    
3853//    self.description != String::from("") &&   
3854//    self.paddle0_id.is_some()   
3855//  }
3856//
3857//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<DBPanel>> {
3858//    use schema::tof_db_panel::dsl::*;
3859//    match tof_db_panel
3860//        //.inner_join(tof_db_localtriggerboard.on(schema::tof_db_paddle::dsl::paddle_id.eq(schema::tof_db_localtriggerboard::dsl::paddle1_id)))
3861//        .load::<DBPanel>(conn) {
3862//      Err(err) => {
3863//        error!("Unable to load Panels from db! {err}");
3864//        return None;
3865//      }
3866//      // dirty mind check
3867//      Ok(pnls) => {
3868//        return Some(pnls);
3869//      }
3870//    }
3871//  }
3872//  
3873//  pub fn get_npaddles(&self) -> u8 {
3874//    let mut npaddles = 0u8;
3875//    if self.paddle0_id.is_some() {
3876//      npaddles += 1;
3877//    }
3878//    if self.paddle1_id.is_some() {
3879//      npaddles += 1;
3880//    }
3881//    if self.paddle2_id.is_some() {
3882//      npaddles += 1;
3883//    }
3884//    if self.paddle3_id.is_some() {
3885//      npaddles += 1;
3886//    }
3887//    if self.paddle4_id.is_some() {
3888//      npaddles += 1;
3889//    }
3890//    if self.paddle5_id.is_some() {
3891//      npaddles += 1;
3892//    }
3893//    if self.paddle6_id.is_some() {
3894//      npaddles += 1;
3895//    }
3896//    if self.paddle7_id.is_some() {
3897//      npaddles += 1;
3898//    }
3899//    if self.paddle8_id.is_some() {
3900//      npaddles += 1;
3901//    }
3902//    if self.paddle9_id.is_some() {
3903//      npaddles += 1;
3904//    }
3905//    if self.paddle10_id.is_some() {
3906//      npaddles += 1;
3907//    }
3908//    if self.paddle11_id.is_some() {
3909//      npaddles += 1;
3910//    }
3911//    npaddles
3912//  }
3913//}
3914//
3915//impl fmt::Display for DBPanel {
3916//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3917//    let mut repr = String::from("<DBPanel");
3918//    repr += &(format!("\n  id    : {}",self.panel_id));
3919//    repr += &(format!("\n  descr : {}",self.description));
3920//    repr += "\n  orientation:";
3921//    repr += &(format!("\n   [{},{},{}]", self.normal_x, self.normal_y, self.normal_z));
3922//    repr += &(format!("\n  paddle list ({}) paddles)", self.get_npaddles()));
3923//    if self.paddle0_id.is_some() {
3924//      repr += &(format!("\n   {}",self.paddle0_id.unwrap()));
3925//    }
3926//    if self.paddle1_id.is_some() {
3927//      repr += &(format!("\n   {}",self.paddle1_id.unwrap()));
3928//    }
3929//    if self.paddle2_id.is_some() { 
3930//      repr += &(format!("\n   {}",self.paddle2_id.unwrap()));
3931//    }
3932//    if self.paddle3_id.is_some() { 
3933//      repr += &(format!("\n   {}",self.paddle3_id.unwrap()));
3934//    }
3935//    if self.paddle4_id.is_some() {
3936//      repr += &(format!("\n   {}",self.paddle4_id.unwrap()));
3937//    }
3938//    if self.paddle5_id.is_some() {
3939//      repr += &(format!("\n   {}",self.paddle5_id.unwrap()));
3940//    }
3941//    if self.paddle6_id.is_some()  {
3942//      repr += &(format!("\n   {}",self.paddle6_id.unwrap()));
3943//    }
3944//    if self.paddle7_id.is_some() {
3945//      repr += &(format!("\n   {}",self.paddle7_id.unwrap()));
3946//    }
3947//    if self.paddle8_id.is_some() {
3948//      repr += &(format!("\n   {}",self.paddle8_id.unwrap()));
3949//    }
3950//    if self.paddle9_id.is_some() {
3951//      repr += &(format!("\n   {}",self.paddle9_id.unwrap()));
3952//    }
3953//    if self.paddle10_id.is_some() {
3954//      repr += &(format!("\n   {}",self.paddle10_id.unwrap()));
3955//    }
3956//    if self.paddle11_id.is_some() {
3957//      repr += &(format!("\n   {}",self.paddle11_id.unwrap()));
3958//    }
3959//    repr += ">";
3960//    write!(f, "{}", repr)
3961//  }
3962//}
3963//
3964//pub struct Panel {
3965//  pub  panel_id    : u8        ,   
3966//  pub  description : String    ,   
3967//  pub  normal_x    : u8        ,   
3968//  pub  normal_y    : u8        ,   
3969//  pub  normal_z    : u8        ,   
3970//  pub  paddle0  : Paddle,   
3971//  pub  paddle1  : Option<Paddle>,   
3972//  pub  paddle2  : Option<Paddle>,   
3973//  pub  paddle3  : Option<Paddle>,   
3974//  pub  paddle4  : Option<Paddle>,   
3975//  pub  paddle5  : Option<Paddle>,   
3976//  pub  paddle6  : Option<Paddle>,   
3977//  pub  paddle7  : Option<Paddle>,   
3978//  pub  paddle8  : Option<Paddle>,   
3979//  pub  paddle9  : Option<Paddle>,   
3980//  pub  paddle10 : Option<Paddle>,   
3981//  pub  paddle11 : Option<Paddle>,   
3982//  // FIXME - these are for the future 
3983//  // when we are buiding the geometry 
3984//  // from the database
3985//  //pub  dh_paddle   : Option<>,   
3986//  //pub  dw_paddle   : Option<>,   
3987//}
3988//
3989//impl Panel {
3990// 
3991//  pub fn new() -> Self {
3992//    Self {
3993//      panel_id    : 0        ,   
3994//      description : String::from(""),   
3995//      normal_x    : 0        ,   
3996//      normal_y    : 0        ,   
3997//      normal_z    : 0        ,   
3998//      paddle0     : Paddle::new(),   
3999//      paddle1     : None,   
4000//      paddle2     : None,   
4001//      paddle3     : None,   
4002//      paddle4     : None,   
4003//      paddle5     : None,   
4004//      paddle6     : None,   
4005//      paddle7     : None,   
4006//      paddle8     : None,   
4007//      paddle9     : None,   
4008//      paddle10    : None,   
4009//      paddle11    : None,   
4010//    }
4011//  }
4012//
4013//
4014//  pub fn get_npaddles(&self) -> u8 {
4015//    let mut npaddles = 1u8;
4016//    if self.paddle1.is_some() {
4017//      npaddles += 1;
4018//    }
4019//    if self.paddle2.is_some() {
4020//      npaddles += 1;
4021//    }
4022//    if self.paddle3.is_some() {
4023//      npaddles += 1;
4024//    }
4025//    if self.paddle4.is_some() {
4026//      npaddles += 1;
4027//    }
4028//    if self.paddle5.is_some() {
4029//      npaddles += 1;
4030//    }
4031//    if self.paddle6.is_some() {
4032//      npaddles += 1;
4033//    }
4034//    if self.paddle7.is_some() {
4035//      npaddles += 1;
4036//    }
4037//    if self.paddle8.is_some() {
4038//      npaddles += 1;
4039//    }
4040//    if self.paddle9.is_some() {
4041//      npaddles += 1;
4042//    }
4043//    if self.paddle10.is_some() {
4044//      npaddles += 1;
4045//    }
4046//    if self.paddle11.is_some() {
4047//      npaddles += 1;
4048//    }
4049//    npaddles
4050//  }
4051//  
4052//  pub fn all(conn: &mut SqliteConnection) -> Option<Vec<Panel>> {
4053//    use schema::tof_db_panel::dsl::*;
4054//    let db_panels : Vec<DBPanel>;
4055//    match tof_db_panel
4056//        //.inner_join(tof_db_localtriggerboard.on(schema::tof_db_paddle::dsl::paddle_id.eq(schema::tof_db_localtriggerboard::dsl::paddle1_id)))
4057//        .load::<DBPanel>(conn) {
4058//      Err(err) => {
4059//        error!("Unable to load Panels from db! {err}");
4060//        return None;
4061//      }
4062//      Ok(pnls) => {
4063//        db_panels = pnls;
4064//      }
4065//    }
4066//    let paddles_op = Paddle::all(conn);
4067//    match paddles_op {
4068//      None => {
4069//        return None;
4070//      }
4071//      Some(_) => ()
4072//    }
4073//    let paddles = paddles_op.unwrap();
4074//    // This is not the best and fastest, but since our diesel skills 
4075//    // are a merely 3, we can't do it right now.
4076//    let mut panels = Vec::<Panel>::new();
4077//    println!("Iterating over {} panels in the DB!", db_panels.len());
4078//    for dbpanel in db_panels {
4079//      let mut pnl  = Panel::new();
4080//      for pdl in paddles.iter() {
4081//        // this call ensures that the following unwraps
4082//        // go through
4083//        if !dbpanel.valid() {
4084//          error!("Got unpopulated Panel from DB for Panel {}", dbpanel);
4085//          continue;
4086//        }
4087//        if pdl.paddle_id == dbpanel.paddle0_id.unwrap() {
4088//          pnl.panel_id     = dbpanel.panel_id as u8;        
4089//          pnl.description  = dbpanel.description.clone();
4090//          pnl.normal_x     = dbpanel.normal_x as u8;     
4091//          pnl.normal_y     = dbpanel.normal_y as u8;     
4092//          pnl.normal_z     = dbpanel.normal_z as u8;    
4093//          pnl.paddle0      = pdl.clone();
4094//        }
4095//        if pdl.paddle_id == dbpanel.paddle1_id.unwrap() {
4096//          pnl.paddle1   = Some(pdl.clone());
4097//        }
4098//        if pdl.paddle_id == dbpanel.paddle2_id.unwrap() {
4099//          pnl.paddle2   = Some(pdl.clone());
4100//        }
4101//        if pdl.paddle_id == dbpanel.paddle3_id.unwrap() {
4102//          pnl.paddle3   = Some(pdl.clone());
4103//        }
4104//        if pdl.paddle_id == dbpanel.paddle4_id.unwrap() {
4105//          pnl.paddle4   = Some(pdl.clone());
4106//        }
4107//        if pdl.paddle_id == dbpanel.paddle5_id.unwrap() {
4108//          pnl.paddle5   = Some(pdl.clone());
4109//        }
4110//        if pdl.paddle_id == dbpanel.paddle6_id.unwrap() {
4111//          pnl.paddle6   = Some(pdl.clone());
4112//        }
4113//        if pdl.paddle_id == dbpanel.paddle7_id.unwrap() {
4114//          pnl.paddle7   = Some(pdl.clone());
4115//        }
4116//        if pdl.paddle_id == dbpanel.paddle8_id.unwrap() {
4117//          pnl.paddle8   = Some(pdl.clone());
4118//        }
4119//        if pdl.paddle_id == dbpanel.paddle9_id.unwrap() {
4120//          pnl.paddle9   = Some(pdl.clone());
4121//        }
4122//        if pdl.paddle_id == dbpanel.paddle10_id.unwrap() {
4123//          pnl.paddle10   = Some(pdl.clone());
4124//        }
4125//        if pdl.paddle_id == dbpanel.paddle11_id.unwrap() {
4126//          pnl.paddle11   = Some(pdl.clone());
4127//        }
4128//      }
4129//      panels.push(pnl);
4130//    }
4131//    Some(panels)
4132//  }
4133//}
4134//
4135//impl fmt::Display for Panel {
4136//  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4137//    let mut repr = String::from("<Panel");
4138//    repr += &(format!("\n  id    : {}",self.panel_id));
4139//    repr += &(format!("\n  descr : {}",self.description));
4140//    repr += "\n  orientation:";
4141//    repr += &(format!("\n   [{},{},{}]", self.normal_x, self.normal_y, self.normal_z));
4142//    repr += &(format!("\n  paddle list ({}) paddles)", self.get_npaddles()));
4143//    repr += &(format!("\n   {}",self.paddle0));
4144//    if self.paddle1.is_some() {
4145//      repr += &(format!("\n   {}",self.paddle1.as_ref().unwrap()));
4146//    }
4147//    if self.paddle2.is_some() { 
4148//      repr += &(format!("\n   {}",self.paddle2.as_ref().unwrap()));
4149//    }
4150//    if self.paddle3.is_some() { 
4151//      repr += &(format!("\n   {}",self.paddle3.as_ref().unwrap()));
4152//    }
4153//    if self.paddle4.is_some() {
4154//      repr += &(format!("\n   {}",self.paddle4.as_ref().unwrap()));
4155//    }
4156//    if self.paddle5.is_some() {
4157//      repr += &(format!("\n   {}",self.paddle5.as_ref().unwrap()));
4158//    }
4159//    if self.paddle6.is_some()  {
4160//      repr += &(format!("\n   {}",self.paddle6.as_ref().unwrap()));
4161//    }
4162//    if self.paddle7.is_some() {
4163//      repr += &(format!("\n   {}",self.paddle7.as_ref().unwrap()));
4164//    }
4165//    if self.paddle8.is_some() {
4166//      repr += &(format!("\n   {}",self.paddle8.as_ref().unwrap()));
4167//    }
4168//    if self.paddle9.is_some() {
4169//      repr += &(format!("\n   {}",self.paddle9.as_ref().unwrap()));
4170//    }
4171//    if self.paddle10.is_some() {
4172//      repr += &(format!("\n   {}",self.paddle10.as_ref().unwrap()));
4173//    }
4174//    if self.paddle11.is_some() {
4175//      repr += &(format!("\n   {}",self.paddle11.as_ref().unwrap()));
4176//    }
4177//    repr += ">";
4178//    write!(f, "{}", repr)
4179//  }
4180//}
4181//
4182//
4183//
4184