profile = Profile(bus, options.path) mainloop = GObject.MainLoop() opts = { "AutoConnect": options.auto_connect, } if (options.name): opts["Name"] = options.name if (options.role): opts["Role"] = options.role if (options.psm is not None): opts["PSM"] = dbus.UInt16(options.psm) if (options.channel is not None): opts["Channel"] = dbus.UInt16(options.channel) if (options.record): opts["ServiceRecord"] = options.record if (options.service): opts["Service"] = options.service if not options.uuid: options.uuid = str(uuid.uuid4()) manager.RegisterProfile(options.path, options.uuid, opts)
admin = bus.get_object("org.ganesha.nfsd", "/org/ganesha/nfsd/ExportMgr") except: # catch *all* exceptions print( "Error: Can't talk to ganesha service on d-bus. Looks like Ganesha is down" ) exit(1) # call method ganesha_9pOpstats = admin.get_dbus_method('Get9pOpStats', 'org.ganesha.nfsd.exportstats') # get parameters if len(sys.argv) != 2 or not (sys.argv[1].isdigit()): print("Usage: %s export_id" % sys.argv[0]) exit(1) export_id = dbus.UInt16(sys.argv[1]) # for each 9p protocol operation OpNames = ("_9P_TSTATFS", "_9P_TLOPEN", "_9P_TLCREATE", "_9P_TSYMLINK", "_9P_TMKNOD", "_9P_TRENAME", "_9P_TREADLINK", "_9P_TGETATTR", "_9P_TSETATTR", "_9P_TXATTRWALK", "_9P_TXATTRCREATE", "_9P_TREADDIR", "_9P_TFSYNC", "_9P_TLOCK", "_9P_TGETLOCK", "_9P_TLINK", "_9P_TMKDIR", "_9P_TRENAMEAT", "_9P_TUNLINKAT", "_9P_TVERSION", "_9P_TAUTH", "_9P_TATTACH", "_9P_TFLUSH", "_9P_TWALK", "_9P_TOPEN", "_9P_TCREATE", "_9P_TREAD", "_9P_TWRITE", "_9P_TCLUNK", "_9P_TREMOVE", "_9P_TSTAT", "_9P_TWSTAT") for opname in OpNames: opstats = ganesha_9pOpstats(export_id, opname) status = opstats[0] errmsg = opstats[1]
2: "b" }, { "a": 1, "b": 2 }, #{"a":(1,"B")}, { 1: 1.1, 2: 2.2 }, [[1, 2, 3], [2, 3, 4]], [["a", "b"], ["c", "d"]], True, False, dbus.Int16(-10), dbus.UInt16(10), 'SENTINEL', #([1,2,3],"c", 1.2, ["a","b","c"], {"a": (1,"v"), "b": (2,"d")}) ] NAME = "org.freedesktop.DBus.TestSuitePythonService" IFACE = "org.freedesktop.DBus.TestSuiteInterface" OBJECT = "/org/freedesktop/DBus/TestSuitePythonObject" class TestDBusBindings(unittest.TestCase): def setUp(self): self.bus = dbus.SessionBus() self.remote_object = self.bus.get_object(NAME, OBJECT) self.remote_object_follow = self.bus.get_object( NAME, OBJECT, follow_name_owner_changes=True)
def volume(self, level) : self.Volume = dbus.UInt16(level % 128)
def beacon(config): """ Broadcast values via zeroconf If the announced values are static, it is advised to set run_once: True (do not poll) on the beacon configuration. The following are required configuration settings: - ``servicetype`` - The service type to announce - ``port`` - The port of the service to announce - ``txt`` - The TXT record of the service being announced as a dict. Grains can be used to define TXT values using one of following two formats: - ``grains.<grain_name>`` - ``grains.<grain_name>[i]`` where i is an integer representing the index of the grain to use. If the grain is not a list, the index is ignored. The following are optional configuration settings: - ``servicename`` - Set the name of the service. Will use the hostname from the minion's ``host`` grain if this value is not set. - ``reset_on_change`` - If ``True`` and there is a change in TXT records detected, it will stop announcing the service and then restart announcing the service. This interruption in service announcement may be desirable if the client relies on changes in the browse records to update its cache of TXT records. Defaults to ``False``. - ``reset_wait`` - The number of seconds to wait after announcement stops announcing and before it restarts announcing in the case where there is a change in TXT records detected and ``reset_on_change`` is ``True``. Defaults to ``0``. - ``copy_grains`` - If ``True``, Salt will copy the grains passed into the beacon when it backs them up to check for changes on the next iteration. Normally, instead of copy, it would use straight value assignment. This will allow detection of changes to grains where the grains are modified in-place instead of completely replaced. In-place grains changes are not currently done in the main Salt code but may be done due to a custom plug-in. Defaults to ``False``. Example Config .. code-block:: yaml beacons: avahi_announce: - run_once: True - servicetype: _demo._tcp - port: 1234 - txt: ProdName: grains.productname SerialNo: grains.serialnumber Comments: 'this is a test' """ ret = [] changes = {} txt = {} global LAST_GRAINS _config = {} list(map(_config.update, config)) if "servicename" in _config: servicename = _config["servicename"] else: servicename = __grains__["host"] # Check for hostname change if LAST_GRAINS and LAST_GRAINS["host"] != servicename: changes["servicename"] = servicename if LAST_GRAINS and _config.get("reset_on_change", False): # Check for IP address change in the case when we reset on change if LAST_GRAINS.get("ipv4", []) != __grains__.get("ipv4", []): changes["ipv4"] = __grains__.get("ipv4", []) if LAST_GRAINS.get("ipv6", []) != __grains__.get("ipv6", []): changes["ipv6"] = __grains__.get("ipv6", []) for item in _config["txt"]: changes_key = "txt." + salt.utils.stringutils.to_unicode(item) if _config["txt"][item].startswith("grains."): grain = _config["txt"][item][7:] grain_index = None square_bracket = grain.find("[") if square_bracket != -1 and grain[-1] == "]": grain_index = int(grain[square_bracket + 1:-1]) grain = grain[:square_bracket] grain_value = __grains__.get(grain, "") if isinstance(grain_value, list): if grain_index is not None: grain_value = grain_value[grain_index] else: grain_value = ",".join(grain_value) txt[item] = _enforce_txt_record_maxlen(item, grain_value) if LAST_GRAINS and (LAST_GRAINS.get(grain, "") != __grains__.get( grain, "")): changes[changes_key] = txt[item] else: txt[item] = _enforce_txt_record_maxlen(item, _config["txt"][item]) if not LAST_GRAINS: changes[changes_key] = txt[item] if changes: if not LAST_GRAINS: changes["servicename"] = servicename changes["servicetype"] = _config["servicetype"] changes["port"] = _config["port"] changes["ipv4"] = __grains__.get("ipv4", []) changes["ipv6"] = __grains__.get("ipv6", []) GROUP.AddService( avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, _config["servicetype"], "", "", dbus.UInt16(_config["port"]), avahi.dict_to_txt_array(txt), ) GROUP.Commit() elif _config.get("reset_on_change", False) or "servicename" in changes: # A change in 'servicename' requires a reset because we can only # directly update TXT records GROUP.Reset() reset_wait = _config.get("reset_wait", 0) if reset_wait > 0: time.sleep(reset_wait) GROUP.AddService( avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, _config["servicetype"], "", "", dbus.UInt16(_config["port"]), avahi.dict_to_txt_array(txt), ) GROUP.Commit() else: GROUP.UpdateServiceTxt( avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, _config["servicetype"], "", avahi.dict_to_txt_array(txt), ) ret.append({"tag": "result", "changes": changes}) if _config.get("copy_grains", False): LAST_GRAINS = __grains__.copy() else: LAST_GRAINS = __grains__ return ret
def beacon(config): ''' Broadcast values via zeroconf If the announced values are static, it is adviced to set run_once: True (do not poll) on the beacon configuration. The following are required configuration settings: 'servicetype': The service type to announce. 'port': The port of the service to announce. 'txt': The TXT record of the service being announced as a dict. Grains can be used to define TXT values using the syntax: grains.<grain_name> or: grains.<grain_name>[i] where i is an integer representing the index of the grain to use. If the grain is not a list, the index is ignored. The following are optional configuration settings: 'servicename': Set the name of the service. Will use the hostname from __grains__['host'] if not set. 'reset_on_change': If true and there is a change in TXT records detected, it will stop announcing the service and then restart announcing the service. This interruption in service announcement may be desirable if the client relies on changes in the browse records to update its cache of the TXT records. Defaults to False. 'reset_wait': The number of seconds to wait after announcement stops announcing and before it restarts announcing in the case where there is a change in TXT records detected and 'reset_on_change' is True. Defaults to 0. 'copy_grains': If set to True, it will copy the grains passed into the beacon when it backs them up to check for changes on the next iteration. Normally, instead of copy, it would use straight value assignment. This will allow detection of changes to grains where the grains are modified in-place instead of completely replaced. In-place grains changes are not currently done in the main Salt code but may be done due to a custom plug-in. Defaults to False. Example Config .. code-block:: yaml beacons: avahi_announce: run_once: True servicetype: _demo._tcp port: 1234 txt: ProdName: grains.productname SerialNo: grains.serialnumber Comments: 'this is a test' ''' ret = [] changes = {} txt = {} global LAST_GRAINS _validate = __validate__(config) if not _validate[0]: log.warning('Beacon {0} configuration invalid, ' 'not adding. {1}'.format(__virtualname__, _validate[1])) return ret if 'servicename' in config: servicename = config['servicename'] else: servicename = __grains__['host'] for item in config['txt']: if config['txt'][item].startswith('grains.'): grain = config['txt'][item][7:] grain_index = None square_bracket = grain.find('[') if square_bracket != -1 and grain[-1] == ']': grain_index = int(grain[square_bracket + 1:-1]) grain = grain[:square_bracket] grain_value = __grains__.get(grain, '') if isinstance(grain_value, list): if grain_index is not None: grain_value = grain_value[grain_index] else: grain_value = ','.join(grain_value) txt[item] = _enforce_txt_record_maxlen(item, grain_value) if LAST_GRAINS and (LAST_GRAINS.get(grain, '') != __grains__.get( grain, '')): changes[str('txt.' + item)] = txt[item] else: txt[item] = _enforce_txt_record_maxlen(item, config['txt'][item]) if not LAST_GRAINS: changes[str('txt.' + item)] = txt[item] if changes: if not LAST_GRAINS: changes['servicename'] = servicename changes['servicetype'] = config['servicetype'] changes['port'] = config['port'] GROUP.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, config['servicetype'], '', '', dbus.UInt16(config['port']), avahi.dict_to_txt_array(txt)) GROUP.Commit() elif config.get('reset_on_change', False): GROUP.Reset() reset_wait = config.get('reset_wait', 0) if reset_wait > 0: time.sleep(reset_wait) GROUP.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, config['servicetype'], '', '', dbus.UInt16(config['port']), avahi.dict_to_txt_array(txt)) GROUP.Commit() else: GROUP.UpdateServiceTxt(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, config['servicetype'], '', avahi.dict_to_txt_array(txt)) ret.append({'tag': 'result', 'changes': changes}) if config.get('copy_grains', False): LAST_GRAINS = __grains__.copy() else: LAST_GRAINS = __grains__ return ret
"org.freedesktop.DBus.ObjectManager") objects = om.GetManagedObjects() for path, interfaces in objects.items(): if "org.bluez.Device1" in interfaces: devices[path] = interfaces["org.bluez.Device1"] scan_filter = dict() if options.uuids: uuids = [] uuid_list = options.uuids.split(',') for uuid in uuid_list: uuids.append(uuid) scan_filter.update({ "UUIDs": uuids }) if options.rssi: scan_filter.update({ "RSSI": dbus.Int16(options.rssi) }) if options.pathloss: scan_filter.update({ "Pathloss": dbus.UInt16(options.pathloss) }) if options.transport: scan_filter.update({ "Transport": options.transport }) adapter.SetDiscoveryFilter(scan_filter) adapter.StartDiscovery() mainloop = GObject.MainLoop() mainloop.run()
def search_status_handler(handle,status): vprint('\n::Search status ' + str(int(status))) if status == FINISHED: location_input_interface.requestListUpdate(dbus.UInt32(session_handle), dbus.UInt32(handle), dbus.UInt16(0), dbus.UInt16(WINDOW_SIZE))
def usage(): print "Usage:\n" \ "Offer a stream tube to [contact] using the trivial stream server:\n" \ "\tpython %s [account-file] [contact]\n" \ "Accept a stream tube from a contact and connect it to the trivial stream client:\n" \ "\tpython %s [account-file]\n" \ "Offer a stream tube to [contact] using the socket [IP]:[port]:\n" \ "\tpython %s [account-file] [contact] [IP] [port]\n" \ "Accept a stream tube from a contact and wait for connections from an external client:\n" \ "\tpython %s [account-file] --no-trivial-client\n" \ % (sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0]) if __name__ == '__main__': args = sys.argv[1:] if len(args) == 2 and args[1] != '--no-trivial-client': client = StreamTubeInitiatorPrivateClient(args[0], contact_id=args[1]) elif len(args) == 1: client = StreamTubeJoinerPrivateClient(args[0], True) elif len(args) == 4: client = StreamTubeInitiatorPrivateClient( args[0], args[1], (args[2], dbus.UInt16(args[3]))) elif len(args) == 2 and args[1] == '--no-trivial-client': client = StreamTubeJoinerPrivateClient(args[0], False) else: usage() sys.exit(0) client.run()
agent = Agent(bus, path) obj = bus.get_object('org.bluez', "/org/bluez"); manager = dbus.Interface(obj, "org.bluez.AgentManager1") manager.RegisterAgent(path, capability) manager.RequestDefaultAgent(path) from btk import HIDProfile, PSM_CTRL, PSM_INTR import uuid print('start hid') import bluetooth as bt sock = bt.BluetoothSocket(bt.L2CAP) sock.setblocking(False) sock.bind(('', PSM_INTR)) sock.listen(1) obj_path = '/ml/jlyu/HIDProfile' profile = HIDProfile(bus, obj_path, sock) opts = { "PSM": dbus.UInt16(PSM_CTRL), "ServiceRecord": open('./sdp_record.xml', 'r').read(), "RequireAuthentication": dbus.Boolean(True), "RequireAuthorization": dbus.Boolean(True), } dbus.Interface( bus.get_object("org.bluez", "/org/bluez"), "org.bluez.ProfileManager1" ).RegisterProfile(obj_path, str(uuid.uuid4()), opts) gobject.MainLoop().run()
def change_selection_criterion(selection_criterion): global current_selection_criterion current_selection_criterion = selection_criterion location_input_interface.SetSelectionCriterion(dbus.UInt32(session_handle), dbus.UInt32(location_input_handle), dbus.UInt16(current_selection_criterion))
def beacon(config): ''' Broadcast values via zeroconf If the announced values are static, it is adviced to set run_once: True (do not poll) on the beacon configuration. Grains can be used to define txt values using the syntax: grains.<grain_name> The default servicename its the hostname grain value. Example Config .. code-block:: yaml beacons: avahi_announce: run_once: True servicetype: _demo._tcp txt: ProdName: grains.productname SerialNo: grains.serialnumber Comments: 'this is a test' ''' ret = [] changes = {} txt = {} global LAST_GRAINS _validate = __validate__(config) if not _validate[0]: log.warning('Beacon {0} configuration invalid, ' 'not adding. {1}'.format(__virtualname__, _validate[1])) return ret if 'servicename' in config: servicename = config['servicename'] else: servicename = __grains__['host'] for item in config['txt']: if config['txt'][item].startswith('grains.'): grain = config['txt'][item][7:] txt[item] = __grains__[grain] if LAST_GRAINS and (LAST_GRAINS[grain] != __grains__[grain]): changes[str('txt.' + item)] = txt[item] else: txt[item] = config['txt'][item] if not LAST_GRAINS: changes[str('txt.' + item)] = txt[item] if changes: if not LAST_GRAINS: changes['servicename'] = servicename changes['servicetype'] = config['servicetype'] changes['port'] = config['port'] else: GROUP.Reset() GROUP.AddService(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, dbus.UInt32(0), servicename, config['servicetype'], '', '', dbus.UInt16(config['port']), avahi.dict_to_txt_array(txt)) GROUP.Commit() ret.append({'tag': 'result', 'changes': changes}) LAST_GRAINS = __grains__ return ret
def testInts(self): self.assertEqual(utils.coerceDbusType(dbus.Byte(12)), 12) self.assertEqual(utils.coerceDbusType(dbus.Int16(12)), 12) self.assertEqual(utils.coerceDbusType(dbus.Int32(12)), 12) self.assertEqual(utils.coerceDbusType(dbus.UInt16(12)), 12) self.assertEqual(utils.coerceDbusType(dbus.UInt32(12)), 12)
if not pkg.startswith(pydir): raise Exception("DBus modules (%s) are not being picked up from the package"%pkg) if not _dbus_bindings.__file__.startswith(builddir): raise Exception("DBus modules (%s) are not being picked up from the package"%_dbus_bindings.__file__) test_types_vals = [1, 12323231, 3.14159265, 99999999.99, "dude", "123", "What is all the fuss about?", "*****@*****.**", '\\u310c\\u310e\\u3114', '\\u0413\\u0414\\u0415', '\\u2200software \\u2203crack', '\\xf4\\xe5\\xe8', [1,2,3], ["how", "are", "you"], [1.23,2.3], [1], ["Hello"], (1,2,3), (1,), (1,"2",3), ("2", "what"), ("you", 1.2), {1:"a", 2:"b"}, {"a":1, "b":2}, #{"a":(1,"B")}, {1:1.1, 2:2.2}, [[1,2,3],[2,3,4]], [["a","b"],["c","d"]], True, False, dbus.Int16(-10), dbus.UInt16(10), 'SENTINEL', #([1,2,3],"c", 1.2, ["a","b","c"], {"a": (1,"v"), "b": (2,"d")}) ] NAME = "org.freedesktop.DBus.TestSuitePythonService" IFACE = "org.freedesktop.DBus.TestSuiteInterface" OBJECT = "/org/freedesktop/DBus/TestSuitePythonObject" class TestDBusBindings(unittest.TestCase): def setUp(self): self.bus = dbus.SessionBus() self.remote_object = self.bus.get_object(NAME, OBJECT) self.remote_object_follow = self.bus.get_object(NAME, OBJECT, follow_name_owner_changes=True) self.iface = dbus.Interface(self.remote_object, IFACE)
def do_VolumeSet(self, volume): self.__engine.SetVolume(dbus.UInt16(volume), reply_handler=lambda: None, error_handler=self.log.warn)
if __name__ == '__main__': dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) session_bus = dbus.SessionBus() name = dbus.service.BusName("com.example.TestService", session_bus) obj = TestService(session_bus, '/com/example/TestObject') #print "Our unique name is %s"%(session_bus.get_unique_name()) obj.frob_props = {} obj.frob_props["y"] = dbus.Byte(1) obj.frob_props["b"] = dbus.Boolean(True) obj.frob_props["n"] = dbus.Int16(2) obj.frob_props["q"] = dbus.UInt16(3) obj.frob_props["i"] = dbus.Int32(4) obj.frob_props["u"] = dbus.UInt32(5) obj.frob_props["x"] = dbus.Int64(6) obj.frob_props["t"] = dbus.UInt64(7) obj.frob_props["d"] = dbus.Double(7.5) obj.frob_props["s"] = dbus.String("a string") obj.frob_props["o"] = dbus.ObjectPath("/some/path") obj.frob_props["ay"] = [dbus.Byte(1), dbus.Byte(11)] obj.frob_props["ab"] = [dbus.Boolean(True), dbus.Boolean(False)] obj.frob_props["an"] = [dbus.Int16(2), dbus.Int16(12)] obj.frob_props["aq"] = [dbus.UInt16(3), dbus.UInt16(13)] obj.frob_props["ai"] = [dbus.Int32(4), dbus.Int32(14)] obj.frob_props["au"] = [dbus.UInt32(5), dbus.UInt32(15)] obj.frob_props["ax"] = [dbus.Int64(6), dbus.Int64(16)] obj.frob_props["at"] = [dbus.UInt64(7), dbus.UInt64(17)]
def AddDevice(self, adapter_device_name, device_address, alias): '''Convenience method to add a Bluetooth device You have to specify a device address which must be a valid Bluetooth address (e.g. 'AA:BB:CC:DD:EE:FF'). The alias is the human-readable name for the device (e.g. as set on the device itself), and the adapter device name is the device_name passed to AddAdapter. This will create a new, unpaired and unconnected device. Returns the new object path. ''' device_name = 'dev_' + device_address.replace(':', '_').upper() adapter_path = '/org/bluez/' + adapter_device_name path = adapter_path + '/' + device_name if adapter_path not in mockobject.objects: raise dbus.exceptions.DBusException( f'Adapter {adapter_device_name} does not exist.', name=BLUEZ_MOCK_IFACE + '.NoSuchAdapter') properties = { 'Address': dbus.String(device_address, variant_level=1), 'AddressType': dbus.String('public', variant_level=1), 'Name': dbus.String(alias, variant_level=1), 'Icon': dbus.String('', variant_level=1), 'Class': dbus.UInt32(0, variant_level=1), 'Appearance': dbus.UInt16(0, variant_level=1), 'UUIDs': dbus.Array([], signature='s', variant_level=1), 'Paired': dbus.Boolean(False, variant_level=1), 'Connected': dbus.Boolean(False, variant_level=1), 'Trusted': dbus.Boolean(False, variant_level=1), 'Blocked': dbus.Boolean(False, variant_level=1), 'WakeAllowed': dbus.Boolean(False, variant_level=1), 'Alias': dbus.String(alias, variant_level=1), 'Adapter': dbus.ObjectPath(adapter_path, variant_level=1), 'LegacyPairing': dbus.Boolean(False, variant_level=1), 'Modalias': dbus.String('', variant_level=1), 'RSSI': dbus.Int16(-79, variant_level=1), # arbitrary 'TxPower': dbus.Int16(0, variant_level=1), 'ManufacturerData': dbus.Array([], signature='a{qv}', variant_level=1), 'ServiceData': dbus.Array([], signature='a{sv}', variant_level=1), 'ServicesResolved': dbus.Boolean(False, variant_level=1), 'AdvertisingFlags': dbus.Array([], signature='ay', variant_level=1), 'AdvertisingData': dbus.Array([], signature='a{yv}', variant_level=1), } self.AddObject( path, DEVICE_IFACE, # Properties properties, # Methods [ ('CancelPairing', '', '', ''), ('Connect', '', '', Connect), ('ConnectProfile', 's', '', ''), ('Disconnect', '', '', Disconnect), ('DisconnectProfile', 's', '', ''), ('Pair', '', '', Pair), ]) device = mockobject.objects[path] device.paired = False device.connected = False manager = mockobject.objects['/'] manager.EmitSignal(OBJECT_MANAGER_IFACE, 'InterfacesAdded', 'oa{sa{sv}}', [ dbus.ObjectPath(path), { DEVICE_IFACE: properties }, ]) return path
def start_ble_beaconing(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() option_list = [ make_option("-i", "--device", action="store", type="string", dest="dev_id"), make_option("-u", "--uuids", action="store", type="string", dest="uuids", help="Filtered service UUIDs [uuid1,uuid2,...]"), make_option("-r", "--rssi", action="store", type="int", dest="rssi", help="RSSI threshold value"), make_option("-p", "--pathloss", action="store", type="int", dest="pathloss", help="Pathloss threshold value"), make_option("-t", "--transport", action="store", type="string", dest="transport", help="Type of scan to run (le/bredr/auto)"), make_option("-c", "--compact", action="store_true", dest="compact"), ] parser = OptionParser(option_list=option_list) (options, args) = parser.parse_args() adapter = bluezutils.find_adapter(options.dev_id) if options.compact: compact = True; bus.add_signal_receiver(interfaces_added, dbus_interface = "org.freedesktop.DBus.ObjectManager", signal_name = "InterfacesAdded") bus.add_signal_receiver(properties_changed, dbus_interface = "org.freedesktop.DBus.Properties", signal_name = "PropertiesChanged", arg0 = "org.bluez.Device1", path_keyword = "path") om = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager") objects = om.GetManagedObjects() for path, interfaces in objects.iteritems(): if "org.bluez.Device1" in interfaces: devices[path] = interfaces["org.bluez.Device1"] scan_filter = dict() if options.uuids: uuids = [] uuid_list = options.uuids.split(',') for uuid in uuid_list: uuids.append(uuid) scan_filter.update({ "UUIDs": uuids }) if options.rssi: scan_filter.update({ "RSSI": dbus.Int16(options.rssi) }) if options.pathloss: scan_filter.update({ "Pathloss": dbus.UInt16(options.pathloss) }) if options.transport: scan_filter.update({ "Transport": options.transport }) adapter.SetDiscoveryFilter(scan_filter) adapter.StartDiscovery()
class Profile(dbus.service.Object): fd = -1 @dbus.service.method("org.bluez.Profile1",in_signature="", out_signature="") def Release(self): print("Release") mainloop.quit() @dbus.service.method("org.bluez.Profile1",in_signature="", out_signature="") def Cancel(self): print("Cancel") @dbus.service.method("org.bluez.Profile1",in_signature="oha{sv}", out_signature="") def NewConnection(self, path, fd, properties): self.fd = fd.take() print("NewConnection(%s, %d)" % (path, self.fd)) server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM) server_sock.setblocking(1) server_sock.send("This is Edison SPP loopback test\nAll data will be loopback\nPlease start:\n") try: while True: data = server_sock.recv(1024) print("received: %s" % data) server_sock.send("looping back: %s\n" % data) except IOError: pass server_sock.close() print("all done") @dbus.service.method("org.bluez.Profile1",in_signature="o", out_signature="") def RequestDisconnection(self, path): print("RequestDisconnection(%s)" % (path)) if (self.fd > 0): os.close(self.fd) self.fd = -1 if __name__ == '__main__': dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object("org.bluez","/org/bluez"), "org.bluez.ProfileManager1") option_list = [make_option("-C", "--channel", action="store",type="int", dest="channel",default=None),] parser = OptionParser(option_list=option_list) (options, args) = parser.parse_args() options.uuid = "1101" options.psm = "3" options.role = "server" options.name = "Edison SPP Loopback" options.service = "spp char loopback" options.path = "/foo/bar/profile" options.auto_connect = False options.record = "" profile = Profile(bus, options.path) mainloop = GObject.MainLoop() opts = {"AutoConnect" : options.auto_connect,} if (options.name): opts["Name"] = options.name if (options.role): opts["Role"] = options.role if (options.psm is not None): opts["PSM"] = dbus.UInt16(options.psm) if (options.channel is not None): opts["Channel"] = dbus.UInt16(options.channel) if (options.record): opts["ServiceRecord"] = options.record if (options.service): opts["Service"] = options.service if not options.uuid: options.uuid = str(uuid.uuid4()) manager.RegisterProfile(options.path, options.uuid, opts) mainloop.run()
#! /usr/bin/env python import time import threading import docker import avahi import dbus from encodings.idna import ToASCII TTL = dbus.UInt32(60) CLASS_IN = dbus.UInt16(0x01) TYPE_CNAME = dbus.UInt16(0x05) class Publisher(object): cnames = set() def run(self, ttl=50): while True: time.sleep(ttl) publisher.publish_all() def publish_all(self): for cname in self.cnames: print("Publishing " + cname) self.publish_cname(cname) def publish_cname(self, cname): bus = dbus.SystemBus() server = dbus.Interface(
const="client", dest="role"), make_option("-s", "--server", action="store_const", const="server", dest="role"), ] mainloop = GObject.MainLoop() parser = OptionParser(option_list=option_list) (options, args) = parser.parse_args() chat = BlueZChat(bus, path) if (options.role): opts["Role"] = options.role if options.role == "server": print "Bluez5 Chat example Server" elif options.role == "client": print "Bluez5 Chat example Client" else: print "One should act as a server the other one as a client" print "take a look at the help" sys.exit(1) # Well don't know so much but the default '6' didn't works, # I have to check bluez and bluetooth doc opts["Channel"] = dbus.UInt16(10) opts["Name"] = "BlueZChat" manager.RegisterProfile(path, uuid, opts) if options.role == "client": GObject.timeout_add(100, connect_to_server) mainloop.run()
def usage(): print "Usage:\n" \ "Offer a stream tube to [muc] using the trivial stream server:\n" \ "\tpython %s [account-file] [muc] --initiator\n" \ "Accept a stream tube from [muc] and connect it to the trivial stream client:\n" \ "\tpython %s [account-file] [muc]\n" \ "Offer a stream tube to [muc] using the socket [IP]:[port]:\n" \ "\tpython %s [account-file] [muc] [IP] [port]\n" \ "Accept a stream tube from [muc] and wait for connections from an external client:\n" \ "\tpython %s [account-file] [muc] --no-trivial-client\n" \ % (sys.argv[0], sys.argv[0], sys.argv[0], sys.argv[0]) if __name__ == '__main__': args = sys.argv[1:] if len(args) == 3 and args[2] == '--initiator': client = StreamTubeInitiatorMucClient(args[0], args[1]) elif len(args) == 2: client = StreamTubeJoinerMucClient(args[0], args[1], True) elif len(args) == 4: client = StreamTubeInitiatorMucClient(args[0], args[1], (args[2], dbus.UInt16(args[3]))) elif len(args) == 3 and args[2] == '--no-trivial-client': client = StreamTubeJoinerMucClient(args[0], args[1], False) else: usage() sys.exit(0) client.run()