예제 #1
0
    def _irq(self, event, data):

        if event == _IRQ_CENTRAL_CONNECT:
            conn_handle, _, _, = data
            self._connections.add(conn_handle)
        elif event == _IRQ_CENTRAL_DISCONNECT:
            conn_handle, _, _, = data
            self._connections.remove(conn_handle)

            self._advertise()

        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data
            if adv_type in (
                    _ADV_IND,
                    _ADV_DIRECT_IND,
            ) and _ENV_SENSE_UUID in decode_services(adv_data):

                self._addr_type = addr_type
                self._addr = bytes(
                    addr
                )  # Note: addr buffer is owned by caller so need to copy it.

                k = decode_name(adv_data) or "?"
                print("Found: " + k + " RSSI = " + str(rssi))
                print("I am: " + self.name + " RSSI = " + str(rssi))
                x = rssi * -1
                if x > 60:
                    print("LED ON")
                    p = machine.Pin(2, machine.Pin.OUT)
                    p.on()
                else:
                    print("LED OFF")
                    p = machine.Pin(2, machine.Pin.OUT)
                    p.off()
                self._ble.gap_scan(None)
                print("stopped. Scanning again")
                self._ble.gap_scan(2000, 30000, 30000)
예제 #2
0
    def _irq(self, event, data):
        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data
            if adv_type in (
                    _ADV_IND, _ADV_DIRECT_IND
            ) and _UART_SERVICE_UUID in decode_services(adv_data):
                # Found a potential device, remember it and stop scanning.
                self._addr_type = addr_type
                self._addr = bytes(
                    addr
                )  # Note: addr buffer is owned by caller so need to copy it.
                self._name = decode_name(adv_data) or "?"
                self._ble.gap_scan(None)

        elif event == _IRQ_SCAN_DONE:
            if self._scan_callback:
                if self._addr:
                    # Found a device during the scan (and the scan was explicitly stopped).
                    self._scan_callback(self._addr_type, self._addr,
                                        self._name)
                    self._scan_callback = None
                else:
                    # Scan timed out.
                    self._scan_callback(None, None, None)

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # Connect successful.
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                self._conn_handle = conn_handle
                self._ble.gattc_discover_services(self._conn_handle)

        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # If it was initiated by us, it'll already be reset.
                self._reset()

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            conn_handle, start_handle, end_handle, uuid = data
            print("service", data)
            if conn_handle == self._conn_handle and uuid == _UART_SERVICE_UUID:
                self._start_handle, self._end_handle = start_handle, end_handle

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete.
            if self._start_handle and self._end_handle:
                self._ble.gattc_discover_characteristics(
                    self._conn_handle, self._start_handle, self._end_handle)
            else:
                print("Failed to find uart service.")

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            conn_handle, def_handle, value_handle, properties, uuid = data
            if conn_handle == self._conn_handle and uuid == _UART_RX_CHAR_UUID:
                self._rx_handle = value_handle
            if conn_handle == self._conn_handle and uuid == _UART_TX_CHAR_UUID:
                self._tx_handle = value_handle

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete.
            if self._tx_handle is not None and self._rx_handle is not None:
                # We've finished connecting and discovering device, fire the connect callback.
                if self._conn_callback:
                    self._conn_callback()
            else:
                print("Failed to find uart rx characteristic.")

        elif event == _IRQ_GATTC_WRITE_DONE:
            conn_handle, value_handle, status = data
            print("TX complete")

        elif event == _IRQ_GATTC_NOTIFY:
            conn_handle, value_handle, notify_data = data
            if conn_handle == self._conn_handle and value_handle == self._tx_handle:
                if self._notify_callback:
                    self._notify_callback(notify_data)
