forked from geissdoerfer/shepherd
-
Notifications
You must be signed in to change notification settings - Fork 2
/
shepherd_io.py
551 lines (459 loc) · 18.8 KB
/
shepherd_io.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
"""
shepherd.shepherd_io
~~~~~
Interface layer, abstracting low-level functionality provided by PRUs and
kernel module. User-space part of the double-buffered data exchange protocol.
"""
import time
from contextlib import suppress
from types import TracebackType
from pydantic import validate_call
from shepherd_core import CalibrationEmulator
from shepherd_core import CalibrationHarvester
from shepherd_core.data_models import GpioTracing
from shepherd_core.data_models import PowerTracing
from shepherd_core.data_models.content.virtual_harvester import HarvesterPRUConfig
from shepherd_core.data_models.content.virtual_source import ConverterPRUConfig
from shepherd_core.data_models.testbed import TargetPort
from typing_extensions import Self
from typing_extensions import TypedDict
from typing_extensions import Unpack
from . import commons
from . import sysfs_interface as sfs
from .logger import log
from .shared_memory import DataBuffer
from .shared_memory import SharedMemory
from .sysfs_interface import check_sys_access
# allow importing shepherd on x86 - for testing
with suppress(ModuleNotFoundError):
from periphery import GPIO
gpio_pin_nums = {
"target_pwr_sel": 31,
"target_io_en": 60,
"target_io_sel": 30,
"en_shepherd": 23,
"en_recorder": 50,
"en_emulator": 51,
}
class ShepherdIOError(Exception):
ID_TIMEOUT = 9999
def __init__(self, message: str, id_num: int = 0, value: int | list | None = 0) -> None:
super().__init__(message + f" [id=0x{id_num:X}, val={value}]")
self.id_num = id_num
self.value = value
class ShepherdIO:
"""Generic ShepherdIO interface.
This class acts as interface between kernel module and firmware on the PRUs,
and user space code. It handles the user space part of the double-buffered
data-exchange protocol between user space and PRUs and configures the
hardware by setting corresponding GPIO pins. This class should usually not
be instantiated, but instead serve as parent class for e.g. Recorder or
Emulator (see __init__.py).
"""
# This _instance-element is part of the singleton implementation
_instance: Self | None = None
@classmethod
def __new__(cls, *_args: tuple, **_kwargs: Unpack[TypedDict]) -> Self:
"""Implements singleton class."""
if cls._instance is None:
cls._instance = object.__new__(cls)
# was raising on reuse and stored weakref.ref before
return cls._instance
log.debug("ShepherdIO-Singleton reused")
return cls._instance
def __init__(
self,
mode: str,
trace_iv: PowerTracing | None,
trace_gpio: GpioTracing | None,
) -> None:
"""Initializes relevant variables.
Args:
mode (str): Shepherd mode, see sysfs_interface for more
"""
check_sys_access()
if not sfs.pru_firmware_is_default():
sfs.load_pru_firmware("pru0-shepherd")
sfs.load_pru_firmware("pru1-shepherd")
self.mode = mode
if mode in {"harvester", "emulator"}:
self.component = mode # TODO: still needed?
else:
self.component = "emulator"
self.gpios = {}
self._buffer_period: float = 0.1 # placeholder value
self.trace_iv = trace_iv
self.trace_gpio = trace_gpio
# placeholders
self.mem_address = 0
self.mem_size = 0
self.samples_per_buffer = 0
self.buffer_period_ns = 0
self.n_buffers = 0
self.shared_mem: SharedMemory
def __del__(self) -> None:
ShepherdIO._instance = None
def __enter__(self) -> Self:
try:
for name, pin in gpio_pin_nums.items():
self.gpios[name] = GPIO(pin, "out")
self.set_shepherd_pcb_power(True)
self.set_io_level_converter(False)
log.debug("Shepherd hardware is powered up")
# If shepherd hasn't been terminated properly
self.reinitialize_prus()
log.debug("Switching to '%s'-mode", self.mode)
sfs.write_mode(self.mode)
self.refresh_shared_mem()
# clean up msg-channel provided by kernel module
self._flush_msgs()
except Exception:
log.exception("ShepherdIO.Init caught an exception -> exit now")
self._power_down_shp()
self._unload_shared_mem()
raise
sfs.wait_for_state("idle", 3)
return self
def __exit__(
self,
typ: type[BaseException] | None = None,
exc: BaseException | None = None,
tb: TracebackType | None = None,
extra_arg: int = 0,
) -> None:
log.info("Now exiting ShepherdIO")
self._power_down_shp()
self._unload_shared_mem()
ShepherdIO._instance = None
@staticmethod
def _send_msg(msg_type: int, values: int | list) -> None:
"""Sends a formatted message to PRU0.
Args:
msg_type (int): Indicates type of message, must be one of the agreed
message types part of the data exchange protocol
values (int): Actual content of the message
"""
sfs.write_pru_msg(msg_type, values)
def _get_msg(self, timeout_n: int = 5) -> tuple[int, list[int]]:
"""Tries to retrieve formatted message from PRU0.
Args:
timeout_n (int): Maximum number of buffer_periods to wait for a message
before raising timeout exception
""" # TODO: cleanest way without exception: ask sysfs-file with current msg-count
for _ in range(timeout_n):
try:
return sfs.read_pru_msg()
except sfs.SysfsInterfaceError: # noqa: PERF203
time.sleep(self._buffer_period)
continue
raise ShepherdIOError("Timeout waiting for message", ShepherdIOError.ID_TIMEOUT)
@staticmethod
def _flush_msgs() -> None:
"""Flushes msg_channel by reading all available bytes."""
while True:
try:
sfs.read_pru_msg()
except sfs.SysfsInterfaceError: # noqa: PERF203
break
def start(
self,
start_time: float | None = None,
wait_blocking: bool = True,
) -> bool:
"""Starts sampling either now or at later point in time.
Args:
start_time (int): Desired start time in unix time
wait_blocking (bool): If true, block until start has completed
"""
if isinstance(start_time, float | int):
log.debug("asking kernel module for start at %.2f", start_time)
success = sfs.set_start(start_time)
if wait_blocking:
self.wait_for_start(3_000_000)
return success
@staticmethod
def wait_for_start(timeout: float) -> None:
"""Waits until shepherd has started sampling.
Args:
timeout (float): Time to wait in seconds
"""
sfs.wait_for_state("running", timeout)
@staticmethod
def reinitialize_prus() -> None:
sfs.set_stop(force=True) # forces idle
sfs.wait_for_state("idle", 5)
def refresh_shared_mem(self) -> None:
if hasattr(self, "shared_mem") and isinstance(self.shared_mem, SharedMemory):
self.shared_mem.__exit__()
# Ask PRU for base address of shared mem (reserved with remoteproc)
self.mem_address = sfs.get_mem_address()
# Ask PRU for size of shared memory (reserved with remoteproc)
self.mem_size = sfs.get_mem_size()
log.debug(
"Shared memory address: \t%s, size: %d byte",
f"0x{self.mem_address:08X}",
# ⤷ not directly in message because of colorizer
self.mem_size,
)
# Ask PRU for size of individual buffers
self.samples_per_buffer = sfs.get_samples_per_buffer()
log.debug("Samples per buffer: \t%d", self.samples_per_buffer)
self.n_buffers = sfs.get_n_buffers()
log.debug("Number of buffers: \t%d", self.n_buffers)
self.buffer_period_ns = sfs.get_buffer_period_ns()
self._buffer_period = self.buffer_period_ns / 1e9
log.debug("Buffer period: \t\t%.3f s", self._buffer_period)
self.shared_mem = SharedMemory(
self.mem_address,
self.mem_size,
self.n_buffers,
self.samples_per_buffer,
self.trace_iv,
self.trace_gpio,
)
self.shared_mem.__enter__()
def _unload_shared_mem(self) -> None:
if self.shared_mem is not None:
self.shared_mem.__exit__()
self.shared_mem = None
def _power_down_shp(self) -> None:
log.debug("ShepherdIO is commanded to power down / cleanup")
count = 1
while count < 6 and sfs.get_state() != "idle":
try:
sfs.set_stop(force=True)
except sfs.SysfsInterfaceError:
log.exception(
"CleanupRoutine caused an exception while trying to stop PRU (n=%d)",
count,
)
try:
sfs.wait_for_state("idle", 3.0)
except sfs.SysfsInterfaceError:
log.warning(
"CleanupRoutine caused an exception while waiting for PRU to go to idle (n=%d)",
count,
)
count += 1
if sfs.get_state() != "idle":
log.warning(
"CleanupRoutine gave up changing state, still '%s'",
sfs.get_state(),
)
self.set_aux_target_voltage(0.0)
self.set_io_level_converter(False)
self.set_power_state_emulator(False)
self.set_power_state_recorder(False)
self.set_shepherd_pcb_power(False)
log.debug("Shepherd hardware is now powered down")
def set_shepherd_pcb_power(self, state: bool) -> None:
"""Controls state of power supplies on shepherd cape.
Args:
state (bool): True for on, False for off
"""
state_str = "enabled" if state else "disabled"
log.debug("Set power-supplies of shepherd-cape to %s", state_str)
self.gpios["en_shepherd"].write(state)
if state:
time.sleep(0.5) # time to stabilize voltage-drop
def set_power_state_recorder(self, state: bool) -> None:
"""
triggered pin is currently connected to ADCs reset-line
NOTE: this might be extended to DAC as well
:param state: bool, enable to get ADC out of reset
:return:
"""
state_str = "enabled" if state else "disabled"
log.debug("Set Recorder of shepherd-cape to %s", state_str)
self.gpios["en_recorder"].write(state)
if state:
time.sleep(0.3) # time to stabilize voltage-drop
def set_power_state_emulator(self, state: bool) -> None:
"""
triggered pin is currently connected to ADCs reset-line
NOTE: this might be extended to DAC as well
:param state: bool, enable to get ADC out of reset
:return:
"""
state_str = "enabled" if state else "disabled"
log.debug("Set Emulator of shepherd-cape to %s", state_str)
self.gpios["en_emulator"].write(state)
if state:
time.sleep(0.3) # time to stabilize voltage-drop
@staticmethod
def convert_target_port_to_bool(target: TargetPort | str | bool | None) -> bool:
if target is None:
return True
if isinstance(target, str):
return TargetPort[target] == TargetPort.A
if isinstance(target, TargetPort):
return target == TargetPort.A
if isinstance(target, bool):
return target
raise ValueError(
f"Parameter 'target' must be A or B (was {target}, type {type(target)})",
)
def select_port_for_power_tracking(
self,
target: TargetPort | bool | None,
) -> None:
"""
choose which targets (A or B) gets the supply with current-monitor,
shepherd hw-rev2 has two ports for targets and two separate power supplies,
but only one is able to measure current, the other is considered "auxiliary"
Args:
target: A or B for that specific Target-Port
"""
current_state = sfs.get_state()
if current_state != "idle":
self.reinitialize_prus()
value = self.convert_target_port_to_bool(target)
log.debug(
"Set routing for (main) supply with current-monitor to target %s",
target,
)
self.gpios["target_pwr_sel"].write(value)
if current_state != "idle":
self.start(wait_blocking=True)
def select_port_for_io_interface(
self,
target: TargetPort | bool | None,
) -> None:
"""choose which targets (A or B) gets the io-connection (serial, swd, gpio) from beaglebone,
shepherd hw-rev2 has two ports for targets and can switch independently
between power supplies
Args:
target: A or B for that specific Target-Port
"""
value = self.convert_target_port_to_bool(target)
log.debug("Set routing for IO to Target %s", target)
self.gpios["target_io_sel"].write(value)
def set_io_level_converter(self, state: bool) -> None:
"""Enables or disables the GPIO level converter to targets.
The shepherd cape has bidirectional logic level translators (LSF0108)
for translating UART, GPIO and SWD signals between BeagleBone and target
voltage levels. This function enables or disables the converter and
additional switches (NLAS4684) to keep leakage low.
Args:
state (bool): True for enabling converter, False for disabling
"""
if state is None:
state = False
state_str = "enabled" if state else "disabled"
log.debug("Set target-io level converter to %s", state_str)
self.gpios["target_io_en"].write(state)
@staticmethod
def set_aux_target_voltage(
voltage: float,
cal_emu: CalibrationEmulator | None = None,
) -> None:
"""Enables or disables the voltage for the second target
The shepherd cape has two DAC-Channels that each serve as power supply for a target
Args:
cal_emu: CalibrationEmulator,
voltage (float): Desired output voltage in volt. Providing 0 or
False disables supply, setting it to True will link it
to the other channel
"""
sfs.write_dac_aux_voltage(voltage, cal_emu)
@staticmethod
def get_aux_voltage(cal_emu: CalibrationEmulator | None = None) -> float:
"""Reads the auxiliary voltage (dac channel B) from the PRU core.
Args:
cal_emu: dict with offset/gain
Returns:
aux voltage
"""
return sfs.read_dac_aux_voltage(cal_emu)
@validate_call
def send_calibration_settings(
self,
cal_: CalibrationEmulator | CalibrationHarvester | None,
) -> None:
"""Sends calibration settings to PRU core
For the virtual source it is required to have the calibration settings.
Note: to apply these settings the pru has to do a re-init (reset)
Args:
cal_ (CalibrationEmulation or CalibrationHarvester): Contains the device's
calibration settings.
"""
if not cal_:
if self.component == "harvester":
cal_ = CalibrationHarvester()
else:
cal_ = CalibrationEmulator()
log.debug("Calibration-Settings:\n%s", cal_)
cal_dict = cal_.export_for_sysfs()
sfs.write_calibration_settings(cal_dict)
@staticmethod
def send_virtual_converter_settings(
settings: ConverterPRUConfig,
) -> None:
"""Sends virtsource settings to PRU core
looks like a simple one-liner but is needed by the child-classes
Note: to apply these settings the pru has to do a re-init (reset)
:param settings: Contains the settings for the virtual source.
"""
sfs.write_virtual_converter_settings(settings)
@staticmethod
def send_virtual_harvester_settings(
settings: HarvesterPRUConfig,
) -> None:
"""Sends virtsource settings to PRU core
looks like a simple one-liner but is needed by the child-classes
Note: to apply these settings the pru has to do a re-init (reset)
:param settings: Contains the settings for the virtual source.
"""
sfs.write_virtual_harvester_settings(settings)
def _return_buffer(self, index: int) -> None:
"""Returns a buffer to the PRU
After reading the content of a buffer and potentially filling it with
emulation data, we have to release the buffer to the PRU to avoid it
running out of buffers.
Args:
index (int): Index of the buffer. 0 <= index < n_buffers
"""
self._send_msg(commons.MSG_BUF_FROM_HOST, index)
def get_buffer(
self,
timeout_n: int = 60,
verbose: bool = False,
) -> tuple[int, DataBuffer]:
"""Reads a data buffer from shared memory.
Polls the msg-channel for a message from PRU0 and, if the message
points to a filled buffer in memory, returns the data in the
corresponding memory location as DataBuffer.
Args:
:param timeout_n: (int) Time in buffer_periods that should be waited for
:param verbose: (bool) more debug output
Returns:
Index and content of corresponding data buffer
Raises:
TimeoutException: If no message is received within
specified timeout
"""
while True:
msg_type, values = self._get_msg(timeout_n)
value = values[0]
if msg_type == commons.MSG_BUF_FROM_PRU:
ts_start = time.time()
buf = self.shared_mem.read_buffer(value, verbose)
if verbose:
log.debug(
"Processing buffer #%d from shared memory took %.2f ms",
value,
1e3 * (time.time() - ts_start),
)
return value, buf
if msg_type == commons.MSG_DBG_PRINT:
log.info("Received cmd to print: %d", value)
continue
if msg_type == commons.MSG_STATUS_RESTARTING_ROUTINE:
log.debug("PRU is restarting its main routine, val=%d", value)
continue
error_msg: str | None = commons.pru_errors.get(msg_type)
if error_msg is not None:
raise ShepherdIOError(error_msg, msg_type, value)
raise ShepherdIOError(
f"Expected msg-type { hex(commons.MSG_BUF_FROM_PRU) }, but got", msg_type, value
)