qlsdk2 0.3.0a3__py3-none-any.whl → 0.4.0a2__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/entity.py ADDED
@@ -0,0 +1,551 @@
1
+ from multiprocessing import Queue, Process
2
+ from typing import Any, Dict, Literal
3
+ # from rsc.command import *
4
+ from qlsdk.core import *
5
+ from qlsdk.core.device import BaseDevice
6
+ from threading import Thread
7
+ from loguru import logger
8
+ from time import time_ns
9
+
10
+ class QLDevice(BaseDevice):
11
+ def __init__(self, socket):
12
+ self.socket = socket
13
+
14
+ # 设备信息
15
+ self.device_id = None
16
+ self.device_name = None
17
+ self.device_type = None
18
+ self.software_version = None
19
+ self.hardware_version = None
20
+ self.connect_time = None
21
+ self.current_time = None
22
+ # mV
23
+ self.voltage = None
24
+ # %
25
+ self.battery_remain = None
26
+ # %
27
+ self.battery_total = None
28
+
29
+ # 可设置参数
30
+ # 采集:采样量程、采样率、采样通道
31
+ # 刺激:刺激电流、刺激频率、刺激时间、刺激通道
32
+ # 采样量程(mV):188、375、563、750、1125、2250、4500
33
+ self._sample_range:Literal[188, 375, 563, 750, 1125, 2250, 4500] = 188
34
+ # 采样率(Hz):250、500、1000、2000、4000、8000、16000、32000
35
+ self._sample_rate:Literal[250, 500, 1000, 2000, 4000, 8000, 16000, 32000] = 500
36
+ self._acq_channels = None
37
+ self._acq_param = {
38
+ "sample_range": 188,
39
+ "sample_rate": 500,
40
+ "channels": [],
41
+ }
42
+
43
+ self._stim_param = {
44
+ "stim_type": 0, # 刺激类型:0-所有通道参数相同, 1: 通道参数不同
45
+ "channels": [],
46
+ "param": [{
47
+ "channel_id": 0, #通道号 从0开始 -- 必填
48
+ "waveform": 3, #波形类型:0-直流,1-交流 2-方波 3-脉冲 -- 必填
49
+ "current": 1, #电流强度(mA) -- 必填
50
+ "duration": 30, #平稳阶段持续时间(s) -- 必填
51
+ "ramp_up": 5, #上升时间(s) 默认0
52
+ "ramp_down": 5, #下降时间(s) 默认0
53
+ "frequency": 500, #频率(Hz) -- 非直流必填
54
+ "phase_position": 0, #相位 -- 默认0
55
+ "duration_delay": "0", #延迟启动时间(s) -- 默认0
56
+ "pulse_width": 0, #脉冲宽度(us) -- 仅脉冲类型电流有效, 默认100us
57
+ },
58
+ {
59
+ "channel_id": 1, #通道号 从0开始 -- 必填
60
+ "waveform": 3, #波形类型:0-直流,1-交流 2-方波 3-脉冲 -- 必填
61
+ "current": 1, #电流强度(mA) -- 必填
62
+ "duration": 30, #平稳阶段持续时间(s) -- 必填
63
+ "ramp_up": 5, #上升时间(s) 默认0
64
+ "ramp_down": 5, #下降时间(s) 默认0
65
+ "frequency": 500, #频率(Hz) -- 非直流必填
66
+ "phase_position": 0, #相位 -- 默认0
67
+ "duration_delay": "0", #延迟启动时间(s) -- 默认0
68
+ "pulse_width": 0, #脉冲宽度(us) -- 仅脉冲类型电流有效, 默认100us
69
+ }
70
+ ]
71
+ }
72
+
73
+ self.stim_paradigm = None
74
+
75
+ signal_info = {
76
+ "param" : None,
77
+ "start_time" : None,
78
+ "finished_time" : None,
79
+ "packet_total" : None,
80
+ "last_packet_time" : None,
81
+ "state" : 0
82
+ }
83
+ stim_info = {
84
+
85
+ }
86
+ Impedance_info = {
87
+
88
+ }
89
+ # 信号采集状态
90
+ # 信号数据包总数(一个信号采集周期内)
91
+ # 信号采集参数
92
+ # 电刺激状态
93
+ # 电刺激开始时间(最近一次)
94
+ # 电刺激结束时间(最近一次)
95
+ # 电刺激参数
96
+ # 启动数据解析线程
97
+ # 数据存储状态
98
+ # 存储目录
99
+
100
+ #
101
+ self.__signal_consumer: Dict[str, Queue[Any]]={}
102
+ self.__impedance_consumer: Dict[str, Queue[Any]]={}
103
+
104
+
105
+ self._parser = DeviceParser(self)
106
+ self._parser.start()
107
+
108
+ # 启动数据接收线程
109
+ self._accept = Thread(target=self.accept)
110
+ self._accept.daemon = True
111
+ self._accept.start()
112
+
113
+ @property
114
+ def acq_channels(self):
115
+ if self._acq_channels is None:
116
+ self._acq_channels = [i for i in range(1, 63)]
117
+ return self._acq_channels
118
+ @property
119
+ def sample_range(self):
120
+ return self._sample_range if self._sample_range else 188
121
+ @property
122
+ def sample_rate(self):
123
+ return self._sample_rate if self._sample_rate else 500
124
+ @property
125
+ def resolution(self):
126
+ return 24
127
+
128
+ @property
129
+ def signal_consumers(self):
130
+ return self.__signal_consumer
131
+
132
+ @property
133
+ def impedance_consumers(self):
134
+ return self.__impedance_consumer
135
+
136
+ def accept(self):
137
+ while True:
138
+ data = self.socket.recv(4096*1024)
139
+ # logger.debug(f"QLDevice接收到数据: {data.hex()}")
140
+ if not data:
141
+ logger.warning(f"设备{self.device_name}连接结束")
142
+ break
143
+
144
+ self._parser.append(data)
145
+
146
+
147
+ def send(self, data):
148
+ self.socket.sendall(data)
149
+
150
+ def add_param(self, key:str, val:str):
151
+ pass
152
+
153
+ # 设置刺激参数
154
+ def set_stim_param(self, param):
155
+ self.stim_paradigm = param
156
+
157
+ # 设置采集参数
158
+ def set_acq_param(self, channels, sample_rate = 500, sample_range = 188):
159
+ self._acq_param["channels"] = channels
160
+ self._acq_param["sample_rate"] = sample_rate
161
+ self._acq_param["sample_range"] = sample_range
162
+ self._acq_channels = channels
163
+ self._sample_rate = sample_rate
164
+ self._sample_range = sample_range
165
+
166
+ # 通用配置
167
+ def set_config(self, key:str, val: str):
168
+ pass
169
+
170
+ def set_impedance_param(self):
171
+ channels = bytes.fromhex("FFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000")
172
+ sample_rate = 1000
173
+ sample_len = 300
174
+ resolution = self.resolution
175
+
176
+ def start_impedance(self):
177
+ logger.info("启动阻抗测量")
178
+ msg = StartImpedanceCommand.build(self).pack()
179
+ # msg = bytes.fromhex("5aa50239320013243f0000001104ffffffffffffffff000000000000000000000000000000000000000000000000e8030000fa00000010000164000000a11e5aa50239320013243a00000012040000000000000000000000000000000000000000000000000000000000000000000001000000000000000325")
180
+ logger.debug(f"start_impedance message is {msg.hex()}")
181
+ self.socket.sendall(msg)
182
+
183
+ def stop_impedance(self):
184
+ logger.info("停止阻抗测量")
185
+ msg = StopImpedanceCommand.build(self).pack()
186
+ # msg = bytes.fromhex("5aa5023932001324100000001304e9df")
187
+ logger.debug(f"stop_impedance message is {msg.hex()}")
188
+ self.socket.sendall(msg)
189
+
190
+ def start_stimulation(self):
191
+ if self.stim_paradigm is None:
192
+ logger.warning("刺激参数未设置,请先设置刺激参数")
193
+ return
194
+ logger.info("启动电刺激")
195
+ # conf = SetStimulationParamCommand.build(self).pack()
196
+ msg = StartStimulationCommand.build(self).pack()
197
+ logger.debug(f"start_stimulation message is {msg.hex()}")
198
+ self.socket.sendall(msg)
199
+
200
+ def stop_stimulation(self):
201
+ logger.info("停止电刺激")
202
+ msg = StopStimulationCommand.pack()
203
+ logger.debug(f"stop_stimulation message is {msg.hex()}")
204
+ self.socket.sendall(msg)
205
+
206
+ # 启动采集
207
+ def start_acquisition(self):
208
+ logger.info("启动信号采集")
209
+ # 设置数据采集参数
210
+ param_bytes = SetAcquisitionParamCommand.build(self).pack()
211
+ # 启动数据采集
212
+ start_bytes = StartAcquisitionCommand.build(self).pack()
213
+ msg = param_bytes + start_bytes
214
+ logger.debug(f"start_acquisition message is {msg.hex()}")
215
+ self.socket.sendall(msg)
216
+
217
+ # 停止采集
218
+ def stop_acquisition(self):
219
+ logger.info("停止信号采集")
220
+ msg = StopAcquisitionCommand.build(self).pack()
221
+ logger.debug(f"stop_acquisition message is {msg}")
222
+ self.socket.sendall(msg)
223
+
224
+ # 订阅实时数据
225
+ def subscribe(self, topic:str=None, q : Queue=None, type : Literal["signal","impedance"]="signal"):
226
+
227
+ # 数据队列
228
+ if q is None:
229
+ q = Queue()
230
+
231
+ # 队列名称
232
+ if topic is None:
233
+ topic = f"{type}_{time_ns()}"
234
+
235
+ # 订阅生理电信号数据
236
+ if type == "signal":
237
+ # topic唯一,用来区分不同的订阅队列(下同)
238
+ if topic in list(self.__signal_consumer.keys()):
239
+ logger.warning(f"exists {type} subscribe of {topic}")
240
+ else:
241
+ self.__signal_consumer[topic] = q
242
+
243
+ # 订阅阻抗数据
244
+ if type == "impedance":
245
+ if topic in list(self.__signal_consumer.keys()):
246
+ logger.warning(f"exists {type} subscribe of {topic}")
247
+ else:
248
+ self.__impedance_consumer[topic] = q
249
+
250
+ return topic, q
251
+
252
+ def __str__(self):
253
+ return f'''
254
+ Device:
255
+ Name: {self.device_name},
256
+ Type: {hex(self.device_type) if self.device_type else None},
257
+ ID: {hex(self.device_id) if self.device_id else None},
258
+ Software: {self.software_version},
259
+ Hardware: {self.hardware_version},
260
+ Connect Time: {self.connect_time},
261
+ Current Time: {self.current_time},
262
+ Voltage: {str(self.voltage) + "mV" if self.voltage else None},
263
+ Battery Remain: {str(self.battery_remain)+ "%" if self.battery_remain else None},
264
+ Battery Total: {str(self.battery_total) + "%" if self.battery_total else None}
265
+ '''
266
+
267
+ def __repr__(self):
268
+ return f'''
269
+ Device:
270
+ Name: {self.device_name},
271
+ Type: {hex(self.device_type)},
272
+ ID: {hex(self.device_id)},
273
+ Software: {self.software_version},
274
+ Hardware: {self.hardware_version},
275
+ Connect Time: {self.connect_time},
276
+ Current Time: {self.current_time},
277
+ Voltage: {self.voltage}mV,
278
+ Battery Remain: {self.battery_remain}%,
279
+ Battery Total: {self.battery_total}%
280
+ '''
281
+
282
+ def __eq__(self, other):
283
+ return self.device_name == other.device_name and self.device_type == other.device_type and self.device_id == other.device_id
284
+
285
+ def __hash__(self):
286
+ return hash((self.device_name, self.device_type, self.device_id))
287
+
288
+ class RSC64RS(QLDevice):
289
+ def __init__(self, socket):
290
+ super().__init__(socket)
291
+
292
+
293
+ class LJS1(QLDevice):
294
+ def __init__(self, socket):
295
+ super().__init__(socket)
296
+
297
+
298
+ class RSC64R(QLDevice):
299
+ def __init__(self, socket):
300
+ super().__init__(socket)
301
+
302
+
303
+ class ARSKindling(QLDevice):
304
+ def __init__(self, socket):
305
+ super().__init__(socket)
306
+
307
+
308
+
309
+
310
+
311
+ class DeviceParser(object):
312
+ def __init__(self, device : QLDevice):
313
+ # 待解析的数据来源于该设备
314
+ self.device = device
315
+ self.running = False
316
+
317
+ self.cache = b''
318
+
319
+ def append(self, buffer):
320
+ self.cache += buffer
321
+ logger.debug(f"append cache len: {len(self.cache)}")
322
+
323
+ # if not self.running:
324
+ # self.start()
325
+
326
+ def __parser__(self):
327
+ logger.info("数据解析开始")
328
+ while self.running:
329
+ # logger.debug(f" cache len: {len(self.cache)}")
330
+ if len(self.cache) < 14:
331
+ continue
332
+ if self.cache[0] != 0x5A or self.cache[1] != 0xA5:
333
+ self.cache = self.cache[1:]
334
+ continue
335
+ pkg_len = int.from_bytes(self.cache[8:12], 'little')
336
+ logger.debug(f" cache len: {len(self.cache)}, pkg_len len: {len(self.cache)}")
337
+ # 一次取整包数据
338
+ if len(self.cache) < pkg_len:
339
+ continue
340
+ pkg = self.cache[:pkg_len]
341
+ self.cache = self.cache[pkg_len:]
342
+ self.unpack(pkg)
343
+
344
+ def unpack(self, packet):
345
+ TCPMessage.parse(packet, self.device)
346
+ # logger.debug(self.device)
347
+ # logger.debug(f'packet len: {len(packet)}, {packet.hex()}')
348
+
349
+ def start(self):
350
+ self.running = True
351
+ parser = Thread(target=self.__parser__,)
352
+ parser.daemon = True
353
+ parser.start()
354
+
355
+
356
+
357
+ class TCPMessage(object):
358
+ # 消息头
359
+ HEADER_PREFIX = b'\x5A\xA5'
360
+ # 消息头总长度 2(prefix) +1(pkgType) +1(deviceType) +4(deviceId) +4(len) +2(cmd)
361
+ HEADER_LEN = 14
362
+ # 消息指令码位置
363
+ CMD_POS = 12
364
+
365
+ @staticmethod
366
+ def parse(data: bytes, device : QLDevice) -> 'DeviceCommand':
367
+ # 数据包校验
368
+ TCPMessage._validate_packet(data)
369
+ # 提取指令码
370
+ cmd_code = int.from_bytes(data[TCPMessage.CMD_POS:TCPMessage.CMD_POS+2], 'little')
371
+ logger.debug(f"收到指令:{hex(cmd_code)}")
372
+ cmd_class = CommandFactory.create_command(cmd_code)
373
+ logger.debug(f"Command class: {cmd_class}")
374
+ instance = cmd_class(device)
375
+ instance.parse_body(data[TCPMessage.HEADER_LEN:-2])
376
+ return instance
377
+
378
+ @staticmethod
379
+ def _validate_packet(data: bytes):
380
+ """Perform full packet validation"""
381
+ if len(data) < TCPMessage.HEADER_LEN + 2: # Header + min body + checksum
382
+ raise ValueError("Packet too short")
383
+
384
+ if data[0:2] != TCPMessage.HEADER_PREFIX:
385
+ raise ValueError("Invalid header prefix")
386
+
387
+ expected_len = int.from_bytes(data[8:12], 'little')
388
+ if len(data) != expected_len:
389
+ raise ValueError(f"Length mismatch: {len(data)} vs {expected_len}")
390
+
391
+ logger.debug(f"checksum: {int.from_bytes(data[-2:], 'little')}")
392
+ checksum = crc16(data[:-2])
393
+ logger.debug(f"checksum recv: {checksum}")
394
+
395
+
396
+
397
+ class DataPacket(object):
398
+ def __init__(self, device: QLDevice):
399
+ self.device = device
400
+ self.header = None
401
+ self.data = None
402
+
403
+ def parse_body(self, body: bytes):
404
+ raise NotImplementedError("Subclasses should implement this method")
405
+
406
+
407
+
408
+ class C64Channel(Enum):
409
+ CH0 = 0
410
+ CH1 = 1
411
+ CH2 = 2
412
+ CH3 = 3
413
+ CH4 = 4
414
+ CH5 = 5
415
+ CH6 = 6
416
+ CH7 = 7
417
+ CH8 = 8
418
+ CH9 = 9
419
+ CH10 = 10
420
+ CH11 = 11
421
+ CH12 = 12
422
+ CH13 = 13
423
+ CH14 = 14
424
+ CH15 = 15
425
+
426
+ class WaveForm(Enum):
427
+ DC = 0
428
+ SQUARE = 1
429
+ AC = 2
430
+ CUSTOM = 3
431
+ PULSE = 4
432
+
433
+ # # 刺激通道
434
+ # class StimulationChannel(object):
435
+ # def __init__(self, channel_id: int, waveform: int, current: float, duration: float, ramp_up: float = None, ramp_down: float = None,
436
+ # frequency: float = None, phase_position: int = None, duration_delay: float = None, pulse_width: int = None, pulse_width_rate: int = 1):
437
+ # self.channel_id = channel_id
438
+ # self.waveform = waveform
439
+ # self.current_max = current
440
+ # self.current_min = current
441
+ # self.duration = duration
442
+ # self.ramp_up = ramp_up
443
+ # self.ramp_down = ramp_down
444
+ # self.frequency = frequency
445
+ # self.phase_position = phase_position
446
+ # self.duration_delay = duration_delay
447
+ # self.pulse_width = pulse_width
448
+ # self.delay_time = 0
449
+ # self.pulse_interval = 0
450
+ # self.with_group_repeats = 1
451
+ # self.pulse_width_rate = 1065353216
452
+ # self.pulse_time_f = 0
453
+ # self.pulse_time_out = 0
454
+ # self.pulse_time_idle = 0
455
+
456
+ # def to_bytes(self):
457
+ # # Convert the object to bytes for transmission
458
+ # result = self.channel_id.to_bytes(1, 'little')
459
+ # wave_form = WaveForm.SQUARE.value if self.waveform == WaveForm.PULSE.value else self.waveform
460
+ # result += wave_form.to_bytes(1, 'little')
461
+ # result += int(self.current_max * 1000 * 1000).to_bytes(4, 'little')
462
+ # # result += int(self.current_min * 1000).to_bytes(2, 'little')
463
+ # result += int(self.frequency).to_bytes(2, 'little')
464
+ # result += int(self.pulse_width).to_bytes(2, 'little')
465
+ # result += int(self.pulse_width_rate).to_bytes(4, 'little')
466
+
467
+ # result += int(self.pulse_interval).to_bytes(2, 'little')
468
+ # result += int(self.with_group_repeats).to_bytes(2, 'little')
469
+ # result += int(self.pulse_time_f).to_bytes(4, 'little')
470
+ # result += int(self.pulse_time_out).to_bytes(4, 'little')
471
+ # result += int(self.pulse_time_idle).to_bytes(4, 'little')
472
+
473
+ # result += int(self.delay_time).to_bytes(4, 'little')
474
+ # result += int(self.ramp_up * 1000).to_bytes(4, 'little')
475
+ # result += int((self.duration + self.ramp_up) * 1000).to_bytes(4, 'little')
476
+ # result += int(self.ramp_down * 1000).to_bytes(4, 'little')
477
+
478
+ # return result
479
+
480
+ # def to_json(self):
481
+ # return {
482
+ # "channel_id": self.channel_id,
483
+ # "waveform": self.waveform,
484
+ # "current_max": self.current_max,
485
+ # "current_min": self.current_min,
486
+ # "duration": self.duration,
487
+ # "ramp_up": self.ramp_up,
488
+ # "ramp_down": self.ramp_down,
489
+ # "frequency": self.frequency,
490
+ # "phase_position": self.phase_position,
491
+ # "duration_delay": self.duration_delay,
492
+ # "pulse_width": self.pulse_width,
493
+ # "delay_time": self.delay_time,
494
+ # "pulse_interval": self.pulse_interval,
495
+ # "with_group_repeats": self.with_group_repeats
496
+ # }
497
+
498
+ # # 刺激范式
499
+ # class StimulationParadigm(object):
500
+ # def __init__(self):
501
+ # self.channels = None
502
+ # self.duration = None
503
+ # self.interval_time = 0
504
+ # self.characteristic = 0
505
+ # self.mode = 0
506
+ # self.repeats = 0
507
+
508
+ # def add_channel(self, channel: StimulationChannel, update=False):
509
+ # if self.channels is None:
510
+ # self.channels = {}
511
+ # channel_id = channel.channel_id + 1
512
+ # if channel_id in self.channels.keys():
513
+ # logger.warning(f"Channel {channel_id} already exists")
514
+ # if update:
515
+ # self.channels[channel_id] = channel
516
+ # else:
517
+ # self.channels[channel_id] = channel
518
+
519
+ # # 计算刺激时间
520
+ # duration = channel.duration + channel.ramp_up + channel.ramp_down
521
+ # if self.duration is None or duration > self.duration:
522
+ # self.duration = duration
523
+
524
+
525
+ # def to_bytes(self):
526
+ # result = to_bytes(list(self.channels.keys()), 64)
527
+ # result += int(self.duration * 1000).to_bytes(4, 'little')
528
+ # result += int(self.interval_time).to_bytes(4, 'little')
529
+ # result += int(self.characteristic).to_bytes(4, 'little')
530
+ # result += int(self.mode).to_bytes(1, 'little')
531
+ # result += int(self.repeats).to_bytes(4, 'little')
532
+ # for channel in self.channels.values():
533
+ # result += channel.to_bytes()
534
+ # return result
535
+
536
+ # def to_json(self):
537
+ # # Convert the object to JSON for transmission
538
+ # return {
539
+ # "channels": list(self.channels.keys()),
540
+ # "duration": self.duration,
541
+ # "interval_time": self.interval_time,
542
+ # "characteristic": self.characteristic,
543
+ # "mode": self.mode,
544
+ # "repeats": self.repeats,
545
+ # "stim": [channel.to_json() for channel in self.channels.values()]
546
+ # }
547
+
548
+ # @staticmethod
549
+ # def from_json(param: Dict[str, Any]):
550
+ # pass
551
+