예제 #3
0
    def _irq(self, event, data):
        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data
            if adv_type in (_ADV_IND, _ADV_DIRECT_IND
                            ) and _ENV_SENSE_UUID in decode_services(adv_data):
                # Found a potential device, remember it and stop scanning.
                self._addr_type = addr_type
                self._addr = bytes(
                    addr
                )  # Note: addr buffer is owned by caller so need to copy it.
                self._name = decode_name(adv_data) or "?"
                self._ble.gap_scan(None)

        elif event == _IRQ_SCAN_DONE:
            if self._scan_callback:
                if self._addr:
                    # Found a device during the scan (and the scan was explicitly stopped).
                    self._scan_callback(self._addr_type, self._addr,
                                        self._name)
                    self._scan_callback = None
                else:
                    # Scan timed out.
                    self._scan_callback(None, None, None)

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # Connect successful.
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                self._conn_handle = conn_handle
                self._ble.gattc_discover_services(self._conn_handle)

        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # If it was initiated by us, it'll already be reset.
                self._reset()

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            conn_handle, start_handle, end_handle, uuid = data
            if conn_handle == self._conn_handle and uuid == _ENV_SENSE_UUID:
                self._start_handle, self._end_handle = start_handle, end_handle

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete.
            if self._start_handle and self._end_handle:
                self._ble.gattc_discover_characteristics(
                    self._conn_handle, self._start_handle, self._end_handle)
            else:
                print("Failed to find environmental sensing service.")

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            conn_handle, def_handle, value_handle, properties, uuid = data
            if conn_handle == self._conn_handle and uuid == _TEMP_UUID:
                self._value_handle = value_handle

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete.
            if self._value_handle:
                # We've finished connecting and discovering device, fire the connect callback.
                if self._conn_callback:
                    self._conn_callback()
            else:
                print("Failed to find temperature characteristic.")

        elif event == _IRQ_GATTC_READ_RESULT:
            # A read completed successfully.
            conn_handle, value_handle, char_data = data
            if conn_handle == self._conn_handle and value_handle == self._value_handle:
                self._update_value(char_data)
                if self._read_callback:
                    self._read_callback(self._value)
                    self._read_callback = None

        elif event == _IRQ_GATTC_READ_DONE:
            # Read completed (no-op).
            conn_handle, value_handle, status = data

        elif event == _IRQ_GATTC_NOTIFY:
            # The ble_temperature.py demo periodically notifies its value.
            conn_handle, value_handle, notify_data = data
            if conn_handle == self._conn_handle and value_handle == self._value_handle:
                self._update_value(notify_data)
                if self._notify_callback:
                    self._notify_callback(self._value)
