Skip to content

eConAlpha

eConAlpha

Bases: Thread

Source code in src\eConEXG\eConAlpha\data_reader.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
class eConAlpha(Thread):
    class Dev(Enum):
        SIGNAL = 10
        SIGNAL_START = 11
        IDLE = 30
        IDLE_START = 31
        TERMINATE = 40
        TERMINATE_START = 41

    dev_args = {
        "type": "eConAlpha",
        "fs_emg": 500,
        "fs_imu": 62.5,
        "channel_emg": {
            0: "CH0",
            1: "CH1",
            2: "CH2",
            3: "CH3",
            4: "CH4",
            5: "CH5",
            6: "CH6",
            7: "CH7",
        },
        "channel_imu": {
            0: "ACC_X",
            1: "ACC_Y",
            2: "ACC_Z",
            3: "GRY_X",
            4: "GRY_Y",
            5: "GRY_Z",
        },
        "AdapterInfo": "Serial Port",
        "samples_per_packet": 8,  # Number of samples per electrode to be sent in one packet
    }

    def __init__(self, port: Optional[str] = None) -> None:
        """
        Args:
            port: if not given, connect to the first available device.
        """
        super().__init__(daemon=True)
        self.__status = eConAlpha.Dev.TERMINATE
        if port is None:
            port = eConAlpha.find_devs()[0]
        self.__save_data = Queue()
        self.__parser = Parser()
        self.dev_args = deepcopy(eConAlpha.dev_args)
        self.dev = sock(port, self.__parser.threshold)
        self.set_frequency()
        self.__with_q = True
        self.__socket_flag = "Device not connected, please connect first."
        self.__bdf_flag = False
        try:
            self.dev.connect_socket()
        except Exception as e:
            try:
                self.dev.close_socket()
            finally:
                raise e
        self.__status = eConAlpha.Dev.IDLE_START
        self.__socket_flag = None
        self.__lsl_imu_flag = False
        self.__lsl_emg_flag = False
        self.__lsl_emg_imu_flag = False
        self._bdf_file = None
        self.__enable_imu = False
        self.dev_args["name"] = port
        self.start()

    def set_frequency(self, fs_emg: Optional[int] = None):
        """
        Change the sampling frequency of eConAlpha.

        Args:
            fs_emg: sampling frequency of emg data, should be 250, 500, 1000 or 2000.
                fs_imu will be automatically set to 1/8 of fs_emg.

        Raises:
            ValueError: if fs_emg is not valid.
            NotImplementedError: device firmware too old, not supporting 500Hz.
        """
        if self.__status == eConAlpha.Dev.SIGNAL:
            raise Exception("Data acquisition already started, please stop first.")
        if fs_emg is None:
            fs_emg = self.dev_args["fs_emg"]
        if fs_emg not in [250, 500, 1000, 2000]:
            raise ValueError("fs_emg should be 250, 500, 1000, or 2000")
        self.dev_args["fs_emg"] = fs_emg
        fs_imu = fs_emg / 8
        self.dev_args["fs_imu"] = fs_imu
        if hasattr(self, "dev"):
            self.dev.set_frequency(fs_emg)

    def get_dev_info(self) -> dict:
        """
        Get current device information, including device name, hardware channel number, acquired channels, sample frequency, etc.

        Returns:
            A dictionary containing device information, which includes:
                `type`: hardware type;
                `channel_emg`: channel dictionary, including EMG channel index and name;
                `channel_imu`: channel dictionary, including IMU channel index and name;
                `AdapterInfo`: adapter used for connection;
                `fs_emg`: sample frequency of EMG in Hz;
                `fs_imu`: sample frequency of IMU in Hz;
        """
        return deepcopy(self.dev_args)

    @staticmethod
    def find_devs() -> list:
        """
        Find available eConAlpha devices.

        Returns:
            available device ports.

        Raises:
            Exception: if no eConAlpha device found.
        """
        return sock.find_devs()

    def get_data(
        self, timeout: Optional[float] = 0.02
    ) -> Optional[list[Optional[list]]]:
        """
        Acquire all available data, make sure this function is called in a loop when `with_q` is set to `True` in`start_acquisition_data()`

        Args:
            timeout: Non-negative value, blocks at most 'timeout' seconds and return, if set to `None`, blocks until new data available.

        Returns:
            A list of frames, each frame is made up of 5 emg data and 1 imu data in a shape as below:
                [[`emg_ch0_0,...,emg_ch8_0`],..., [`emg_ch0_7,...,emg_ch8_7`], [`acc_x`, `acc_y`, `acc_z`,`gry_x`,`gry_y`,`gry_z`]],
                    in which number `0~4` after `_` indicates the time order of channel data.

        Raises:
            Exception: if device not connected, connection failed, data transmission timeout/init failed, or unknown error.

        Data Unit:
            - emg: µV
            - acc: mg
            - gry: bps
        """
        self.__check_dev_status()
        if not self.__with_q:
            return
        try:
            data: list = self.__save_data.get(timeout=timeout)
        except queue.Empty:
            return []
        while not self.__save_data.empty():
            data.extend(self.__save_data.get())
        return data

    def start_acquisition_data(self, with_q: bool = True) -> None:
        """
        Send data acquisition command to device, block until data acquisition started or failed.

        Args:
            with_q: if True, signal data will be stored in a queue and **should** be acquired by calling `get_data()` in a loop in case data queue is full.
                if False, new data will not be directly available and can only be accessed through lsl stream.

        """
        self.__check_dev_status()
        self.__with_q = with_q
        if self.__status == eConAlpha.Dev.SIGNAL:
            return
        self.__status = eConAlpha.Dev.SIGNAL_START
        while self.__status not in [eConAlpha.Dev.SIGNAL, eConAlpha.Dev.TERMINATE]:
            time.sleep(0.01)
        self.__check_dev_status()

    def stop_acquisition(self) -> None:
        """
        Stop data or impedance acquisition, block until data acquisition stopped or failed.
        """
        self.__check_dev_status()
        self.__status = eConAlpha.Dev.IDLE_START
        while self.__status not in [eConAlpha.Dev.IDLE, eConAlpha.Dev.TERMINATE]:
            time.sleep(0.01)
        self.__check_dev_status()

    def open_lsl_emg(self):
        """
        Open LSL EMG stream, can be invoked after `start_acquisition_data()`.

        Raises:
            Exception: if data acquisition not started or LSL stream already opened.
            LSLException: if LSL stream creation failed.
            importError: if `pylsl` is not installed or liblsl not installed for unix like system.
        """
        if self.__status != eConAlpha.Dev.SIGNAL:
            raise Exception("Data acquisition not started, please start first.")
        if hasattr(self, "_lsl_emg"):
            raise Exception("LSL stream already opened.")
        from ..utils.lslWrapper import lslSender

        # Create an expanded channel dictionary for LSL stream creation,
        # replicating each electrode label 'samples_per_packet' times.
        expanded_channels = {}
        current_key = 0
        for label in self.dev_args["channel_emg"].values():
            for _ in range(self.dev_args["samples_per_packet"]):
                expanded_channels[current_key] = label
                current_key += 1

        # Use the expanded channel dictionary for initializing the LSL stream
        self._lsl_emg = lslSender(
            expanded_channels,  # Expanded channels reflecting samples_per_packet
            f"{self.dev_args['type']}EMG{self.dev_args['name'][-2:]}",
            "EMG",
            self.dev_args["fs_emg"],
            with_trigger=False,
        )
        self.__lsl_emg_flag = True

    def close_lsl_emg(self):
        """
        Close LSL EMG stream manually, invoked automatically after `stop_acquisition()` and `close_dev()`
        """
        self.__lsl_emg_flag = False
        if hasattr(self, "_lsl_emg"):
            del self._lsl_emg

    def open_lsl_imu(self):
        """
        Open LSL IMU stream, can be invoked after `start_acquisition_data()`.

        Raises:
            Exception: if data acquisition not started or LSL stream already opened.
            LSLException: if LSL stream creation failed.
            importError: if `pylsl` is not installed or liblsl not installed for unix like system.
        """
        if self.__status != eConAlpha.Dev.SIGNAL:
            raise Exception("Data acquisition not started, please start first.")
        if hasattr(self, "_lsl_imu"):
            raise Exception("LSL stream already opened.")
        from ..utils.lslWrapper import lslSender

        self._lsl_imu = lslSender(
            self.dev_args["channel_imu"],
            f"{self.dev_args['type']}IMU{self.dev_args['name'][-2:]}",
            "IMU",
            self.dev_args["fs_imu"],
            unit="degree",
            with_trigger=False,
        )
        self.__lsl_imu_flag = True

    def close_lsl_imu(self):
        """
        Close LSL IMU stream manually, invoked automatically after `stop_acquisition()` and `close_dev()`
        """
        self.__lsl_imu_flag = False
        if hasattr(self, "_lsl_imu"):
            del self._lsl_imu

    def open_lsl_emg_imu(self):
        """
        Open LSL stream to transmit EMG and IMU simultaneously, can be invoked after `start_acquisition_data()`.

        Raises:
            Exception: if data acquisition not started or LSL stream already opened.
            LSLException: if LSL stream creation failed.
            importError: if `pylsl` is not installed or liblsl not installed for unix like system.
        """
        if self.__status != eConAlpha.Dev.SIGNAL:
            raise Exception("Data acquisition not started, please start first.")
        if hasattr(self, "_lsl_emg_imu"):
            raise Exception("LSL stream already opened.")
        from ..utils.lslWrapper import lslSender

        key = 0
        elctds = {}
        # Expand EMG channels: repeat each EMG electrode label 'samples_per_packet' times.
        for v in self.dev_args["channel_emg"].values():
            for _ in range(self.dev_args["samples_per_packet"]):
                elctds[key] = v
                key += 1
        # Add IMU channels as they are (no expansion)
        for v in self.dev_args["channel_imu"].values():
            elctds[key] = v
            key += 1

        self._lsl_emg_imu = lslSender(
            elctds,
            f"{self.dev_args['type']}EMG-IMU{self.dev_args['name'][-2:]}",
            "EMG-IMU",
            self.dev_args["fs_emg"] + self.dev_args["fs_imu"],
            unit="degree",
            with_trigger=False,
        )
        # Note: This combined LSL stream now reflects the expanded EMG channels
        # and original IMU channels, ensuring the packet structure is maintained.
        self.__lsl_emg_imu_flag = True

    def close_lsl_emg_imu(self):
        """
        Close LSL EMG and IMU stream manually, invoked automatically after `stop_acquisition()` and `close_dev()`
        """
        self.__lsl_emg_imu_flag = False
        if hasattr(self, "_lsl_emg_imu"):
            del self._lsl_emg_imu

    def setIMUFlag(self, check):
        self.__enable_imu = check

    def create_bdf_file(self, filename: str):
        """
        Create a BDF file and save data to it, invoke it after `start_acquisition_data()`.

        Args:
            filename: file name to save data, accept absolute or relative path.

        Raises:
            Exception: if data acquisition not started or `save_bdf_file` is invoked and BDF file already created.
            OSError: if BDF file creation failed, this may be caused by invalid file path or permission issue.
            importError: if `pyedflib` is not installed.
        """
        if self.__status != eConAlpha.Dev.SIGNAL:
            raise Exception("Data acquisition not started")
        if self._bdf_file is not None:
            raise Exception("BDF file already created.")
        from ..utils.bdfWrapper import bdfSaverEMG, bdfSaverEMGIMU

        if filename[-4:].lower() != ".bdf":
            filename += ".bdf"
        if self.__enable_imu:
            self._bdf_file = bdfSaverEMGIMU(
                filename,
                self.dev_args["channel_emg"],
                self.dev_args["fs_emg"],
                self.dev_args["channel_imu"],
                self.dev_args["fs_imu"],
                self.dev_args["type"],
            )
        else:
            self._bdf_file = bdfSaverEMG(
                filename,
                self.dev_args["channel_emg"],
                self.dev_args["fs_emg"],
                self.dev_args["type"],
            )
        self.__bdf_flag = True

    def close_bdf_file(self):
        """
        Close and save BDF file manually, invoked automatically after `stop_acquisition()` or `close_dev()`
        """
        self.__bdf_flag = False
        if self._bdf_file is not None:
            self._bdf_file.close_bdf()
            self._bdf_file = None

    def send_bdf_marker(self, marker: str):
        """
        Send marker to BDF file, can be invoked after `create_bdf_file()`, otherwise it will be ignored.

        Args:
            marker: marker string to write.
        """
        if hasattr(self, "_bdf_file"):
            self._bdf_file.write_Annotation(marker)

    def shock_band(self):
        """
        Send a command to vibrate the arm band
        """
        self.dev.shock_band()

    def close_dev(self):
        """
        Close device connection and release resources.
        """
        if self.__status != eConAlpha.Dev.TERMINATE:
            # ensure socket is closed correctly
            self.__status = eConAlpha.Dev.TERMINATE_START
            while self.__status != eConAlpha.Dev.TERMINATE:
                time.sleep(0.1)
        if self.is_alive():
            self.join()

    def __recv_data(self):
        try:
            self.dev.start_data()
            self.__status = eConAlpha.Dev.SIGNAL
        except Exception:
            self.__socket_flag = "SIGNAL mode initialization failed."
            self.__status = eConAlpha.Dev.TERMINATE_START

        while self.__status in [eConAlpha.Dev.SIGNAL]:
            try:
                data = self.dev.recv_socket()
                if not data:
                    raise Exception("Data transmission timeout.")
                ret = self.__parser.parse_data(data)
                if ret:
                    if self.__with_q:
                        self.__save_data.put(ret)
                    if self.__bdf_flag:
                        self._bdf_file.write_chunk(ret)
                    if self.__lsl_emg_flag:
                        self._lsl_emg.push_chunk(
                            [frame for frames in ret for frame in frames[:-1]]
                        )
                    if self.__lsl_imu_flag:
                        self._lsl_imu.push_chunk([frame[-1] for frame in ret])
                    if self.__lsl_emg_imu_flag:
                        self._lsl_emg_imu.push_chunk(
                            [frame for frames in ret for frame in frames[:-1]]
                            + [frame[-1] for frame in ret]
                        )
            except Exception as e:
                print(e)
                self.__socket_flag = "Data transmission timeout."
                self.__status = eConAlpha.Dev.TERMINATE_START

        # clear buffer
        self.close_lsl_emg()
        self.close_lsl_imu()
        self.close_lsl_emg_imu()
        self.close_bdf_file()
        # self.dev.stop_recv()
        self.__parser.clear_buffer()
        self.__save_data.put(None)
        while self.__save_data.get() is not None:
            continue
        # stop recv data
        if self.__status != eConAlpha.Dev.TERMINATE_START:
            try:  # stop data acquisition when thread ended
                self.dev.stop_recv()
            except Exception:
                if self.__status == eConAlpha.Dev.IDLE_START:
                    self.__socket_flag = "Connection lost."
                self.__status = eConAlpha.Dev.TERMINATE_START

    def run(self):
        while self.__status != eConAlpha.Dev.TERMINATE_START:
            if self.__status == eConAlpha.Dev.SIGNAL_START:
                self.__recv_data()
            elif self.__status == eConAlpha.Dev.IDLE_START:
                self.__status = eConAlpha.Dev.IDLE
                while self.__status == eConAlpha.Dev.IDLE:
                    time.sleep(0.1)
            else:
                self.__socket_flag = f"Unknown status: {self.__status.name}"
                break
        try:
            self.dev.close_socket()
        finally:
            self.__status = eConAlpha.Dev.TERMINATE

    def __check_dev_status(self):
        if self.__socket_flag is None:
            return
        if self.is_alive():
            self.close_dev()
        raise Exception(str(self.__socket_flag))

__init__(port=None)

Parameters:

Name Type Description Default
port Optional[str]

if not given, connect to the first available device.

None
Source code in src\eConEXG\eConAlpha\data_reader.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def __init__(self, port: Optional[str] = None) -> None:
    """
    Args:
        port: if not given, connect to the first available device.
    """
    super().__init__(daemon=True)
    self.__status = eConAlpha.Dev.TERMINATE
    if port is None:
        port = eConAlpha.find_devs()[0]
    self.__save_data = Queue()
    self.__parser = Parser()
    self.dev_args = deepcopy(eConAlpha.dev_args)
    self.dev = sock(port, self.__parser.threshold)
    self.set_frequency()
    self.__with_q = True
    self.__socket_flag = "Device not connected, please connect first."
    self.__bdf_flag = False
    try:
        self.dev.connect_socket()
    except Exception as e:
        try:
            self.dev.close_socket()
        finally:
            raise e
    self.__status = eConAlpha.Dev.IDLE_START
    self.__socket_flag = None
    self.__lsl_imu_flag = False
    self.__lsl_emg_flag = False
    self.__lsl_emg_imu_flag = False
    self._bdf_file = None
    self.__enable_imu = False
    self.dev_args["name"] = port
    self.start()

close_bdf_file()

Close and save BDF file manually, invoked automatically after stop_acquisition() or close_dev()

