#!/usr/bin/python import sys import traceback # Used to get methods and stuff import dbus from time import sleep from xml.etree import ElementTree priorityPhone="dev_DC_74_A8_ED_40_43" controller="hci0" print "Auto connect started! Setting up bus" bus=dbus.SystemBus() def getDevices(bus): devices=[] obj = bus.get_object('org.bluez', '/org/bluez/'+controller) iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable') xml_string = iface.Introspect() for child in ElementTree.fromstring(xml_string): if child.tag == 'node' and child.attrib['name'] != priorityPhone: devices.append(child.attrib['name']) return devices def getDevice(bus): obj = bus.get_object('org.bluez', '/org/bluez/'+controller) iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable') xml_string = iface.Introspect() for child in ElementTree.fromstring(xml_string): if child.tag == 'node': return child.attrib['name'] def getPlayer(bus, device): obj = bus.get_object('org.bluez', '/org/bluez/'+controller+'/'+device) iface = dbus.Interface(obj, 'org.freedesktop.DBus.Introspectable') xml_string = iface.Introspect() for child in ElementTree.fromstring(xml_string): if child.tag == 'node': if child.attrib['name'].startswith("player"): return child.attrib['name'] print "Scanning for devices on controller: " + controller devices=getDevices(bus) print(devices) if not devices: print 'No connected devices' else: connectedToDevice=False for device in devices: deviceObj = bus.get_object('org.bluez', '/org/bluez/'+controller+'/'+device) print device deviceInterface = dbus.Interface(deviceObj, 'org.bluez.Device1') devInt = dbus.Interface(deviceObj, dbus_interface='org.freedesktop.DBus.Properties') # I use this to get properties (I don't know another way) mcAll = devInt.GetAll('org.bluez.Device1') if mcAll["Connected"]==True: print("Already connected to device: " + device) connectedToDevice=True if connectedToDevice==False: print "Connecting to devices" for device in devices: if not device: print 'No such device' else: print "Attempting to connect to " + device deviceObj = bus.get_object('org.bluez', '/org/bluez/'+controller+'/'+device) deviceInterface = dbus.Interface(deviceObj, 'org.bluez.Device1') devInt = dbus.Interface(deviceObj, dbus_interface='org.freedesktop.DBus.Properties') # I use this to get properties (I don't know another way) try: deviceInterface.Connect() print "Connected to device " + device sleep(2) bus=dbus.SystemBus() player=getPlayer(bus, device) if not player: print 'No player could be found for device ' + device print 'Player path: /org/bluez/'+controller+'/'+device+'/'+player print "Connecting to player and sending play commend" deviceObj = bus.get_object('org.bluez', '/org/bluez/'+controller+'/'+device+'/'+player) deviceInterface = dbus.Interface(deviceObj, 'org.bluez.MediaPlayer1') deviceInterface.Play() print "Play command sent!" break except Exception, e: print(str(traceback.format_exc())) print("Failed! Error: " + str(e)) print "Auto connect complete."