예제 #4
0
파일: micro.py 프로젝트: ste7anste7an/ble
    def _irq(self, event, data):
        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data
            if addr == MAC_MICRO:
                print('type:{} addr:{} adv_type: {} rssi:{} data:{}'.format(
                    addr_type, ubinascii.hexlify(addr), adv_type, rssi,
                    ubinascii.hexlify(adv_data)))
                print("service", decode_services(adv_data))
                # if adv_type in (_ADV_IND, _ADV_DIRECT_IND) and _ACC_SERVICE_UUID in decode_services(
                #     adv_data
                # ):
                # Found a potential device, remember it and stop scanning.
                self._addr_type = addr_type
                self._addr = bytes(
                    addr
                )  # Note: addr buffer is owned by caller so need to copy it.
                self._name = decode_name(adv_data) or "?"
                self._ble.gap_scan(None)

        elif event == _IRQ_SCAN_DONE:
            if self._scan_callback:
                if self._addr:
                    # Found a device during the scan (and the scan was explicitly stopped).
                    self._scan_callback(self._addr_type, self._addr,
                                        self._name)
                    self._scan_callback = None
                else:
                    # Scan timed out.
                    self._scan_callback(None, None, None)

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # Connect successful.
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                self._conn_handle = conn_handle
                self._ble.gattc_discover_services(self._conn_handle)

        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # If it was initiated by us, it'll already be reset.
                self._reset()

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            conn_handle, start_handle, end_handle, uuid = data
            print("service", data)
            if conn_handle == self._conn_handle and uuid == _ACC_SERVICE_UUID:
                self._start_handle, self._end_handle = start_handle, end_handle
                #self._ble.gattc_discover_characteristics(self._conn_handle, start_handle, end_handle)

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete.
            if self._start_handle and self._end_handle:
                self._ble.gattc_discover_characteristics(
                    self._conn_handle, self._start_handle, self._end_handle)
            else:
                print("Failed to find uart service.")

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            conn_handle, def_handle, value_handle, properties, uuid = data
            print('gattc_char', data)
            if conn_handle == self._conn_handle and uuid == _ACC_DATA_UUID:
                self._rx_handle = value_handle
                print("_IRQ_GATTC_CHARACTERISTIC_RESULT, handle", value_handle)
                #self._ble.gatts_notify(conn_handle, value_handle )
            # if conn_handle == self._conn_handle and uuid == _UART_TX_CHAR_UUID:
            #     self._tx_handle = value_handle

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete.
            #if self._tx_handle is not None and self._rx_handle is not None:
            if self._rx_handle is not None:
                # We've finished connecting and discovering device, fire the connect callback.
                print("CHARACTERISTIC_DONE")
                self._ble.gattc_discover_descriptors(self._conn_handle,
                                                     self._start_handle,
                                                     self._end_handle)

                if self._conn_callback:
                    self._conn_callback()
            else:
                print("Failed to find uart rx characteristic.")

        elif event == _IRQ_GATTC_DESCRIPTOR_RESULT:
            # Connected device returned a descriptor.
            conn_handle, value_handle, uuid = data
            print('desciptor_result', data)
            if conn_handle == self._conn_handle and uuid == _ACC_DESCR_UUID:
                print("set acc_handle", value_handle)
                self._acc_handle = value_handle

        elif event == _IRQ_GATTC_DESCRIPTOR_DONE:
            print('descriptor done', data)

        elif event == _IRQ_GATTC_WRITE_DONE:
            conn_handle, value_handle, status = data
            print("TX complete")

        elif event == _IRQ_GATTC_NOTIFY:
            print("_IRQ_GATTC_NOTIFY")
            conn_handle, value_handle, notify_data = data
            notify_data = bytes(notify_data)
            print("data:", notify_data)

            if conn_handle == self._conn_handle and value_handle == self._rx_handle:
                if self._notify_callback:
                    self._notify_callback(notify_data)
        elif event == _IRQ_GATTC_READ_RESULT:
            print("_IRQ_GATTC_READ_RESULT")
            # A read completed successfully.
            conn_handle, value_handle, char_data = data
            if conn_handle == self._conn_handle and value_handle == self._value_handle:
                print("READ data", bytes(char_data))

        elif event == _IRQ_GATTC_READ_DONE:
            print("_IRQ_GATTC_READ_DONE")
            # Read completed (no-op).
            conn_handle, value_handle, status = data
    def _irq(self, event, data):
        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data

            #print('============================================================================================')
            mystringaddr= str(ubinascii.hexlify(addr))
            MACadd=(mystringaddr[2:4]).upper()
            MACadd= MACadd + ':' + (mystringaddr[4:6]).upper()
            MACadd= MACadd + ':' + (mystringaddr[6:8]).upper()
            MACadd= MACadd + ':' + (mystringaddr[8:10]).upper()
            MACadd= MACadd + ':' + (mystringaddr[10:12]).upper()
            MACadd= MACadd + ':' + (mystringaddr[12:14]).upper()
            
            isconnectable=''
            if adv_type == 0:
                isconnectable='0x00 - ADV_IND - connectable and scannable undirected advertising '
            elif adv_type == 1:
                isconnectable='0x01 - ADV_DIRECT_IND - connectable directed advertising '
            elif adv_type == 2:
                isconnectable='0x02 - ADV_SCAN_IND - scannable undirected advertising '
            elif adv_type == 3:
                isconnectable='0x03 - ADV_NONCONN_IND - non-connectable undirected advertising '
            elif adv_type == 4:
                isconnectable='0x04 - SCAN_RSP - scan response '
           
            if True: # decode_name(adv_data) == 'iPad de Manu':
                print('type:{} addr:{} connectable type:{} rssi:{} data:{}'.format(addr_type, ubinascii.hexlify(addr), adv_type, rssi, ubinascii.hexlify(adv_data)))
                #print( 'bytes(addr) :', bytes(addr) , 'randomized MAC address: ' , MACadd, isconnectable)
                #print( ' ')
                if len( decode_services(adv_data) )>0 :
                    print(' ......... decode_services:',  decode_services(adv_data) )
                    print(' ............. decode_name:',  decode_name(adv_data) )
                
        
            if adv_type in (_ADV_IND, _ADV_DIRECT_IND) and _UART_SERVICE_UUID in decode_services(adv_data):  # Found a potential device, remember it and stop scanning.
                print(' ****************************************** ')
                print(' * Found a potential phone to connect to. *')
                print(' ****************************************** ')
                print('type:{} addr:{} connectable type:{} rssi:{} data:{}'.format(addr_type, ubinascii.hexlify(addr), adv_type, rssi, ubinascii.hexlify(adv_data)))
                #print( 'bytes(addr) :', bytes(addr) , 'randomized MAC address: ' , MACadd, isconnectable)
                #print( ' ')
                if len( decode_services(adv_data) )>0 :
                    print(' ......... decode_services:',  decode_services(adv_data) )
                    print(' ............. decode_name:',  decode_name(adv_data) )
                print('  ')
                print('  ')
                
                self._addr_type = addr_type
                self._addr = bytes(addr)  # Note: addr buffer is owned by caller so need to copy it.
                self._name = decode_name(adv_data) or "?"
                self._ble.gap_scan(None)

        elif event == _IRQ_SCAN_DONE:
            if self._scan_callback:
                if self._addr:
                    # Found a device during the scan (and the scan was explicitly stopped).
                    self._scan_callback(self._addr_type, self._addr, self._name)
                    self._scan_callback = None
                else:
                    # Scan timed out.
                    self._scan_callback(None, None, None)

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # Connect successful.
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                self._conn_handle = conn_handle
                self._ble.gattc_discover_services(self._conn_handle)

        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # If it was initiated by us, it'll already be reset.
                self._reset()

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            conn_handle, start_handle, end_handle, uuid = data
            print("    ----> Service : ", data)
            if conn_handle == self._conn_handle and uuid == _UART_SERVICE_UUID:
                self._start_handle, self._end_handle = start_handle, end_handle

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete.
            if self._start_handle and self._end_handle:
                self._ble.gattc_discover_characteristics(self._conn_handle, self._start_handle, self._end_handle)
            else:
                print("Failed to find uart service.")

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            conn_handle, def_handle, value_handle, properties, uuid = data
            print('     .........Characteristics: ', def_handle, value_handle, properties, uuid)
            
            if conn_handle == self._conn_handle and uuid == _UART_RX_CHAR_UUID:
                self._rx_handle = value_handle
            if conn_handle == self._conn_handle and uuid == _UART_TX_CHAR_UUID:
                self._tx_handle = value_handle

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete.
            if self._tx_handle is not None or self._rx_handle is not None:       # or was originally and
                # We've finished connecting and discovering device, fire the connect callback.
                print('self._tx_handle = ', self._tx_handle)
                print('self._rx_handle = ', self._rx_handle)
                if self._conn_callback:
                    print('I have reached this point. Yeahhh....')
                    self._conn_callback()
            else:
                print("Failed to find uart rx or tx characteristic.")

        elif event == _IRQ_GATTC_WRITE_DONE:
            conn_handle, value_handle, status = data
            print("TX complete")

        elif event == _IRQ_GATTC_NOTIFY:
            conn_handle, value_handle, notify_data = data
            if conn_handle == self._conn_handle and value_handle == self._tx_handle:
                if self._notify_callback:
                    self._notify_callback(notify_data)