Source code in src\eConEXG\eConAlpha\data_reader.py
358
359
360
361
362
363
364
365
def close_bdf_file(self):
    """
    Close and save BDF file manually, invoked automatically after `stop_acquisition()` or `close_dev()`
    """
    self.__bdf_flag = False
    if self._bdf_file is not None:
        self._bdf_file.close_bdf()
        self._bdf_file = None

close_dev()

Close device connection and release resources.

Source code in src\eConEXG\eConAlpha\data_reader.py
383
384
385
386
387
388
389
390
391
392
393
def close_dev(self):
    """
    Close device connection and release resources.
    """
    if self.__status != eConAlpha.Dev.TERMINATE:
        # ensure socket is closed correctly
        self.__status = eConAlpha.Dev.TERMINATE_START
        while self.__status != eConAlpha.Dev.TERMINATE:
            time.sleep(0.1)
    if self.is_alive():
        self.join()

close_lsl_emg()

Close LSL EMG stream manually, invoked automatically after stop_acquisition() and close_dev()

Source code in src\eConEXG\eConAlpha\data_reader.py
229
230
231
232
233
234
235
def close_lsl_emg(self):
    """
    Close LSL EMG stream manually, invoked automatically after `stop_acquisition()` and `close_dev()`
    """
    self.__lsl_emg_flag = False
    if hasattr(self, "_lsl_emg"):
        del self._lsl_emg

