Пример #1
0
def getDisableScaling(app_id: str = 'dde-file-manager', target: bool = False) -> bool:
    """
    GetDisableScaling (string id) -> (bool value): 获取id对应的程序是否禁用缩放,true表示禁用,false表示不禁用
    :param app_id: 对应程序的id,可以使用GetAllItemInfos接口获得,默认检查文件管理器
    :param target: 预期结果,文件管理器默认是可以缩放
    :return:True or False
    """
    property_obj = sessionCommon.session_bus(DBUS_NAMEN, DBUS_PATH, IFACE_NAME)
    is_scaling = property_obj.GetDisableScaling(dbus.String(app_id))
    if isinstance(is_scaling, dbus.Boolean):
        if dbus.Boolean(target) == is_scaling:
            logging.info(f'is_scaling: {is_scaling}')
            return True
        else:
            logging.info(f'请检查{app_id}是否可以缩放')
            return False
    else:
        logging.info('返回的数据类型有误')
        return False
Пример #2
0
def advertising_main(mainloop, bus, adapter_name):
    adapter = adapters.find_adapter(bus, LE_ADVERTISING_MANAGER_IFACE, adapter_name)
    print('adapter: %s' % (adapter,))
    if not adapter:
        raise Exception('LEAdvertisingManager1 interface not found')

    adapter_props = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter), "org.freedesktop.DBus.Properties")

    print('powering on')
    adapter_props.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(1))
    print('powered on')

    ad_manager = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter), LE_ADVERTISING_MANAGER_IFACE)

    test_advertisement = TestAdvertisement(bus, 0)

    ad_manager.RegisterAdvertisement(test_advertisement.get_path(), {},
                                     reply_handler=register_ad_cb,
                                     error_handler=functools.partial(register_ad_error_cb, mainloop))
Пример #3
0
 def test_get_properties(self, eth0_file_mock):
     variant_details = variant_definitions['NEBHNT-OUT1']
     advertisement = BluetoothConnectionAdvertisement(
         110, 'A1:B2:C3:DD:E5:F6', 'peripheral', variant_details)
     properties = advertisement.get_properties()
     expected = {
         'org.bluez.LEAdvertisement1': {
             'Type':
             'peripheral',
             'IncludeTxPower':
             dbus.Boolean(True),
             'LocalName':
             dbus.String('Nebra %s Hotspot %s' % ('Outdoor', 'DDE5F6')),
             'ServiceUUIDs':
             dbus.Array([DEFAULT_SERVICE_UUID],
                        signature=dbus.Signature('s'))
         }
     }
     self.assertDictEqual(properties, expected)
Пример #4
0
def isItemOnDesktop(app_id: str = 'dde-file-manager', target: bool = False) -> bool:
    """
    IsItemOnDesktop (string id) -> (bool result):获取id对应的程序是否有桌面图标,true表示桌面有图标,false表示没有
    :param app_id:应程序的id,可以使用GetAllItemInfos接口获得,默认检查文件管理器
    :param target:预期结果,文件管理器默认无图标
    :return:True or False
    """
    property_obj = sessionCommon.session_bus(DBUS_NAMEN, DBUS_PATH, IFACE_NAME)
    is_item_on_desktop = property_obj.IsItemOnDesktop(dbus.String(app_id))
    if isinstance(is_item_on_desktop, dbus.Boolean):
        if dbus.Boolean(target) == is_item_on_desktop:
            logging.info(f'is_item_on_desktop: {is_item_on_desktop}')
            return True
        else:
            logging.info(f'请检查{app_id}是否存在桌面图标')
            return False
    else:
        logging.info('返回的数据类型有误')
        return False