예제 #6
0
    def _irq(self, event, data):
        """
        Interrupt request handler.

        See https://docs.micropython.org/en/latest/library/ubluetooth.html for description.

        Parameters:
            event (int):  interrupt request ID
            data (tuple): event specific data as tuple  
        """
        self._debug("bt_irq - event: {}".format(event), 3)
        
        if event == _IRQ_SCAN_RESULT:
            self._debug("bt irq - scan result", 2)
            # A single scan result.
            addr_type, addr, adv_type, rssi, adv_data = data
            _addr_type = 'Public' if (addr_type == ADDR_TYPE_PUBLIC) else 'Random' 
            _addr = bytes(addr)
            _addr = binascii.hexlify(_addr)
            if adv_type == _ADV_IND:
                _adv_type = 'ADV_IND'
            elif adv_type == _ADV_DIRECT_IND:
                _adv_type = 'ADV_DIRECT_IND'
            elif adv_type == _ADV_SCAN_IND:
                _adv_type = 'ADV_SCAN_IND'
            elif adv_type == _ADV_NONCONN_IND:
                _adv_type = 'ADV_NONCONN_IND'
            else:
                _adv_type = 'SCAN_RSP'
            
            _adv_data = bytes(adv_data)
            _name = decode_name(_adv_data) or "?"
            _services = decode_services(adv_data)
            self._debug('addr_type: {}; addr: {}; adv_type: {}; rssi: {} dBm; name: {}; services: {}'.format(
                _addr_type, _addr, _adv_type, rssi, _name, _services), 1
            )

            if adv_type in (_ADV_IND, _ADV_DIRECT_IND, _ADV_SCAN_RSP) and bytes(addr) == self.search_addr:
                # Found a potential device, remember it and stop scanning.
                self._addr_type = addr_type
                self.rssi = rssi
                self.addr_found = True
                self._addr = bytes(
                    addr
                )  # Note: addr buffer is owned by caller so need to copy it.
                if _name != '?':
                    self.name = _name
                self._debug('Device name: {}'.format(_name), 1)
                self._ble.gap_scan(None)


        elif event == _IRQ_SCAN_DONE:
            self._debug("bt irq - scan done", 2)
            if self._scan_callback:
                if self._addr:
                    # Found a device during the scan (and the scan was explicitly stopped).
                    self._scan_callback(self._addr_type, self._addr, self.name)
                    self._scan_callback = None
                    if AUTO_MODE:
                        self.gap_connect(self._addr_type, self._addr)
                else:
                    # Scan timed out.
                    self._scan_callback(None, None, None)

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # gap_connect() successful.
            self._debug("bt irq - peripheral connect", 2)
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                self._conn_handle = conn_handle
                if self._conn_callback:
                    self._conn_callback()
                    self._conn_callback = None
                if AUTO_MODE:
                    if _DISCOVER_SERVICES:
                        self.discover_services()
                    else:
                        self.read_firmware(callback=self.read_firmware_done)
        
        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # If it was initiated by us, it'll already be reset.
                self._reset()

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            self._debug("bt irq - gattc service result", 2)
            conn_handle, start_handle, end_handle, uuid = data
            
            if conn_handle == self._conn_handle:
                self._debug("{} -> service handle: {}...{}".format(uuid, start_handle, end_handle), 1)
                self.services[str(uuid)] = start_handle, end_handle
                if uuid == self.search_service:
                    self._debug("Wanted service {} has been discovered!".format(self.search_service), 1)
                    self._start_handle = start_handle
                    self._end_handle   = end_handle

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete.
            self._debug("bt irq - gattc service done", 2)
            self.state = S_SERVICE_DONE
            if self._serv_done_callback:
                self._serv_done_callback()
                self._serv_done_callback = None
            if AUTO_MODE:
                if _DISCOVER_CHARACTERISTICS:
                    # Note: In AUTO_MODE _start_handle/_end_handle should have been set according to desired service
                    #       in _IRQ_GATTC_SERVICE_RESULT.
                    if self._start_handle and self._end_handle:
                        self.discover_characteristics(self._start_handle, self._end_handle)
                    else:
                        self._debug("Failed to find gattc service.", 3)
                else:
                    self.read_firmware(callback=self.read_firmware_done)
                    
        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            self._debug("bt irq - gattc characteristic result", 2)
            conn_handle, def_handle, value_handle, properties, uuid = data
            
            if conn_handle == self._conn_handle:
                self._debug("{}; def_handle: {}; value_handle: {}; properties: {}".format(
                    uuid, def_handle, value_handle, properties), 1
                )
                self.characteristics[str(uuid)] = def_handle, value_handle, properties

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete.
            self._debug("bt irq - gattc characteristic done", 2)
            self.state = S_CHARACTERISTIC_DONE
            if self._char_done_callback:
                self._char_done_callback()
                self._char_done_callback = None
            if AUTO_MODE:
                self.read_firmware(callback=self.read_firmware_done)

        elif event == _IRQ_GATTC_READ_RESULT:
            # A read completed successfully.
            self._debug("bt irq - gattc read result", 2)
            conn_handle, value_handle, char_data = data
            if conn_handle == self._conn_handle and value_handle == self._value_handle:
                self._update_value(char_data)
                if self._read_callback:
                    self._read_callback(self._value)
                    self._read_callback = None

        elif event == _IRQ_GATTC_READ_DONE:
            # Read completed (no-op).
            self._debug("bt irq - gattc read done", 2)
            conn_handle, value_handle, status = data
            if AUTO_MODE and self.state == S_READ_FIRMWARE_DONE:
                self.mode_change(self.mode_change_done)

        elif event == _IRQ_GATTC_WRITE_DONE:
            # A gattc_write() has completed.
            # Note: The value_handle will be zero on btstack (but present on NimBLE).
            # Note: Status will be zero on success, implementation-specific value otherwise.
            self._debug("bt irq - gattc write done", 2)
            conn_handle, value_handle, status = data
            if conn_handle == self._conn_handle and value_handle == self._value_handle:
                self._debug("status: {}".format(status), 3)
                if self._write_callback:
                    self._write_callback()
                    self._write_callback = None
                if AUTO_MODE and self.state == S_MODE_CHANGE_DONE:
                    self.read_sensor(callback=self.read_sensor_done)

        elif event == _IRQ_GATTC_NOTIFY:
            self._debug("bt irq - gattc notify", 2)
            
            conn_handle, value_handle, notify_data = data
            if conn_handle == self._conn_handle and value_handle == self._value_handle:
                self._update_value(notify_data)
                if self._notify_callback:
                    self._notify_callback(self._value)