close_lsl_emg_imu()

Close LSL EMG and IMU stream manually, invoked automatically after stop_acquisition() and close_dev()

Source code in src\eConEXG\eConAlpha\data_reader.py
309
310
311
312
313
314
315
def close_lsl_emg_imu(self):
    """
    Close LSL EMG and IMU stream manually, invoked automatically after `stop_acquisition()` and `close_dev()`
    """
    self.__lsl_emg_imu_flag = False
    if hasattr(self, "_lsl_emg_imu"):
        del self._lsl_emg_imu

close_lsl_imu()

Close LSL IMU stream manually, invoked automatically after stop_acquisition() and close_dev()

Source code in src\eConEXG\eConAlpha\data_reader.py
262
263
264
265
266
267
268
def close_lsl_imu(self):
    """
    Close LSL IMU stream manually, invoked automatically after `stop_acquisition()` and `close_dev()`
    """
    self.__lsl_imu_flag = False
    if hasattr(self, "_lsl_imu"):
        del self._lsl_imu

create_bdf_file(filename)

Create a BDF file and save data to it, invoke it after start_acquisition_data().

Parameters:

Name Type Description Default
filename str

file name to save data, accept absolute or relative path.

required

Raises:

Type Description
Exception

if data acquisition not started or save_bdf_file is invoked and BDF file already created.

