Skip to main content

liftof_tui/
lib.rs

1#[macro_use] extern crate log;
2
3pub mod menu;
4pub mod colors;
5pub mod widgets;
6pub mod tabs;
7pub mod layout;
8
9use std::sync::Mutex;
10use std::sync::Arc;
11use std::path::PathBuf;
12
13use std::collections::HashMap;
14use std::collections::VecDeque;
15
16use tui_logger::TuiLoggerWidget;
17use ratatui::{
18  style::{
19    Color,
20    Style,
21  },
22  widgets::{
23    Block,
24    Borders,
25  },
26};
27
28pub use crate::tabs::*;
29pub use crate::layout::*;
30
31use crate::colors::ColorTheme;
32use gondola_core::prelude::*;
33
34use crossbeam_channel::{
35  Sender,
36  Receiver
37};
38
39use toml;
40use toml::{
41  Value
42};
43
44pub type WaveformCache = HashMap<u8,HashMap<u8, Arc<Mutex<VecDeque<RBWaveform>>>>>;
45
46/// Create a global storage for RBWaveforms 
47pub fn global_waveform_cache() -> WaveformCache {
48  let mut cache = WaveformCache::new();
49  //let rbs   = ReadoutBoard::all();
50  //let paddles = TofPaddle::all_as_dict();
51  for k in 1..50 {
52    let ch_dict = HashMap::<u8, Arc<Mutex<VecDeque<RBWaveform>>>>::new();
53    cache.insert(k as u8, ch_dict);
54    for j in 1..10 {
55      let wfs     = Arc::new(Mutex::new(VecDeque::<RBWaveform>::new()));
56      cache.get_mut(&k).unwrap().insert(j as u8, wfs); 
57    }
58  }
59  cache
60}
61
62/// A map which keeps track of the types of telemetry packets 
63/// received
64pub fn telly_packet_counter(pack_map : &mut HashMap<&str, usize>, packet_type : &TelemetryPacketType) {
65  let pack_key : &str;
66  match packet_type {
67    TelemetryPacketType::Unknown            => pack_key = "Unknown",
68    TelemetryPacketType::CardHKP            => pack_key = "CardHKP",
69    TelemetryPacketType::CoolingHK          => pack_key = "CoolingHKP",
70    TelemetryPacketType::PDUHK              => pack_key = "PDUHK",
71    TelemetryPacketType::Tracker            => pack_key = "Tracker",
72    TelemetryPacketType::TrackerDAQCntr     => pack_key = "TrakcerDAQCntr",
73    TelemetryPacketType::TrkTempLeak        => pack_key = "TrkTempLeak",
74    TelemetryPacketType::BoringEvent        => pack_key = "BoringEvent",
75    TelemetryPacketType::RBWaveform         => pack_key = "RBWaveform",
76    TelemetryPacketType::AnyTofHK           => pack_key = "AnyTofHK",
77    TelemetryPacketType::GcuEvtBldSettings  => pack_key = "GcuEvtBldSettings",
78    TelemetryPacketType::LabJackHK          => pack_key = "LabJackHK",
79    TelemetryPacketType::MagHK              => pack_key = "MagHK",
80    TelemetryPacketType::GcuMon             => pack_key = "GcuMon",
81    TelemetryPacketType::InterestingEvent   => pack_key = "InterestingEvent",
82    TelemetryPacketType::NoGapsTriggerEvent => pack_key = "NoGapsTriggerEvent",
83    TelemetryPacketType::NoTofDataEvent     => pack_key = "NoTofDataEvent",
84    TelemetryPacketType::Ack                => pack_key = "Ack",     
85    TelemetryPacketType::AnyTrackerHK       => pack_key = "AnyTrackerHK",
86    TelemetryPacketType::TmP33              => pack_key = "TmP33",
87    TelemetryPacketType::TmP34              => pack_key = "TmP34",
88    TelemetryPacketType::TmP37              => pack_key = "TmP37",
89    TelemetryPacketType::TmP38              => pack_key = "TmP38",
90    TelemetryPacketType::TmP64              => pack_key = "TmP64",
91    TelemetryPacketType::TmP96              => pack_key = "TmP96",
92    TelemetryPacketType::TmP214             => pack_key = "TmP214",
93    _                                       => pack_key = "Unknown",
94  }
95  if pack_map.get(pack_key).is_some() {
96    *pack_map.get_mut(pack_key).unwrap() += 1;
97  } else {
98    pack_map.insert(pack_key, 1);
99  }
100}
101
102/// Use the TuiLoggerWidget to display 
103/// the most recent log messages
104///
105///
106pub fn render_logs<'a>(theme : ColorTheme) -> TuiLoggerWidget<'a> {
107  TuiLoggerWidget::default()
108    .style_error(Style::default().fg(Color::Red))
109    .style_debug(Style::default().fg(Color::Green))
110    .style_warn(Style::default().fg(Color::Yellow))
111    .style_trace(Style::default().fg(Color::Gray))
112    .style_info(Style::default().fg(Color::Blue))
113    .block(
114      Block::default()
115        .title("Logs")
116        .border_style(theme.style())
117        .borders(Borders::ALL),
118    )   
119    .style(theme.style())
120}
121
122/// Count the different types of tofpackets and store the result 
123/// in a HashMap
124///
125/// # Arguments:
126///
127///   * packet_type : TofPacket type to llokup it's position in 
128///                   the map
129///   * packet_size : The size of the packet including header in bytes
130///   * packet_map  : An arc/mutex to the HashMap we use to store
131///                   the counted values in.
132fn packet_sorter(packet_type : &TofPacketType,
133                 packet_size : usize,
134                 packet_map  : &Arc<Mutex<HashMap<&str,(usize,usize)>>>) {
135  match packet_map.lock() {
136    Ok(mut pm) => {
137      let pack_key : &str;
138      //let pt = packet_type.cl
139      //let pt = packet_type.clone();
140      //let pack_key = pt.as_ref();
141      match packet_type {
142        TofPacketType::Unknown               => pack_key = "Unknown", 
143        TofPacketType::RBEvent               => pack_key = "RBEvent",
144        TofPacketType::TofEvent              => pack_key = "TofEvent",
145        TofPacketType::RBWaveform            => pack_key = "RBWaveform",
146        TofPacketType::TofEventDeprecated    => pack_key = "TofEventDeprecated",
147        TofPacketType::DataSinkHB            => pack_key = "DataSinkHB",    
148        TofPacketType::MasterTrigger         => pack_key = "MasterTrigger",
149        TofPacketType::TriggerConfig         => pack_key = "TriggerConfig",
150        TofPacketType::MasterTriggerHB       => pack_key = "MasterTriggerHHB", 
151        TofPacketType::EventBuilderHB        => pack_key = "EventBuilderHB",
152        TofPacketType::RBChannelMaskConfig   => pack_key = "RBChannelMaskConfig",
153        TofPacketType::TofRBConfig           => pack_key = "TofRBConfig",
154        TofPacketType::AnalysisEngineConfig  => pack_key = "AnalysisEngineConfig",
155        TofPacketType::RBEventHeader         => pack_key = "RBEventHeader",    // needs to go away
156        TofPacketType::TOFEventBuilderConfig => pack_key = "TOFEventBuilderConfig",
157        TofPacketType::DataPublisherConfig   => pack_key = "DataPublisherConfig",
158        TofPacketType::TofRunConfig          => pack_key = "TofRunConfig",
159        TofPacketType::CPUMoniData           => pack_key = "CPUMoniData",
160        TofPacketType::MtbMoniData           => pack_key = "MtbMoniData",
161        TofPacketType::RBMoniData            => pack_key = "RBMoniData",
162        TofPacketType::PBMoniData            => pack_key = "PBMoniData",
163        TofPacketType::LTBMoniData           => pack_key = "LTBMoniData",
164        TofPacketType::PAMoniData            => pack_key = "PAMoniData",
165        TofPacketType::RBEventMemoryView     => pack_key = "RBEventMemoryView", // We'll keep it for now - indicates that the event
166        TofPacketType::RBCalibration         => pack_key = "RBCalibration",
167        TofPacketType::TofCommand            => pack_key = "TofCommand",
168        TofPacketType::TofCommandV2          => pack_key = "TofCommandV2",
169        TofPacketType::TofResponse           => pack_key = "TofResponse",
170        TofPacketType::RBCommand             => pack_key = "RBCommand",
171        TofPacketType::RBPing                => pack_key = "RBPing",
172        TofPacketType::PreampBiasConfig      => pack_key = "PreampBiasConfig",
173        TofPacketType::RunConfig             => pack_key = "RunConfig",
174        TofPacketType::LTBThresholdConfig    => pack_key = "LTBThresholdConfig",
175        TofPacketType::TofDetectorStatus     => pack_key = "TofDetectorStatus",
176        TofPacketType::ConfigBinary          => pack_key = "ConfigBinary",
177        TofPacketType::LiftofRBBinary        => pack_key = "LiftofRBBinary",
178        TofPacketType::LiftofBinaryService   => pack_key = "LiftofBinaryService",
179        TofPacketType::LiftofCCBinary        => pack_key = "LiftofCCBinary",
180        TofPacketType::LiftofSettings        => pack_key = "LiftofSettings",
181        TofPacketType::LiftofSettingsDiff    => pack_key = "LiftofSettingsDiff",
182        TofPacketType::RBCalibrationFlightV  => pack_key = "RBCalibrationFlightV",
183        TofPacketType::RBCalibrationFlightT  => pack_key = "RBCalibrationFlightT",
184        TofPacketType::BfswAckPacket         => pack_key = "BfswAckPacket",
185        TofPacketType::MultiPacket           => pack_key = "MultiPacket",
186        TofPacketType::PanicPacket           => pack_key = "PanicPacket",
187        TofPacketType::TofPulseTemplate      => pack_key = "TofPulseTemplate"
188      }
189      if pm.get(pack_key).is_some() {
190        pm.get_mut(pack_key).unwrap().0 += 1;
191        pm.get_mut(pack_key).unwrap().1 += packet_size;
192      } else {
193        pm.insert(pack_key, (1, packet_size));
194      }
195    }
196    Err(err) => {
197      error!("Can't lock shared memory! {err}");
198    }
199  }
200}
201
202/// Receive packets from an incoming stream
203/// and distrubute them to their receivers
204/// while taking notes of everything
205///
206/// This is a Pablo Pubsub kind of persona
207/// (see a fantastic talk at RustConf 2023)
208pub fn packet_distributor(tp_from_sock       : Receiver<TofPacket>,
209                          tp_sender_mt       : Sender<TofPacket>,
210                          tp_sender_rb       : Sender<TofPacket>,
211                          tp_sender_cp       : Sender<TofPacket>,
212                          tp_sender_tr       : Sender<TofPacket>,
213                          ts_send            : Sender<TofPacket>,
214                          tp_sender_hb       : Sender<TofPacket>,
215                          str_list           : Arc<Mutex<VecDeque<String>>>,
216                          pck_map            : Arc<Mutex<HashMap<&str, (usize, usize)>>>,
217                          mut writer         : Option<TofPacketWriter>,
218                          mut wf_cache       : Box<WaveformCache>,
219                          latest_config      : Arc<Mutex<String>>) {
220  let mut n_pack = 0usize;
221
222  loop {
223    match tp_from_sock.recv() {
224      Err(err) => error!("Can't receive TofPacket! {err}"),
225      Ok(tp) => {
226        let packet_size = tp.payload.len() + 9; // 9 is overhead for TofPacket 
227        packet_sorter(&tp.packet_type, packet_size, &pck_map);
228        n_pack += 1;
229        match str_list.lock() {
230          Err(err) => error!("Can't lock shared memory! {err}"),
231          Ok(mut _list)    => {
232            //let prefix  = String::from_utf8(payload[0..4].to_vec()).expect("Can't get prefix!");
233            //let message = format!("{}-{} {}", n_pack,prefix, tp.to_string());
234            let message = format!("{} : {}", n_pack, tp);
235            _list.push_back(message);
236          }
237        }
238        //continue; 
239        // if --capture, write file
240        if writer.is_some() {
241          writer.as_mut().unwrap().add_tof_packet(&tp);
242        }
243        match tp.packet_type {
244          TofPacketType::TofResponse => { 
245            match tp_sender_tr.send(tp) {
246              Err(err) => error!("Can't send TP! {err}"),
247              Ok(_)    => (),
248            }
249          }
250          TofPacketType::MtbMoniData => {
251            match tp_sender_mt.send(tp) {
252              Err(err) => error!("Can't send TP! {err}"),
253              Ok(_)    => (),
254            }
255          }
256          TofPacketType::RBWaveform => {
257            match tp.unpack::<RBWaveform>() {
258              Ok(wf) => {
259                 
260                let rb_id = wf.rb_id;
261                let ch_a  = wf.rb_channel_a + 1;
262                let ch_b  = wf.rb_channel_b + 1;
263                debug!("Successfully unpacked RBWaveform! {} {} {}", rb_id, ch_a, ch_b);
264                //if rb_id != 25 {
265                //  continue;
266                //} 
267                //if ch_a != 3 {
268                //  continue
269                //}
270                //println!("{wf}");
271                if rb_id > 50 || rb_id == 0 {
272                  continue;
273                }
274                if ch_a > 9 || ch_a == 0 {
275                  error!("Invalid channel B {}", ch_a);
276                  continue;
277                }
278                if ch_b > 9 || ch_b == 0 {
279                  error!("Invalid channel A {}", ch_b);
280                  continue;
281                }
282                //error!("1 : Pushing wf with rb id {} to {}", wf.rb_id, rb_id);
283                match wf_cache.get_mut(&wf.rb_id).unwrap().get_mut(&ch_a).unwrap().lock() {
284                  Err(err)  => {
285                    error!("Unable to lock waveform cache! {err}");
286                  }
287                  Ok(mut cache) => {
288                    //error!("2 : Pushing wf with rb id {} to {}", wf.rb_id, rb_id);
289                    cache.push_back(wf.clone());
290                    //error!("3 : Pushing wf with rb id {} to {}", wf.rb_id, rb_id);
291                    debug!("Last wf in cache has rb id {}", cache.back().unwrap().rb_id); 
292                    if cache.len() > 1000 {
293                      cache.pop_front();
294                    }
295                  }
296                }
297                match wf_cache.get_mut(&wf.rb_id).unwrap().get_mut(&ch_b).unwrap().lock() {
298                  Err(err)  => {
299                    error!("Unable to lock waveform cache! {err}");
300                  }
301                  Ok(mut cache) => {
302                    cache.push_back(wf.clone());
303                    if cache.len() > 1000 {
304                      cache.pop_front();
305                    }
306                   // println!("Pushing waveform for {rb_id} - {ch_b} to cache of len {}", cache.len());
307                  }
308                }
309              }
310              Err(err) => {
311                error!("Unable to unpack RBWaveform! {err}");
312              }
313            }
314            //match rbwf_sender.send(tp) {
315            //  Err(err) => error!("Can't send TP! {err}"),
316            //  Ok(_)    => (),
317            //}
318          }
319          TofPacketType::LiftofSettings => {
320            info!("Saving received liftof-config.toml data!");
321            let output_file_path = PathBuf::from("latest-liftof-config.toml");
322            match decompress_toml(&tp.payload.as_slice(), &output_file_path) {
323              Err(err) => {
324                error!("Unable to decompressed the received bytes into a valid .toml file! {err}")
325              }
326              Ok(_)    => ()
327            }
328            let contents     = fs::read_to_string(output_file_path).unwrap();
329            let value: Value = toml::from_str(&contents).unwrap();
330            match latest_config.lock() {
331              Ok(mut cfg) => {
332                *cfg = toml::to_string_pretty(&value).unwrap();
333              }
334              Err(err) => {
335                error!("Can not lock String to save config! {err}");
336              }
337            }
338            //latest_config    = Arc::new(toml::to_string_pretty(&value).unwrap());
339            //println!("{:?}", latest_config);
340          }
341          TofPacketType::TofEvent => {
342            match ts_send.send(tp) {
343              Err(err) => error!("Can't send TP! {err}"),
344              Ok(_)    => (),
345            }
346          }
347          TofPacketType::RBEvent |
348          TofPacketType::RBEventMemoryView | 
349          TofPacketType::LTBMoniData |
350          TofPacketType::PAMoniData  |
351          TofPacketType::PBMoniData  |
352          TofPacketType::RBMoniData => {
353            match tp_sender_rb.send(tp) {
354              Err(err) => error!("Can't send TP! {err}"),
355              Ok(_)    => (),
356            }
357          }
358          TofPacketType::CPUMoniData => {
359            match tp_sender_cp.send(tp) {
360              Err(err) => error!("Can't send TP! {err}"),
361              Ok(_)    => (),
362            }
363          }
364          TofPacketType::DataSinkHB      |
365          TofPacketType::EventBuilderHB  | 
366          TofPacketType::MasterTriggerHB => {
367            match tp_sender_hb.send(tp) {
368              Err(err) => error!("Can't send TP! {err}"),
369              Ok(_)    => {
370              },
371            }
372          }
373          _ => () 
374        }
375      }
376    } 
377  }
378}
379
380