예제 #7
0
    def _irq(self, event, data):
        # print("IRQ", event)
        if event == _IRQ_SCAN_RESULT:
            addr_type, addr, adv_type, rssi, adv_data = data
            if adv_type in (_ADV_IND, _ADV_DIRECT_IND):  # magic??
                name = decode_name(adv_data)
                services = decode_services(adv_data)
                log.debug("Scan found '%s', svcs: %s", name, services)
                # ask the filter callback whether this is our device
                if self._filter_callback(addr_type, addr, name, services):
                    # looks like we found something...
                    self._addr_type = addr_type  # 0=public, 1=randomized
                    self._addr = bytes(
                        addr
                    )  # addr buffer is owned by caller: need to copy it.
                    self._name = decode_name(
                        adv_data) or "?"  # decode_name makes a copy
                    self._ble.gap_scan(None)  # stop scanning

        elif event == _IRQ_SCAN_DONE:
            if self._addr:
                # Found a device during the scan.
                log.debug("Found device, ending scan")
                self._connect()  # connect to the device found
            else:
                # Scan timed out.
                log.info("Scan timed-out")
                self._reset(OSError(errno.ETIMEDOUT))

        elif event == _IRQ_PERIPHERAL_CONNECT:
            # Connect successful.
            conn_handle, addr_type, addr = data
            if addr_type == self._addr_type and addr == self._addr:
                log.debug("Connected %s", data)
                self._conn_handle = conn_handle
                self._ble.gattc_discover_services(
                    self._conn_handle)  # start services discovery

        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Disconnect (either initiated by us or the remote end).
            conn_handle, _, _ = data
            if conn_handle == self._conn_handle:
                # Not reset by us.
                self._reset(OSError(errno.ECONNABORTED))

        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Connected device returned a service.
            conn_handle, start_handle, end_handle, uuid = data
            log.debug("Found service: %s", data)
            if conn_handle == self._conn_handle and uuid in self._svc_uuids:
                # That's a service we need to pay attention to.
                self.services[bluetooth.UUID(uuid)] = BLEService(
                    start_handle, end_handle)

        elif event == _IRQ_GATTC_SERVICE_DONE:
            # Service query complete, fetch characteristics of the services we're looking for.
            conn_handle, status = data
            if conn_handle != self._conn_handle:
                return
            # Start querying for characteristics.
            log.debug("Found %d services, %d to discover", len(self.services),
                      len(self._svc_uuids))
            if not self._discover_chars():
                log.warning("No services to discover?")
                self._reset(OSError(errno.ENOENT))

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Connected device returned a characteristic.
            conn_handle, def_handle, value_handle, properties, uuid = data
            if conn_handle != self._conn_handle:
                return
            log.debug("Found char: %d", data)
            uuid = bluetooth.UUID(uuid)  # make copy.
            char = BLECharacteristic(self, def_handle, value_handle,
                                     properties)
            svc = self.services[self._cur_svc]
            svc.chars[uuid] = char
            self._char_list.append(char)  # queue to discover descriptors
            # fix up end_handle of previous char (yuck!!)
            if self._prev_char:
                self._prev_char._end_handle = def_handle - 1
            self._prev_char = char

        elif event == _IRQ_GATTC_CHARACTERISTIC_DONE:
            # Characteristic query complete, see whether we need to query for more.
            conn_handle, status = data
            if conn_handle != self._conn_handle:
                return
            # fix up end_handle of last char (yuck!!)
            if self._prev_char:
                self._prev_char._end_handle = self.services[
                    self._cur_svc]._end_handle
            self._prev_char = None
            # Query for char's of other services
            if not self._discover_chars():
                # Start querying for descriptors.
                log.debug("Dicovering dscs for %d chars", len(self._char_list))
                if not self._discover_dscs():
                    log.info("Done with discovery")
                    self._cur_svc = None
                    self._cur_char = None
                    self._ready = True
                    self._pending[self.EV_CONN].signal(
                        status)  # TODO: what's status?

        elif event == _IRQ_GATTC_DESCRIPTOR_RESULT:
            # Connected device returned a descriptor.
            conn_handle, value_handle, uuid = data
            if conn_handle != self._conn_handle:
                return
            log.debug("Descriptor: %s", data)
            uuid = bluetooth.UUID(uuid)  # make copy.
            dsc = BLEDescriptor(conn_handle, value_handle)
            self._cur_char.descriptors[uuid] = dsc

        elif event == _IRQ_GATTC_DESCRIPTOR_DONE:
            # Descriptor query complete, see whether we need to query for more.
            conn_handle, status = data
            if conn_handle != self._conn_handle:
                return
            # Continue querying for descriptors.
            if not self._discover_dscs():
                log.info("Done with discovery")
                self._cur_svc = None
                self._cur_char = None
                self._ready = True
                self._pending[self.EV_CONN].signal(
                    status)  # TODO: what's status?

        elif event == _IRQ_GATTC_READ_RESULT:
            # A read completed successfully.
            conn_handle, value_handle, char_data = data
            if conn_handle == self._conn_handle:
                self._pending[value_handle].signal(char_data)
                del self._pending[value_handle]

        elif event == _IRQ_GATTC_WRITE_DONE:
            conn_handle, value_handle, status = data
            if conn_handle == self._conn_handle:
                self._pending[value_handle].signal(
                    status)  # TODO: what's status?
                del self._pending[value_handle]

        elif event == _IRQ_GATTC_NOTIFY:
            conn_handle, value_handle, notify_data = data
            if conn_handle == self._conn_handle:
                self._pending[value_handle].signal(notify_data)