qlsdk2 0.5.1.1__py3-none-any.whl → 0.6.0__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.
qlsdk/rsc/device/c64s1.py CHANGED
@@ -1,145 +1,15 @@
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
-
7
1
  from loguru import logger
8
2
  from qlsdk.persist import RscEDFHandler
9
- from qlsdk.rsc.interface import IDevice, IParser
3
+ from qlsdk.rsc.interface import IDevice
10
4
  from qlsdk.rsc.command import *
11
- from qlsdk.rsc.parser.base import TcpMessageParser
12
5
  from qlsdk.rsc.device.base import QLBaseDevice
13
6
 
14
7
  class C64S1(QLBaseDevice):
15
8
 
16
- device_type = 0x40 # C64RS设备类型标识符
9
+ device_type = 0x40 # C64RS-S1设备类型标识符
17
10
 
18
11
  def __init__(self, socket):
19
12
  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 = TcpMessageParser(self)
129
- self._parser.start()
130
-
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
13
 
144
14
  @classmethod
145
15
  def from_parent(cls, parent:IDevice) -> IDevice:
@@ -155,211 +25,5 @@ class C64S1(QLBaseDevice):
155
25
  self._edf_handler.set_device_no(self.device_no)
156
26
  self._edf_handler.set_storage_path(self._storage_path)
157
27
  self._edf_handler.set_file_prefix(self._file_prefix if self._file_prefix else 'C64S1')