OSError

if BDF file creation failed, this may be caused by invalid file path or permission issue.

importError

if pyedflib is not installed.

Source code in src\eConEXG\eConAlpha\data_reader.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
def create_bdf_file(self, filename: str):
    """
    Create a BDF file and save data to it, invoke it after `start_acquisition_data()`.

    Args:
        filename: file name to save data, accept absolute or relative path.

    Raises:
        Exception: if data acquisition not started or `save_bdf_file` is invoked and BDF file already created.
        OSError: if BDF file creation failed, this may be caused by invalid file path or permission issue.
        importError: if `pyedflib` is not installed.
    """
    if self.__status != eConAlpha.Dev.SIGNAL:
        raise Exception("Data acquisition not started")
    if self._bdf_file is not None:
        raise Exception("BDF file already created.")
    from ..utils.bdfWrapper import bdfSaverEMG, bdfSaverEMGIMU

    if filename[-4:].lower() != ".bdf":
        filename += ".bdf"
    if self.__enable_imu:
        self._bdf_file = bdfSaverEMGIMU(
            filename,
            self.dev_args["channel_emg"],
            self.dev_args["fs_emg"],
            self.dev_args["channel_imu"],
            self.dev_args["fs_imu"],
            self.dev_args["type"],
        )
    else:
        self._bdf_file = bdfSaverEMG(
            filename,
            self.dev_args["channel_emg"],
            self.dev_args["fs_emg"],
            self.dev_args["type"],
        )
    self.__bdf_flag = True

