This repository has been archived by the owner on Nov 3, 2020. It is now read-only.
/
list_uarts.py
60 lines (50 loc) · 2.46 KB
/
list_uarts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Search for BLE UART devices and list all that are found.
# Author: Tony DiCola
import atexit
import time
import Adafruit_BluefruitLE
from Adafruit_BluefruitLE.services import UART
# Get the BLE provider for the current platform.
ble = Adafruit_BluefruitLE.get_provider()
# Main function implements the program logic so it can run in a background
# thread. Most platforms require the main thread to handle GUI events and other
# asyncronous events like BLE actions. All of the threading logic is taken care
# of automatically though and you just need to provide a main function that uses
# the BLE provider.
def main():
# Clear any cached data because both bluez and CoreBluetooth have issues with
# caching data and it going stale.
ble.clear_cached_data()
# Get the first available BLE network adapter and make sure it's powered on.
adapter = ble.get_default_adapter()
adapter.power_on()
print('Using adapter: {0}'.format(adapter.name))
# Start scanning with the bluetooth adapter.
adapter.start_scan()
# Use atexit.register to call the adapter stop_scan function before quiting.
# This is good practice for calling cleanup code in this main function as
# a try/finally block might not be called since this is a background thread.
atexit.register(adapter.stop_scan)
print('Searching for UART devices...')
print('Press Ctrl-C to quit (will take ~30 seconds on OSX).')
# Enter a loop and print out whenever a new UART device is found.
known_uarts = set()
while True:
# Call UART.find_devices to get a list of any UART devices that
# have been found. This call will quickly return results and does
# not wait for devices to appear.
found = set(UART.find_devices())
# Check for new devices that haven't been seen yet and print out
# their name and ID (MAC address on Linux, GUID on OSX).
new = found - known_uarts
for device in new:
print('Found UART: {0} [{1}]'.format(device.name, device.id))
known_uarts.update(new)
# Sleep for a second and see if new devices have appeared.
time.sleep(1.0)
# Initialize the BLE system. MUST be called before other BLE calls!
ble.initialize()
# Start the mainloop to process BLE events, and run the provided function in
# a background thread. When the provided main function stops running, returns
# an integer status code, or throws an error the program will exit.
ble.run_mainloop_with(main)