Created
          August 15, 2016 14:05 
        
      - 
      
 - 
        
Save bisko/fa4ba41d9826fa411da55304f3fbf6d2 to your computer and use it in GitHub Desktop.  
    Python scan and autoconnect to devices
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | import dbus | |
| import bluetooth | |
| import sys | |
| import subprocess | |
| # Hardcoded devices, order is the priority | |
| devices = ["C8:85:50:88:30:ED", "FC:64:BA:0E:C0:10"] | |
| has_connected = False | |
| bus = dbus.SystemBus() | |
| manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") | |
| objects = manager.GetManagedObjects() | |
| for path in objects.keys(): | |
| # print("[ %s ]" % (path)) | |
| interfaces = objects[path] | |
| for interface in interfaces.keys(): | |
| if interface != "org.bluez.Device1": | |
| continue | |
| properties = interfaces[interface] | |
| for key in properties.keys(): | |
| #print(" %s = %s" % (key, properties[key])) | |
| if key == "Connected" and properties[key] == 1: | |
| print("DEVICE IS CONNECTED: %s" % properties["Address"]) | |
| has_connected = True | |
| if has_connected == True: | |
| print("Device already connected") | |
| sys.exit() | |
| try: | |
| nearby = bluetooth.discover_devices(duration=5, lookup_names=False) | |
| found_devices = [] | |
| if len(nearby) > 0: | |
| for addr in nearby: | |
| found_devices.append(addr) | |
| if len(found_devices) > 0: | |
| for dev in devices: | |
| if dev in found_devices: | |
| print("Found device: %s\n" % dev) | |
| device_connect = bus.get_object('org.bluez', '/org/bluez/hci0/dev_%s' % dev.replace(':', '_')) | |
| interface = dbus.Interface(device_connect, 'org.bluez.Device1') | |
| interface.Connect() | |
| break; | |
| except: | |
| print("Got an exception, restarting bluetooth subsystem") | |
| systemd1 = bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1') | |
| manager = dbus.Interface(systemd1, 'org.freedesktop.systemd1.Manager') | |
| job = manager.RestartUnit('bluetooth.service', 'fail') | |
| subprocess.call(['hciconfig', 'hci0', 'down']) | |
| subprocess.call(['hciconfig', 'hci0', 'up']) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment