Adding in context manager for Connection and Peer classes
* Connection implements async context manager to disconnect when
context is left
* The Connection only calls disconnect if the context manager exits
without an exception
* Peer implements async context manager to discover when entering the
context
* Device.connect_as_gatt implements an async context manager to nest the
connection and peer context managers
* Added HCI_StatusError that can be raised when a HCI Command Status
event is received that doesn't show "PENDING" as status
* Added Connection.sustain to wait for a timeout or disconnect
* Peer.sustain also maps to Connectin.sustain
* Updated battery_client.py to use .connect_as_gatt and .sustain
* Updated heart_rate_client.py to use .connect_as_gatt and .sustain
diff --git a/examples/battery_client.py b/examples/battery_client.py
index 297e9f4..f545f12 100644
--- a/examples/battery_client.py
+++ b/examples/battery_client.py
@@ -43,28 +43,24 @@
# Connect to the peer
target_address = sys.argv[2]
print(f'=== Connecting to {target_address}...')
- connection = await device.connect(target_address)
- print(f'=== Connected to {connection}')
+ async with device.connect_as_gatt(target_address) as peer:
+ print(f'=== Connected to {peer}')
+ battery_service = peer.create_service_proxy(BatteryServiceProxy)
- # Discover the Battery Service
- peer = Peer(connection)
- print('=== Discovering Battery Service')
- battery_service = await peer.discover_service_and_create_proxy(BatteryServiceProxy)
+ # Check that the service was found
+ if not battery_service:
+ print('!!! Service not found')
+ return
- # Check that the service was found
- if not battery_service:
- print('!!! Service not found')
- return
+ # Subscribe to and read the battery level
+ if battery_service.battery_level:
+ await battery_service.battery_level.subscribe(
+ lambda value: print(f'{color("Battery Level Update:", "green")} {value}')
+ )
+ value = await battery_service.battery_level.read_value()
+ print(f'{color("Initial Battery Level:", "green")} {value}')
- # Subscribe to and read the battery level
- if battery_service.battery_level:
- await battery_service.battery_level.subscribe(
- lambda value: print(f'{color("Battery Level Update:", "green")} {value}')
- )
- value = await battery_service.battery_level.read_value()
- print(f'{color("Initial Battery Level:", "green")} {value}')
-
- await hci_source.wait_for_termination()
+ await peer.sustain()
# -----------------------------------------------------------------------------