コード例 #1
0
    def __init__(self, com_port=None):
        """ Create a GoDirectBackendBLE object for managing the pygatt BGAPI backend
		Args:
			com_port (str): None for autodetection, or COM port used by the BLE dongle e.g. 'COM9'
		"""

        self._logger = logging.getLogger('godirect')
        self._adapter = None
        if com_port != None:
            self._adapter = pygatt.BGAPIBackend(serial_port=com_port)
        else:
            self._adapter = pygatt.BGAPIBackend()
        self._adapter.start()
        super().__init__()
コード例 #2
0
 def __init__(self, auth_id=None, key=None, port=None, bgapi=False):
     self.auth_id = auth_id
     self.key = key
     if bgapi:
         self.adapter = pygatt.BGAPIBackend(serial_port=port)
     else:
         self.adapter = pygatt.GATTToolBackend()
     """
     reset_on_start = True
     retries        = 5
     while( retries ):
         retval = self.adapter.start(reset_on_start=reset_on_start)
         if( None == retval ):
             log.error('BLEAdapter error: cannot connect to device')
             retries = retries - 1
             self.connected = False
         else:
             retries = 0
             self.connected = True
     """
     reset_on_start = True
     try:
         #retval = self.adapter.start(reset_on_start=reset_on_start)
         self.adapter.start()
         self.connected = True
     except:
         log.error('BLEAdapter error: cannot start adapter')
         self.connected = False
     return
コード例 #3
0
def try_get_best_possible_bluetooth_adapter():
    """ Try to get the best possible, working Bluetooth adapter for the current environment """

    if can_use_bt_gatttool():
        return pygatt.GATTToolBackend()
    else:
        return pygatt.BGAPIBackend()
コード例 #4
0
ファイル: helper.py プロジェクト: eugenehp/uvicMuse
def list_muses(backend='bgapi', interface=None):
    backend = resolve_backend(backend)

    if backend == 'gatt':
        interface = interface or 'hci0'
        adapter = pygatt.GATTToolBackend(interface)
    else:
        adapter = pygatt.BGAPIBackend(serial_port=interface)

    adapter.start()
    # print('Searching for Muses, this may take up to 10 seconds...                                 ')
    devices = adapter.scan(timeout=10.5)
    adapter.stop()
    muses = []

    for device in devices:
        if device['name'] and 'Muse' in device['name']:
            muses = muses + [device]

    if muses:
        for muse in muses:
            pass
            # print('Found device %s, MAC Address %s' %
            #       (muse['name'], muse['address']))
    else:
        pass
        # print('No Muses found.')

    return muses
コード例 #5
0
def main():
    # Initialize the adapter according to the backend used
    adapter = None
    if BACKEND == "BLED112":
        adapter = pygatt.BGAPIBackend()  # BLED112 backend for Windows
    elif BACKEND == "GATTTOOL":
        adapter = pygatt.GATTToolBackend()  # GATTtool backend for Linux

    device = None

    try:
        # Connect to BLED112
        adapter.start()

        # Scan for available BLE devices
        print("Scanning devices for %s seconds..." % str(SCAN_TIMEOUT))
        device_li = adapter.scan(timeout=SCAN_TIMEOUT)
        i = 1
        for d in device_li:
            print("%s. %s -- %s" % (str(i), str(d["address"]), str(d["name"])))
            i += 1

        # Check list size
        if len(device_li) == 0:
            print("No device found!")
            return

        # Ask the user which device to connect to
        print("\nSelect which device to connect to (0 to exit):")
        device_ind = None
        while (device_ind == None):
            user_in = input()
            try:
                user_in = int(user_in)
                if (user_in == 0):
                    return
                if (user_in < 0 or user_in > len(device_li)):
                    raise
                device_ind = user_in - 1
            except:
                print("Invalid input")

        # Connect to the device
        print("\nConnecting to the selected device...")
        device = adapter.connect(address=device_li[device_ind]["address"])
        print("Connected successfully!\n")

        # Subscribe to the wanted characteristic data
        print("Subscribing to the characteristic with UUID %s..." %
              MY_CHAR_UUID)
        device.subscribe(MY_CHAR_UUID, callback=handle_my_char_data)
        print("Subscribed to the characteristic successfully!\n")

        # Block the function from exiting
        input()
    finally:
        if device != None:
            device.disconnect()
        adapter.stop()
コード例 #6
0
def call_result(label_result, n1):
    num1 = str(n1.get())
    label_result.config(text="Comport is %s" % num1)
    adapter = pygatt.BGAPIBackend(serial_port=str(num1))
    adapter.start()
    listOfDevices = adapter.scan()
    print(listOfDevices)
    return
コード例 #7
0
def _list_muses_gatt(backend, interface=None):
    interface = interface or "hci0"
    if backend == "gatt":
        adapter = pygatt.GATTToolBackend(interface)
    elif backend == "bgapi":
        adapter = pygatt.BGAPIBackend(serial_port=interface)
    adapter.start()
    devices = adapter.scan(timeout=MUSE_SCAN_TIMEOUT)
    adapter.stop()
    return [d for d in devices if d["name"] and "Muse" in d["name"]]
