bardiabarabadi / uvicMUSE

BlueMuse Alternative with MATLAB Stream (UDP)
BSD 3-Clause "New" or "Revised" License
11 stars 6 forks source link

Advice on subscribing to EEG characteristics using bleak and pygatt #15

Closed sunshineinsandiego closed 3 years ago

sunshineinsandiego commented 3 years ago

Hi - I am trying to stream EEG data from my Muse2 into a non-LSL stream, but I'm having significant trouble subscribing to just one electrode. I've tried with both pygatt and bleak libraries. I can successfully establish a connection to my headset, but the connection drops when I try to start notifications. I have tried the following approaches and receive an output: `"Is connected".

The characteristic UUIDs I am using are from the constants.py file:

MUSE_GATT_ATTR_TP9 = '273e0003-4c4d-454d-96be-f03bac821358'
MUSE_GATT_ATTR_AF7 = '273e0004-4c4d-454d-96be-f03bac821358'
MUSE_GATT_ATTR_AF8 = '273e0005-4c4d-454d-96be-f03bac821358'
MUSE_GATT_ATTR_TP10 = '273e0006-4c4d-454d-96be-f03bac821358'
MUSE_GATT_ATTR_RIGHTAUX = '273e0007-4c4d-454d-96be-f03bac821358'

My bleak attempt is:

import sys
import os
import asyncio

from bleak import BleakClient

ADDRESS = '28686572-5A71-435E-952A-6F4292F5B04A'
CHARACTERISTIC_UUID = '273e0003-4c4d-454d-96be-f03bac821358'

if len(sys.argv) == 3:
    ADDRESS = sys.argv[1]
    CHARACTERISTIC_UUID = sys.argv[2]

def notification_handler(sender, data):
    """Simple notification handler which prints the data received."""
    print("{0}: {1}".format(sender, data))

async def run(address):

    async with BleakClient(address) as client:

        await client.connect()
        print("Is connected")
        await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
        await asyncio.sleep(5.0)
        await client.stop_notify(CHARACTERISTIC_UUID)

if __name__ == "__main__":

    os.environ["PYTHONASYNCIODEBUG"] = str(1)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(ADDRESS))

And my pygatt attempt is:

import pygatt
import time
from binascii import hexlify

adapter = pygatt.BGAPIBackend()
#adapter = pygatt.GATTToolBackend('hci0') linux backend

def handle_data(handle, raw_value):
    """
    handle -- integer, characteristic read handle the data was received on
    raw_value -- bytearray, the data returned in the notification
    """

    value = hexlify(raw_value)
    print(value)

try:
    adapter.start()
    device = adapter.connect('00:55:DA:B7:98:9C')

    device.subscribe('273e0006-4c4d-454d-96be-f03bac821358',
                     callback=handle_data)
finally:
    adapter.stop()

The outputs for both scripts are:

% python3 bleaktest.py
Is connected
% python3 pygatttest.py
Is connected

Any help/advice would be welcome. Thank you!

sunshineinsandiego commented 3 years ago

Closing this! Turns out this is simply a wait time issue. Adding asyncio wait in the main loop solves the problem. Still working on translating the bleak version to pygatt.