Skip to content

Commit ec3ac15

Browse files
minor dyscom related changes
1 parent dbca556 commit ec3ac15

9 files changed

Lines changed: 198 additions & 20 deletions

‎examples/dyscom/example_dyscom_get.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,11 @@ async def main() -> int:
6363
# get file info for calibration file
6464
file_info = await dyscom.get_file_info(calibration_filename)
6565
print(f"Calibration file info checksum: {file_info.checksum}")
66+
67+
####
68+
# switch device into mass storage -> does not work
69+
# mass_storage = await dyscom.sys(DyscomSysType.DEVICE_STORAGE)
70+
# print(f"System call to set into mass storage, type {mass_storage.sys_type.name}, state: {mass_storage.state.name}")
6671
finally:
6772
# always close the serial port connection, even if an exception occurred above,
6873
# otherwise the COM port stays locked for subsequent runs

‎examples/dyscom/example_dyscom_send_file.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Provides an example how to use dyscom level layer to read stored data from device"""
22

33
import asyncio
4+
import datetime
45

56
from science_mode_4 import DeviceI24
67
from science_mode_4 import SerialPortConnection
@@ -47,6 +48,9 @@ async def main() -> int:
4748
init_params.filter = DyscomFilterType.PREDEFINED_FILTER_1
4849
# we want no live data and write all data to memory card
4950
init_params.flags = [DyscomInitFlag.ENABLE_SD_STORAGE_MODE]
51+
# device stops recording at the minute boundary of start time + duration,
52+
# so duration must be long enough to cover the measurement below
53+
init_params.duration = datetime.timedelta(minutes=2)
5054
init_result = await dyscom.init(init_params)
5155

5256
# start dyscom measurement

‎src/__main__.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import sys
55
import asyncio
6+
import datetime
67

78
from science_mode_4.device_i24 import DeviceI24
89
from science_mode_4.dyscom.dyscom_types import DyscomFilterType, DyscomInitFlag, DyscomInitParams, DyscomPowerModulePowerType,\
@@ -52,6 +53,8 @@ async def main() -> int:
5253
init_params.filter = DyscomFilterType.PREDEFINED_FILTER_1
5354
# we want no live data and write all data to memory card
5455
init_params.flags = [DyscomInitFlag.ENABLE_SD_STORAGE_MODE]
56+
# device stops recording at the minute boundary of start time + duration
57+
init_params.duration = datetime.timedelta(minutes=2)
5558
init_result = await dyscom.init(init_params)
5659

5760
# start dyscom measurement

‎src/science_mode_4/dyscom/dyscom_helper.py‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
class DyscomHelper:
99
"""Provides some helper functions"""
1010

11-
_unpack_func = struct.Struct("<BBBBBBBHh").unpack
11+
# big endian, matching datetime_to_bytes() and all other multi byte dyscom fields
12+
_unpack_func = struct.Struct(">BBBBBBBHh").unpack
1213

1314
@staticmethod
1415
def datetime_to_bytes(dt: datetime.datetime) -> bytes:
@@ -23,7 +24,9 @@ def datetime_to_bytes(dt: datetime.datetime) -> bytes:
2324
bb.append_byte(dt.second)
2425
bb.append_byte((dt.weekday() + 1) % 7)
2526
bb.append_value(dt.timetuple().tm_yday - 1, 2, True)
26-
bb.append_value(dt.year - 1900, 2, True)
27+
# full year (e.g. 2026), not years since 1900 like struct tm: verified with a real I24,
28+
# sending 126 for 2026 made the device set its clock (and file names) to year 2014
29+
bb.append_value(dt.year, 2, True)
2730

2831
return bb.get_bytes()
2932

@@ -32,11 +35,11 @@ def datetime_to_bytes(dt: datetime.datetime) -> bytes:
3235
def bytes_to_datetime(data: bytes) -> datetime.datetime:
3336
"""Converts dyscom datetime bytes to a datetime"""
3437
# pylint:disable=unused-variable
35-
hour, dst, day, minute, month, second, _, _, year_since_1900 = \
38+
hour, dst, day, minute, month, second, _, _, year = \
3639
DyscomHelper._unpack_func(data)
3740

3841
# do we need to consider dst?
39-
result = datetime.datetime(1900 + year_since_1900, month, day, hour, minute, second)
42+
result = datetime.datetime(year, month, day, hour, minute, second)
4043
return result
4144

4245

‎src/science_mode_4/dyscom/dyscom_layer.py‎

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@
77
from science_mode_4.protocol.commands import Commands
88
from science_mode_4.protocol.exceptions import ProtocolError
99
from science_mode_4.utils.logger import logger
10-
from .dyscom_types import DyscomFrequencyOut, DyscomGetOperationModeType, DyscomInitState, DyscomPowerModuleType,\
11-
DyscomPowerModulePowerType, DyscomSignalType, DyscomSysState, DyscomSysType
10+
from .dyscom_types import DyscomFilterType, DyscomFrequencyOut, DyscomGetOperationModeType, DyscomInitFlag, DyscomInitState,\
11+
DyscomPowerModuleType, DyscomPowerModulePowerType, DyscomSignalType, DyscomSysState, DyscomSysType
1212
from .dyscom_init import DyscomInitResult, PacketDyscomInit, PacketDyscomInitAck, DyscomInitParams
1313
from .dyscom_get_file_system_status import PacketDyscomGetFileSystemStatus, PacketDyscomGetAckFileSystemStatus,\
1414
DyscomGetFileSystemStatusResult
@@ -34,6 +34,11 @@ class LayerDyscom(Layer):
3434

3535
async def init(self, params: DyscomInitParams) -> DyscomInitResult:
3636
"""Send dyscom init command and waits for response"""
37+
if (DyscomInitFlag.ENABLE_SD_STORAGE_MODE in params.flags) and (params.duration.total_seconds() < 60):
38+
# firmware stops a sd recording at the minute boundary of start time + duration,
39+
# so a duration below one minute stops the recording (almost) immediately
40+
logger().warning("Dyscom init with sd storage mode and duration %s, recording will stop almost immediately, "
41+
"set duration to at least one minute", params.duration)
3742
p = PacketDyscomInit(params)
3843
ack: PacketDyscomInitAck = await self.send_packet_and_wait(p)
3944
self._check_result_error(ack.result_error, "DyscomInit")
@@ -46,7 +51,8 @@ async def init(self, params: DyscomInitParams) -> DyscomInitResult:
4651

4752

4853
async def get_file_system_status(self) -> DyscomGetFileSystemStatusResult:
49-
"""Sends dyscom get type file system status and waits for response, returns file system ready, used size and free size"""
54+
"""Sends dyscom get type file system status and waits for response, returns file system ready, used size and free size.
55+
Note: not implemented by I24 firmware, all values are always 0"""
5056
p = PacketDyscomGetFileSystemStatus()
5157
ack: PacketDyscomGetAckFileSystemStatus = await self.send_packet_and_wait(p)
5258
self._check_result_error(ack.result_error, "DyscomGetFileSystemStatus")
@@ -56,7 +62,8 @@ async def get_file_system_status(self) -> DyscomGetFileSystemStatusResult:
5662

5763

5864
async def get_list_of_measurement_meta_info(self) -> int:
59-
"""Sends dyscom get type list of measurement meta info and waits for response, returns number of measurements"""
65+
"""Sends dyscom get type list of measurement meta info and waits for response, returns number of measurements.
66+
Note: not implemented by I24 firmware, number of measurements is always 0 and no DL_MMI packets are sent"""
6067
p = PacketDyscomGetListOfMeasurementMetaInfo()
6168
ack: PacketDyscomGetAckListOfMeasurementMetaInfo = await self.send_packet_and_wait(p)
6269
self._check_result_error(ack.result_error, "DyscomGetListOfMeasurementMetaInfo")
@@ -104,7 +111,8 @@ async def get_file_info(self, filename: str) -> DyscomGetFileInfoResult:
104111

105112

106113
async def get_battery(self) -> DyscomGetBatteryResult:
107-
"""Sends dyscom get type batter and waits for response, returns voltage, current, percentage, temperature and energy state"""
114+
"""Sends dyscom get type battery and waits for response, returns voltage, current, percentage, temperature and energy state.
115+
Note: not implemented by I24 firmware, all values are always 0"""
108116
p = PacketDyscomGetBatteryStatus()
109117
ack: PacketDyscomGetAckBatteryStatus = await self.send_packet_and_wait(p)
110118
self._check_result_error(ack.result_error, "DyscomGetBatteryStatus")
@@ -139,7 +147,10 @@ async def power_module(self, module: DyscomPowerModuleType, power: DyscomPowerMo
139147

140148

141149
async def sys(self, sys_type: DyscomSysType, filename: str = "") -> DyscomSysResult:
142-
"""Sends dyscom sys and waits for response, returns type, state and filename"""
150+
"""Sends dyscom sys and waits for response, returns type, state and filename.
151+
Note: DELETE_FILE does not work with I24 firmware, because the firmware ignores filename.
152+
DEVICE_STORAGE is acknowledged as successful, but I24 firmware does not switch to USB mass
153+
storage mode (USB MSC is not implemented), device reports operation mode UNDEFINED afterwards"""
143154
p = PacketDyscomSys(sys_type, filename)
144155
ack: PacketDyscomSysAck = await self.send_packet_and_wait(p)
145156
self._check_result_error(ack.result_error, "DyscomSys")
@@ -152,7 +163,7 @@ async def sys(self, sys_type: DyscomSysType, filename: str = "") -> DyscomSysRes
152163

153164
def send_send_file_ack(self, block_number: int):
154165
"""Sends dyscom send file ack and returns immediately without waiting for response"""
155-
logger().info("Dyscom send file ack, block_number: %d", block_number)
166+
logger().debug("Dyscom send file ack, block_number: %d", block_number)
156167
p = PacketDyscomSendFileAck(block_number)
157168
self.send_packet(p)
158169

@@ -249,8 +260,14 @@ async def get_meas_file_content(self, filename: str) -> tuple[DyscomFrequencyOut
249260

250261
result[signal_type] = []
251262

252-
# sample rate
253-
sample_rate = DyscomFrequencyOut(meas_data[3])
263+
# sample rate, derived from filter (header byte 4) like firmware does, because header byte 3
264+
# (output frequency) is written by firmware before filter is applied and may contain the
265+
# frequency of the previous init
266+
filter_sample_rate_map = {DyscomFilterType.FILTER_OFF: DyscomFrequencyOut.SAMPLES_PER_SECOND_4K,
267+
DyscomFilterType.PREDEFINED_FILTER_1: DyscomFrequencyOut.SAMPLES_PER_SECOND_1K,
268+
DyscomFilterType.PREDEFINED_FILTER_2: DyscomFrequencyOut.SAMPLES_PER_SECOND_4K,
269+
DyscomFilterType.PREDEFINED_FILTER_3: DyscomFrequencyOut.SAMPLES_PER_SECOND_1K}
270+
sample_rate = filter_sample_rate_map[DyscomFilterType(meas_data[4])]
254271

255272
# build string to unpack samples
256273
# each sample consist of a time difference and n time signal type values

‎src/science_mode_4/dyscom/dyscom_send_measurement_meta_info.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99

1010
class PacketDyscomSendMeasurementMetaInfo(PacketAck):
1111
"""Packet for dyscom send measurement meta info (this is technically not an acknowledge, but it is handled as such,
12-
because it is send automatically from device)"""
12+
because it is send automatically from device).
13+
Note: I24 firmware never sends this packet"""
1314

