qlsdk2 0.6.0__py3-none-any.whl → 0.6.0a1__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.
@@ -1,3 +1,9 @@
1
+
2
+ from multiprocessing import Queue
3
+ from threading import Thread
4
+ from time import sleep, time_ns
5
+ from typing import Any, Dict, Literal
6
+
1
7
  from loguru import logger
2
8
  from qlsdk.core.entity import C256RSPacket
3
9
  from qlsdk.persist import RscEDFHandler
@@ -6,19 +12,135 @@ from qlsdk.rsc.command import *
6
12
  from qlsdk.rsc.device.base import QLBaseDevice
7
13
 
8
14
  class C256RS(QLBaseDevice):
9
- # C256RS设备类型标识符
10
- device_type_001 = 0x51
11
- device_type = 0x45
15
+
16
+ device_type = 0x51 # C64RS设备类型标识符
12
17
 
13
18
  def __init__(self, socket):
14
19
  super().__init__(socket)
20
+ self.socket = socket
21
+
22
+ self._id = None
23
+
24
+ # 设备信息
25
+ self.device_id = None
26
+ self.device_name = None
27
+ self._device_no = None
28
+ self.software_version = None
29
+ self.hardware_version = None
30
+ self.connect_time = None
31
+ self.current_time = None
32
+ # mV
33
+ self.voltage = None
34
+ # %
35
+ self.battery_remain = None
36
+ # %
37
+ self.battery_total = None
38
+ # persist
39
+ self._recording = False
40
+ self._storage_path = None
41
+ self._file_prefix = None
42
+
43
+ # 可设置参数
44
+ # 采集:采样量程、采样率、采样通道
45
+ # 刺激:刺激电流、刺激频率、刺激时间、刺激通道
46
+ # 采样量程(mV):188、375、563、750、1125、2250、4500
47
+ self._sample_range:Literal[188, 375, 563, 750, 1125, 2250, 4500] = 188
48
+ # 采样率(Hz):250、500、1000、2000、4000、8000、16000、32000
49
+ self._sample_rate:Literal[250, 500, 1000, 2000, 4000, 8000, 16000, 32000] = 500
50
+ self._physical_max = self._sample_range * 1000 # 物理最大值(uV)
51
+ self._physical_min = -self._sample_range * 1000 # 物理最小值(uV)
52
+ self._digital_max = 8388607
53
+ self._digital_min = -8388608
54
+ self._physical_range = self._physical_max - self._physical_min
55
+ self._digital_range = 16777215
56
+ self._acq_channels = None
57
+ self._acq_param = {
58
+ "sample_range": 188,
59
+ "sample_rate": 500,
60
+ "channels": [],
61
+ }
62
+
63
+ self._stim_param = {
64
+ "stim_type": 0, # 刺激类型:0-所有通道参数相同, 1: 通道参数不同
65
+ "channels": [],
66
+ "param": [{
67
+ "channel_id": 0, #通道号 从0开始 -- 必填
68
+ "waveform": 3, #波形类型:0-直流,1-交流 2-方波 3-脉冲 -- 必填
69
+ "current": 1, #电流强度(mA) -- 必填
70
+ "duration": 30, #平稳阶段持续时间(s) -- 必填
71
+ "ramp_up": 5, #上升时间(s) 默认0
72
+ "ramp_down": 5, #下降时间(s) 默认0
73
+ "frequency": 500, #频率(Hz) -- 非直流必填
74
+ "phase_position": 0, #相位 -- 默认0
75
+ "duration_delay": "0", #延迟启动时间(s) -- 默认0
76
+ "pulse_width": 0, #脉冲宽度(us) -- 仅脉冲类型电流有效, 默认100us
77
+ },
78
+ {
79
+ "channel_id": 1, #通道号 从0开始 -- 必填
80
+ "waveform": 3, #波形类型:0-直流,1-交流 2-方波 3-脉冲 -- 必填
81
+ "current": 1, #电流强度(mA) -- 必填
82
+ "duration": 30, #平稳阶段持续时间(s) -- 必填
83
+ "ramp_up": 5, #上升时间(s) 默认0
84
+ "ramp_down": 5, #下降时间(s) 默认0
85
+ "frequency": 500, #频率(Hz) -- 非直流必填
86
+ "phase_position": 0, #相位 -- 默认0
87
+ "duration_delay": "0", #延迟启动时间(s) -- 默认0
88
+ "pulse_width": 0, #脉冲宽度(us) -- 仅脉冲类型电流有效, 默认100us
89
+ }
90
+ ]
91
+ }
92
+
93
+ self.stim_paradigm = None
94
+
95
+ signal_info = {
96
+ "param" : None,
97
+ "start_time" : None,
98
+ "finished_time" : None,
99
+ "packet_total" : None,
100
+ "last_packet_time" : None,
101
+ "state" : 0
102
+ }
103
+ stim_info = {
104
+
105
+ }
106
+ Impedance_info = {
107
+
108
+ }
109
+ # 信号采集状态
110
+ # 信号数据包总数(一个信号采集周期内)
111
+ # 信号采集参数
112
+ # 电刺激状态
113
+ # 电刺激开始时间(最近一次)
114
+ # 电刺激结束时间(最近一次)
115
+ # 电刺激参数
116
+ # 启动数据解析线程
117
+ # 数据存储状态
118
+ # 存储目录
119
+
120
+ #
121
+ self.__signal_consumer: Dict[str, Queue[Any]]={}
122
+ self.__impedance_consumer: Dict[str, Queue[Any]]={}
123
+
124
+ # EDF文件处理器
125
+ self._edf_handler = None
126
+ self.storage_enable = True
127
+
128
+ # self._parser: IParser = RSCMessageParser(self)
129
+ # self._parser.start()
15
130
 
