ConstellationDAQ 0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. constellation/core/__init__.py +21 -0
  2. constellation/core/base.py +207 -0
  3. constellation/core/broadcastmanager.py +317 -0
  4. constellation/core/cdtp.py +246 -0
  5. constellation/core/chirp.py +257 -0
  6. constellation/core/chp.py +67 -0
  7. constellation/core/cmdp.py +218 -0
  8. constellation/core/commandmanager.py +259 -0
  9. constellation/core/configuration.py +144 -0
  10. constellation/core/controller.py +724 -0
  11. constellation/core/cscp.py +193 -0
  12. constellation/core/datareceiver.py +285 -0
  13. constellation/core/datasender.py +275 -0
  14. constellation/core/error.py +55 -0
  15. constellation/core/fsm.py +385 -0
  16. constellation/core/heartbeatchecker.py +324 -0
  17. constellation/core/heartbeater.py +68 -0
  18. constellation/core/monitoring.py +469 -0
  19. constellation/core/network.py +125 -0
  20. constellation/core/protocol.py +98 -0
  21. constellation/core/py.typed +0 -0
  22. constellation/core/satellite.py +512 -0
  23. constellation/core/version_code_name +1 -0
  24. constellation/satellites/CaenHV/CaenHV.py +322 -0
  25. constellation/satellites/CaenHV/__main__.py +11 -0
  26. constellation/satellites/CaenHV/lib_caen_ndt1470.py +479 -0
  27. constellation/satellites/H5DataWriter/H5DataWriter.py +177 -0
  28. constellation/satellites/H5DataWriter/__main__.py +11 -0
  29. constellation/satellites/Influx/Influx.py +72 -0
  30. constellation/satellites/Influx/__main__.py +10 -0
  31. constellation/satellites/Keithley/Keithley.py +188 -0
  32. constellation/satellites/Keithley/Keithley2410.py +116 -0
  33. constellation/satellites/Keithley/KeithleyInterface.py +204 -0
  34. constellation/satellites/Keithley/__main__.py +11 -0
  35. constellation/satellites/Mariner/Mariner.py +144 -0
  36. constellation/satellites/Mariner/__main__.py +11 -0
  37. constellation/satellites/__init__.py +4 -0
  38. constellation/tools/H5datareader.py +127 -0
  39. constellation/tools/list_interfaces.py +39 -0
  40. constellationdaq-0.1.dist-info/METADATA +90 -0
  41. constellationdaq-0.1.dist-info/RECORD +43 -0
  42. constellationdaq-0.1.dist-info/WHEEL +4 -0
  43. constellationdaq-0.1.dist-info/entry_points.txt +13 -0