1415

1516
def __init__(self, data: bytes):

‎src/science_mode_4/dyscom/dyscom_types.py‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,9 @@ class DyscomInitParams():
160160
proband_name: str = ""
161161
investigator_name: str = ""
162162
proband_number: str = ""
163+
# planned measurement duration, only relevant for sd storage mode: the device stops recording
164+
# at the minute boundary of start time + duration (seconds are ignored by firmware), so with
165+
# the default of 0 a sd recording stops almost immediately after start
163166
duration: datetime.timedelta = field(default_factory=datetime.timedelta)
164167
signal_type: list[DyscomSignalType] = field(default_factory=lambda: [DyscomSignalType.BI, DyscomSignalType.EMG_1])
165168
sync_signal: bool = False
@@ -176,6 +179,10 @@ def get_data(self) -> bytes:
176179
raise ValueError(f"Investigator name must be shorter than 129 {self.investigator_name}")
177180
if len(self.proband_number) > 36:
178181
raise ValueError(f"Proband number must be shorter than 37 {self.proband_number}")
182+
# total_seconds() instead of seconds, which is only the seconds part without days
183+
duration_in_seconds = int(self.duration.total_seconds())
184+
if (duration_in_seconds < 0) or (duration_in_seconds > 0xFFFFFFFF):
185+
raise ValueError(f"Duration must be between 0..{0xFFFFFFFF} seconds {duration_in_seconds}")
179186