Пример #5
0
def launch_route_calculation(route):
    global g_current_route
    global g_route_handle
    global g_routing_interface
    global g_navigationcore_session_handle
    g_current_route = route
    print 'Route name: ' + routes[g_current_route].getElementsByTagName(
        "name")[0].childNodes[0].data
    #get route handle
    ret = g_routing_interface.CreateRoute(
        dbus.UInt32(g_navigationcore_session_handle))
    g_route_handle = ret[1]
    routes[g_current_route].getElementsByTagName(
        "handle")[0].childNodes[0].data = g_route_handle
    print 'Route handle: ' + str(g_route_handle)
    start = routes[g_current_route].getElementsByTagName(
        "start")[0].childNodes[0].data
    dest = routes[g_current_route].getElementsByTagName(
        "destination")[0].childNodes[0].data
    print 'Calculating route from \
' + start + '(' + str(locations[routes[g_current_route].getElementsByTagName(
        "start")[0].childNodes[0].data][0]) + ',' + str(
            locations[routes[g_current_route].getElementsByTagName(
                "start")[0].childNodes[0].data][1]) + ') to \
' + dest + '(' + str(locations[routes[g_current_route].getElementsByTagName(
                    "destination")[0].childNodes[0].data][0]) + ',' + str(
                        locations[routes[g_current_route].getElementsByTagName(
                            "destination")[0].childNodes[0].data][1]) + ')'
    #set waypoints
    waypointDoubleCapiType = 0x03
    g_routing_interface.SetWaypoints(dbus.UInt32(g_navigationcore_session_handle), \
                                   dbus.UInt32(g_route_handle), \
                                   dbus.Boolean(0), \
                                   dbus.Array([ \
                                        dbus.Dictionary({dbus.Int32(GENIVI_NAVIGATIONCORE_LATITUDE):dbus.Struct([dbus.Byte(waypointDoubleCapiType),dbus.Double(locations[routes[g_current_route].getElementsByTagName("start")[0].childNodes[0].data][0])]),dbus.Int32(GENIVI_NAVIGATIONCORE_LONGITUDE):dbus.Struct([dbus.Byte(waypointDoubleCapiType),dbus.Double(locations[routes[g_current_route].getElementsByTagName("start")[0].childNodes[0].data][1])])}), \
                                        dbus.Dictionary({dbus.Int32(GENIVI_NAVIGATIONCORE_LATITUDE):dbus.Struct([dbus.Byte(waypointDoubleCapiType),dbus.Double(locations[routes[g_current_route].getElementsByTagName("destination")[0].childNodes[0].data][0])]),dbus.Int32(GENIVI_NAVIGATIONCORE_LONGITUDE):dbus.Struct([dbus.Byte(waypointDoubleCapiType),dbus.Double(locations[routes[g_current_route].getElementsByTagName("destination")[0].childNodes[0].data][1])])}) \
                                   ]) \
                                   )

    #calculate route
    g_routing_interface.CalculateRoute(
        dbus.UInt32(g_navigationcore_session_handle),
        dbus.UInt32(g_route_handle))
def main():
    global mainloop

    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    bus = dbus.SystemBus()

    adapter = find_adapter(bus)
    if not adapter:
        print 'LEAdvertisingManager1 interface not found'
        return

    # ADVERTISE

    adapter_props = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter),
                                   "org.freedesktop.DBus.Properties")

    adapter_props.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(1))

    ad_manager = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, adapter),
                                LE_ADVERTISING_MANAGER_IFACE)

    test_advertisement = TestAdvertisement(bus, 0)

    # Service
    service_manager = dbus.Interface(
        bus.get_object(BLUEZ_SERVICE_NAME, adapter), GATT_MANAGER_IFACE)

    app = Application(bus)

    mainloop = gobject.MainLoop()

    ad_manager.RegisterAdvertisement(test_advertisement.get_path(), {},
                                     reply_handler=register_ad_cb,
                                     error_handler=register_ad_error_cb)

    print('Registering GATT application...')

    service_manager.RegisterApplication(app.get_path(), {},
                                        reply_handler=register_app_cb,
                                        error_handler=register_app_error_cb)

    mainloop.run()
Пример #7
0
def make_connection(bus, event_func, params=None):
    default_params = {
        'account': 'test',
        'server': '127.0.0.1',
        'password': '',
        'fullname': 'Test User',
        'username': '******',
        'charset': 'UTF-8',
        'quit-message': 'happy testing...',
        'use-ssl': dbus.Boolean(False),
        'port': dbus.UInt32(6900),
        'keepalive-interval': dbus.UInt32(0),
        }

    if params:
        default_params.update(params)

    return servicetest.make_connection(bus, event_func, 'idle', 'irc',
        default_params)
Пример #8
0
 def pool_create(pool_name, devices):
     """
     Create a pool
     :param pool_name: The name of the pool to create
     :param str devices: A list of devices that can be used to create the pool
     :return: The return values of the CreatePool call
     :rtype: The D-Bus types (b(oao)), q, and s
     """
     iface = dbus.Interface(
         StratisDbus._BUS.get_object(StratisDbus._BUS_NAME,
                                     StratisDbus._TOP_OBJECT),
         StratisDbus._MNGR_IFACE,
     )
     return iface.CreatePool(
         pool_name,
         (dbus.Boolean(False), dbus.UInt16(0)),
         devices,
         timeout=StratisDbus._TIMEOUT,
     )
Пример #9
0
def add_simmanager_api(mock):
    '''Add org.ofono.SimManager API to a mock'''

    iface = 'org.ofono.SimManager'
    mock.AddProperties(
        iface, {
            'CardIdentifier':
            _parameters.get('CardIdentifier', 12345),
            'Present':
            _parameters.get('Present', dbus.Boolean(True)),
            'SubscriberNumbers':
            _parameters.get('SubscriberNumbers', ['123456789', '234567890']),
            'SubscriberIdentity':
            _parameters.get('SubscriberIdentity', 23456),
            'ServiceNumbers':
            _parameters.get(
                'ServiceNumbers',
                dbus.Dictionary(
                    {
                        'Fake Service': dbus.String('555-555',
                                                    variant_level=1),
                        'Faker Service': dbus.String('555-321',
                                                     variant_level=1),
                        'Fakest Service': dbus.String('555-123',
                                                      variant_level=1)
                    },
                    signature='sv')),
            'LockedPins':
            _parameters.get('LockedPins', ['pin']),
            'Retries':
            _parameters.get('Retries', {'pin': dbus.Byte(3)}),
            'PinRequired':
            _parameters.get('PinRequired', 'none')
        })

    mock.AddMethods(
        iface,
        [('GetProperties', '', 'a{sv}', 'ret = self.GetAll("%s")' % iface),
         ('SetProperty', 'sv', '', 'self.Set("%(i)s", args[0], args[1]); '
          'self.EmitSignal("%(i)s", "PropertyChanged", "sv", [args[0], '
          'args[1]])' % {
              'i': iface
          }), ('ResetPin', 'sss', '', '')])
Пример #10
0
    def trust(self, address):
        try:
            device = bluezutils.find_device(address)
        except bluezutils.BluezUtilError as error:
            print(error)
            return False
        else:
            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:
                print(error)
                return False

        return True
Пример #11
0
    def GetAll(self, interface_name):
        """Return the advertisement properties.

        This method is registered with the D-Bus at
        ``org.freedesktop.DBus.Properties``

        :param interface: interface to get the properties of.

        The interface must be ``org.bluez.LEAdvertisement1`` otherwise an
        exception is raised.
        """
        if interface_name != constants.LE_ADVERTISEMENT_IFACE:
            raise InvalidArgsException()

        response = dict()
        response['Type'] = self.props[interface_name]['Type']
        if self.props[interface_name]['ServiceUUIDs'] is not None:
            response['ServiceUUIDs'] = dbus.Array(
                self.props[interface_name]['ServiceUUIDs'],
                signature='s')
        if self.props[interface_name]['ServiceData'] is not None:
            response['ServiceData'] = dbus.Dictionary(
                self.props[interface_name]['ServiceData'],
                signature='sv')
        if self.props[interface_name]['ManufacturerData'] is not None:
            response['ManufacturerData'] = dbus.Dictionary(
                self.props[interface_name]['ManufacturerData'],
                signature='qv')
        if self.props[interface_name]['SolicitUUIDs'] is not None:
            response['SolicitUUIDs'] = dbus.Array(
                self.props[interface_name]['SolicitUUIDs'],
                signature='s')
        if self.props[interface_name]['LocalName'] is not None:
            response['LocalName'] = dbus.String(
                    self.props[interface_name]['LocalName'])
        if self.props[interface_name]['Appearance'] is not None:
            response['Appearance'] = dbus.UInt16(
                    self.props[interface_name]['Appearance'])
        response['IncludeTxPower'] = dbus.Boolean(
            self.props[interface_name]['IncludeTxPower'])

        return response
Пример #12
0
def changeResource(set, resource, attribute, value):

    res = get_resource(set, resource)

    if res:
        try:
            if attribute == "shared" or attribute == "mandatory":
                val = False
                if value == "True" or value == "1":
                    val = True

                res.setProperty(attribute, dbus.Boolean(val, variant_level=1))
                print("(%s/%s) set attribute '%s' to '%s'" %
                      (set, resource, attribute, val))
            else:
                attrs = res.getProperties()["attributes"]

                if attribute in attrs:

                    if type(attrs[attribute]) is dbus.String:
                        attrs[attribute] = dbus.String(value)
                    elif type(attrs[attribute]) is dbus.Int32:
                        attrs[attribute] = dbus.Int32(value)
                    elif type(attrs[attribute]) is dbus.UInt32:
                        attrs[attribute] = dbus.UInt32(value)
                    elif type(attrs[attribute]) is dbus.Double:
                        attrs[attribute] = dbus.Double(value)

                    res.setProperty("attributes_conf", attrs)
                    print("(%s/%s) set attribute '%s' to '%s'" %
                          (set, resource, attribute, str(attrs[attribute])))
                else:
                    print(
                        "ERROR (%s/%s): attribute '%s' not supported in resource"
                        % (set, resource, attribute))
        except dbus.DBusException as e:
            print(
                "ERROR (%s/%s): failed to set attribute '%s' in resource: %s" %
                (set, resource, attribute, e))
        except:
            print("ERROR (%s/%s): failed to convert value type to D-Bus" %
                  (set, resource))
Пример #13
0
 def dbus_config(self, category):
     value = None
     postfix = ''
     if self.struct[category]['type'] == 'Dictionary':
         value = {}
         postfix = '.Configuration'
     elif self.struct[category]['type'] == 'Array':
         value = dbus.Array([],
                            signature=dbus.Signature('s'),
                            variant_level=1)
         postfix = '.Configuration'
     for entry in sorted(
             self.struct[category]['settings'],
             key=lambda x: self.struct[category]['settings'][x]['order']):
         setting = self.struct[category]['settings'][entry]
         if (setting['value'] != '' or (hasattr(setting, 'changed') and not hasattr(setting, 'notempty'))) \
            and (not 'parent' in setting or ('parent' in setting and self.struct[category]['settings'][setting['parent']['entry']]['value'] \
                                             in setting['parent']['value'])):
             if setting['dbus'] == 'Array':
                 value = dbus.Array(dbus.String(setting['value'],
                                                variant_level=1).split(','),
                                    signature=dbus.Signature('s'),
                                    variant_level=1)
             else:
                 if self.struct[category]['type'] == 'Boolean':
                     if setting['value'] == '1' or setting[
                             'value'] == dbus.Boolean(True,
                                                      variant_level=1):
                         setting['value'] = True
                     else:
                         setting['value'] = False
                     value = getattr(dbus,
                                     setting['dbus'])(setting['value'],
                                                      variant_level=1)
                 elif self.struct[category]['type'] == 'Dictionary':
                     value[entry] = getattr(dbus, setting['dbus'])(
                         setting['value'], variant_level=1)
                 elif self.struct[category]['type'] == 'Array':
                     value.append(
                         getattr(dbus, setting['dbus'])(setting['value'],
                                                        variant_level=1))
     return (category + postfix, value)
Пример #14
0
def main():
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
    global bus
    bus = dbus.SystemBus()
    wpas_obj = bus.get_object(WPAS_DBUS_SERVICE, WPAS_DBUS_OPATH)

    if len(sys.argv) != 2:
        print("Missing ifname argument")
        os._exit(1)

    wpas = dbus.Interface(wpas_obj, WPAS_DBUS_INTERFACE)
    bus.add_signal_receiver(scanDone,
                            dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE,
                            signal_name="ScanDone")
    bus.add_signal_receiver(bssAdded,
                            dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE,
                            signal_name="BSSAdded")
    bus.add_signal_receiver(bssRemoved,
                            dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE,
                            signal_name="BSSRemoved")
    bus.add_signal_receiver(propertiesChanged,
                            dbus_interface=WPAS_DBUS_INTERFACES_INTERFACE,
                            signal_name="PropertiesChanged")
    bus.add_signal_receiver(wpsEvent,
                            dbus_interface=WPAS_DBUS_WPS_INTERFACE,
                            signal_name="Event")
    bus.add_signal_receiver(credentials,
                            dbus_interface=WPAS_DBUS_WPS_INTERFACE,
                            signal_name="Credentials")

    ifname = sys.argv[1]

    path = wpas.GetInterface(ifname)
    if_obj = bus.get_object(WPAS_DBUS_SERVICE, path)
    if_obj.Set(WPAS_DBUS_WPS_INTERFACE,
               'ProcessCredentials',
               dbus.Boolean(1),
               dbus_interface=dbus.PROPERTIES_IFACE)
    wps = dbus.Interface(if_obj, WPAS_DBUS_WPS_INTERFACE)
    wps.Start({'Role': 'enrollee', 'Type': 'pbc'})

    gobject.MainLoop().run()
Пример #15
0
 def _modem_status_change(name, value):
     """
         Handler for modem status changes.
         If modem is connected (online) then instantiate the VoiceCallManager
         and start listening for calls.
         This is the only place where the bluetooth connction can be established.
         @name: string : Name of property change that trigger this handler
         @value: dbus datatype : The new value that property takes
     """
     if name == 'Online':
         print(f"Modem online status change {path}")
         if value == dbus.Boolean(True, variant_level=1):
             print("Previously paired mobile phone has just connected.")
             self.modem_object = self.all_modem_objects[path][0]
             self.modem_name = self.all_modem_objects[path][1]
             self._refresh_pulseaudio_cards()
             print("fire signal to indicate that we can start listening for calls")
             self.status_service.emit(config.READY)
         else:
             print("phone has disconnected from RPi")
Пример #16
0
    def test_enable_animations(self):
        # Check that "Enable animations" is off
        self.assertEqual(self.obj_xsettings_props.Get('org.gtk.Settings', 'EnableAnimations'),
                dbus.Boolean(True, variant_level=1))

        # Make vino appear
        vino = self.spawn_server('org.gnome.Vino',
                '/org/gnome/vino/screens/0',
                'org.gnome.VinoScreen')

        dbus_con = self.get_dbus()
        obj_vino = dbus_con.get_object('org.gnome.Vino', '/org/gnome/vino/screens/0')
        mock_vino = dbus.Interface(obj_vino, dbusmock.MOCK_IFACE)
        mock_vino.AddProperty('', 'Connected', dbus.Boolean(False, variant_level=1))

        time.sleep(0.1)

        # Check animations are still enabled
        self.assertEqual(self.obj_xsettings_props.Get('org.gtk.Settings', 'EnableAnimations'),
                dbus.Boolean(True, variant_level=1))

        # Connect a remote user
        mock_vino.EmitSignal('org.freedesktop.DBus.Properties',
                             'PropertiesChanged',
                            'sa{sv}as',
                            ['org.gnome.VinoScreen',
                            dbus.Dictionary({'Connected': dbus.Boolean(True, variant_level=1)}, signature='sv'),
                            dbus.Array([], signature='s')
                            ])

        time.sleep(0.1)

        # gdbus debug output
        # gdbus_log_write = open(os.path.join(self.workdir, 'gdbus.log'), 'wb')
        # process = subprocess.Popen(['gdbus', 'introspect', '--session', '--dest', 'org.gnome.Vino', '--object-path', '/org/gnome/vino/screens/0'],
        #         stdout=gdbus_log_write, stderr=subprocess.STDOUT)
        # time.sleep(1)

        # Check that "Enable animations" is off
        self.assertEqual(self.obj_xsettings_props.Get('org.gtk.Settings', 'EnableAnimations'),
                dbus.Boolean(False, variant_level=1))

        vino.terminate()
        vino.wait()
        time.sleep(0.1)

        # Check animations are back enabled
        self.assertEqual(self.obj_xsettings_props.Get('org.gtk.Settings', 'EnableAnimations'),
                dbus.Boolean(True, variant_level=1))
Пример #17
0
def saveAudioState():
    """
    获取当前停靠在dock栏上的所有的引用id列表,目前仅仅是写入设置参数到配置文件,无实际功能效果
    :param activePlayback:设置设备的参数信息,格式为{"card": string类型, "device": string类型, mute:bool类型}
    card和device的值可以在终端用命令 aplay -L列表所有的音频设备信息
    :return:True or False
    """
    time.sleep(2)
    activePlayback = {"card": 'HDMI', "device": '3', "mute": dbus.Boolean(False)}
    property_obj = system_bus()
    dbus_out = property_obj.SaveAudioState(activePlayback)
    logging.info(dbus_out)
    out = excute_cmd('aplay -L|grep DEV=3')
    logging.info(out)
    if out:
        logging.info("设置参数成功")
        return True
    else:
        logging.info("设置参数失败")
        return False
Пример #18
0
    def test_add_object_with_methods(self):
        '''add a new object with methods'''

        self.dbus_mock.AddObject('/obj1',
                                 'org.freedesktop.Test.Sub',
                                 {
                                     'state': dbus.String('online', variant_level=1),
                                     'cute': dbus.Boolean(True, variant_level=1),
                                 },
                                 [
                                     ('Do0', '', 'i', 'ret = 42'),
                                     ('Do1', 'i', 'i', 'ret = 31337'),
                                 ])

        obj1 = self.dbus_con.get_object('org.freedesktop.Test', '/obj1')

        self.assertEqual(obj1.Do0(), 42)
        self.assertEqual(obj1.Do1(1), 31337)
        self.assertRaises(dbus.exceptions.DBusException,
                          obj1.Do2, 31337)
Пример #19
0
    def test_convert(self):
        """test converting from dbus types to python types"""

        if sys.version_info[0] == 2:
            str_type = unicode
        else:
            str_type = str

        tests = ((dbus.Boolean(True), bool), (dbus.Byte(10), int),
                 (dbus.Int16(10), int), (dbus.Int32(10), int),
                 (dbus.Int64(10), int), (dbus.UInt16(10), int),
                 (dbus.UInt32(10), int), (dbus.UInt64(10), int),
                 (dbus.Double(10.01), float), (dbus.String('test'), str_type),
                 (dbus.ObjectPath('/path/to/stuff'),
                  str_type), (dbus.Signature('uu'),
                              str_type), (dbus.Dictionary({1: 1}),
                                          dict), (dbus.Struct((1, )), tuple))

        for test in tests:
            self.assertIsInstance(convert(test[0]), test[1])
Пример #20
0
    def on_conversation_user_joined(self, contact):
        handle = self._conn.ensure_contact_handle(contact)
        logger.info("User %s joined" % str(handle))

        if self._initial_handle == handle:
            return

        props = {
            telepathy.CHANNEL + '.ChannelType': dbus.String(telepathy.CHANNEL_TYPE_TEXT),
            telepathy.CHANNEL + '.TargetHandleType': dbus.UInt32(telepathy.HANDLE_TYPE_NONE),
            CHANNEL_INTERFACE_CONFERENCE + '.InitialChannels': dbus.Array([self._object_path], signature='o'),
            CHANNEL_INTERFACE_CONFERENCE + '.InitialInviteeIDs': dbus.Array([dbus.String(handle.get_name())], signature='s'),
            telepathy.CHANNEL + '.Requested': dbus.Boolean(False)
            }

        new_channel = self._conn_ref()._channel_manager.channel_for_props(props,
            signal=True, conversation=None)

        logger.info('Created new MUC channel to replace this 1-1 one: %s' % \
            new_channel._object_path)
Пример #21
0
def setTime(usec, relative, message):
    """
    设置当前时间和日期
    :param usec:自1970年1月1日零时起, 到当前时间的微秒数
    :param relative:是否关联
    :param message:关于设置当前时间和日期的认证信息
    :return:True or False
    :examlpe:1595487474000000,True,''
    """
    time.sleep(2)
    property_obj = systemCommon.system_bus(dbus_name, dbus_path, iface_name)
    result = property_obj.SetTime(dbus.Int64(usec), dbus.Boolean(relative),
                                  dbus.String(message))
    logging.info(result)
    if not result:
        logging.info('设置当前时间和日期成功')
        return True
    else:
        logging.info("设置当前时间和日期失败")
        return False
Пример #22
0
 def get_properties(self):
     properties = dict()
     properties['Type'] = self.ad_type
     if self.service_uuids is not None:
         properties['ServiceUUIDs'] = dbus.Array(self.service_uuids,
                                                 signature='s')
     if self.solicit_uuids is not None:
         properties['SolicitUUIDs'] = dbus.Array(self.solicit_uuids,
                                                 signature='s')
     if self.manufacturer_data is not None:
         properties['ManufacturerData'] = dbus.Dictionary(
             self.manufacturer_data, signature='qv')
     if self.service_data is not None:
         properties['ServiceData'] = dbus.Dictionary(self.service_data,
                                                     signature='sv')
     if self.local_name is not None:
         properties['LocalName'] = dbus.String(self.local_name)
     if self.include_tx_power is not None:
         properties['IncludeTxPower'] = dbus.Boolean(self.include_tx_power)
     return {LE_ADVERTISEMENT_IFACE: properties}
Пример #23
0
    def test_20_enable_modules(self):
        manager = self.get_interface(self.manager_obj, '.Manager')
        manager_intro = dbus.Interface(self.manager_obj,
                                       "org.freedesktop.DBus.Introspectable")
        intro_data = manager_intro.Introspect()
        modules = self._get_modules()
        modules_loaded = any('interface name="%s.Manager.%s"' %
                             (self.iface_prefix, module) in intro_data
                             for module in modules)

        if modules_loaded:
            self.skipTest("Modules already loaded, nothing to test")
        else:
            manager.EnableModules(dbus.Boolean(True))
            intro_data = manager_intro.Introspect()

            for module in modules:
                self.assertIn(
                    'interface name="%s.Manager.%s"' %
                    (self.iface_prefix, module), intro_data)
Пример #24
0
    def make_discoverable(self):
        try:
            adapter = bluezutils.find_adapter()
        except bluezutils.BluezUtilError as error:
            print(error)
            return False
        else:
            try:
                props = dbus.Interface(
                    self.__bus.get_object("org.bluez", adapter.object_path),
                    "org.freedesktop.DBus.Properties")

                if not props.Get("org.bluez.Adapter1", "Discoverable"):
                    props.Set("org.bluez.Adapter1", "Discoverable",
                              dbus.Boolean(1))
            except dbus.exceptions.DBusException as error:
                print(error)
                return False

        return True
Пример #25
0
def createMapView():
    global g_mapviewer_sessionhandle
    global g_mapviewer_sessionstatus
    global g_mapviewer_sessionlist
    global g_mapviewer_maphandle

    #get mapviewer session handle
    ret = g_mapviewer_session_interface.CreateSession(
        dbus.String('test mapviewer'))
    g_mapviewer_sessionhandle = ret[1]
    print('Mapviewer session handle: ' + str(g_mapviewer_sessionhandle))

    g_mapviewer_sessionstatus = g_mapviewer_session_interface.GetSessionStatus(
        dbus.UInt32(g_mapviewer_sessionhandle))
    print('Mapviewer session status: ' + str(g_mapviewer_sessionstatus))

    g_mapviewer_sessionlist = g_mapviewer_session_interface.GetAllSessions()
    print('Mapviewer active sessions = ' + str(len(g_mapviewer_sessionlist)))

    #get mapviewer handle
    ret = g_mapviewercontrol_interface.CreateMapViewInstance( \
      dbus.UInt32(g_mapviewer_sessionhandle), \
      dbus.Struct((dbus.UInt16(HORIZONTAL_SIZE),dbus.UInt16(VERTICAL_SIZE))), \
     dbus.Int32(genivi.MAIN_MAP))
    g_mapviewer_maphandle = ret[1]

    print('MapView handle: ' + str(g_mapviewer_maphandle))

    time.sleep(2)

    print('Stop following the car position')
    g_mapviewercontrol_interface.SetFollowCarMode( \
        dbus.UInt32(g_mapviewer_sessionhandle), \
        dbus.UInt32(g_mapviewer_maphandle), \
        dbus.Boolean(False))

    print('Set the 2D perspective')
    g_mapviewercontrol_interface.SetMapViewPerspective(\
        dbus.UInt32(g_mapviewer_sessionhandle),\
        dbus.UInt32(g_mapviewer_maphandle), \
        genivi.PERSPECTIVE_TWO_D)
Пример #26
0
    def __init__(self, mainloop, bus):
        self.mainloop = mainloop

        adapter = self.find_adapter(bus)
        if not adapter:
            print('LEAdvertisingManager1 interface not found')
            return

        adapter_props = dbus.Interface(
            bus.get_object(BLUEZ_SERVICE_NAME, adapter),
            "org.freedesktop.DBus.Properties")
        adapter_props.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(1))
        ad_manager = dbus.Interface(
            bus.get_object(BLUEZ_SERVICE_NAME, adapter),
            LE_ADVERTISING_MANAGER_INTERFACE)
        advertisement = TransmitAdvertisement(bus, 0)

        ad_manager.RegisterAdvertisement(
            advertisement.get_path(), {},
            reply_handler=self.registration_succeeded,
            error_handler=self.registration_failed)
Пример #27
0
    def trust(self, address, adapter_idx=0):
        try:
            device = bluezutils.find_device(self._adapters[adapter_idx],
                                            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
def find_adapter(bus):
    remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'),
                                DBUS_OM_IFACE)
    objects = remote_om.GetManagedObjects()

    adapter = None
    adapter_props = None

    for o, props in objects.items():
        if ADV_MONITOR_MANAGER_IFACE in props:
            adapter = o
            break

    if adapter:
        # Turn on the bluetooth adapter.
        adapter_props = dbus.Interface(
                                bus.get_object(BLUEZ_SERVICE_NAME, adapter),
                                DBUS_PROP_IFACE)
        adapter_props.Set('org.bluez.Adapter1', 'Powered', dbus.Boolean(1))

    return adapter, adapter_props
Пример #29
0
def wrap_dbus_value(value):
    if value == None:
        return VeDbusInvalid
    if isinstance(value, float):
        return dbus.Double(value, variant_level=1)
    if isinstance(value, bool):
        return dbus.Boolean(value, variant_level=1)
    if isinstance(value, int):
        return dbus.Int32(value, variant_level=1)
    if isinstance(value, str):
        return dbus.String(value, variant_level=1)
    if isinstance(value, list):
        return dbus.Array([wrap_dbus_value(x) for x in value], variant_level=1)
    if isinstance(value, long):
        return dbus.Int64(value, variant_level=1)
    if isinstance(value, dict):
        return dbus.Dictionary(
            {(wrap_dbus_value(k), wrap_dbus_value(v))
             for k, v in value.items()},
            variant_level=1)
    return value
Пример #30
0
    def activate(self, leaf, iobj):
        bus = dbus.SessionBus()
        interface = _create_dbus_connection()
        for valid_account in interface.Get(ACCOUNTMANAGER_IFACE,
                                           "ValidAccounts"):
            account = bus.get_object(ACCOUNTMANAGER_IFACE, valid_account)
            connection_status = account.Get(ACCOUNT_IFACE, "ConnectionStatus")
            if connection_status != 0:
                continue

            if iobj.object == "offline":
                false = dbus.Boolean(0, variant_level=1)
                account.Set(ACCOUNT_IFACE, "Enabled", false)
            else:
                connection_path = account.Get(ACCOUNT_IFACE, "Connection")
                connection_iface = connection_path.replace("/", ".")[1:]
                connection = bus.get_object(connection_iface, connection_path)
                simple_presence = dbus.Interface(connection,
                                                 SIMPLE_PRESENCE_IFACE)
                simple_presence.SetPresence(iobj.object,
                                            _STATUSES.get(iobj.object))