Exemple #1
0
    def get_name(self, i):
        print('--------------------------------------------------')
        logging.debug('Type: {} - Address: {}', self.type, utils.decode_mac(self.address))
        if self.connect():
            time.sleep(1)
            if self.read_data(0x0003):
                try:
                    self.name = self.char_data.decode("utf-8")
                    self.name = self.name[:self.name.find('\x00')]  # drop trailing zeroes
                    logging.debug('Name: {} - Length: {}', self.name, len(self.name))
                except Exception as e:
                    utils.log_error_to_file('ERROR: setup ' + utils.decode_mac(self.address) + ' - ' + str(e))

            self.disconnect()
Exemple #2
0
 def connect(self, mswait=2000, type=0):
     # Connect to the device at self.address
     count = 0
     while not self.connected and count < 60000:
         logging.info('Trying to connect to {}...', utils.decode_mac(self.address))
         try:
             self.bt.gap_connect(type, self.address)
         except Exception as e:
             utils.log_error_to_file('ERROR: connect to ' + utils.decode_mac(self.address) + ' - ' + str(e))
         now = time.ticks_ms()
         while time.ticks_diff(time.ticks_ms(), now) < mswait:
             if self.connected:
                 break
         count += mswait
     return self.connected
Exemple #3
0
    def disconnect(self):
        logging.info('Disconnecting...')
        try:
            conn = self.bt.gap_disconnect(self.conn_handle)
        except Exception as e:
            utils.log_error_to_file('ERROR: disconnect from ' + utils.decode_mac(self.address) + ' - ' + str(e))

        # Returns false on timeout
        timer = 0
        while self.connected:
            # print('.', end='')
            time.sleep(1)
            timer += 1
            if timer > 60:
                return False
        return True
Exemple #4
0
    def read_data(self, value_handle):
        self.read_flag = False

        logging.info('Reading data...')
        try:
            self.bt.gattc_read(self.conn_handle, value_handle)
        except Exception as e:
            utils.log_error_to_file('ERROR: read from ' + utils.decode_mac(self.address) + ' - ' + str(e))
            return False

        # Returns false on timeout
        timer = 0
        while not self.read_flag:
            # print('.', end='')
            time.sleep(1)
            timer += 1
            if timer > 60:
                return False
        return True
Exemple #5
0
    def write_data(self, value_handle, data):
        self.write_flag = False
        self.write_status = -1

        # Checking for connection before write
        self.connect()
        logging.debug('Writing data...')
        try:
            self.bt.gattc_write(self.conn_handle, value_handle, data, 1)
        except Exception as e:
            utils.log_error_to_file('ERROR: write to ' + utils.decode_mac(self.address) + ' - ' + str(e))
            return False

        # Returns false on timeout
        timer = 0
        while not self.write_flag:
            # print('.', end='')
            time.sleep(1)
            timer += 1
            if timer > 60:
                return False
        return self.write_status == 0
