qlsdk2 0.2.0a1__py3-none-any.whl → 0.3.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.
qlsdk/__init__.py CHANGED
@@ -1,9 +1,12 @@
1
1
  # __version__ = "0.1.1"
2
2
 
3
3
  # 暴露公共接口
4
- from .ar4m import AR4M, AR4, AR4Packet
4
+ from .ar4m import AR4M
5
+ from .ar4 import AR4
6
+ from .x8 import X8
7
+ from .x8m import X8M
5
8
 
6
- __all__ = ['AR4M', 'AR4', 'AR4Packet']
9
+ __all__ = ['AR4M', 'AR4', 'AR4Packet', 'X8']
7
10
 
8
11
  # from importlib import import_module
9
12
  # from pathlib import Path
qlsdk/ar4/__init__.py ADDED
@@ -0,0 +1,128 @@
1
+ from multiprocessing import Queue
2
+ from typing import Literal
3
+ from loguru import logger
4
+ from qlsdk.sdk import LMDevice, LMPacket
5
+ import numpy as np
6
+ from qlsdk.persist import EdfHandler
7
+ import time
8
+
9
+ # 设备对象
10
+ class AR4(LMDevice):
11
+ def __init__(self, box_mac:str, is_persist:bool=True, storage_path:str=None):
12
+ # 是否持久化-保存为文件
13
+ self._is_persist = is_persist
14
+ self._storage_path = storage_path
15
+ self._edf_handler = None
16
+
17
+ self._recording = False
18
+ self._record_start_time = None
19
+
20
+ self._acq_info = {}
21
+ # 订阅者列表,数值为数字信号值
22
+ self._dig_subscriber: dict[str, Queue] = {}
23
+ # 订阅者列表,数值为物理信号值
24
+ self._phy_subscriber: dict[str, Queue] = {}
25
+
26
+ super().__init__(box_mac)
27
+
28
+ def set_storage_path(self, storage_path):
29
+ self._storage_path = storage_path
30
+
31
+ @property
32
+ def device_type(self):
33
+ return "AR4"
34
+
35
+
36
+ def eeg_accept(self, packet):
37
+ if len(self._dig_subscriber) > 0 or len(self._phy_subscriber) > 0:
38
+ for consumer in self._dig_subscriber.values():
39
+ consumer.put(packet)
40
+
41
+ if len(self._phy_subscriber) > 0:
42
+ logger.info(f"dig data eeg: {packet.eeg}")
43
+ logger.info(f"dig data acc: {packet.acc}")
44
+ packet.eeg = self.eeg2phy(np.array(packet.eeg))
45
+ packet.acc = self.acc2phy(np.array(packet.acc))
46
+ logger.info(f"phy data eeg: {packet.eeg}")
47
+ logger.info(f"phy data acc: {packet.acc}")
48
+ for consumer2 in self._phy_subscriber.values():
49
+ consumer2.put(packet)
50
+
51
+ if self._is_persist:
52
+ if self._edf_handler is None:
53
+ self.start_record()
54
+ self._recording = True
55
+ self._record_start_time = packet.time_stamp
56
+ logger.info(f"开始记录数据: {self.box_mac}")
57
+
58
+ # 处理数据包
59
+ self._edf_handler.append(packet)
60
+
61
+ def start_record(self):
62
+ if self._is_persist:
63
+ if self._edf_handler is None:
64
+ self._edf_handler = EdfHandler(self.sample_frequency, self.eeg_phy_max, self.eeg_phy_min, self.eeg_dig_max, self.eeg_dig_min, storage_path=self._storage_path)
65
+ self._edf_handler.set_device_type(self.device_type)
66
+ self._edf_handler.set_storage_path(self._storage_path)
67
+
68
+ def stop_record(self):
69
+ if self._edf_handler:
70
+ # 等待设备端数据传输完成
71
+ time.sleep(0.5)
72
+ # 添加结束标识
73
+ self._edf_handler.append(None)
74
+ self._edf_handler = None
75
+ self._recording = False
76
+ logger.info(f"停止记录数据: {self.box_mac}")
77
+
78
+ # 订阅推送消息
79
+ def subscribe(self, topic: str = None, q: Queue = Queue(), value_type: Literal['phy', 'dig'] = 'phy') -> tuple[str, Queue]:
80
+ if topic is None:
81
+ topic = f"msg_{self.box_mac}"
82
+
83
+ if value_type == 'dig':
84
+ if topic in list(self._dig_subscriber.keys()):
85
+ logger.warning(f"ar4 {self.box_mac} 订阅主题已存在: {topic}")
86
+ return topic, self._dig_subscriber[topic]
87
+ self._dig_subscriber[topic] = q
88
+ else:
89
+ if topic in list(self._phy_subscriber.keys()):
90
+ logger.warning(f"ar4 {self.box_mac} 订阅主题已存在: {topic}")
91
+ return topic, self._phy_subscriber[topic]
92
+ self._phy_subscriber[topic] = q
93
+
94
+ return topic, q
95
+
96
+ def eeg2phy(self, digtal):
97
+ # 向量化计算(自动支持广播)
98
+ return super().eeg2phy(digtal)
99
+
100
+ def acc2phy(self, digtal):
101
+ return super().eeg2phy(digtal)
102
+
103
+ class X8Packet(LMPacket):
104
+ def __init__(self, data: bytes):
105
+ super().__init__(data)
106
+ self._data = data
107
+ self._head = None
108
+ self._body = None
109
+
110
+ @property
111
+ def head(self):
112
+ return self._head
113
+
114
+ @property
115
+ def body(self):
116
+ return self._body
117
+
118
+ def parse(self):
119
+ # 解析数据包头部和数据体
120
+ if len(self._data) < 4:
121
+ logger.error(f"数据包长度不足: {len(self._data)}")
122
+ return False
123
+
124
+ # 解析头部和数据体
125
+ self._head = self._data[:4]
126
+ self._body = self._data[4:]
127
+
128
+ return True
qlsdk/ar4m/__init__.py CHANGED
@@ -1,50 +1,21 @@
1
- __path__ = __import__("pkgutil").extend_path(__path__, __name__)
2
-
3
- from .ar4sdk import AR4SDK, AR4, Packet, AR4Packet
4
-
5
-
6
- from time import sleep, time
7
- from threading import Lock, Timer
1
+ from qlsdk.sdk import Hub
2
+ from qlsdk.ar4 import AR4
8
3
  from loguru import logger
