0

`I am trying to scan for devices advertising the UART service using Micropython on esp32. but I get AttributeError: 'NoneType' object has no attribute 'scan'

below is my code:

# Initialize and enable the BLE radio.
ble = ubluetooth.BLE()
ble.active(True)

# Create a BLE scanner object.
scanner = ble.gap_scan(10, 30000, 30000)

# Scan for devices advertising the UART service.
print('Scanning for devices advertising the UART service...')
devices = scanner.scan(10)

# Connect to the first device with the matching UART service UUID.
for device in devices:
    for advertised_service in device.services:
        if advertised_service.uuid == UART_SERVICE_UUID:
            # Connect to the device.
            print(f'Connecting to device {device.name}...')
            connection = ble.connect(device)
            # Wait for the connection to be established.
            while not connection.is_connected:
                pass
            print('Connection established!')
            # Stop scanning.
            scanner.stop()
            break
    if connection.is_connected:
        break

`

Miracle
  • 1
  • 2
  • 1
    Does this answer your question? [Why do I get AttributeError: 'NoneType' object has no attribute 'something'?](https://stackoverflow.com/questions/8949252/why-do-i-get-attributeerror-nonetype-object-has-no-attribute-something) – Ulrich Eckhardt Jan 01 '23 at 21:31

1 Answers1

0

Your code reads:

# Create a BLE scanner object.
scanner = ble.gap_scan(10, 30000, 30000)

# Scan for devices advertising the UART service.
print('Scanning for devices advertising the UART service...')
devices = scanner.scan(10)

You're using the gap_scan() method incorrectly. According to the documentation, when the scanner detects a device it calls the callback function. You're getting an error because gap_scan() doesn't return anything, which is consistent with the documentation.

You need to register an event handler in order to see the results of a scan. So:

def ble_callback_handler(event, data):
    if event == _IRQ_SCAN_RESULT:
        # A single scan result. Do whatever you need with this
        addr_type, addr, adv_type, rssi, adv_data = data
    elif event == _IRQ_SCAN_DONE:
        # Scan duration finished or manually stopped.

# register a callback handler
ble.irq(ble_callback_handler)

# start scanning
ble.gap_scan(10, 30000, 30000)
romkey
  • 6,218
  • 3
  • 16
  • 12