title: Use Python and bleak library to notify a bluetooth GATT device, but the result is not stable
body: <p>I try to use Python to control some BLE GATT devices.
  I find Bleak (<a href="https://bleak.readthedocs.io/en/latest/" rel="nofollow noreferrer">https://bleak.readthedocs.io/en/latest/</a>) this library to communicate with GATT device.</p>
  <p>When I use it, most of the time it works really well.</p>
  <p>But once I try to communicate with a BLE GATT medical equipment, I found I can't always notify with this equipment.</p>
  <p>Here is my code, I just do a little changes from Bleak's github example：(<a href="https://github.com/hbldh/bleak/blob/develop/examples/enable_notifications.py" rel="nofollow noreferrer">https://github.com/hbldh/bleak/blob/develop/examples/enable_notifications.py</a>)</p>
  <pre><code>import asyncio
  import logging
  
  from bleak import discover
  from bleak import BleakClient
  
  devices_dict = {}
  devices_list = []
  receive_data = []
  
  #To discover BLE devices nearby 
  async def scan():
      dev = await discover()
      for i in range(0,len(dev)):
          #Print the devices discovered
          print(&quot;[&quot; + str(i) + &quot;]&quot; + dev[i].address,dev[i].name,dev[i].metadata[&quot;uuids&quot;])
          #Put devices information into list
          devices_dict[dev[i].address] = []
          devices_dict[dev[i].address].append(dev[i].name)
          devices_dict[dev[i].address].append(dev[i].metadata[&quot;uuids&quot;])
          devices_list.append(dev[i].address)
  
  #An easy notify function, just print the recieve data
  def notification_handler(sender, data):
      print(', '.join('{:02x}'.format(x) for x in data))
  
  async def run(address, debug=False):
      log = logging.getLogger(__name__)
      if debug:
          import sys
  
          log.setLevel(logging.DEBUG)
          h = logging.StreamHandler(sys.stdout)
          h.setLevel(logging.DEBUG)
          log.addHandler(h)
  
      async with BleakClient(address) as client:
          x = await client.is_connected()
          log.info(&quot;Connected: {0}&quot;.format(x))
  
          for service in client.services:
              log.info(&quot;[Service] {0}: {1}&quot;.format(service.uuid, service.description))
              for char in service.characteristics:
                  if &quot;read&quot; in char.properties:
                      try:
                          value = bytes(await client.read_gatt_char(char.uuid))
                      except Exception as e:
                          value = str(e).encode()
                  else:
                      value = None
                  log.info(
                      &quot;\t[Characteristic] {0}: (Handle: {1}) ({2}) | Name: {3}, Value: {4} &quot;.format(
                          char.uuid,
                          char.handle,
                          &quot;,&quot;.join(char.properties),
                          char.description,
                          value,
                      )
                  )
                  for descriptor in char.descriptors:
                      value = await client.read_gatt_descriptor(descriptor.handle)
                      log.info(
                          &quot;\t\t[Descriptor] {0}: (Handle: {1}) | Value: {2} &quot;.format(
                              descriptor.uuid, descriptor.handle, bytes(value)
                          )
                      )
  
                  #Characteristic uuid
                  CHARACTERISTIC_UUID = &quot;put your characteristic uuid&quot;
  
                  await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
                  await asyncio.sleep(5.0)
                  await client.stop_notify(CHARACTERISTIC_UUID)
  
  if __name__ == &quot;__main__&quot;:
      print(&quot;Scanning for peripherals...&quot;)
  
      #Build an event loop
      loop = asyncio.get_event_loop()
      #Run the discover event
      loop.run_until_complete(scan())
  
      #let user chose the device
      index = input('please select device from 0 to ' + str(len(devices_list)) + &quot;:&quot;)
      index = int(index)
      address = devices_list[index]
      print(&quot;Address is &quot; + address)
  
      #Run notify event
      loop = asyncio.get_event_loop()
      loop.set_debug(True)
      loop.run_until_complete(run(address, True))
  </code></pre>
  <p>In most situation, this code can work well as <a href="https://i.stack.imgur.com/GBVfS.png" rel="nofollow noreferrer">this image</a>.</p>
  <p>But sometimes (about 25% ratio), this problem just happened：</p>
  <pre><code>[0]08:6B:D7:12:F1:33 Nonin3150_502892837['uuid']
  [1]1D:BD:4A:69:8B:AB Unknown []
  [2]73:15:CD:47:AF:08 Unknown []
  [3]40:4E:36:5B:8D:1B HTC BS 1BBDB9 ['uuid']
  [4]6B:FB:E5:DD:7F:4E Unknown []
  [5]69:A7:87:23:5C:7C Unknown []
  please select device from 0 to 6:0
  Address is 08:6B:D7:12:F1:33
  Traceback (most recent call last):
    File &quot;D:/Bletest/nonin_test.py&quot;, line 91, in &lt;module&gt;
      loop.run_until_complete(run(address, True))
    File &quot;C:\Users\rizal\AppData\Local\Programs\Python\Python37\lib\asyncio\base_events.py&quot;, line 579, in run_until_complete
      return future.result()
    File &quot;D:/Bletest/nonin_test.py&quot;, line 36, in run
      async with BleakClient(address) as client:
    File &quot;C:\Users\rizal\AppData\Local\Programs\Python\Python37\lib\site-packages\bleak\backends\client.py&quot;, line 60, in __aenter__
      await self.connect()
    File &quot;C:\Users\rizal\AppData\Local\Programs\Python\Python37\lib\site-packages\bleak\backends\dotnet\client.py&quot;, line 154, in connect
      &quot;Device with address {0} was not found.&quot;.format(self.address)
  bleak.exc.BleakError: Device with address 08:6B:D7:12:F1:33 was not found.
  
  Process finished with exit code 1
  </code></pre>
  <p>I have no idea why the program can discover this equipment, but can't notify with it.</p>
  <p>Is this my code's problem, or it may caused by this equipment's program flow?</p>