def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Bluetooth Devices Manager")) # initialize bluetooh self.bluetool = Bluetooth() self["actions"] = ActionMap( [ "OkCancelActions", "WizardActions", "ColorActions", "SetupActions", "NumberActions", "MenuActions" ], { "ok": self.keyOK, "cancel": self.keyCancel, "red": self.keyRed, "green": self.keyGreen, "yellow": self.keyYellow, "blue": self.keyBlue, }, -1) self["ConnStatus"] = Label() self["key_red"] = Label(_("Scan")) self["key_green"] = Label(_("Connect")) self["key_yellow"] = Label(_("Disconnect")) self["key_blue"] = Label(_("Paired")) self.devicelist = [] self["devicelist"] = MenuList(self.devicelist) self.scan = eTimer() self.scan.callback.append(self.DevicesToPair) self.scanning = False self.keyRed()
def __init__(self, stdscreen): self.scan_timeout = 90 self.bt = Bluetooth() self.bt.start_scanning(self.scan_timeout) self.screen = stdscreen curses.curs_set(0) mainMenu = [ ('Rescan devices\t\t(scans for {} seconds in background, system bus will be processed every 10 seconds)'.format(self.scan_timeout), self.rescan_devices), ('Trust controller\t\t(shows only untrusted pairable controllers)', self.trust_controller_menu), ('Pair controller\t\t(shows only unpaired pairable controllers)', self.pair_controller_menu), ('Connect controller\t\t(shows only paired and trusted connectable controllers)', self.connect_device_menu), ('Disconnect controller\t(shows only connected controllers)', self.disconnect_device_menu), ('Remove controller\t\t(shows only trusted, paired OR connected controllers)', self.remove_device_menu), ] self.make_menu(mainMenu) self.menu.display()
def NewConnection(self, path, fd, properties): address = str(path) address = address[len(address) - 17:len(address)] address = address.replace("_", ":") logger.info("Connected: {}\n".format(address)) blue_socket = socket.fromfd(fd.take(), socket.AF_UNIX, socket.SOCK_STREAM) socket_sink = SocketSink(sock=blue_socket) self.bridge = TCPBridge(sink=socket_sink, port_in=self.tcp_port_in, port_out=self.tcp_port_out) try: self.bridge.start(in_background=False) except TCPBridgeError as error: logger.error(str(error) + "\n") self.bridge.stop() blue_socket.close() logger.info("Disconnected: {}\n".format(address)) Bluetooth().disconnect(address)
from bluetool import Bluetooth bluetooth = Bluetooth() adapters = bluetooth.list_interfaces() print(adapters)
pass def display_pin_code(self, dev_info, *args): """Should return None or raise _Rejected""" pass def request_confirmation(self, dev_info, *args): """Should return bool""" pass def request_authorization(self, dev_info): """Should return bool""" pass _bluetooth = Bluetooth() class Agent(dbus.service.Object): def __init__( self, client_class=None, timeout=180, path="/org/bluez/my_bluetooth_agent"): dbus.service.Object.__init__(self, dbus.SystemBus(), path) if client_class is not None: self._client = client_class() else: self._client = Client() def _trust(self, dbus_device):
from bluetool import Bluetooth bluetooth = Bluetooth() adapters = bluetooth.list_interfaces() print(bluetooth.get_connected_devices()) print("---------------------------------") #bluetooth.scan(timeout=10, adapter_idx=1) #print(bluetooth.get_available_devices()) ADDR_UE_BOOM_2 = '88:C6:26:EE:BC:FE' ADDR_UE_BOOM = '88:C6:26:40:2C:2C' ADDR_BLP9820 = '30:21:15:54:78:AA' #print(bluetooth.remove(address=ADDR_UE_BOOM_2, adapter_idx=1)) print(bluetooth.disconnect(address=ADDR_BLP9820, adapter_idx=1)) # 88:C6:26:EE:BC:FE UE BOOM 2 print(bluetooth.disconnect(address=ADDR_UE_BOOM_2, adapter_idx=0)) #print(bluetooth.remove(address=ADDR_UE_BOOM, adapter_idx=0))
class MyApp(object): def __init__(self, stdscreen): self.scan_timeout = 90 self.bt = Bluetooth() self.bt.start_scanning(self.scan_timeout) self.screen = stdscreen curses.curs_set(0) mainMenu = [ ('Rescan devices\t\t(scans for {} seconds in background, system bus will be processed every 10 seconds)' .format(self.scan_timeout), self.rescan_devices), ('Trust controller\t\t(shows only untrusted pairable controllers)', self.trust_controller_menu), ('Pair controller\t\t(shows only unpaired pairable controllers)', self.pair_controller_menu), ('Connect controller\t\t(shows only paired and trusted connectable controllers)', self.connect_device_menu), ('Disconnect controller\t(shows only connected controllers)', self.disconnect_device_menu), ('Remove controller\t\t(shows only trusted, paired OR connected controllers)', self.remove_device_menu), ] self.make_menu(mainMenu) self.menu.display() def make_menu(self, menulist): self.menu = Menu(menulist, self.screen) def trust_controller_menu(self): properties = [ 'Icon', 'RSSI', 'Trusted', ] menu = [] for device in self.bt.get_available_devices(): mac_address = device['mac_address'] for property in properties: device[property] = self.bt.get_device_property( mac_address, property) if ((device['Icon'] == 'input-gaming') and (device['Trusted'] == 0)): menu.append( ('{}\t{}\tRSSI: {}'.format(device['mac_address'], device['name'], device['RSSI']), self.trust_controller)) self.make_menu(menu) self.menu.display() def trust_controller(self): mac = self.get_selected_device()[0] self.bt.trust(mac) if self.bt.get_device_property(mac, 'Trusted') == 1: self.menu.items[self.menu.position] = ( 'MAC {} ({}) trusted!\n'.format(mac, self.get_selected_device()[1]), self.navigate_to_back) else: self.menu.items[self.menu.position] = ( 'Error trusting MAC {} ({})!\n'.format( mac, self.get_selected_device()[1]), self.navigate_to_back) def pair_controller_menu(self): properties = [ 'Icon', 'Paired', 'RSSI', 'Trusted', ] menu = [] for device in self.bt.get_devices_to_pair(): mac_address = device['mac_address'] for property in properties: device[property] = self.bt.get_device_property( mac_address, property) if ((device['Icon'] == 'input-gaming') and (device['Trusted'] == 1) and device['Paired'] == 0): menu.append( ('{}\t{}\tRSSI: {}'.format(device['mac_address'], device['name'], device['RSSI']), self.pair_controller)) self.make_menu(menu) self.menu.display() def pair_controller(self): mac = self.get_selected_device()[0] self.bt.pair(mac) if self.bt.get_device_property(mac, 'Paired') == 1: self.menu.items[self.menu.position] = ( 'MAC {} ({}) paired!\n'.format(mac, self.get_selected_device()[1]), self.navigate_to_back) else: self.menu.items[self.menu.position] = ( 'Error paring MAC {} ({})!\n'.format( mac, self.get_selected_device()[1]), self.navigate_to_back) def connect_device_menu(self): properties = [ 'Icon', 'RSSI', 'Connected', 'Paired', 'Trusted', ] menu = [] for device in self.bt.get_available_devices(): mac_address = device['mac_address'] for property in properties: device[property] = self.bt.get_device_property( mac_address, property) if ((device['Icon'] == 'input-gaming') and (device['Paired'] == 1) and (device['Trusted'] == 1) and (device['Connected'] == 0)): menu.append( ('{}\t{}\tRSSI: {}'.format(device['mac_address'], device['name'], device['RSSI']), self.connect_device)) self.make_menu(menu) self.menu.display() def connect_device(self): mac = self.get_selected_device()[0] self.bt.connect(mac) if self.bt.get_device_property(mac, 'Connected') == 1: self.menu.items[self.menu.position] = ( 'MAC {} ({}) connected!\n'.format( mac, self.get_selected_device()[1]), self.navigate_to_back) else: self.menu.items[self.menu.position] = ( 'Error connecting MAC {} ({})!\n'.format( mac, self.get_selected_device()[1]), self.navigate_to_back) def disconnect_device_menu(self): properties = [ 'Icon', 'Connected', 'RSSI', ] menu = [] for device in self.bt.get_connected_devices(): mac_address = device['mac_address'] for property in properties: device[property] = self.bt.get_device_property( mac_address, property) if ((device['Icon'] == 'input-gaming') and (device['Connected'] == 1)): menu.append( ('{}\t{}\tRSSI: {}'.format(device['mac_address'], device['name'], device['RSSI']), self.disconnect_device)) self.make_menu(menu) self.menu.display() def disconnect_device(self): mac = self.get_selected_device()[0] self.bt.disconnect(mac) if self.bt.get_device_property(mac, 'Connected') == 0: self.menu.items[self.menu.position] = ( 'MAC {} ({}) disconnected!\n'.format( mac, self.get_selected_device()[1]), self.navigate_to_back) else: self.menu.items[self.menu.position] = ( 'Error disconnecting MAC {} ({})!\n'.format( mac, self.get_selected_device()[1]), self.navigate_to_back) def remove_device_menu(self): properties = [ 'Icon', 'Paired', 'Trusted', 'RSSI', 'Blocked', 'Connected', ] menu = [] for device in self.bt.get_available_devices(): mac_address = device['mac_address'] for property in properties: device[property] = self.bt.get_device_property( mac_address, property) if ((device['Icon'] == 'input-gaming') and ((device['Paired'] == 1) or (device['Trusted'] == 1) or (device['Blocked'] == 1))): menu.append(( '{}\t{}\tRSSI: {}\tTrusted: {}\tPaired: {}\tConnected: {}\tBlocked: {}' .format(device['mac_address'], device['name'], device['RSSI'], device['Trusted'], device['Paired'], device['Connected'], device['Blocked']), self.remove_device)) self.make_menu(menu) self.menu.display() def remove_device(self): mac = self.get_selected_device()[0] self.bt.remove(mac) self.menu.items[self.menu.position] = ('MAC {} ({}) removed!\n'.format( mac, self.get_selected_device()[1]), self.navigate_to_back) def rescan_devices(self): self.menu.window.addstr( 9, 1, 'Scanning for device for {} seconds in background now, please refresh views...' .format(self.scan_timeout), curses.A_NORMAL) self.bt.start_scanning(self.scan_timeout) def get_selected_device(self): return (self.menu.items[self.menu.position][0].split('\t')) def navigate_to_back(self): self.menu.navigate(len(self.menu.items) - 1)
self.menu.window.addstr( 9, 1, 'Scanning for device for {} seconds in background now, please refresh views...' .format(self.scan_timeout), curses.A_NORMAL) self.bt.start_scanning(self.scan_timeout) def get_selected_device(self): return (self.menu.items[self.menu.position][0].split('\t')) def navigate_to_back(self): self.menu.navigate(len(self.menu.items) - 1) if __name__ == "__main__": if (len(sys.argv) == 1): bt = Bluetooth() print('Scanning for available devices for 15 seconds, please wait...') bt.start_scanning(15) time.sleep(15) print('Getting pairable devices, please wait...') devices = bt.get_devices_to_pair() print(devices) for device in devices: mac = device['mac_address'] name = device['name'] print('Found MAC: {}\tName: {}'.format(mac, name)) if bt.get_device_property(mac, 'Icon') == 'input-gaming': print('Found controller {} Name: {}, trusting...'.format( mac, name)) bt.trust(mac) if bt.get_device_property(mac, 'Trusted') == 1:
class BluetoothDevicesManager(Screen): skin = """ <screen name="BluetoothDevicesManager" position="center,center" size="700,450" > <ePixmap pixmap="skin_default/buttons/red.png" position="10,10" size="35,25" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/green.png" position="180,10" size="35,25" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/yellow.png" position="370,10" size="35,25" alphatest="on" /> <ePixmap pixmap="skin_default/buttons/blue.png" position="550,10" size="35,25" alphatest="on" /> <eLabel name="" position="0,40" size="700,1" zPosition="2" backgroundColor="#ffffff" /> <eLabel name="" position="0,355" size="700,1" zPosition="2" backgroundColor="#ffffff" /> <widget name="key_red" position="45,10" zPosition="1" size="140,22" font="Regular;22" halign="left" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" /> <widget name="key_green" position="215,10" zPosition="1" size="140,22" font="Regular;22" halign="left" valign="center" backgroundColor="#1f771f" foregroundColor="#ffffff" transparent="1" /> <widget name="key_yellow" position="405,10" zPosition="1" size="140,22" font="Regular;22" halign="left" valign="center" backgroundColor="#a08500" foregroundColor="#ffffff" transparent="1" /> <widget name="key_blue" position="585,10" zPosition="1" size="140,22" font="Regular;22" halign="left" valign="center" backgroundColor="#18188b" foregroundColor="#ffffff" transparent="1" /> <widget name="devicelist" position="10,50" size="690,300" foregroundColor="#ffffff" zPosition="10" scrollbarMode="showOnDemand" transparent="1"/> <widget name="ConnStatus" position="10,365" size="690,80" zPosition="1" font="Regular;22" halign="center" valign="center" backgroundColor="#9f1313" foregroundColor="#ffffff" transparent="1" /> </screen>""" def __init__(self, session): Screen.__init__(self, session) Screen.setTitle(self, _("Bluetooth Devices Manager")) # initialize bluetooh self.bluetool = Bluetooth() self["actions"] = ActionMap( [ "OkCancelActions", "WizardActions", "ColorActions", "SetupActions", "NumberActions", "MenuActions" ], { "ok": self.keyOK, "cancel": self.keyCancel, "red": self.keyRed, "green": self.keyGreen, "yellow": self.keyYellow, "blue": self.keyBlue, }, -1) self["ConnStatus"] = Label() self["key_red"] = Label(_("Scan")) self["key_green"] = Label(_("Connect")) self["key_yellow"] = Label(_("Disconnect")) self["key_blue"] = Label(_("Paired")) self.devicelist = [] self["devicelist"] = MenuList(self.devicelist) self.scan = eTimer() self.scan.callback.append(self.DevicesToPair) self.scanning = False self.keyRed() def keyRed(self): print("[BluetoothManager] keyRed") self.showConnections() if self.scanning: return self.setTitle(_("Scanning...")) self.devicelist = [] self.devicelist.append((_("Scanning for devices..."), None)) self["devicelist"].setList(self.devicelist) # add background task for scanning self.bluetool.start_scanning() self.scan.start(10000) self.scanning = True def DevicesToPair(self): print("[BluetoothManager] DevicesToPair") self.setTitle(_("Scan Results...")) self.scan.stop() self.scanning = False self.devicelist = [] self.devicelist.append((_("MAC:\t\tDevice name:"), None)) devices_to_pair = self.bluetool.get_devices_to_pair() for d in devices_to_pair: self.devicelist.append( (d['mac_address'] + "\t" + d['name'], d['mac_address'])) if not len(devices_to_pair): self["ConnStatus"].setText(_("There are no devices to pair")) self["devicelist"].setList(self.devicelist) def showConnections(self): print("[BluetoothManager] showConnections") connected_devices = ",".join( [d['name'] for d in self.bluetool.get_connected_devices()]) if not connected_devices: self["ConnStatus"].setText(_("Not connected to any device")) else: self["ConnStatus"].setText( _("Connected to %s") % connected_devices) def keyGreen(self): print("[BluetoothManager] keyGreen") selectedItem = self["devicelist"].getCurrent() if selectedItem is None or selectedItem[1] is None: return device = selectedItem[1] if device in [ d['mac_address'] for d in self.bluetool.get_connected_devices() ]: return if device in [ d['mac_address'] for d in self.bluetool.get_paired_devices() ]: if self.bluetool.connect(device): self.showConnections() else: self["ConnStatus"].setText(_("Failed to connect %s") % device) return msg = _("Trying to pair with:") + " " + device self["ConnStatus"].setText(msg) if self.bluetool.pair(device): self["ConnStatus"].setText(_("Sucessfuly paired %s") % device) self.bluetool.trust(device) self.bluetool.connect(device) self.DevicesToPair() self.showConnections() else: self["ConnStatus"].setText(_("Fail to pair %s") % device) def keyYellow(self): print("[BluetoothManager] keyBlue") selectedItem = self["devicelist"].getCurrent() if selectedItem is None or selectedItem[1] is None: return device = selectedItem[1] if self.bluetool.remove(device): self["ConnStatus"].setText(_("Sucessfuly removed %s") % device) self.keyBlue() else: self["ConnStatus"].setText(_("Fail to remove %s") % device) def keyBlue(self): print("[BluetoothManager] keyBlue") self.setTitle(_("Paired Devices")) self.devicelist = [] self.devicelist.append((_("MAC:\t\tDevice name:"), None)) paired_devices = self.bluetool.get_paired_devices() for d in paired_devices: self.devicelist.append( (d['mac_address'] + "\t" + d['name'], d['mac_address'])) if not len(paired_devices): self["ConnStatus"].setText(_("Not paired to any device")) self["devicelist"].setList(self.devicelist) def keyCancel(self): print("[BluetoothManager] keyCancel") self.close() def keyOK(self): print("[BluetoothManager] keyOK") self.keyGreen() def setListOnView(self): return self.devicelist
###@package scan_devices scan devices this file scans all the bluetooth devices in the area and writes them to a file for the function to read from bluetool import Bluetooth import json d = [] bt = Bluetooth() bt.scan() devices = bt.get_available_devices() f = open('/home/pi/hub-repository/shutter/shutter/controller/scripts/scan_results.json', 'w+').close() f = open('/home/pi/hub-repository/shutter/shutter/controller/scripts/scan_results.json', 'w+') f.write(json.dumps(devices)) f.close() print(devices)
from bluetool import Bluetooth scanner = Bluetooth() scanner.scan() found = scanner.get_available_devices() print(found)
match = 0 if GPIO.input(13) == False: beep.pair() print "Performing inquiry..." nearby_devices = discover_devices(lookup_names=True) print "Found %d devices" % len(nearby_devices) for addr, name in nearby_devices: for k in range(len(MACs)): if MACs[k] == addr: match = match + 1 beep.match() port = btConnect.connect(MACs[k]) print "MAC: " + addr + " found on DB" print "RRSS service port: " + str(port) print "Pairing..." Pair = Bluetooth() print Pair.pair(addr) if match == 0: beep.noMatch()
from bluetool import Bluetooth from time import sleep bluetooth = Bluetooth() print("Scanning started...") bluetooth.scan() print("Scanning completed...") devices = bluetooth.get_available_devices() print("Available devices") print(devices) print("pairing with D8:32:E3:38:02:9D") if bluetooth.pair('D8:32:E3:38:02:9D'): print("Pairing completed") sleep(7) else: print("Unable to Pair") exit(1) print("Connecting with D8:32:E3:38:02:9D") if bluetooth.connect('D8:32:E3:38:02:9D'): print("Connected successfully!") else: print("Unable to connect")
from bluetool import Bluetooth bluetooth = Bluetooth() adapters = bluetooth.list_interfaces() print(adapters[1]) print(bluetooth.get_connected_devices()) print("---------------------------------") #bluetooth.scan(timeout=10, adapter_idx=1) #print(bluetooth.get_available_devices()) ADDR_UE_BOOM_2 = '88:C6:26:EE:BC:FE' ADDR_UE_BOOM = '88:C6:26:40:2C:2C' ADDR_BLP9820 = '30:21:15:54:78:AA' print(bluetooth.pair(address=ADDR_BLP9820, adapter_idx=1)) print(bluetooth.connect(address=ADDR_BLP9820, adapter_idx=1)) #print(bluetooth.pair(address=ADDR_UE_BOOM_2, adapter_idx=0)) #print(bluetooth.connect(address=ADDR_UE_BOOM_2, adapter_idx=0))
import os mac = "00:58:56:4C:2F:2F" from bluetool import Bluetooth from time import sleep bluetooth = Bluetooth() print("Scanning started...") bluetooth.scan() print("Scanning completed...") devices = bluetooth.get_available_devices() print("Available devices") print(devices) print("pairing with", mac) if bluetooth.pair(mac): print("Pairing completed") sleep(7) else: print("Unable to Pair") exit(1) print("Connecting with", mac) if bluetooth.connect(mac): print("Connected successfully!") else: print("Unable to connect") # Playing audio # for i in range(3): # os.system("mpg123 Kaathalae_Kaathalae-SunMusiQ.Com.mp3 ") # sleep(10)
from bluetool import Bluetooth bluetooth = Bluetooth() bluetooth.scan() devices = bluetooth.get_available_devices() print(devices)