158
-
159
- @property
160
- def edf_handler(self):
161
- if not self.storage_enable:
162
- return None
163
-
164
- if self._edf_handler is None:
165
- self.init_edf_handler()
166
-
167
- return self._edf_handler
168
-
169
- @property
170
- def acq_channels(self):
171
- if self._acq_channels is None:
172
- self._acq_channels = [i for i in range(1, 63)]
173
- return self._acq_channels
174
- @property
175
- def sample_range(self):
176
- return self._sample_range if self._sample_range else 188
177
- @property
178
- def sample_rate(self):
179
- return self._sample_rate if self._sample_rate else 500
180
- @property
181
- def resolution(self):
182
- return 24
183
-
184
- @property
185
- def signal_consumers(self):
186
- return self.__signal_consumer
187
-
188
- @property
189
- def impedance_consumers(self):
190
- return self.__impedance_consumer
191
-
192
- # 设置记录文件路径
193
- def set_storage_path(self, path):
194
- self._storage_path = path
195
-
196
- # 设置记录文件名称前缀
197
- def set_file_prefix(self, prefix):
198
- self._file_prefix = prefix
199
-
200
- # 接收socket消息
201
- def accept(self):
202
- while True:
203
- # 缓冲去4M
204
- data = self.socket.recv(4096*1024)
205
- if not data:
206
- logger.warning(f"设备{self.device_name}连接结束")
207
- break
208
-
209
- self._parser.append(data)
210
-
211
-
212
- # socket发送数据
213
- def send(self, data):
214
- self.socket.sendall(data)
215
-
216
- # 设置刺激参数
217
- def set_stim_param(self, param):
218
- self.stim_paradigm = param
219
-
220
- # 设置采集参数
221
- def set_acq_param(self, channels, sample_rate = 500, sample_range = 188):
222
- self._acq_param["channels"] = channels
223
- self._acq_param["sample_rate"] = sample_rate
224
- self._acq_param["sample_range"] = sample_range
225
- self._acq_channels = channels
226
- self._sample_rate = sample_rate
227
- self._sample_range = sample_range
228
-
229
- # 通用配置-TODO
230
- def set_config(self, key:str, val: str):
231
- pass
232
-
233
- def start_impedance(self):
234
- logger.info("启动阻抗测量")
235
- msg = StartImpedanceCommand.build(self).pack()
236
- logger.debug(f"start_impedance message is {msg.hex()}")
237
- self.socket.sendall(msg)
238
-
239
- def stop_impedance(self):
240
- logger.info("停止阻抗测量")
241
- msg = StopImpedanceCommand.build(self).pack()
242
- logger.debug(f"stop_impedance message is {msg.hex()}")
243
- self.socket.sendall(msg)
244
-
245
- def start_stimulation(self):
246
- if self.stim_paradigm is None:
247
- logger.warning("刺激参数未设置,请先设置刺激参数")
248
- return
249
- logger.info("启动电刺激")
250
- msg = StartStimulationCommand.build(self).pack()
251
- logger.debug(f"start_stimulation message is {msg.hex()}")
252
- self.socket.sendall(msg)
253
- t = Thread(target=self._stop_stimulation_trigger, args=(self.stim_paradigm.duration,))
254
- t.start()
255
-
256
- def _stop_stimulation_trigger(self, duration):
257
- delay = duration
258
- while delay > 0:
259
- sleep(1)
260
- delay -= 1
261
- logger.info(f"_stop_stimulation_trigger duration: {duration}")
262
- if self._edf_handler:
263
- self._edf_handler.trigger("stimulation should be stopped")
264
- else:
265
- logger.warning("stop stim trigger fail. no edf writer alive")
266
-
267
- def stop_stimulation(self):
268
- logger.info("停止电刺激")
269
- msg = StopStimulationCommand.pack()
270
- logger.debug(f"stop_stimulation message is {msg.hex()}")
271
- self.socket.sendall(msg)
272
-
273
- # 启动采集
274
- def start_acquisition(self, recording = True):
275
- logger.info("启动信号采集")
276
- self._recording = recording
277
- # 设置数据采集参数
278
- param_bytes = SetAcquisitionParamCommand.build(self).pack()
279
- # 启动数据采集
280
- start_bytes = StartAcquisitionCommand.build(self).pack()
281
- msg = param_bytes + start_bytes
282
- logger.debug(f"start_acquisition message is {msg.hex()}")
283
- self.socket.sendall(msg)
284
-
285
- # 停止采集
286
- def stop_acquisition(self):
287
- logger.info("停止信号采集")
288
- msg = StopAcquisitionCommand.build(self).pack()
289
- logger.debug(f"stop_acquisition message is {msg.hex()}")
290
- self.socket.sendall(msg)
291
- if self._edf_handler:
292
- # 发送结束标识
293
- self.edf_handler.write(None)
294
-
295
- # 订阅实时数据
296
- def subscribe(self, topic:str=None, q : Queue=None, type : Literal["signal","impedance"]="signal"):
297
-
298
- # 数据队列
299
- if q is None:
300
- q = Queue(maxsize=1000)
301
-
302
- # 队列名称
303
- if topic is None:
304
- topic = f"{type}_{time_ns()}"
305
-
306
- # 订阅生理电信号数据
307
- if type == "signal":
308
- # topic唯一,用来区分不同的订阅队列(下同)
309
- if topic in list(self.__signal_consumer.keys()):
310
- logger.warning(f"exists {type} subscribe of {topic}")
311
- else:
312
- self.__signal_consumer[topic] = q
313
-
314
- # 订阅阻抗数据
315
- if type == "impedance":
316
- if topic in list(self.__signal_consumer.keys()):
317
- logger.warning(f"exists {type} subscribe of {topic}")
318
- else:
319
- self.__impedance_consumer[topic] = q
320
-
321
- return topic, q
322
-
323
- def trigger(self, desc):
324
- if self._edf_handler:
325
- self.edf_handler.trigger(desc)
326
- else:
327
- logger.warning("no edf handler, no place to recording trigger")
328
-
329
- def __str__(self):
330
- return f'''
331
- Device:
332
- Name: {self.device_name},
333
- Type: {hex(self.device_type) if self.device_type else None},
334
- ID: {self.device_id if self.device_id else None},
335
- Software: {self.software_version},
336
- Hardware: {self.hardware_version},
337
- Connect Time: {self.connect_time},
338
- Current Time: {self.current_time},
339
- Voltage: {str(self.voltage) + "mV" if self.voltage else None},
340
- Battery Remain: {str(self.battery_remain)+ "%" if self.battery_remain else None},
341
- Battery Total: {str(self.battery_total) + "%" if self.battery_total else None}
342
- '''
343
-
344
- def __repr__(self):
345
- return f'''
346
- Device:
347
- Name: {self.device_name},
348
- Type: {hex(self.device_type)},
349
- ID: {self.device_id},
350
- Software: {self.software_version},
351
- Hardware: {self.hardware_version},
352
- Connect Time: {self.connect_time},
353
- Current Time: {self.current_time},
354
- Voltage: {self.voltage}mV,
355
- Battery Remain: {self.battery_remain}%,
356
- Battery Total: {self.battery_total}%
357
- '''
358
-
359
- def __eq__(self, other):
360
- return self.device_name == other.device_name and self.device_type == other.device_type and self.device_id == other.device_id
361
-
362
- def __hash__(self):
363
- return hash((self.device_name, self.device_type, self.device_id))
364
-
365
-
28
+ logger.debug(f"EDF Handler initialized")
29
+
@@ -30,5 +30,6 @@ DeviceFactory.register(C64RS.device_type, C64RS)
30
30
  DeviceFactory.register(ARSKindling.device_type, ARSKindling)
31
31
 
32
32
 
33
+
33
34
 
34
35
 
@@ -10,118 +10,76 @@ class IDevice(ABC):
10
10
  pass
11
11
 
12
12
  def set_device_type(self, value: int):
13
- pass
13
+ raise NotImplementedError("Not Supported")
14
14
 
15
15
  def set_storage_path(self, path: str):
16
- pass
16
+ raise NotImplementedError("Not Supported")
17
17
 
18
18
  def set_file_prefix(self, pre: str):
19
- pass
19
+ raise NotImplementedError("Not Supported")
20
20
 
21
21
  def set_acq_param(self, channels, sample_rate = 500, sample_range = 188):
22
- pass
22
+ raise NotImplementedError("Not Supported")
23
23
 
24
24
  @property
25
25
  def device_no(self) -> str:
26
26
  pass
27
+
28
+ def set_impedance_channels(self):
29
+ raise NotImplementedError("Not Supported")
30
+
27
31
 
28
- def produce(self, data, type:Literal['signal', 'impedance']="signal") -> None:
29
- pass
32
+ def read_msg(self, size: int) -> bytes:
33
+ raise NotImplementedError("Not Supported")
34
+
35
+ def produce(self, body: bytes, type:Literal['signal', 'impedance']="signal") -> None:
36
+ raise NotImplementedError("Not Supported")
30
37
 
31
38
  def start_listening(self):
32
- pass
39
+ raise NotImplementedError("Not Supported")
33
40
 
34
41
  def stop_listening(self):
35
- pass
42
+ raise NotImplementedError("Not Supported")
36
43
 
37
44
  def set_device_no(self, value: str):
38
- pass
45
+ raise NotImplementedError("Not Supported")
39
46
 
40
47
  def from_parent(cls, parent) :
41
- pass
42
-
43
- def start_implementation(self) -> None:
44
- pass
45
-
46
- def stop_implementation(self) -> None:
47
- pass
48
+ raise NotImplementedError("Not Supported")
48
49
 
49
50
  def start_acquisition(self) -> None:
50
- pass
51
+ raise NotImplementedError("Not Supported")
51
52
 
52
53
  def stop_acquisition(self) -> None:
53
- pass
54
+ raise NotImplementedError("Not Supported")
54
55
 
55
56
  def subscribe(self, type="signal") -> None:
56
- pass
57
-
57
+ raise NotImplementedError("Not Supported")
58
58
  def unsubscribe(self, topic) -> None:
59
- pass
59
+ raise NotImplementedError("Not Supported")
60
60
 
61
61
  def start_stimulation(self, type="signal", duration=0) -> None:
62
- pass
62
+ raise NotImplementedError("Not Supported")
63
63
 
64
64
  def stop_stimulation(self) -> None:
65
- pass
65
+ raise NotImplementedError("Not Supported")
66
+ def disconnect(self) -> None:
67
+ raise NotImplementedError("Not Supported")
66
68
 
67
- def gen_set_acquirement_param(self) -> bytes:
69
+ def set_stim_param(self, param):
68
70
  pass
69
71
 
72
+ def trigger(self, desc):
73
+ pass
70
74
 
75
+ def enable_storage(self, enable: bool = True):
76
+ pass
71
77
 