16
- @classmethod
17
- def from_parent(cls, parent:IDevice) -> IDevice:
18
- rlt = cls(parent.socket)
19
- rlt.device_id = parent.device_id
20
- rlt._device_no = parent.device_no
21
- return rlt
131
+ # 启动数据接收线程
132
+ # self._accept = Thread(target=self.accept)
133
+ # self._accept.daemon = True
134
+ # self._accept.start()
135
+
136
+ @property
137
+ def device_no(self):
138
+ return self._device_no
139
+
140
+ @device_no.setter
141
+ def device_no(self, value: str):
142
+ self._device_no = value
143
+
22
144
 
23
145
  def init_edf_handler(self):
24
146
  self._edf_handler = RscEDFHandler(self.sample_rate, self.sample_range * 1000 , - self.sample_range * 1000, self.resolution)
@@ -26,19 +148,211 @@ class C256RS(QLBaseDevice):
26
148
  self._edf_handler.set_device_no(self.device_no)
27
149
  self._edf_handler.set_storage_path(self._storage_path)
28
150
  self._edf_handler.set_file_prefix(self._file_prefix if self._file_prefix else 'C256RS')
29
- logger.debug(f"EDF Handler initialized")
30
-
151
+
152
+ @property
153
+ def edf_handler(self):
154
+ if not self.storage_enable:
155
+ return None
156
+
157
+ if self._edf_handler is None:
158
+ self.init_edf_handler()
159
+
160
+ return self._edf_handler
161
+
31
162
  @property
32
163
  def acq_channels(self):
33
164
  if self._acq_channels is None:
34
165
  self._acq_channels = [i for i in range(1, 256)]
35
- return self._acq_channels
166
+ return self._acq_channels
167
+ @property
168
+ def sample_range(self):
169
+ return self._sample_range if self._sample_range else 188
170
+ @property
171
+ def sample_rate(self):
172
+ return self._sample_rate if self._sample_rate else 500
173
+ @property
174
+ def resolution(self):
175
+ return 24
176
+
177
+ @property
178
+ def signal_consumers(self):
179
+ return self.__signal_consumer
180
+
181
+ @property
182
+ def impedance_consumers(self):
183
+ return self.__impedance_consumer
184
+
185
+ # 设置记录文件路径
186
+ def set_storage_path(self, path):
187
+ self._storage_path = path
188
+
189
+ # 设置记录文件名称前缀
190
+ def set_file_prefix(self, prefix):
191
+ self._file_prefix = prefix
192
+
193
+ # 接收socket消息
194
+ def accept(self):
195
+ pass
196
+ # while True:
197
+ # # 缓冲去4M
198
+ # data = self.socket.recv(4096*1024)
199
+ # if not data:
200
+ # logger.warning(f"设备{self.device_name}连接结束")
201
+ # break
202
+
203
+ # self._parser.append(data)
204
+
205
+ # socket发送数据
206
+ def send(self, data):
207
+ self.socket.sendall(data)
208
+
209
+ # 设置刺激参数
210
+ def set_stim_param(self, param):
211
+ self.stim_paradigm = param
212
+
213
+ # 设置采集参数
214
+ def set_acq_param(self, channels, sample_rate = 500, sample_range = 188):
215
+ self._acq_param["channels"] = channels
216
+ self._acq_param["sample_rate"] = sample_rate
217
+ self._acq_param["sample_range"] = sample_range
218
+ self._acq_channels = channels
219
+ self._sample_rate = sample_rate
220
+ self._sample_range = sample_range
36
221
 
37
222
  def _signal_wrapper(self, body: bytes):
38
223
  return C256RSPacket().transfer(body)
39
224
 