find_devs() staticmethod

Find available eConAlpha devices.

Returns:

Type Description
list

available device ports.

Raises:

Type Description
Exception

if no eConAlpha device found.

Source code in src\eConEXG\eConAlpha\data_reader.py
121
122
123
124
125
126
127
128
129
130
131
132
@staticmethod
def find_devs() -> list:
    """
    Find available eConAlpha devices.

    Returns:
        available device ports.

    Raises:
        Exception: if no eConAlpha device found.
    """
    return sock.find_devs()

get_data(timeout=0.02)

Acquire all available data, make sure this function is called in a loop when with_q is set to True instart_acquisition_data()

Parameters:

Name Type Description Default
timeout Optional[float]

Non-negative value, blocks at most 'timeout' seconds and return, if set to None, blocks until new data available.

0.02

Returns:

Type Description
Optional[list[Optional[list]]]

A list of frames, each frame is made up of 5 emg data and 1 imu data in a shape as below: [[emg_ch0_0,...,emg_ch8_0],..., [emg_ch0_7,...,emg_ch8_7], [acc_x, acc_y, acc_z,gry_x,gry_y,gry_z]], in which number 0~4 after _ indicates the time order of channel data.

Raises:

Type Description
Exception

if device not connected, connection failed, data transmission timeout/init failed, or unknown error.

Data Unit
  • emg: µV
  • acc: mg
  • gry: bps
Source code in src\eConEXG\eConAlpha\data_reader.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
def get_data(
    self, timeout: Optional[float] = 0.02
) -> Optional[list[Optional[list]]]:
    """
    Acquire all available data, make sure this function is called in a loop when `with_q` is set to `True` in`start_acquisition_data()`

    Args:
        timeout: Non-negative value, blocks at most 'timeout' seconds and return, if set to `None`, blocks until new data available.

    Returns:
        A list of frames, each frame is made up of 5 emg data and 1 imu data in a shape as below:
            [[`emg_ch0_0,...,emg_ch8_0`],..., [`emg_ch0_7,...,emg_ch8_7`], [`acc_x`, `acc_y`, `acc_z`,`gry_x`,`gry_y`,`gry_z`]],
                in which number `0~4` after `_` indicates the time order of channel data.

    Raises:
        Exception: if device not connected, connection failed, data transmission timeout/init failed, or unknown error.

    Data Unit:
        - emg: µV
        - acc: mg
        - gry: bps
    """
    self.__check_dev_status()
    if not self.__with_q:
        return
    try:
        data: list = self.__save_data.get(timeout=timeout)
    except queue.Empty:
        return []
    while not self.__save_data.empty():
        data.extend(self.__save_data.get())
    return data

get_dev_info()

Get current device information, including device name, hardware channel number, acquired channels, sample frequency, etc.

Returns:

Type Description
dict

A dictionary containing device information, which includes: type: hardware type; channel_emg: channel dictionary, including EMG channel index and name; channel_imu: channel dictionary, including IMU channel index and name; AdapterInfo: adapter used for connection; fs_emg: sample frequency of EMG in Hz; fs_imu: sample frequency of IMU in Hz;

Source code in src\eConEXG\eConAlpha\data_reader.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def get_dev_info(self) -> dict:
    """
    Get current device information, including device name, hardware channel number, acquired channels, sample frequency, etc.

    Returns:
        A dictionary containing device information, which includes:
            `type`: hardware type;
            `channel_emg`: channel dictionary, including EMG channel index and name;
            `channel_imu`: channel dictionary, including IMU channel index and name;
            `AdapterInfo`: adapter used for connection;
            `fs_emg`: sample frequency of EMG in Hz;
            `fs_imu`: sample frequency of IMU in Hz;
    """
    return deepcopy(self.dev_args)

open_lsl_emg()

Open LSL EMG stream, can be invoked after start_acquisition_data().

Raises:

Type Description
Exception

if data acquisition not started or LSL stream already opened.

LSLException

if LSL stream creation failed.

importError

if pylsl is not installed or liblsl not installed for unix like system.