Exemple #6
0
    def bt_irq(self, event, data):
        if event == _IRQ_SCAN_RESULT:
            # A single scan result.
            addr_type, addr, connectable, rssi, adv_data = data
            if addr_type == 0:
                logging.debug('Address type: {} - Address: {}', addr_type, utils.decode_mac(addr))
                if not self.address_already_present(bytes(addr)):
                    self.addresses[self.device_index] = (self.device_index, addr_type, bytes(addr), DEVICE_NAME_PLACEHOLDER, 0)
                    self.device_index += 1
                
        elif event == _IRQ_SCAN_COMPLETE:
            # Scan duration finished or manually stopped.
            logging.info('Scan complete')
            self.scan_complete = True
            
        elif event == _IRQ_PERIPHERAL_CONNECT:
            logging.debug('Peripheral connected.')
            self.conn_handle, _, _, = data
            self.connected = True
            
        if event == _IRQ_CENTRAL_CONNECT:
            # A central has connected to this peripheral.
            self.conn_handle, addr_type, addr = data
            logging.debug('A central has connected to this peripheral.')
            logging.debug('Connection handle: {} - Address type: {} - Address: {}', self.conn_handle, addr_type, addr)

        elif event == _IRQ_CENTRAL_DISCONNECT:
            # A central has disconnected from this peripheral.
            self.conn_handle, addr_type, addr = data
            logging.debug('A central has disconnected from this peripheral.')
            logging.debug('Connection handle: {} - Address type: {} - Address: {}', self.conn_handle, addr_type, addr)

        elif event == _IRQ_GATTS_WRITE:
            # A central has written to this characteristic or descriptor.
            self.conn_handle, attr_handle = data
            logging.debug('A central has written to this characteristic or descriptor.')
            logging.debug('Connection handle: {} - Attribute handle: {}', self.conn_handle, attr_handle)

        elif event == _IRQ_GATTS_READ_REQUEST:
            # A central has issued a read. Note: this is a hard IRQ.
            # Return None to deny the read.
            # Note: This event is not supported on ESP32.
            self.conn_handle, attr_handle = data
            
        elif event == _IRQ_PERIPHERAL_DISCONNECT:
            # Connected peripheral has disconnected.
            self.conn_handle, addr_type, addr = data
            logging.debug('Peripheral disconnected.')
            logging.debug('Connection handle: {} - Address type: {} - Address: {}', self.conn_handle, addr_type, utils.decode_mac(addr))
            self.connected = False
            # print('Set connect flag', self.connected)
            
        elif event == _IRQ_GATTC_SERVICE_RESULT:
            # Called for each service found by gattc_discover_services().
            self.conn_handle, start_handle, end_handle, uuid = data
            logging.debug('Called for each service found by gattc_discover_services().')
            logging.debug('Connection handle: {} - Start handle: {} - End handle: {} - UUID: {}', self.conn_handle, start_handle, end_handle, uuid)

        elif event == _IRQ_GATTC_CHARACTERISTIC_RESULT:
            # Called for each characteristic found by gattc_discover_services().
            self.conn_handle, def_handle, value_handle, properties, uuid = data
            logging.debug('Called for each characteristic found by gattc_discover_services().')
            logging.debug('Connection handle: {} - Def handle: {} - Value handle: {} - Properties: {} - UUID: {}', self.conn_handle, def_handle, value_handle, properties, uuid)
            # print('Value handle {:02x}'.format(value_handle))
            # characteristics[self.index] = value_handle
            # self.index += 1
            
        elif event == _IRQ_GATTC_DESCRIPTOR_RESULT:
            # Called for each descriptor found by gattc_discover_descriptors().
            conn_handle, dsc_handle, uuid = data
            logging.debug('Called for each descriptor found by gattc_discover_descriptors().')
            logging.debug('Connection handle: {} - Dsc handle: {} - UUID: {}', conn_handle, dsc_handle, uuid)

        elif event == _IRQ_GATTC_READ_RESULT:
            # A gattc_read() has completed.
            conn_handle, value_handle, char_data = data
            logging.debug('A gattc_read() has completed.')
            logging.debug('Connection handle: {} - Value handle: {} - Char data: {}', conn_handle, value_handle, char_data)

            for b in range(len(char_data)):
                self.char_data[b] = char_data[b]
                
            self.read_flag = True

        elif event == _IRQ_GATTC_WRITE_STATUS:
            # A gattc_write() has completed.
            self.conn_handle, value_handle, status = data
            logging.debug('A gattc_write() has completed - status.')
            logging.debug('Connection handle: {} - Value handle: {} - Status: {}', self.conn_handle, value_handle, status)
            self.write_flag = True
            self.write_status = status
            
        elif event == _IRQ_GATTC_NOTIFY:
            # A peripheral has sent a notify request.
            self.conn_handle, value_handle, notify_data = data
            logging.debug('A peripheral has sent a notify request.')
            logging.debug('Connection handle: {} - Value handle: {} - Notify data: {}', self.conn_handle, value_handle, notify_data)
            for b in range(len(notify_data)):
                self.notify_data[b] = notify_data[b]
            
            self.notify_flag = True
            
        elif event == _IRQ_GATTC_INDICATE:
            # A peripheral has sent an indicate request.
            self.conn_handle, value_handle, self.notify_data = data
            logging.debug('A peripheral has sent an indicate request.')
            logging.debug('Connection handle: {} - Value handle: {} - Notify data: {}', self.conn_handle, value_handle, self.notify_data)
Exemple #7
0
connect_wifi()
update_time()
cleanup()

try:
    mqtt_client = connect_mqtt()
except OSError as e:
    restart_and_reconnect()

myBLE = ble.Ble()
myBLE.setup(scan_for_devices, devices_list)

for a in myBLE.addresses:
    device_index, type, address, name, last_read = a
    logging.info('Device found - Type: {} - Address: {} - Name: {}', type,
                 utils.decode_mac(address), name)

last_time_update = utils.timestamp('day')
last_cleanup = utils.timestamp('day')
last_scan = time.time()
while True:
    today = utils.timestamp('day')
    current_time = time.time()

    # Update the RTC once a day
    if today != last_time_update:
        update_time()
        last_time_update = today

    # Cleanup filesystem once a day
    if today != last_cleanup: