Ejemplo n.º 1
0
def connect_balanceboard():
    global bbaddress
    #device is something like "/sys/devices/platform/soc/3f201000.uart/tty/ttyAMA0/hci0/hci0:11/0005:057E:0306.000C"
    device = wait_for_balanceboard()

    iface = xwiimote.iface(device)
    iface.open(xwiimote.IFACE_BALANCE_BOARD)

    (kg, err) = average_mesurements(measurements(iface))

    #
    # do something with this data
    # like log to file or send to server
    #
    print("{:.2f} +/- {:.2f}".format(kg / 100.0 + calibration, err /
                                     100.0))  #add adjustment to final result
    print("publish to MQTT")
    client.publish("mqtt/topic",
                   "{:.2f}".format(kg / 100.0 + calibration),
                   retain=True)  #publish to topic

    # find address of the balance board (once) and disconnect (if found).
    if bbaddress is None:
        bbaddress = find_device_address()
    if bbaddress is not None:
        device = bluezutils.find_device(bbaddress)
        device.Disconnect()
Ejemplo n.º 2
0
    def __configure_pair_agent(self):
        print("Configuring agent pair")
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        bus = dbus.SystemBus()

        parser = OptionParser()
        parser.add_option("-i",
                          "--adapter",
                          action="store",
                          type="string",
                          dest="adapter_pattern",
                          default=None)
        parser.add_option("-c",
                          "--capability",
                          action="store",
                          type="string",
                          dest="capability")
        parser.add_option("-t",
                          "--timeout",
                          action="store",
                          type="int",
                          dest="timeout",
                          default=60000)
        (options, args) = parser.parse_args()

        capability = self.AGENT_CAPABILITY
        if options.capability:
            capability = options.capability

        self.mainloop = GObject.MainLoop()

        path = "/test/agent"
        self.agent = Agent.Agent(bus, path, self.mainloop)

        obj = bus.get_object(self.BUS_NAME, "/org/bluez")
        manager = dbus.Interface(obj, "org.bluez.AgentManager1")
        manager.RegisterAgent(path, capability)

        print("Agent registered")

        # Fix-up old style invocation (BlueZ 4)
        if len(args) > 0 and args[0].startswith("hci"):
            options.adapter_pattern = args[0]
            del args[:1]

        if len(args) > 0:
            device = bluezutils.find_device(args[0], options.adapter_pattern)
            self.dev_path = device.object_path
            self.agent.set_exit_on_release(False)
            device.Pair(reply_handler=self.__pair_reply,
                        error_handler=self.__pair_error,
                        timeout=60000)
            self.device_obj = device
        else:
            manager.RequestDefaultAgent(path)
Ejemplo n.º 3
0
 def reconnect(self):
     if os.path.isfile(LAST_DEVICE) and os.path.getsize(LAST_DEVICE) > 0:
         try:
             last_device = open(LAST_DEVICE).read()
         except Exception as error:
             return False
         
         device = bluezutils.find_device(last_device)
         return bluezutils.dev_connect(device.object_path)
     else:
         return False
Ejemplo n.º 4
0
    def remove(self, address):
        try:
            adapter = bluezutils.find_adapter()
            dev = bluezutils.find_device(address)
        except (bluezutils.BluezUtilError,
                dbus.exceptions.DBusException) as error:
            print_error(str(error) + "\n")
            return False

        try:
            adapter.RemoveDevice(dev.object_path)
        except dbus.exceptions.DBusException as error:
            print_error(str(error) + "\n")
            return False

        return True
Ejemplo n.º 5
0
    def remove(self, address):
        try:
            adapter = bluezutils.find_adapter()
            dev = bluezutils.find_device(address)
        except (bluezutils.BluezUtilError,
                dbus.exceptions.DBusException) as error:
            logger.error(str(error) + "\n")
            return False

        try:
            adapter.RemoveDevice(dev.object_path)
        except dbus.exceptions.DBusException as error:
            logger.error(str(error) + "\n")
            return False

        logger.info("Successfully removed: {}".format(address))
        return True
Ejemplo n.º 6
0
    def get_device_property(self, address, prop):
        try:
            device = bluezutils.find_device(address)
        except (bluezutils.BluezUtilError,
                dbus.exceptions.DBusException) as error:
            logger.error(str(error) + "\n")
            return None

        try:
            props = dbus.Interface(
                self._bus.get_object("org.bluez", device.object_path),
                "org.freedesktop.DBus.Properties")

            return props.Get("org.bluez.Device1", prop)
        except dbus.exceptions.DBusException as error:
            logger.error(str(error) + "\n")
            return None
Ejemplo n.º 7
0
    def disconnect(self, address):
        try:
            device = bluezutils.find_device(address)
        except (bluezutils.BluezUtilError,
                dbus.exceptions.DBusException) as error:
            print_error(str(error) + "\n")
            return False

        try:
            props = dbus.Interface(
                self._bus.get_object("org.bluez", device.object_path),
                "org.freedesktop.DBus.Properties")

            if props.Get("org.bluez.Device1", "Connected"):
                device.Disconnect()
        except dbus.exceptions.DBusException as error:
            print_error(str(error) + "\n")
            return False

        return True
Ejemplo n.º 8
0
    def trust(self, address):
        try:
            device = bluezutils.find_device(address)
        except (bluezutils.BluezUtilError,
                dbus.exceptions.DBusException) as error:
            logger.error(str(error) + "\n")
            return False

        try:
            props = dbus.Interface(
                self._bus.get_object("org.bluez", device.object_path),
                "org.freedesktop.DBus.Properties")

            if not props.Get("org.bluez.Device1", "Trusted"):
                props.Set("org.bluez.Device1", "Trusted", dbus.Boolean(1))
        except dbus.exceptions.DBusException as error:
            logger.error(str(error) + "\n")
            return False

        return True
Ejemplo n.º 9
0
    def connect(self, address):
        try:
            device = bluezutils.find_device(address)
        except (bluezutils.BluezUtilError,
                dbus.exceptions.DBusException) as error:
            logger.error(str(error) + "\n")
            return False

        try:
            props = dbus.Interface(
                self._bus.get_object("org.bluez", device.object_path),
                "org.freedesktop.DBus.Properties")

            if not props.Get("org.bluez.Device1", "Connected"):
                device.Connect()
        except dbus.exceptions.DBusException as error:
            logger.error(str(error) + "\n")
            return False

        logger.info("Successfully connected to {}".format(address))
        return True
Ejemplo n.º 10
0
def connect_balanceboard():
	global bbaddress
	#device is something like "/sys/devices/platform/soc/3f201000.uart/tty/ttyAMA0/hci0/hci0:11/0005:057E:0306.000C"
	device = wait_for_balanceboard()

	iface = xwiimote.iface(device)
	iface.open(xwiimote.IFACE_BALANCE_BOARD)


	(kg, err) = average_mesurements(measurements(iface))

	#
	# do something with this data
	# like log to file or send to server
	#
	print("{:.2f} +/- {:.2f}".format(kg/100.0, err/100.0))

	# find address of the balance board (once) and disconnect (if found).
	if bbaddress is None:
		bbaddress = find_device_address()
	if bbaddress is not None:
		device = bluezutils.find_device(bbaddress)
		device.Disconnect()
Ejemplo n.º 11
0
 def disconnect(self, adapter):
     device = bluezutils.find_device(adapter)
     return bluezutils.dev_disconnect(device.object_path)
Ejemplo n.º 12
0
def disconnect_device(deviceaddress):
    device = bluezutils.find_device(deviceaddress)
    device.Disconnect()
Ejemplo n.º 13
0
        adapter = bluezutils.find_adapter_in_objects(managed_objects,
                                                     options.dev_id)
        try:
            dev = bluezutils.find_device_in_objects(managed_objects, args[1],
                                                    options.dev_id)
            path = dev.object_path
        except:
            path = args[1]
        adapter.RemoveDevice(path)
    sys.exit(0)

if (args[0] == "connect"):
    if (len(args) < 2):
        print("Need address parameter")
    else:
        device = bluezutils.find_device(args[1], options.dev_id)
        if (len(args) > 2):
            device.ConnectProfile(args[2])
        else:
            device.Connect()
    sys.exit(0)

if (args[0] == "disconnect"):
    if (len(args) < 2):
        print("Need address parameter")
    else:
        device = bluezutils.find_device(args[1], options.dev_id)
        if (len(args) > 2):
            device.DisconnectProfile(args[2])
        else:
            device.Disconnect()
Ejemplo n.º 14
0
def get_device(deviceaddress):
    return bluezutils.find_device(deviceaddress)
Ejemplo n.º 15
0
def connect_device(deviceaddress):
    device = bluezutils.find_device(deviceaddress)
    device.Connect()
Ejemplo n.º 16
0
def connect_device(mac_address):
    tdl_mac_address = "A0:E6:F8:6C:8B:87"
    device = bluezutils.find_device(mac_address, None)
    device.Connect()
    print("Connected")
Ejemplo n.º 17
0
def main():
    # Set up the main loop.
    DBusGMainLoop(set_as_default=True)
    global bus
    bus = dbus.SystemBus()
    global mainloop
    mainloop = GObject.MainLoop()
    address = None

    if (len(sys.argv) > 1):
        global fwup_filename
        fwup_filename = sys.argv[1]

    om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'), DBUS_OM_IFACE)
    om.connect_to_signal('InterfacesRemoved', interfaces_removed_cb)

    print('Getting objects...')
    objects = om.GetManagedObjects()
    chrcs = []

    # List devices found
    for path, interfaces in objects.items():
        device = interfaces.get("org.bluez.Device1")
        if (device is None):
            continue
        try:
            if (device["Name"] == FWUPDATE_TARGET):
                print("Found FWUPDATE TARGET!")
                address = device["Address"]
                break
        except:
            continue

    if address is None:
        print("device not found.")
        return

    device = bluezutils.find_device(address, HCI)
    if (device is None):
        print("Cannot 'find_device'")
    else:
        device.Connect()
        print("Connected")

    # List characteristics found
    for path, interfaces in objects.items():
        if GATT_CHRC_IFACE not in interfaces.keys():
            continue
        chrcs.append(path)

    # List sevices found
    for path, interfaces in objects.items():
        if GATT_SERVICE_IFACE not in interfaces.keys():
            continue

        chrc_paths = [d for d in chrcs if d.startswith(path + "/")]

        if process_fwupdate_service(path, chrc_paths):
            break

    if not fwupdate_service:
        print('No FWUPDATE found.')
        sys.exit(1)

    start_client()
    mainloop.run()
Ejemplo n.º 18
0
def get_device(deviceaddress):
    return bluezutils.find_device(deviceaddress)
Ejemplo n.º 19
0
def connect_device(deviceaddress):
    device = bluezutils.find_device(deviceaddress)
    device.Connect()
Ejemplo n.º 20
0
def pair_with_agent(_osmc_bt,
                    device_uuid,
                    adapter_pattern=None,
                    capability='KeyboardDisplay',
                    timeout=15000):
    global osmc_bt, mainloop, agent, dev_path, device_obj, paired
    osmc_bt = _osmc_bt
    paired = False

    try:
        device = bluezutils.find_device(device_uuid, adapter_pattern)
    except:
        device = None
        return_status('DEVICE_NOT_FOUND', ['Device not Found'])
        return False

    dev_path = device.object_path
    rvl_conn = ravel.system_bus()

    # Check if already paired
    message = dbsy.Message.new_method_call \
      (
        destination = dbsy.valid_bus_name(BUS_NAME),
        path = dbsy.valid_path(dev_path),
        iface = "org.freedesktop.DBus.Properties",
        method = "Get"
      )
    message.append_objects('ss', "org.bluez.Device1", 'Paired')
    error = None
    reply = rvl_conn.connection.send_with_reply_and_block(message, error=error)
    if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR:
        reply.set_error(error)
        result = None
        set_trusted(rvl_conn, False)
        rvl_conn = None
        return paired
    else:
        result = reply.expect_return_objects("v")[0]
        if result[0] == 'b' and result[1] == True:
            print('Already paired')
            paired = True
            set_trusted(rvl_conn, True)
            rvl_conn = None
            return paired

    # Create the agent object
    agent = AgentInterface(rvl_conn, capability)

    # This bit needed to run in Spyder3 IDE
    try:
        nest_asyncio.apply()
    except:
        pass

    # there's probably a more elegant way to do this
    try:
        mainloop = asyncio.get_running_loop()
        if mainloop:
            mainloop.stop()
    except:
        pass
    mainloop = asyncio.new_event_loop()
    rvl_conn.attach_asyncio(mainloop)

    message = dbsy.Message.new_method_call \
      (
        destination = dbsy.valid_bus_name(BUS_NAME),
        path = dbsy.valid_path(dev_path),
        iface = "org.bluez.Device1",
        method = "Pair"
      )

    async def pair(conn, message):
        print('Pairing')
        await_reply = await conn.connection.send_await_reply(message)
        print('Finished')
        return await_reply

    reply = mainloop.run_until_complete(pair(rvl_conn, message))
    error_name, error_message = handle_reply(reply, None)
    print(error_name)
    if error_name == "org.freedesktop.DBus.Error.NoReply" and device:
        error_message = 'Timed out. Cancelling pairing'
        message = dbsy.Message.new_method_call \
          (
             destination = dbsy.valid_bus_name(BUS_NAME),
             path = dbsy.valid_path(dev_path),
             iface = "org.bluez.Device1",
             method = "CancelPairing"
          )
        try:
            rvl_conn.connection.send_with_reply_and_block(message)
            set_trusted(rvl_conn, False)
        except:
            pass

    if error_message is not None:
        print('PAIRING_FAILED ' + error_message)
        return_status('PAIRING_FAILED', [error_message])
        try:
            set_trusted(rvl_conn, False)
        except:
            pass
    else:
        print('PAIRING_OK')
        return_status('PAIRING_OK', [])
        paired = True
        set_trusted(rvl_conn, True)

    agent.close()
    rvl_conn = None
    return paired
Ejemplo n.º 21
0
	mainloop = GObject.MainLoop()

	obj = bus.get_object(BUS_NAME, "/org/bluez");
	manager = dbus.Interface(obj, "org.bluez.AgentManager1")
	manager.RegisterAgent(path, capability)

	print("Agent registered. Now press the controller's PS button.")

	# Fix-up old style invocation (BlueZ 4)
	if len(args) > 0 and args[0].startswith("hci"):
		options.adapter_pattern = args[0]
		del args[:1]

	if len(args) > 0:
		device = bluezutils.find_device(args[0],
						options.adapter_pattern)
		dev_path = device.object_path
		agent.set_exit_on_release(False)
		device.Pair(reply_handler=pair_reply, error_handler=pair_error,
								timeout=60000)
		device_obj = device
	else:
		manager.RequestDefaultAgent(path)

	mainloop.run()

	#adapter.UnregisterAgent(path)
	#print("Agent unregistered")

Ejemplo n.º 22
0
def disconnect_device(deviceaddress):
    device = bluezutils.find_device(deviceaddress)
    device.Disconnect()
Ejemplo n.º 23
0
                      dest="timeout",
                      default=60000)
    (options, args) = parser.parse_args()
    if options.capability:
        capability = options.capability

    agent = Agent(bus, AGENT_PATH)
    mainloop = GObject.MainLoop()
    obj = bus.get_object(BUS_NAME, "/org/bluez")
    manager = dbus.Interface(obj, "org.bluez.AgentManager1")
    manager.RegisterAgent(AGENT_PATH, capability)

    print("Agent registered")

    # Fix-up old style invocation (BlueZ 4)
    if len(args) > 0 and args[0].startswith("hci"):
        options.adapter_pattern = args[0]
        del args[:1]

    if len(args) > 0:
        device = bluezutils.find_device(args[0], options.adapter_pattern)
        dev_path = device.object_path
        agent.set_exit_on_release(False)
        device.Pair(reply_handler=pair_reply,
                    error_handler=pair_error,
                    timeout=60000)
        device_obj = device
    else:
        manager.RequestDefaultAgent(AGENT_PATH)

    mainloop.run()
Ejemplo n.º 24
0
#!/usr/bin/python


import dbus
import bluezutils


def dev_connect(path):
  dev = dbus.Interface(bus.get_object("org.bluez", path), "org.bluez.Device1")
  dev.Connect()


bus = dbus.SystemBus()
device = bluezutils.find_device("0C:A6:94:E3:76:DA")

dev_connect(device.object_path)

dev_path = device.object_path

print(device.object_path)