40
- def get_stim_param(self) -> bytes:
41
- return self.stim_paradigm.to_bytes_c256()
225
+ def start_impedance(self):
226
+ logger.info("启动阻抗测量")
227
+ msg = StartImpedanceCommand.build(self).pack()
228
+ logger.debug(f"start_impedance message is {msg.hex()}")
229
+ self.socket.sendall(msg)
230
+
231
+ def stop_impedance(self):
232
+ logger.info("停止阻抗测量")
233
+ msg = StopImpedanceCommand.build(self).pack()
234
+ logger.debug(f"stop_impedance message is {msg.hex()}")
235
+ self.socket.sendall(msg)
236
+
237
+ def start_stimulation(self):
238
+ if self.stim_paradigm is None:
239
+ logger.warning("刺激参数未设置,请先设置刺激参数")
240
+ return
241
+ logger.info("启动电刺激")
242
+ msg = StartStimulationCommand.build(self).pack()
243
+ logger.debug(f"start_stimulation message is {msg.hex()}")
244
+ self.socket.sendall(msg)
245
+ t = Thread(target=self._stop_stimulation_trigger, args=(self.stim_paradigm.duration,))
246
+ t.start()
247
+
248
+ def _stop_stimulation_trigger(self, duration):
249
+ delay = duration
250
+ while delay > 0:
251
+ sleep(1)
252
+ delay -= 1
253
+ logger.info(f"_stop_stimulation_trigger duration: {duration}")
254
+ if self._edf_handler:
255
+ self._edf_handler.trigger("stimulation should be stopped")
256
+ else:
257
+ logger.warning("stop stim trigger fail. no edf writer alive")
258
+
259
+ def stop_stimulation(self):
260
+ logger.info("停止电刺激")
261
+ msg = StopStimulationCommand.pack()
262
+ logger.debug(f"stop_stimulation message is {msg.hex()}")
263
+ self.socket.sendall(msg)
264
+
265
+ # 启动采集
266
+ def start_acquisition(self, recording = True):
267
+ logger.info("启动信号采集")
268
+ self._recording = recording
269
+ # 设置数据采集参数
270
+ param_bytes = SetAcquisitionParamCommand.build(self).pack()
271
+ # 启动数据采集
272
+ start_bytes = StartAcquisitionCommand.build(self).pack()
273
+ msg = param_bytes + start_bytes
274
+ logger.debug(f"start_acquisition message is {msg.hex()}")
275
+ self.socket.sendall(msg)
276
+
277
+ # 停止采集
278
+ def stop_acquisition(self):
279
+ logger.info("停止信号采集")
280
+ msg = StopAcquisitionCommand.build(self).pack()
281
+ logger.debug(f"stop_acquisition message is {msg.hex()}")
282
+ self.socket.sendall(msg)
283
+ if self._edf_handler:
284
+ # 发送结束标识
285
+ self.edf_handler.write(None)
286
+
287
+ # 订阅实时数据
288
+ def subscribe(self, topic:str=None, q : Queue=None, type : Literal["signal","impedance"]="signal"):
289
+
290
+ # 数据队列
291
+ if q is None:
292
+ q = Queue(maxsize=10240000) # 10M缓存
293
+
294
+ # 队列名称
295
+ if topic is None:
296
+ topic = f"{type}_{time_ns()}"
297
+
298
+ # 订阅生理电信号数据
299
+ if type == "signal":
300
+ # topic唯一,用来区分不同的订阅队列(下同)
301
+ if topic in list(self.__signal_consumer.keys()):
302
+ logger.warning(f"exists {type} subscribe of {topic}")
303
+ else:
304
+ self.__signal_consumer[topic] = q
305
+
306
+ # 订阅阻抗数据
307
+ if type == "impedance":
308
+ if topic in list(self.__signal_consumer.keys()):
309
+ logger.warning(f"exists {type} subscribe of {topic}")
310
+ else:
311
+ self.__impedance_consumer[topic] = q
312
+
313
+ return topic, q
314
+
315
+ def trigger(self, desc):
316
+ if self._edf_handler:
317
+ self.edf_handler.trigger(desc)
318
+ else:
319
+ logger.warning("no edf handler, no place to recording trigger")
320
+
321
+ def __str__(self):
322
+ return f'''
323
+ Device:
324
+ Name: {self.device_name},
325
+ Type: {hex(self.device_type) if self.device_type else None},
326
+ ID: {self.device_id if self.device_id else None},
327
+ Software: {self.software_version},
328
+ Hardware: {self.hardware_version},
329
+ Connect Time: {self.connect_time},
330
+ Current Time: {self.current_time},
331
+ Voltage: {str(self.voltage) + "mV" if self.voltage else None},
332
+ Battery Remain: {str(self.battery_remain)+ "%" if self.battery_remain else None},
333
+ Battery Total: {str(self.battery_total) + "%" if self.battery_total else None}
334
+ '''
335
+
336
+ def __repr__(self):
337
+ return f'''
338
+ Device:
339
+ Name: {self.device_name},
340
+ Type: {hex(self.device_type)},
341
+ ID: {self.device_id},
342
+ Software: {self.software_version},
343
+ Hardware: {self.hardware_version},
344
+ Connect Time: {self.connect_time},
345
+ Current Time: {self.current_time},
346
+ Voltage: {self.voltage}mV,
347
+ Battery Remain: {self.battery_remain}%,
348
+ Battery Total: {self.battery_total}%
349
+ '''
350
+
351
+ def __eq__(self, other):
352
+ return self.device_name == other.device_name and self.device_type == other.device_type and self.device_id == other.device_id
353
+
354
+ def __hash__(self):
355
+ return hash((self.device_name, self.device_type, self.device_id))
356
+
42
357
 
43
- DeviceFactory.register(C256RS.device_type, C256RS)
44
- DeviceFactory.register(C256RS.device_type_001, C256RS)
358
+ DeviceFactory.register(C256RS.device_type, C256RS)