180187

181188
bb = ByteBuilder()
@@ -186,7 +193,7 @@ def get_data(self) -> bytes:
186193
bb.append_bytes(DyscomHelper.str_to_bytes(self.investigator_name, 129))
187194
bb.append_bytes(DyscomHelper.str_to_bytes(self.proband_number, 37))
188195
bb.append_value(len(self.signal_type), 2, True)
189-
bb.append_value(self.duration.seconds, 4, True)
196+
bb.append_value(duration_in_seconds, 4, True)
190197
for x in range(8):
191198
bb.append_byte(self.signal_type[x] if x < len(self.signal_type) else DyscomSignalType.UNUSED)
192199
bb.append_byte(0)
@@ -201,4 +208,17 @@ def get_data(self) -> bytes:
201208

202209

203210
def set_data(self, data: bytes):
204-
"""Convert bytes to information"""
211+
"""Convert bytes to information, inverse of get_data()"""
212+
self.register_map_ads129x.set_data(data[0:26])
213+
self.start_time = DyscomHelper.bytes_to_datetime(data[26:37])
214+
self.system_time = DyscomHelper.bytes_to_datetime(data[37:48])
215+
self.proband_name = DyscomHelper.bytes_to_str(data[48:177], 129)
216+
self.investigator_name = DyscomHelper.bytes_to_str(data[177:306], 129)
217+
self.proband_number = DyscomHelper.bytes_to_str(data[306:343], 37)
218+
signal_type_count = min(int.from_bytes(data[343:345], "big"), 8)
219+
self.duration = datetime.timedelta(seconds=int.from_bytes(data[345:349], "big"))
220+
self.signal_type = [DyscomSignalType(x) for x in data[349:349 + signal_type_count]]
221+
# data[357] is a reserved byte
222+
self.sync_signal = data[358] != 0
223+
self.filter = DyscomFilterType(data[359])
224+
self.flags = {f for f in DyscomInitFlag if data[360] & (1 << f)}