9
4
 
10
- class AR4M(object):
5
+
6
+ class AR4M(Hub):
11
7
  def __init__(self):
12
- self._lock = Lock()
13
- self._search_timer = None
14
- self._search_running = False
8
+ super().__init__()
15
9
  self._devices: dict[str, AR4] = {}
10
+ self._search_running = False
11
+ self._search_timer = None
16
12
 
17
- @property
18
- def devices(self):
19
- return self._devices
20
- def search(self):
21
- if not self._search_running:
22
- self._search_running = True
23
- self._search()
24
-
25
- def _search(self):
26
- if self._search_running:
27
-
28
- self._search_timer = Timer(2, self._search_ar4)
29
- self._search_timer.daemon = True
30
- self._search_timer.start()
31
-
32
-
33
- def _search_ar4(self):
34
- try:
35
- devices = AR4SDK.enum_devices()
36
- # logger.debug(f"_search_ar4 devices size: {len(devices)}")
37
- for dev in devices:
38
- # logger.debug(f"slot: {dev.slot}, mac: {dev.mac}-{hex(dev.mac)}, hub_name: {dev.hub_name.str}")
39
- if dev.mac in list(self._devices.keys()):
40
- ar4 = self._devices[dev.mac]
41
- ar4.update_info()
42
- else:
43
- ar4 = AR4(hex(dev.mac), dev.slot, dev.hub_name.str.decode("utf-8"))
44
- if ar4.init():
45
- self._devices[dev.mac] = ar4
46
- logger.info(f"add device mac: {ar4.box_mac} slot: {ar4.slot} hub_name: {ar4.hub_name}")
47
- except Exception as e:
48
- logger.error(f"_search_ar4 异常: {str(e)}")
49
- finally:
50
- self._search()
13
+ def add_device(self, mac: str):
14
+ if mac in list(self._devices.keys()):
15
+ self._devices[mac].update_info()
16
+ logger.debug(f"update x8 device mac: {mac}")
17
+ else:
18
+ dev = AR4(mac)
19
+ if dev.connected:
20
+ self._devices[mac] = dev
21
+ logger.info(f"add x8 device mac: {dev}")
@@ -0,0 +1 @@
1
+ from .edf import EdfHandler
qlsdk/persist/edf.py ADDED
@@ -0,0 +1,186 @@
1
+ from datetime import datetime
2
+ from multiprocessing import Lock, Queue
3
+ from pyedflib import FILETYPE_BDFPLUS, FILETYPE_EDFPLUS, EdfWriter
4
+ from threading import Thread
5
+ from loguru import logger
6
+ import numpy as np
7
+ import os
8
+
9
+ class EdfHandler(object):
10
+ def __init__(self, sample_frequency, physical_max, physical_min, digital_max, digital_min, resolution=16, storage_path = None):
11
+ self.physical_max = physical_max
12
+ self.physical_min = physical_min
13
+ self.digital_max = digital_max
14
+ self.digital_min = digital_min
15
+ self.eeg_channels = None
16
+ self.eeg_sample_rate = 500
17
+ self.acc_channels = None
18
+ self.acc_sample_rate = 50
19
+ self._cache = Queue()
20
+ self.resolution = resolution
21
+ self.sample_frequency = sample_frequency
22
+ # bytes per second
23
+ self.bytes_per_second = 0
24
+ self._edf_writer = None
25
+ self._cache2 = tuple()
26
+ self._recording = False
27
+ self._edf_writer = None
28
+ self.annotations = None
29
+ # 每个数据块大小
30
+ self._chunk = np.array([])
31
+ self._Lock = Lock()
32
+ self._duration = 0
33
+ self._points = 0
34
+ self._first_pkg_id = None
35
+ self._last_pkg_id = None
36
+ self._first_timestamp = None
37
+ self._end_time = None
38
+ self._patient_code = "patient_code"
39
+ self._patient_name = "patient_name"
40
+ self._device_type = None
41
+ self._total_packets = 0
42
+ self._lost_packets = 0
43
+ self._storage_path = storage_path
44
+
45
+ @property
46
+ def file_name(self):
47
+ if self._storage_path:
48
+ try:
49
+ os.makedirs(self._storage_path, exist_ok=True) # 自动创建目录,存在则忽略
50
+ return f"{self._storage_path}/{self._device_type}_{self._first_timestamp}.edf"
51
+ except Exception as e:
52
+ logger.error(f"创建目录[{self._storage_path}]失败: {e}")
53
+
54
+ return f"{self._device_type}_{self._first_timestamp}.edf"
55
+
56
+ @property
57
+ def file_type(self):
58
+ return FILETYPE_BDFPLUS if self.resolution == 24 else FILETYPE_EDFPLUS
59
+
60
+ def set_device_type(self, device_type):
61
+ self._device_type = device_type
62
+
63
+ def set_storage_path(self, storage_path):
64
+ self._storage_path = storage_path
65
+
66
+ def set_patient_code(self, patient_code):
67
+ self._patient_code = patient_code
68
+
69
+ def set_patient_name(self, patient_name):
70
+ self._patient_name = patient_name
71
+
72
+ def append(self, data):
73
+ if data:
74
+ # 通道数
75
+ if self._first_pkg_id is None:
76
+ self.eeg_channels = data.eeg_ch_count
77
+ self.acc_channels = data.acc_ch_count
78
+ self._first_pkg_id = data.pkg_id
79
+ self._first_timestamp = data.time_stamp
80
+
81
+ if self._last_pkg_id and self._last_pkg_id != data.pkg_id - 1:
82
+ self._lost_packets += data.pkg_id - self._last_pkg_id - 1
83
+ logger.warning(f"数据包丢失: {self._last_pkg_id} -> {data.pkg_id}, 丢包数: {data.pkg_id - self._last_pkg_id - 1}")
84
+
85
+ self._last_pkg_id = data.pkg_id
86
+ self._total_packets += 1
87
+
88
+ # 数据
89
+ self._cache.put(data)
90
+ if not self._recording:
91
+ self.start()
92
+
93
+ def trigger(self, data):
94
+ pass
95
+
96
+ def start(self):
97
+ self._recording = True
98
+ record_thread = Thread(target=self._consumer)
99
+ record_thread.start()
100
+
101
+ def _consumer(self):
102
+ logger.debug(f"开始消费数据 _consumer: {self._cache.qsize()}")
103
+ while True:
104
+ if self._recording or (not self._cache.empty()):
105
+ try:
106
+ data = self._cache.get(timeout=10)
107
+ if data is None:
108
+ break
109
+ # 处理数据
110
+ self._points += len(data.eeg[0])
111
+ self._write_file(data.eeg, data.acc)
112
+ except Exception as e:
113
+ logger.error("数据队列为空,超时(10s)结束")
114
+ break
115
+ else:
116
+ break
117
+
118
+ self.close()
119
+
120
+ def _write_file(self, eeg_data, acc_data):
121
+ try:
122
+ if self._edf_writer is None:
123
+ self.initialize_edf()
124
+
125
+ if (self._chunk.size == 0):
126
+ self._chunk = np.asarray(eeg_data)
127
+ else:
128
+ self._chunk = np.hstack((self._chunk, eeg_data))
129
+
130
+ if self._chunk.size >= self.eeg_sample_rate * self.eeg_channels:
131
+ self._write_chunk(self._chunk[:self.sample_frequency])
132
+ self._chunk = self._chunk[self.sample_frequency:]
133
+
134
+ except Exception as e:
135
+ logger.error(f"写入数据异常: {str(e)}")
136
+
137
+ def close(self):
138
+ self._recording = False
139
+ if self._edf_writer:
140
+ self._end_time = datetime.now().timestamp()
141
+ self._edf_writer.writeAnnotation(0, 1, "start recording ")
142
+ self._edf_writer.writeAnnotation(self._duration, 1, "recording end")
143
+ self._edf_writer.close()
144
+
145
+ logger.info(f"文件: {self.file_name}完成记录, 总点数: {self._points}, 总时长: {self._duration}秒 丢包数: {self._lost_packets}/{self._total_packets + self._lost_packets}")
146
+
147
+
148
+
149
+ def initialize_edf(self):
150
+ # 创建EDF+写入器
151
+ self._edf_writer = EdfWriter(
152
+ self.file_name,
153
+ self.eeg_channels,
154
+ file_type=self.file_type
155
+ )
156
+
157
+ # 设置头信息
158
+ self._edf_writer.setPatientCode(self._patient_code)
159
+ self._edf_writer.setPatientName(self._patient_name)
160
+ self._edf_writer.setEquipment(self._device_type)
161
+ self._edf_writer.setStartdatetime(datetime.now())
162
+
163
+ # 配置通道参数
164
+ signal_headers = []
165
+ for ch in range(self.eeg_channels):
166
+ signal_headers.append({
167
+ "label": f'channels {ch + 1}',
168
+ "dimension": 'uV',
169
+ "sample_frequency": self.sample_frequency,
170
+ "physical_min": self.physical_min,
171
+ "physical_max": self.physical_max,
172
+ "digital_min": self.digital_min,
173
+ "digital_max": self.digital_max
174
+ })
175
+
176
+ self._edf_writer.setSignalHeaders(signal_headers)
177
+
178
+ def _write_chunk(self, chunk):
179
+ logger.debug(f"写入数据: {chunk}")
180
+ # 转换数据类型为float64(pyedflib要求)
181
+ data_float64 = chunk.astype(np.float64)
182
+ # 写入时转置为(样本数, 通道数)格式
183
+ self._edf_writer.writeSamples(data_float64)
184
+ self._duration += 1
185
+
186
+
qlsdk/sdk/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ from .ar4sdk import LMDevice, LMPacket, AR4SDK
2
+ from .hub import Hub