Source code in src\eConEXG\eConAlpha\data_reader.py
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
def open_lsl_emg(self):
    """
    Open LSL EMG stream, can be invoked after `start_acquisition_data()`.

    Raises:
        Exception: if data acquisition not started or LSL stream already opened.
        LSLException: if LSL stream creation failed.
        importError: if `pylsl` is not installed or liblsl not installed for unix like system.
    """
    if self.__status != eConAlpha.Dev.SIGNAL:
        raise Exception("Data acquisition not started, please start first.")
    if hasattr(self, "_lsl_emg"):
        raise Exception("LSL stream already opened.")
    from ..utils.lslWrapper import lslSender

    # Create an expanded channel dictionary for LSL stream creation,
    # replicating each electrode label 'samples_per_packet' times.
    expanded_channels = {}
    current_key = 0
    for label in self.dev_args["channel_emg"].values():
        for _ in range(self.dev_args["samples_per_packet"]):
            expanded_channels[current_key] = label
            current_key += 1

    # Use the expanded channel dictionary for initializing the LSL stream
    self._lsl_emg = lslSender(
        expanded_channels,  # Expanded channels reflecting samples_per_packet
        f"{self.dev_args['type']}EMG{self.dev_args['name'][-2:]}",
        "EMG",
        self.dev_args["fs_emg"],
        with_trigger=False,
    )
    self.__lsl_emg_flag = True

open_lsl_emg_imu()

Open LSL stream to transmit EMG and IMU simultaneously, can be invoked after start_acquisition_data().

Raises:

Type Description
Exception

if data acquisition not started or LSL stream already opened.

LSLException

if LSL stream creation failed.

importError

if pylsl is not installed or liblsl not installed for unix like system.

Source code in src\eConEXG\eConAlpha\data_reader.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
def open_lsl_emg_imu(self):
    """
    Open LSL stream to transmit EMG and IMU simultaneously, can be invoked after `start_acquisition_data()`.

    Raises:
        Exception: if data acquisition not started or LSL stream already opened.
        LSLException: if LSL stream creation failed.
        importError: if `pylsl` is not installed or liblsl not installed for unix like system.
    """
    if self.__status != eConAlpha.Dev.SIGNAL:
        raise Exception("Data acquisition not started, please start first.")
    if hasattr(self, "_lsl_emg_imu"):
        raise Exception("LSL stream already opened.")
    from ..utils.lslWrapper import lslSender

    key = 0
    elctds = {}
    # Expand EMG channels: repeat each EMG electrode label 'samples_per_packet' times.
    for v in self.dev_args["channel_emg"].values():
        for _ in range(self.dev_args["samples_per_packet"]):
            elctds[key] = v
            key += 1
    # Add IMU channels as they are (no expansion)
    for v in self.dev_args["channel_imu"].values():
        elctds[key] = v
        key += 1

    self._lsl_emg_imu = lslSender(
        elctds,
        f"{self.dev_args['type']}EMG-IMU{self.dev_args['name'][-2:]}",
        "EMG-IMU",
        self.dev_args["fs_emg"] + self.dev_args["fs_imu"],
        unit="degree",
        with_trigger=False,
    )
    # Note: This combined LSL stream now reflects the expanded EMG channels
    # and original IMU channels, ensuring the packet structure is maintained.
    self.__lsl_emg_imu_flag = True

open_lsl_imu()

Open LSL IMU stream, can be invoked after start_acquisition_data().

Raises:

Type Description
Exception

if data acquisition not started or LSL stream already opened.

LSLException

if LSL stream creation failed.

importError

if pylsl is not installed or liblsl not installed for unix like system.

Source code in src\eConEXG\eConAlpha\data_reader.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
def open_lsl_imu(self):
    """
    Open LSL IMU stream, can be invoked after `start_acquisition_data()`.

    Raises:
        Exception: if data acquisition not started or LSL stream already opened.
        LSLException: if LSL stream creation failed.
        importError: if `pylsl` is not installed or liblsl not installed for unix like system.
    """
    if self.__status != eConAlpha.Dev.SIGNAL:
        raise Exception("Data acquisition not started, please start first.")
    if hasattr(self, "_lsl_imu"):
        raise Exception("LSL stream already opened.")
    from ..utils.lslWrapper import lslSender

    self._lsl_imu = lslSender(
        self.dev_args["channel_imu"],
        f"{self.dev_args['type']}IMU{self.dev_args['name'][-2:]}",
        "IMU",
        self.dev_args["fs_imu"],
        unit="degree",
        with_trigger=False,
    )
    self.__lsl_imu_flag = True