コード例 #8
0
def prime(backend_override=None):
    # for windows use BGAPI
    # for linux use GATTTools as default, allow switching to BGAPI
    global primed
    if not primed:
        global adapter
        if backend_override is not None:
            if backend_override == "BGAPI":
                adapter = pygatt.BGAPIBackend()
            elif backend_override == "GATTTOOL":
                adapter = pygatt.GATTToolBackend()
            else:
                print("Wrong override string!!")
                print("falling back to default setting")
                return prime()
        else:
            if platform == "win":
                adapter = pygatt.BGAPIBackend()
            elif platform == "linux":
                adapter = pygatt.GATTToolBackend()
            elif platform == "android":
                print("BLEBackend support untested!!")
                adapter = pygatt.GATTToolBackend()
            elif platform == "macosx":
                print("BLEBackend support untested!!")
                print("Apple devices are not supported by giiker_engine")
                print(" ")
                print("it will now attempt to function normally")
                adapter = pygatt.GATTToolBackend()
            elif platform == "unknown":
                print("can't recognise the host OS,")
                print("I have no clue if this will work")
                print("giving it a shot anyway")
                adapter = pygatt.GATTToolBackend()
        try:
            adapter.start()
        except:
            raise ConnectionRefusedError
        finally:
            primed = True
    else:
        return "primed already"
コード例 #9
0
 def __init__(self):
     self.adapter = pygatt.BGAPIBackend()
     self.adapter.start()
     self.prune = True  # len(sys.argv) > 1 and "-prune" in sys.argv
     self.thread = True
     self.receive_thread = threading.Thread(target=self.receive_loop)
     self.receive_thread.start()
     self.discover_thread = threading.Thread(target=self.ble_discover_loop)
     self.discover_thread.start()
     self.is_recording = False
     self.connected_devices = {}
コード例 #10
0
ファイル: BLE.py プロジェクト: AndreLYL/BLE_Device
    def BLE_connection_setup(self):
        self.adapter = pygatt.BGAPIBackend(serial_port=self.BLE_COM_PORT)

        # Enable logging to get debug information
        if self.logging_enable:
            logging.basicConfig()
            logging.getLogger('pygatt').setLevel(logging.DEBUG)

        self.adapter.start()
        device_list = self.adapter.scan(timeout=5)
        print("Device List:")
        print(device_list)
        self.device = self.adapter.connect(self.BLE_MAC, timeout=20)
コード例 #11
0
 def __init__(self):
     """
     Initialize Bluetooth Parameters
     If using the bluetooth dongle, then use BGAPIBackend, otherwise use Gattool Backend for pygatt.
     """
     self.adapter = pygatt.BGAPIBackend()
     self.adapter.start()
     """If prune is true, then it should only show neurostimulator devices, else it shows all devices"""
     self.prune = True  # len(sys.argv) > 1 and "-prune" in sys.argv
     self.thread = True
     self.receive_thread = threading.Thread(target=self.receive_loop)
     self.receive_thread.start()
     self.discover_thread = threading.Thread(target=self.ble_discover_loop)
     self.discover_thread.start()
     self.is_recording = False
     self.connected_devices = {}
コード例 #12
0
ファイル: muse.py プロジェクト: kowalej/muse-lsl
    def connect(self, interface=None, backend='auto'):
        """Connect to the device"""
        try:
            if self.backend == 'bluemuse':
                print('Starting BlueMuse.')
                subprocess.call('start bluemuse:', shell=True)

            else:
                if self.backend == 'gatt':
                    self.interface = self.interface or 'hci0'
                    self.adapter = pygatt.GATTToolBackend(self.interface)
                else:
                    self.adapter = pygatt.BGAPIBackend(
                        serial_port=self.interface)

                self.adapter.start()
                self.device = self.adapter.connect(self.address)

                # subscribes to EEG stream
                if self.enable_eeg:
                    self._subscribe_eeg()

                if self.enable_control:
                    self._subscribe_control()

                if self.enable_telemetry:
                    self._subscribe_telemetry()

                if self.enable_acc:
                    self._subscribe_acc()

                if self.enable_gyro:
                    self._subscribe_gyro()

                self.last_timestamp = self.time_func()

            return True

        except (pygatt.exceptions.NotConnectedError, pygatt.exceptions.NotificationTimeout):
            print('Connection to', self.address, 'failed')
            return False
コード例 #13
0
    def BLE_init(self):
        adapter = pygatt.BGAPIBackend(serial_port=self.BLE_COM_PORT)
        if self.logging_enable:
            logging.basicConfig()
            logging.getLogger('pygatt').setLevel(logging.DEBUG)

        try:
            adapter.start()
            device_list = adapter.scan(timeout=5)
            print("Device List:")
            print(device_list)

            try:
                device = adapter.connect(self.BLE_MAC, timeout=20)

            except:
                print("Couldn't connecting to device, retrying...")
                device = adapter.connect(self.BLE_MAC, timeout=20)
        finally:
            print("BLE device sucessfully connected!")
        return adapter, device
コード例 #14
0
def main():
    # init control node
    rospy.init_node('strength1', anonymous=False)
    forca_msg = Int8()
    stre = strength.Strength()
    adapter = pygatt.BGAPIBackend()
    #adapter = pygatt.GATTToolBackend()
    YOUR_DEVICE_ADDRESS = "C2:2F:AE:9E:AB:D0"
    #YOUR_DEVICE_ADDRESS = "FF:A6:B9:57:F6:DC"
    ADDRESS_TYPE = pygatt.BLEAddressType.random
    adapter.start()
    print("connecting")
    device = adapter.connect(YOUR_DEVICE_ADDRESS, address_type=ADDRESS_TYPE)
    print("connected")
    pub = {}
    pub['strength1'] = rospy.Publisher('strength1', Int8, queue_size=10)

    while not rospy.is_shutdown():
        msg_notify = stre.notify(device)
        msg_strength = int(msg_notify[4] + msg_notify[5], 16)
        forca_msg.data = msg_strength
        print('Received data: {} forca {} '.format(msg_notify, msg_strength))
        pub['strength1'].publish(forca_msg)
    adapter.stop()