Skip to main content

gondola_core/packets/
tof_packet.rs

1//! TofPacket provides a wrapper to write objects which implement
2//! TofPackable into files
3// This file is part of gaps-online-software and published 
4// under the GPLv3 license
5
6use crate::prelude::*;
7
8/// Internal Tof communication protocol.
9/// Simple, yet powerful
10///
11/// A TofPacket has the following layout
12/// on disk
13/// HEAD    : u16 = 0xAAAA
14/// TYPE    : u8  = PacketType
15/// SIZE    : u32
16/// PAYLOAD : [u8;6-SIZE]
17/// TAIL    : u16 = 0x5555 
18///
19/// The total packet size is thus 13 + SIZE
20#[derive(Debug, Clone)]
21#[cfg_attr(feature="pybindings", pyclass)]
22pub struct TofPacket {
23  /// Type of the structure encoded in payload
24  pub packet_type        : TofPacketType,
25  /// The bytestream encoded structure
26  pub payload            : Vec<u8>,
27  // fields which won't get serialized
28  /// mark a packet as not eligible to be written to disk
29  pub no_write_to_disk   : bool,
30  /// mark a packet as not eligible to be sent over network 
31  /// FIXME - future extension
32  pub no_send_over_nw    : bool,
33  /// creation_time for the instance
34  // FIXME - do we really need the last 2?
35  pub creation_time      : Instant,
36  pub valid              : bool, // will be always valid, unless invalidated
37  pub tof_paddles        : Arc<HashMap<u8,  TofPaddle>>, 
38}
39
40impl fmt::Display for TofPacket {
41  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
42    let p_len = self.payload.len();
43    if p_len < 4 {
44      write!(f, "<TofPacket: type {:?}, payload size {}>", self.packet_type, p_len)
45    } else {
46      write!(f, "<TofPacket: type {:?}, payload [ {} {} {} {} .. {} {} {} {}] of size {} >",
47             self.packet_type,
48             self.payload[0], self.payload[1], self.payload[2], self.payload[3],
49             self.payload[p_len-4], self.payload[p_len-3], self.payload[p_len - 2], self.payload[p_len-1], p_len ) 
50    }
51  }
52}
53
54impl Default for TofPacket {
55  fn default() -> Self {
56    Self::new()
57  }
58}
59
60/// Implement because TofPacket saves the creation time, 
61/// which never will be the same for 2 different instances
62impl PartialEq for TofPacket {
63  fn eq(&self, other: &Self) -> bool {
64    (self.packet_type == other.packet_type)           &&
65    (self.payload == other.payload)                   &&
66    (self.no_write_to_disk == other.no_write_to_disk) &&
67    (self.no_send_over_nw == other.no_send_over_nw)   &&
68    (self.valid == other.valid)
69  }
70}
71
72impl TofPacket {
73
74  pub fn new() -> Self {
75    let creation_time = Instant::now();
76    Self {
77      packet_type      : TofPacketType::Unknown,
78      payload          : Vec::<u8>::new(),
79      no_write_to_disk : false,
80      no_send_over_nw  : false,
81      creation_time    : creation_time,
82      valid            : true,
83      tof_paddles      : Arc::new(HashMap::<u8, TofPaddle>::new()),
84    }
85  }
86
87  /// Generate a bytestream of self for ZMQ, prefixed with 
88  /// BRCT so all RBs will see it
89  pub fn zmq_payload_brdcast(&self) -> Vec<u8> {
90    let mut payload     = String::from("BRCT").into_bytes(); 
91    let mut stream  = self.to_bytestream();
92    payload.append(&mut stream);
93    payload
94  }
95  
96  /// Generate a bytestream of self for ZMQ, prefixed with 
97  /// RBX, to address only a certain board
98  pub fn zmq_payload_rb(&self, rb_id : u8) -> Vec<u8> {
99    let mut payload     = format!("RB{:02}", rb_id).into_bytes(); 
100    let mut stream  = self.to_bytestream();
101    payload.append(&mut stream);
102    payload
103  }
104
105  /// Unpack the TofPacket and return its content
106  pub fn unpack<T>(&self) -> Result<T, SerializationError>
107    where T: TofPackable + Serialization {
108
109    // first check TOF_PACKET_ALT, if that is != UNKNOWN, 
110    // call from_bytestream_alt. If it is UNKNOWN, proceed
111    // "as usual"
112    let mut pos : usize = 0;
113    if T::TOF_PACKET_TYPE_ALT != TofPacketType::Unknown {
114      if T::TOF_PACKET_TYPE_ALT == self.packet_type {
115        let unpacked : T = T::from_bytestream_alt(&self.payload, &mut pos)?;
116        return Ok(unpacked); 
117      } else if T::TOF_PACKET_TYPE == self.packet_type {
118        let unpacked : T = T::from_bytestream(&self.payload, &mut pos)?;
119        return Ok(unpacked); 
120      } else {
121        error!("This packet of type {} is neither for a {} nor a {}  packet!", self.packet_type, T::TOF_PACKET_TYPE, T::TOF_PACKET_TYPE_ALT);
122        return Err(SerializationError::IncorrectPacketType); 
123      }
124    } else { // TOF_PACKET_ALT is UNKNOWN, so we just proceed as usual
125      if T::TOF_PACKET_TYPE != self.packet_type {
126        error!("This bytestream is not for a {} packet!", self.packet_type);
127        return Err(SerializationError::IncorrectPacketType);
128      } else {
129        let unpacked : T = T::from_bytestream(&self.payload, &mut pos)?;
130        Ok(unpacked)
131      }
132    }
133  }
134  
135  pub fn age(&self) -> u64 {
136    self.creation_time.elapsed().as_secs()
137  }
138
139  /// In case this packet is of type TofEvent, 
140  /// we can retrieve the event id without unpacking it 
141  ///
142  /// # Returns 
143  ///   * None in case this is not an packet of type 
144  ///     TofEvent 
145  ///   * Some(eventid ) - event id from packet for 
146  ///     TofEvents
147  pub fn get_event_id(&self) -> Option<u32> {
148    if self.packet_type != TofPacketType::TofEvent {
149      return None;
150    }
151    // the event id is at position 6 in the tofpacket bytestream 
152    let mut pos : usize  = 6;
153    let event_id = parse_u32(&self.payload,&mut pos);
154    Some(event_id)
155  }
156}
157
158
159impl Serialization for TofPacket {
160  const HEAD : u16 = 0xaaaa;
161  const TAIL : u16 = 0x5555;
162  const SIZE : usize = 0; // FIXME - size/prelude_size 
163
164  fn from_bytestream(stream : &Vec<u8>, pos : &mut usize)
165  -> Result<Self, SerializationError> {
166    if stream.len() < 2 {
167      return Err(SerializationError::StreamTooShort);
168    }
169    let head = parse_u16(stream, pos);
170    if Self::HEAD != head {
171      error!("TofPacket does not start with HEAD signature! {}", Self::HEAD);
172      return Err(SerializationError::HeadInvalid);
173    }
174    let packet_type : TofPacketType;
175    let packet_type_enc = parse_u8(stream, pos);
176    match TofPacketType::try_from(packet_type_enc) {
177      Ok(pt) => packet_type = pt,
178      Err(_) => {
179        error!("Can not decode packet with packet type {}", packet_type_enc);
180        return Err(SerializationError::UnknownPayload);}
181    }
182    let payload_size = parse_u32(stream, pos) as usize;
183    *pos += payload_size;
184    debug!("Attempting to decode {packet_type} : {payload_size} bytes!");
185    let tail = parse_u16(stream, pos);
186    if Self::TAIL != tail {
187      error!("Packet does not end with TAIL signature, but ends with {} instead", tail);
188      return Err(SerializationError::TailInvalid);
189    }
190    *pos -= 2; // for tail parsing
191    *pos -= payload_size;
192
193    let mut tp = TofPacket::new();
194    tp.packet_type = packet_type;
195    tp.payload.extend_from_slice(&stream[*pos..*pos+payload_size]);
196    // Fix position marker
197    *pos += 2 + payload_size;
198    Ok(tp) 
199  }
200  
201  fn to_bytestream(&self) 
202    -> Vec<u8> {
203    let mut bytestream = Vec::<u8>::with_capacity(6 + self.payload.len());
204    bytestream.extend_from_slice(&TofPacket::HEAD.to_le_bytes());
205    let p_type = self.packet_type as u8;
206    bytestream.push(p_type);
207    // payload size of 32 bit accomodates up to 4 GB packet
208    // a 16 bit size would only hold 65k, which might be not
209    // good enough if we sent multiple events in a batch in 
210    // the same TofPacket (in case we do that)
211    let payload_len = self.payload.len() as u32;
212    //let foo = &payload_len.to_le_bytes();
213    //debug!("TofPacket binary payload: {foo:?}");
214    bytestream.extend_from_slice(&payload_len.to_le_bytes());
215    bytestream.extend_from_slice(self.payload.as_slice());
216    bytestream.extend_from_slice(&TofPacket::TAIL.to_le_bytes());
217    bytestream
218  }
219}
220
221#[cfg(feature="random")]
222impl FromRandom for TofPacket {
223
224  fn from_random() -> Self {
225    // FIXME - this should be an actual, realistic
226    // distribution
227    let choices = [
228      TofPacketType::TofEvent,
229      TofPacketType::TofEvent,
230      TofPacketType::TofEvent,
231      TofPacketType::RBWaveform,
232      TofPacketType::RBWaveform,
233      TofPacketType::TofEvent,
234      TofPacketType::TofEvent,
235      TofPacketType::TofEvent,
236      TofPacketType::TofEvent,
237      TofPacketType::TofEvent,
238      TofPacketType::TofEvent,
239      TofPacketType::MasterTrigger,
240      TofPacketType::MasterTrigger,
241      TofPacketType::MasterTrigger,
242      TofPacketType::RBMoniData,
243      TofPacketType::PBMoniData,
244      TofPacketType::LTBMoniData,
245      TofPacketType::PAMoniData,
246      TofPacketType::CPUMoniData,
247      TofPacketType::MtbMoniData,
248    ];
249    let mut rng  = rand::rng();
250    let idx = rng.random_range(0..choices.len());
251    let packet_type = choices[idx];
252    match packet_type {
253      TofPacketType::TofEvent => {
254        let te = TofEvent::from_random();
255        return te.pack()
256      }
257      TofPacketType::RBWaveform => {
258        let te = RBWaveform::from_random();
259        return te.pack()
260      }
261      TofPacketType::RBMoniData => {
262        let te = RBMoniData::from_random();
263        return te.pack()
264      }
265      TofPacketType::PAMoniData => {
266        let te = PAMoniData::from_random();
267        return te.pack()
268      }
269      TofPacketType::LTBMoniData => {
270        let te = LTBMoniData::from_random();
271        return te.pack()
272      }
273      TofPacketType::PBMoniData => {
274        let te = PBMoniData::from_random();
275        return te.pack()
276      }
277      TofPacketType::CPUMoniData => {
278        let te = CPUMoniData::from_random();
279        return te.pack()
280      }
281      TofPacketType::MtbMoniData  => {
282        let te = MtbMoniData::from_random();
283        return te.pack()
284      }
285      _ => {
286        let te = TofEvent::from_random();
287        return te.pack()
288      }
289    }
290  }
291}
292
293impl Frameable for TofPacket {
294  const CRFRAMEOBJECT_TYPE : CRFrameObjectType = CRFrameObjectType::TofPacket;
295}
296
297#[cfg(feature="pybindings")]
298#[pymethods]
299impl TofPacket {
300
301  #[getter]
302  fn get_packet_type(&self) -> TofPacketType {
303    self.packet_type
304  }
305
306  fn get_paddle(&self, paddle_id : u8) -> PyResult<TofPaddle> {
307    match self.tof_paddles.get(&paddle_id) {
308      None => {
309        let msg = "TofPacket does not contain a reference to paddle {paddle_id}!";
310        return Err(PyValueError::new_err(msg));
311      }
312      Some(paddle) => {
313        return Ok(paddle.clone());
314      }
315    }
316  }
317
318  // FIXME - trust in te process that it referenceces te input vector and not clones it
319  /// Factory function for TofPackets
320  ///
321  /// # Arguments:
322  ///
323  ///   * stream    : bytes presumably representing
324  ///                 a TofPacket
325  ///   * start_pos : the assumed position of 
326  ///                 HEAD identifier in the
327  ///                 bytestream (start of 
328  ///                 TofPacket)
329  #[staticmethod]
330  #[pyo3(name = "from_bytestream")]
331  fn from_bytestream_py<'_py>(stream : Vec<u8>, start_pos : usize) -> PyResult<Self>{
332    let mut pos = start_pos;  
333    match Self::from_bytestream(&stream, &mut pos) {
334      Ok(tp) => {
335        return Ok(tp);
336      }
337      Err(err) => {
338        let err_msg = format!("Unable to TofPacket from bytestream! {err}");
339        return Err(PyIOError::new_err(err_msg));
340      }
341    }
342  }
343
344  #[pyo3(name="to_bytestream")]
345  fn to_bytestream_py(&self) -> Vec<u8> {
346    self.to_bytestream()
347  }
348
349  #[getter]
350  #[pyo3(name="payload")]
351  fn get_payload_py(&self) -> Vec<u8> {
352    self.payload.clone()
353  }
354  
355  /// In case this packet is of type TofEvent, 
356  /// we can retrieve the event id without unpacking it 
357  ///
358  /// # Returns 
359  ///   * None in case this is not an packet of type 
360  ///     TofEvent 
361  ///   * Some(eventid ) - event id from packet for 
362  ///     TofEvents
363  #[pyo3(name="event_id")] 
364  #[getter]
365  fn get_event_id_py(&self) -> Option<u32> { 
366    self.get_event_id() 
367  }
368
369  #[pyo3(name="unpack")]
370  fn unpack_py(&self,py: Python) -> PyResult<Py<PyAny>> {
371    match self.packet_type {
372      TofPacketType::Unknown               => {
373        let msg = "TofPacket is of type 'Unknown' and thus can't be unpacked!";
374        return Err(PyValueError::new_err(msg));
375      }, 
376      TofPacketType::RBEvent               => {
377        match self.unpack::<RBEvent>() {
378          Ok(data) => {
379            return Ok(Py::new(py, data)?.into_any());
380          }
381          Err(err) => {
382            return Err(PyValueError::new_err(err.to_string()));
383          }
384        }
385      }, 
386      TofPacketType::TofEventDeprecated  => {
387        match self.unpack::<TofEvent>() {
388          Ok(data) => {
389            return Ok(Py::new(py, data)?.into_any());
390          }
391          Err(err) => {
392            return Err(PyValueError::new_err(err.to_string()));
393          }
394        }
395      }, 
396      TofPacketType::RBWaveform               => {
397        match self.unpack::<RBWaveform>() {
398          Ok(data) => {
399            return Ok(Py::new(py, data)?.into_any());
400          }
401          Err(err) => {
402            return Err(PyValueError::new_err(err.to_string()));
403          }
404        }
405      }, 
406      TofPacketType::TofEvent               => {
407        match self.unpack::<TofEvent>() {
408          Ok(data) => {
409            return Ok(Py::new(py, data)?.into_any());
410          }
411          Err(err) => {
412            return Err(PyValueError::new_err(err.to_string()));
413          }
414        }
415      }, 
416      TofPacketType::DataSinkHB               => {
417        match self.unpack::<DataSinkHB>() {
418          Ok(data) => {
419            return Ok(Py::new(py, data)?.into_any());
420          }
421          Err(err) => {
422            return Err(PyValueError::new_err(err.to_string()));
423          }
424        }
425      }, 
426      //TofPacketType::MasterTrigger         => {}, 
427      //TofPacketType::TriggerConfig         => {},
428      //TofPacketType::MasterTriggerHB       => {}, 
429      //TofPacketType::EventBuilderHB        => {},
430      //TofPacketType::RBChannelMaskConfig   => {},
431      //TofPacketType::TofRBConfig           => {},
432      //TofPacketType::AnalysisEngineConfig  => {},
433      //TofPacketType::RBEventHeader         => {},    
434      //TofPacketType::TOFEventBuilderConfig => {},
435      //TofPacketType::DataPublisherConfig   => {},
436      //TofPacketType::TofRunConfig          => {},
437      //TofPacketType::CPUMoniData           => {},
438      //TofPacketType::MtbMoniData           => {},
439      //TofPacketType::RBMoniData            => {},
440      //TofPacketType::PBMoniData            => {},
441      //TofPacketType::LTBMoniData           => {},
442      //TofPacketType::PAMoniData            => {},
443      //TofPacketType::RBEventMemoryView     => {}, 
444      //TofPacketType::RBCalibration         => {},
445      //TofPacketType::TofCommand            => {},
446      //TofPacketType::TofCommandV2          => {},
447      //TofPacketType::TofResponse           => {},
448      //TofPacketType::RBCommand             => {},
449      //TofPacketType::RBPing                => {},
450      //TofPacketType::PreampBiasConfig      => {},
451      //TofPacketType::RunConfig             => {},
452      //TofPacketType::LTBThresholdConfig    => {},
453      //TofPacketType::TofDetectorStatus     => {},
454      //TofPacketType::ConfigBinary          => {},
455      //TofPacketType::LiftofRBBinary        => {},
456      //TofPacketType::LiftofBinaryService   => {},
457      //TofPacketType::LiftofCCBinary        => {},
458      //TofPacketType::RBCalibrationFlightV  => {},
459      //TofPacketType::RBCalibrationFlightT  => {},
460      //TofPacketType::BfswAckPacket         => {},
461      //TofPacketType::MultiPacket           => {},
462      _               => {
463        match self.unpack::<TofEvent>() {
464          Ok(data) => {
465            return Ok(Py::new(py, data)?.into_any());
466          }
467          Err(err) => {
468            return Err(PyValueError::new_err(err.to_string()));
469          }
470        }
471      }, 
472    }
473  }
474}
475
476#[cfg(feature="pybindings")]
477pythonize!(TofPacket);
478
479//--------------------------------------------------
480
481#[test]
482#[cfg(feature="random")] 
483fn tofpacket_get_event_id() {
484  let te = TofEvent::from_random();
485  let evid = te.event_id;
486  let pack = te.pack();
487  assert_eq!(evid, pack.get_event_id().unwrap());
488}
489