send_bdf_marker(marker)

Send marker to BDF file, can be invoked after create_bdf_file(), otherwise it will be ignored.

Parameters:

Name Type Description Default
marker str

marker string to write.

required
Source code in src\eConEXG\eConAlpha\data_reader.py
367
368
369
370
371
372
373
374
375
def send_bdf_marker(self, marker: str):
    """
    Send marker to BDF file, can be invoked after `create_bdf_file()`, otherwise it will be ignored.

    Args:
        marker: marker string to write.
    """
    if hasattr(self, "_bdf_file"):
        self._bdf_file.write_Annotation(marker)

set_frequency(fs_emg=None)

Change the sampling frequency of eConAlpha.

Parameters:

Name Type Description Default
fs_emg Optional[int]

sampling frequency of emg data, should be 250, 500, 1000 or 2000. fs_imu will be automatically set to 1/8 of fs_emg.

None

Raises:

Type Description
ValueError

if fs_emg is not valid.

NotImplementedError

device firmware too old, not supporting 500Hz.

Source code in src\eConEXG\eConAlpha\data_reader.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
def set_frequency(self, fs_emg: Optional[int] = None):
    """
    Change the sampling frequency of eConAlpha.

    Args:
        fs_emg: sampling frequency of emg data, should be 250, 500, 1000 or 2000.
            fs_imu will be automatically set to 1/8 of fs_emg.

    Raises:
        ValueError: if fs_emg is not valid.
        NotImplementedError: device firmware too old, not supporting 500Hz.
    """
    if self.__status == eConAlpha.Dev.SIGNAL:
        raise Exception("Data acquisition already started, please stop first.")
    if fs_emg is None:
        fs_emg = self.dev_args["fs_emg"]
    if fs_emg not in [250, 500, 1000, 2000]:
        raise ValueError("fs_emg should be 250, 500, 1000, or 2000")
    self.dev_args["fs_emg"] = fs_emg
    fs_imu = fs_emg / 8
    self.dev_args["fs_imu"] = fs_imu
    if hasattr(self, "dev"):
        self.dev.set_frequency(fs_emg)

shock_band()

Send a command to vibrate the arm band

Source code in src\eConEXG\eConAlpha\data_reader.py
377
378
379
380
381
def shock_band(self):
    """
    Send a command to vibrate the arm band
    """
    self.dev.shock_band()

start_acquisition_data(with_q=True)

Send data acquisition command to device, block until data acquisition started or failed.

Parameters:

Name Type Description Default
with_q bool

if True, signal data will be stored in a queue and should be acquired by calling get_data() in a loop in case data queue is full. if False, new data will not be directly available and can only be accessed through lsl stream.

True
Source code in src\eConEXG\eConAlpha\data_reader.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def start_acquisition_data(self, with_q: bool = True) -> None:
    """
    Send data acquisition command to device, block until data acquisition started or failed.

    Args:
        with_q: if True, signal data will be stored in a queue and **should** be acquired by calling `get_data()` in a loop in case data queue is full.
            if False, new data will not be directly available and can only be accessed through lsl stream.

    """
    self.__check_dev_status()
    self.__with_q = with_q
    if self.__status == eConAlpha.Dev.SIGNAL:
        return
    self.__status = eConAlpha.Dev.SIGNAL_START
    while self.__status not in [eConAlpha.Dev.SIGNAL, eConAlpha.Dev.TERMINATE]:
        time.sleep(0.01)
    self.__check_dev_status()

stop_acquisition()

Stop data or impedance acquisition, block until data acquisition stopped or failed.

Source code in src\eConEXG\eConAlpha\data_reader.py
185
186
187
188
189
190
191
192
193
def stop_acquisition(self) -> None:
    """
    Stop data or impedance acquisition, block until data acquisition stopped or failed.
    """
    self.__check_dev_status()
    self.__status = eConAlpha.Dev.IDLE_START
    while self.__status not in [eConAlpha.Dev.IDLE, eConAlpha.Dev.TERMINATE]:
        time.sleep(0.01)
    self.__check_dev_status()