72
- class RscDevice(IDevice):
73
- def __init__(self, socket):
74
- super().__init__(socket)
75
-
76
- def start_implementation(self):
77
- """
78
- Start the device implementation
79
- """
80
- raise NotImplementedError("This method should be overridden by subclasses")
81
-
82
- def stop_implementation(self):
83
- """
84
- Stop the device implementation
85
- """
86
- raise NotImplementedError("This method should be overridden by subclasses")
87
-
88
- def start_acquisition(self):
89
- """
90
- Start data acquisition
91
- """
92
- raise NotImplementedError("This method should be overridden by subclasses")
93
-
94
- def stop_acquisition(self):
95
- """
96
- Stop data acquisition
97
- """
98
- raise NotImplementedError("This method should be overridden by subclasses")
99
-
100
- def subscribe(self, type="signal"):
101
- """
102
- Subscribe to data of a specific type (default is "signal")
103
- """
104
- raise NotImplementedError("This method should be overridden by subclasses")
105
-
106
- def unsubscribe(self, topic):
107
- """
108
- Unsubscribe from a specific topic
109
- """
110
- raise NotImplementedError("This method should be overridden by subclasses")
111
-
112
- def start_stimulation(self, type="signal", duration=0):
113
- """
114
- Start stimulation of a specific type (default is "signal") for a given duration
115
- """
116
- raise NotImplementedError("This method should be overridden by subclasses")
117
-
118
- def stop_stimulation(self):
119
- """
120
- Stop stimulation
121
- """
122
- raise NotImplementedError("This method should be overridden by subclasses")
123
-
124
- class ProxyDevice(IDevice):
125
- def __init__(self, socket, proxy_socket):
126
- super().__init__(socket)
127
- self.proxy_socket = proxy_socket
78
+ def set_impedance_channel(self):
79
+ raise NotImplementedError("Not Supported")
80
+
81
+ def start_impedance(self):
82
+ raise NotImplementedError("Not Supported")
83
+
84
+ def stop_impedance(self):
85
+ raise NotImplementedError("Not Supported")
@@ -9,4 +9,10 @@ class IParser(ABC):
9
9
  pass
10
10
 
11
11
  def set_device(self, device):
12
+ pass
13
+
14
+ def start(self):
15
+ pass
16
+
17
+ def stop(self):
12
18
  pass
@@ -90,11 +90,11 @@ class DeviceContainer(object):
90
90
  device.start_listening()
91
91
  # GET_DEVICE_INFO
92
92
  msg = GetDeviceInfoCommand.build(device).pack()
93
- logger.trace(f"发送获取设备信息命令: {msg.hex()}")
93
+ logger.debug(f"发送获取设备信息命令: {msg.hex()}")
94
94
  device.send(msg)
95
95
  # 添加设备
96
96
  while True:
97
- if device.device_name:
97
+ if device.device_no:
98
98
  real_device = DeviceFactory.create_device(device)
99
99
  device.stop_listening()
100
100
  real_device.start_listening()
@@ -117,6 +117,14 @@ class DeviceContainer(object):
117
117
  # 标记设备为已连接
118
118
  self._broadcaster.mark_device_as_connected(device.device_no)
119
119
 
120
+ def remove_device(self, device_no:str=None):
121
+ if device_no is None:
122
+ return
123
+
124
+ if device_no in self._devices:
125
+ del self._devices[device_no]
126
+ logger.info(f"从设备列表移除设备[{device_no}],已连接设备数量:{len(self._devices)}")
127
+
120
128
  def get_device(self, device_no:str=None)->IDevice:
121
129
  logger.info(f"已连接设备数量:{len(self._devices)}")
122
130
  if len(self._devices) == 0:
@@ -4,6 +4,7 @@ from threading import Thread, Lock
4
4
  from loguru import logger
5
5
 
6
6
  from qlsdk.core.message import UDPMessage
7
+ from qlsdk.core.local import get_ips
7
8
 
8
9
  '''
9
10
  广播器类,用于发送和接收设备广播消息
@@ -55,6 +56,7 @@ class UdpBroadcaster:
55
56
  def broadcast_devices(self):
56
57
 
57
58
  while self.running:
59
+ ips = get_ips()
58
60
  with self.lock:
59
61
  for device_id in self.devices_to_broadcast:
60
62
  message = UDPMessage.search(device_id)