‎tests/test_dyscom_init_params.py‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22
# pylint: disable=missing-function-docstring
33
# test names are self-explanatory, docstrings would only restate them
44

5+
import datetime
56
import time
67

7-
from science_mode_4.dyscom.dyscom_types import DyscomInitParams
8+
import pytest
9+
from science_mode_4.dyscom.dyscom_helper import DyscomHelper
10+
from science_mode_4.dyscom.dyscom_types import DyscomFilterType, DyscomInitFlag, DyscomInitParams, DyscomSignalType
811
from science_mode_4.dyscom.ads129x.ads129x_config_register_1 import Ads129xPowerMode
912

1013

@@ -39,3 +42,64 @@ def test_signal_type_defaults_are_independent_lists():
3942

4043
a.signal_type.append(a.signal_type[0])
4144
assert len(b.signal_type) == 2
45+
46+
47+
def test_set_data_is_inverse_of_get_data():
48+
# regression test: set_data() was an empty stub, so e.g. the init params of a
49+
# received measurement meta info packet were always silently left at their defaults
50+
source = DyscomInitParams()
51+
source.register_map_ads129x.config_register_1.power_mode = Ads129xPowerMode.LOW_POWER
52+
source.start_time = datetime.datetime(2025, 3, 4, 5, 6, 7)
53+
source.system_time = datetime.datetime(2024, 12, 31, 23, 59, 58)
54+
source.proband_name = "proband"
55+
source.investigator_name = "investigator"
56+
source.proband_number = "42"
57+
source.duration = datetime.timedelta(seconds=3600)
58+
source.signal_type = [DyscomSignalType.EMG_1, DyscomSignalType.EMG_2, DyscomSignalType.BREATHING]
59+
source.sync_signal = True
60+
source.filter = DyscomFilterType.PREDEFINED_FILTER_2
61+
source.flags = {DyscomInitFlag.ENABLE_SD_STORAGE_MODE, DyscomInitFlag.MUTE}
62+
63+
target = DyscomInitParams()
64+
target.set_data(source.get_data())
65+
66+
assert target == source
67+
68+
69+
def test_bytes_to_datetime_is_inverse_of_datetime_to_bytes():
70+
# regression test: bytes_to_datetime() unpacked year and day of year as little endian
71+
# while datetime_to_bytes() writes them big endian, e.g. year 2025 was read as 33900
72+
dt = datetime.datetime(2025, 3, 4, 5, 6, 7)
73+
assert DyscomHelper.bytes_to_datetime(DyscomHelper.datetime_to_bytes(dt)) == dt
74+
75+
76+
def test_datetime_to_bytes_encodes_full_year_big_endian():
77+
# regression test: the year was sent as years since 1900 (126 for 2026), but the
78+
# I24 expects the full year - verified on a real device, which then set its clock
79+
# to year 2014 instead of 2026
80+
data = DyscomHelper.datetime_to_bytes(datetime.datetime(2026, 9, 26, 23, 41, 35))
81+
assert data[9:11] == (2026).to_bytes(2, "big")
82+
# day of year (0 based) is big endian as well
83+
assert data[7:9] == (268).to_bytes(2, "big")
84+
85+
86+
def _encoded_duration(params: DyscomInitParams) -> int:
87+
# duration is located after register map (26), start/system time (2 * 11), proband/investigator
88+
# name (2 * 129), proband number (37) and signal type count (2)
89+
offset = 26 + 2 * 11 + 2 * 129 + 37 + 2
90+
return int.from_bytes(params.get_data()[offset:offset + 4], "big")
91+
92+
93+
def test_duration_includes_days():
94+
# regression test: timedelta.seconds is only the seconds part without days,
95+
# so a duration of 1 day + 5 seconds was encoded as 5 seconds
96+
params = DyscomInitParams()
97+
params.duration = datetime.timedelta(days=1, seconds=5)
98+
assert _encoded_duration(params) == 86405
99+
100+
101+
def test_negative_duration_raises():
102+
params = DyscomInitParams()
103+
params.duration = datetime.timedelta(seconds=-1)
104+
with pytest.raises(ValueError):
105+
params.get_data()

0 commit comments

Comments
 (0)