@@ -0,0 +1,246 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ SPDX-FileCopyrightText: 2024 DESY and the Constellation authors
4
+ SPDX-License-Identifier: CC-BY-4.0
5
+
6
+ Module implementing the Constellation Data Transmission Protocol.
7
+ """
8
+
9
+ from enum import Enum
10
+ from typing import Any
11
+
12
+ import msgpack # type: ignore[import-untyped]
13
+ import zmq
14
+
15
+ from .protocol import MessageHeader, Protocol
16
+
17
+
18
+ class CDTPMessageIdentifier(Enum):
19
+ """Defines the message types of the CDTP.
20
+
21
+ Part of the Constellation Satellite Data Protocol, see
22
+ docs/protocols/cdtp.md for details.
23
+
24
+ """
25
+
26
+ DAT = 0x0
27
+ BOR = 0x1
28
+ EOR = 0x2
29
+
30
+
31
+ class CDTPMessage:
32
+ """Class holding details of a received CDTP command."""
33
+
34
+ name: str = ""
35
+ timestamp: msgpack.Timestamp = msgpack.Timestamp(0)
36
+ msgtype: CDTPMessageIdentifier | None = None
37
+ sequence_number: int = -1
38
+ meta: dict[str, Any] = {}
39
+ payload: Any = None
40
+
41
+ def set_header(
42
+ self,
43
+ name: str,
44
+ timestamp: msgpack.Timestamp,
45
+ msgtype: int,
46
+ seqno: int,
47
+ meta: dict[str, Any],
48
+ ) -> None:
49
+ """Sets information retrieved from a message header."""
50
+ self.name = name
51
+ self.timestamp = timestamp
52
+ try:
53
+ self.msgtype = CDTPMessageIdentifier(msgtype)
54
+ except ValueError as exc:
55
+ raise RuntimeError(
56
+ f"Received invalid sequence identifier with msg: {msgtype}"
57
+ ) from exc
58
+ self.sequence_number = seqno
59
+ self.meta = meta
60
+
61
+ def __str__(self) -> str:
62
+ """Pretty-print request."""
63
+ s = "Data message from {} received at {} of type {}, "
64
+ s += "sequence number {} {} payload and meta {}."
65
+ return s.format(
66
+ self.name,
67
+ self.timestamp,
68
+ self.msgtype,
69
+ self.sequence_number,
70
+ "with a" if self.payload is not None else "without a",
71
+ self.meta,
72
+ )
73
+
74
+
75
+ class DataTransmitter:
76
+ """Base class for sending Constellation data packets via ZMQ."""
77
+
78
+ def __init__(self, name: str, socket: zmq.Socket | None): # type: ignore[type-arg]
79
+ """Initialize transmitter.
80
+
81
+ socket: the ZMQ socket to use if no other is specified on send()/recv()
82
+ calls.
83
+
84
+ name: the name to use in the message header.
85
+ """
86
+ self.name: str = name
87
+ self.msgheader: MessageHeader = MessageHeader(name, Protocol.CDTP)
88
+ # if no socket: might just use the transmitter for decoding
89
+ # TODO : refactorize into own class
90
+ self._socket: zmq.Socket | None = socket # type: ignore[type-arg]
91
+ self.sequence_number: int = 0
92
+
93
+ def send_start(
94
+ self, payload: Any, meta: dict[str, Any] | None = None, flags: int = 0
95
+ ) -> None:
96
+ """
97
+ Send starting message of data run over a ZMQ socket.
98
+
99
+ Follows the Constellation Data Transmission Protocol.
100
+
101
+ payload: meta information about the beginning of run.
102
+
103
+ flags: additional ZMQ socket flags to use during transmission.
104
+
105
+ """
106
+ self.sequence_number = 0
107
+ packer = msgpack.Packer()
108
+ self._dispatch(
109
+ msgtype=CDTPMessageIdentifier.BOR,
110
+ payload=packer.pack(payload),
111
+ meta=meta,
112
+ flags=flags,
113
+ )
114
+
115
+ def send_data(
116
+ self, payload: Any, meta: dict[str, Any] | None = None, flags: int = 0
117
+ ) -> None:
118
+ """
119
+ Send data message of data run over a ZMQ socket.
120
+
121
+ Follows the Constellation Data Transmission Protocol.
122
+
123
+ payload: meta information about the beginning of run.
124
+
125
+ meta: optional dictionary that is sent as a map of string/value
126
+ pairs with the header.
127
+
128
+ flags: additional ZMQ socket flags to use during transmission.
129
+
130
+ """
131
+ self.sequence_number += 1
132
+ self._dispatch(
133
+ msgtype=CDTPMessageIdentifier.DAT,
134
+ payload=payload,
135
+ meta=meta,
136
+ flags=flags,
137
+ )
138
+
139
+ def send_end(
140
+ self, payload: Any, meta: dict[str, Any] | None = None, flags: int = 0
141
+ ) -> None:
142
+ """
143
+ Send ending message of data run over a ZMQ socket.
144
+
145
+ Follows the Constellation Data Transmission Protocol.
146
+
147
+ payload: meta information about the end of run.
148
+
149
+ flags: additional ZMQ socket flags to use during transmission.
150
+
151
+ """
152
+ packer = msgpack.Packer()
153
+ self._dispatch(
154
+ msgtype=CDTPMessageIdentifier.EOR,
155
+ payload=packer.pack(payload),
156
+ meta=meta,
157
+ flags=flags,
158
+ )
159
+
160
+ def recv(self, flags: int = 0) -> CDTPMessage | None:
161
+ """Receive a multi-part data transmission.
162
+
163
+ Follows the Constellation Data Transmission Protocol.
164
+
165
+ flags: additional ZMQ socket flags to use during transmission.
166
+
167
+ Returns: CTDPMessage
168
+
169
+ """
170
+ # check that we have a valid socket
171
+ if not self._socket:
172
+ return None
173
+ try:
174
+ binmsg = self._socket.recv_multipart(flags=flags)
175
+ except zmq.ZMQError:
176
+ return None
177
+ return self.decode(binmsg)
178
+
179
+ def decode(self, binmsg: list[bytes]) -> CDTPMessage:
180
+ """Decode a binary message into a CTDPMessage."""
181
+ msg = CDTPMessage()
182
+ msg.set_header(*self.msgheader.decode(binmsg[0]))
183
+
184
+ # Retrieve payload
185
+ if msg.msgtype in [CDTPMessageIdentifier.EOR, CDTPMessageIdentifier.BOR]:
186
+ # decode single-frame EOR/BOR payload
187
+ msg.payload = msgpack.unpackb(binmsg[1])
188
+ else:
189
+ # one-or-many binary frames
190
+ msg.payload = binmsg[1:]
191
+ if len(msg.payload) <= 1:
192
+ # unpack list
193
+ try:
194
+ msg.payload = binmsg[1]
195
+ except IndexError:
196
+ msg.payload = None
197
+ return msg
198
+
199
+ def _dispatch(
200
+ self,
201
+ msgtype: CDTPMessageIdentifier,
202
+ payload: Any = None,
203
+ meta: dict[str, Any] | None = None,
204
+ flags: int = 0,
205
+ ) -> None:
206
+ """Dispatch CDTP message.
207
+
208
+ msgtype: flag identifying whether transmitting beginning-of-run, data or end-of-run
209
+
210
+ payload: data to send.
211
+
212
+ meta: dictionary to include in the map of the message header.
213
+
214
+ flags: additional ZMQ socket flags to use during transmission.
215
+
216
+ Returns: None
217
+
218
+ """
219
+ # check that we have a valid socket
220
+ if not self._socket:
221
+ return
222
+
223
+ if payload:
224
+ flags = zmq.SNDMORE | flags
225
+ # message header
226
+ self.msgheader.send(
227
+ self._socket,
228
+ meta=meta,
229
+ flags=flags,
230
+ msgtype=msgtype.value,
231
+ seqno=self.sequence_number,
232
+ )
233
+
234
+ # payload
235
+ if payload:
236
+ # send multiple frames?
237
+ if isinstance(payload, list):
238
+ for idx, frame in enumerate(payload):
239
+ # final package?
240
+ if idx == len(payload) - 1:
241
+ flags = flags & (~zmq.SNDMORE) # flip SNDMORE bit
242
+ self._socket.send(frame, flags=flags)
243
+ else:
244
+ # single frame
245
+ flags = flags & (~zmq.SNDMORE) # flip SNDMORE bit
246
+ self._socket.send(payload, flags=flags)
@@ -0,0 +1,257 @@
1
+ """
2
+ SPDX-FileCopyrightText: 2024 DESY and the Constellation authors
3
+ SPDX-License-Identifier: CC-BY-4.0
4
+
5
+ Module implementing the Constellation Host Identification and Reconnaissance Protocol (CHIRP).
6
+ """
7
+
8
+ from hashlib import md5
9
+ import io
10
+ from uuid import UUID
11
+ from enum import Enum
12
+ from .network import get_broadcast, get_broadcast_socket, decode_ancdata, ANC_BUF_SIZE
13
+
14
+
15
+ CHIRP_PORT = 7123
16
+ CHIRP_HEADER = "CHIRP\x01"
17
+
18
+
19
+ def get_uuid(name: str) -> UUID:
20
+ """Return the UUID for a string using MD5 hashing."""
21
+ hash = md5(name.encode(), usedforsecurity=False)
22
+ return UUID(bytes=hash.digest())
23
+
24
+
25
+ class CHIRPServiceIdentifier(Enum):
26
+ """Identifies the type of service.
27
+
28
+ The CONTROL service identifier indicates a CSCP (Constellation Satellite
29
+ Control Protocol) service.
30
+
31
+ The HEARTBEAT service identifier indicates a CHP (Constellation Heartbeat
32
+ Protocol) service.
33
+
34
+ The MONITORING service identifier indicates a CMDP (Constellation Monitoring
35
+ Distribution Protocol) service.
36
+
37
+ The DATA service identifier indicates a CDTP (Constellation Data
38
+ Transmission Protocol) service.
39
+
40
+ The NONE identifier is used for initialization only, and is not a valid
41
+ service type.
42
+
43
+ """
44
+
45
+ NONE = 0x0
46
+ CONTROL = 0x1
47
+ HEARTBEAT = 0x2
48
+ MONITORING = 0x3
49
+ DATA = 0x4
50
+
51
+
52
+ class CHIRPMessageType(Enum):
53
+ """Identifies the type of message sent or received via the CHIRP protocol.
54
+
55
+ See docs/protocols/chirp.md for details.
56
+
57
+ REQUEST: A message with REQUEST type indicates that CHIRP hosts should reply
58
+ with an OFFER
59
+
60
+ OFFER: A message with OFFER type indicates that service is available
61
+
62
+ DEPART: A message with DEPART type indicates that a service is no longer
63
+ available
64
+
65
+ NONE: Value used for initialization only, not a valid message type.
66
+
67
+ """
68
+
69
+ NONE = 0x0
70
+ REQUEST = 0x1
71
+ OFFER = 0x2
72
+ DEPART = 0x3
73
+
74
+
75
+ class CHIRPMessage:
76
+ """Class to hold a CHIRP message."""
77
+
78
+ def __init__(
79
+ self,
80
+ msgtype: CHIRPMessageType = CHIRPMessageType.NONE,
81
+ group_uuid: UUID = UUID(int=0),
82
+ host_uuid: UUID = UUID(int=0),
83
+ serviceid: CHIRPServiceIdentifier = CHIRPServiceIdentifier.NONE,
84
+ port: int = 0,
85
+ ):
86
+ """Initialize attributes."""
87
+ self.msgtype = msgtype
88
+ self.group_uuid = group_uuid
89
+ self.host_uuid = host_uuid
90
+ self.serviceid = serviceid
91
+ self.port = port
92
+ self.from_address: str = ""
93
+ self.dest_address: str = ""
94
+
95
+ def pack(self) -> bytes:
96
+ """Serialize message to raw bytes."""
97
+ bytes = io.BytesIO()
98
+ bytes.write(CHIRP_HEADER.encode())
99
+ bytes.write(self.msgtype.value.to_bytes(length=1))
100
+ bytes.write(self.group_uuid.bytes)
101
+ bytes.write(self.host_uuid.bytes)
102
+ bytes.write(self.serviceid.value.to_bytes(length=1))
103
+ bytes.write(self.port.to_bytes(length=2, byteorder="big"))
104
+ return bytes.getvalue()
105
+
106
+ def unpack(self, msg: bytes) -> None:
107
+ """Decode from bytes."""
108
+ # Check message length
109
+ if len(msg) != 42:
110
+ raise RuntimeError(
111
+ f"Invalid CHIRP message: length is {len(msg)} instead of 42 bytes long"
112
+ )
113
+ # Check header
114
+ if msg[0:6] != CHIRP_HEADER.encode():
115
+ raise RuntimeError(
116
+ f"Invalid CHIRP message: header {msg[0:6]!r} is malformed"
117
+ )
118
+ # Decode message
119
+ self.msgtype = CHIRPMessageType(int.from_bytes(msg[6:7]))
120
+ self.group_uuid = UUID(bytes=msg[7:23])
121
+ self.host_uuid = UUID(bytes=msg[23:39])
122
+ self.serviceid = CHIRPServiceIdentifier(int.from_bytes(msg[39:40]))
123
+ self.port = int.from_bytes(msg[40:42], byteorder="big")
124
+
125
+ def __str__(self) -> str:
126
+ """Pretty-print CHIRP message."""
127
+ s = "CHIRP message from {} received of type {}, "
128
+ s += "host id {}, service id {} on port {}."
129
+ return s.format(
130
+ self.from_address,
131
+ self.msgtype,
132
+ self.host_uuid,
133
+ self.serviceid,
134
+ self.port,
135
+ )
136
+
137
+
138
+ class CHIRPBeaconTransmitter:
139
+ """Class for broadcasting CHRIP messages.
140
+
141
+ See docs/protocols/chirp.md for details.
142
+
143
+ """
144
+
145
+ def __init__(
146
+ self,
147
+ name: str,
148
+ group: str,
149
+ interface: str,
150
+ ) -> None:
151
+ """Initialize attributes and open broadcast socket."""
152
+ self._host_uuid = get_uuid(name)
153
+ self._group_uuid = get_uuid(group)
154
+
155
+ # whether or not to filter broadcasts on group
156
+ self._filter_group = True
157
+
158
+ # whether or not there are incoming packets
159
+ self.busy = False
160
+
161
+ # Create UPP broadcasting socket
162
+ #
163
+ # NOTE: Socket options are often OS-specific; the ones below were chosen
164
+ # for supporting Linux-based systems.
165
+ #
166
+ self._sock = get_broadcast_socket()
167
+ # blocking (i.e. with a timeout for recv calls)
168
+ self._sock.setblocking(True)
169
+ self._sock.settimeout(0.05)
170
+ # determine to what address(es) to send broadcasts to
171
+ self._broadcast_addrs = list(get_broadcast(interface))
172
+ # bind to specified interface(s) to listen to incoming broadcast.
173
+ # NOTE: only support for IPv4 is implemented
174
+ if interface == "*":
175
+ # INADDR_ANY for IPv4
176
+ interface = ""
177
+ else:
178
+ # use broadcast address instead
179
+ interface = self._broadcast_addrs[0]
180
+ # one socket for listening
181
+ self._sock.bind((interface, CHIRP_PORT))
182
+
183
+ @property
184
+ def host(self) -> UUID:
185
+ """Get the UUID of the host this transmitter was set up for."""
186
+ return self._host_uuid
187
+
188
+ @property
189
+ def group(self) -> UUID:
190
+ """Get the UUID of the Constellation group of this transmitter."""
191
+ return self._group_uuid
192
+
193
+ @property
194
+ def filter(self) -> bool:
195
+ """Whether or not incoming broadcasts are filtered on group."""
196
+ return self._filter_group
197
+
198
+ @filter.setter
199
+ def filter(self, val: bool) -> None:
200
+ """Whether or not incoming broadcasts are filtered on group."""
201
+ self._filter_group = val
202
+
203
+ def broadcast(
204
+ self,
205
+ serviceid: CHIRPServiceIdentifier,
206
+ msgtype: CHIRPMessageType,
207
+ port: int = 0,
208
+ dest_address: str = "",
209
+ ) -> None:
210
+ """Broadcast a given service."""
211
+ msg = CHIRPMessage(msgtype, self._group_uuid, self._host_uuid, serviceid, port)
212
+ self.busy = True
213
+ if not dest_address:
214
+ # send to all
215
+ for bcast in self._broadcast_addrs:
216
+ self._sock.sendto(msg.pack(), (bcast, CHIRP_PORT))
217
+ else:
218
+ self._sock.sendto(msg.pack(), (dest_address, CHIRP_PORT))
219
+ self.busy = False
220
+
221
+ def listen(self) -> CHIRPMessage | None:
222
+ """Listen in on CHIRP port and return message if data was received."""
223
+ try:
224
+ buf, ancdata, flags, from_address = self._sock.recvmsg(
225
+ 1024,
226
+ ANC_BUF_SIZE,
227
+ )
228
+ self.busy = True
229
+ except (BlockingIOError, TimeoutError):
230
+ # no data waiting for us
231
+ self.busy = False
232
+ return None
233
+
234
+ # Unpack msg
235
+ msg = CHIRPMessage()
236
+ try:
237
+ msg.unpack(buf)
238
+ except Exception as e:
239
+ raise RuntimeError(
240
+ f"Received malformed message by host {from_address}: {e}"
241
+ ) from e
242
+
243
+ # ignore msg from this (our) host
244
+ if self._host_uuid == msg.host_uuid:
245
+ return None
246
+
247
+ # optionally drop messages from other groups
248
+ if self._filter_group and self._group_uuid != msg.group_uuid:
249
+ return None
250
+
251
+ msg.from_address = from_address[0]
252
+ msg.dest_address, _destport = decode_ancdata(ancdata)
253
+ return msg
254
+
255
+ def close(self) -> None:
256
+ """Close the socket."""
257
+ self._sock.close()
@@ -0,0 +1,67 @@
1
+ """
2
+ SPDX-FileCopyrightText: 2024 DESY and the Constellation authors
3
+ SPDX-License-Identifier: CC-BY-4.0
4
+ """
5
+
6
+ import time
7
+ import io
8
+ import msgpack # type: ignore[import-untyped]
9
+ import zmq
10
+ from typing import Tuple
11
+ from .protocol import Protocol
12
+
13
+
14
+ def CHPDecodeMessage(buf: bytes) -> Tuple[str, msgpack.Timestamp, int, int]:
15
+ """Decode a CHP binary message.
16
+
17
+ Returns host, timestamp, state and interval.
18
+
19
+ """
20
+ unpacker = msgpack.Unpacker()
21
+ unpacker.feed(buf)
22
+ protocol = unpacker.unpack()
23
+ host = unpacker.unpack()
24
+ timestamp = unpacker.unpack()
25
+ state = unpacker.unpack()
26
+ interval = unpacker.unpack()
27
+ if not protocol == Protocol.CHP.value:
28
+ raise RuntimeError(f"Received message with malformed CHP header: {protocol}!")
29
+ return host, timestamp, state, interval
30
+
31
+
32
+ class CHPTransmitter:
33
+ """Send and receive via the Constellation Heartbeat Protocol (CHP)."""
34
+
35
+ def __init__(self, name: str, socket: zmq.Socket): # type: ignore[type-arg]
36
+ """Initialize transmitter."""
37
+ self.name = name
38
+ self._socket = socket
39
+
40
+ def send(self, state: int, interval: int, flags: int = 0) -> None:
41
+ """Send state and interval via CHP."""
42
+ stream = io.BytesIO()
43
+ packer = msgpack.Packer()
44
+ stream.write(packer.pack(Protocol.CHP))
45
+ stream.write(packer.pack(self.name))
46
+ stream.write(packer.pack(msgpack.Timestamp.from_unix_nano(time.time_ns())))
47
+ stream.write(packer.pack(state))
48
+ stream.write(packer.pack(interval))
49
+ self._socket.send(stream.getbuffer(), flags=flags)
50
+
51
+ def recv(
52
+ self, flags: int = zmq.NOBLOCK
53
+ ) -> Tuple[str, msgpack.Timestamp, int, int] | Tuple[None, None, None, None]:
54
+ """Receive a heartbeat via CHP."""
55
+ try:
56
+ buf = self._socket.recv(flags)
57
+ except zmq.ZMQError as e:
58
+ if "Resource temporarily unavailable" not in e.strerror:
59
+ raise RuntimeError(
60
+ "CommandTransmitter encountered zmq exception"
61
+ ) from e
62
+ return None, None, None, None
63
+ return CHPDecodeMessage(buf)
64
+
65
+ def close(self) -> None:
66
+ """Close the socket of the transmitter."""
67
+ self._socket.close()