def updateNotify(): """ 功能:读取是否打开更新通知 方式:判读返回值类型 :return: True or False """ result = getPropertiesValue(dbus.String('UpdateNotify')) if isinstance(result, dbus.Boolean): logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return True else: logging.info(f'返回的数据类型与预期不符') logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return False
def autoDownloadUpdates(): """ 功能:读取是否自动下载更新包 方式:判读返回值类型 :return: True or False """ result = getPropertiesValue(dbus.String('AutoDownloadUpdates')) if isinstance(result, dbus.Boolean): logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return True else: logging.info(f'返回的数据类型与预期不符') logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return False
def setAutoCheckUpdates(target: bool = True) -> bool: """ SetAutoCheckUpdates:设置是否自动检查更新,对应设置中心->更新->更新设置—>检查更新 :param target:True or False :return:True or False """ property_obj = systemCommon.system_bus(dbus_name, dbus_path, iface_name) property_obj.SetAutoCheckUpdates(dbus.Boolean(target)) result = getPropertiesValue(dbus.String('AutoCheckUpdates')) logging.info(f'AutoCheckUpdates:{result}') if result == dbus.Boolean(target): logging.info(f'AutoCheckUpdates设置为 {target} 成功') return True else: logging.info(f'AutoCheckUpdates设置为 {target} 失败') return False
def updatablePackages(): """ 功能:读取可更新Package的信息 方式:判读返回值类型 :return: True or False """ result = getPropertiesValue(dbus.String('UpdatablePackages')) if isinstance(result, dbus.Array): logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return True else: logging.info(f'返回的数据类型与预期不符') logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return False
def power_report(self, power, *args): p_config = self.config['mwdisplay'] power_str = "%d" % power # Make sure output fits the display if len(power_str) > p_config['digits']: power_str = power_str[:p_config['digits']] # Left pad with spaces while len(power_str) < p_config['digits']: power_str = " " + power_str board_busname = 'fi.hacklab.ardubus.' + p_config['board'] board_path = '/fi/hacklab/ardubus/' + p_config['board'] self.call_cached(board_busname, board_path, 'set_i2cascii_data', dbus.Byte(p_config['idx']), dbus.String(power_str)) pass
def setUpdateNotify(target: bool = True) -> bool: """ SetUpdateNotify:设置是否通知更新。,对应设置中心->更新->更新设置—>更新提醒 :param target:True or False :return:True or False """ property_obj = systemCommon.system_bus(dbus_name, dbus_path, iface_name) property_obj.SetUpdateNotify(dbus.Boolean(target)) result = getPropertiesValue(dbus.String('UpdateNotify')) logging.info(f'UpdateNotify:{result}') if result == dbus.Boolean(target): logging.info(f'UpdateNotify设置为 {target} 成功') return True else: logging.info(f'UpdateNotify设置为 {target} 失败') return False
def test_lv_rename(self): # Rename a regular LV lv = self._create_lv() path = self._lookup(lv.LvCommon.Name) prev_path = path new_name = 'renamed_' + lv.LvCommon.Name self.handle_return(lv.Lv.Rename(dbus.String(new_name), dbus.Int32(g_tmo), EOD)) path = self._lookup(new_name) self._check_consistency() self.assertTrue(prev_path == path, "%s != %s" % (prev_path, path))
def updatableApps(): """ 功能:读取可更新App(应用商店软件)的信息,等同与ApplicationUpdateInfos的返回值 方式:判读返回值类型 :return: True or False """ result = getPropertiesValue(dbus.String('UpdatableApps')) if isinstance(result, dbus.Array): logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return True else: logging.info(f'返回的数据类型与预期不符') logging.info(f'返回的数据类型为:{type(result)}') logging.info(f'result:{result}') return False
def test_unknown_type_id(self): """Unknown type Ids should result in a plain type, along with a log message. """ data = dbus.Array([ dbus.Int32(543), dbus.Int32(0), dbus.Boolean(False), dbus.String("Hello World") ]) attr = create_value_instance(data, None, None) self.assertThat(attr, IsInstance(PlainType)) self.assertThat(attr, IsInstance(dbus.Array)) self.assertThat(attr, Equals([0, False, "Hello World"]))
def get_properties(self): """ This method gets called when the service daemon request for the advertising propertises.""" 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.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) if self.data is not None: properties["Data"] = dbus.Dictionary(self.data, signature="yv") return {LE_ADVERTISEMENT_IFACE: properties}
def delete_component(self, component): """ Delete filter component via dbus API Args: @param component: name of component """ logging.info('delete component:' + component) dbus_send.dbus_send('org.chromium.ComponentUpdaterService', 'org.chromium.ComponentUpdaterService', '/org/chromium/ComponentUpdaterService', 'UnloadComponent', timeout_seconds=20, user='******', args=[dbus.String(component)])
def force_upgrade_atrus(): """ Executes a forced upgrade of the Atrus device. @returns True if the upgrade succeeded. False otherwise. """ args = [dbus.String('/lib/firmware/google/atrus-fw-bundle-latest.bin')] result = dbus_send.dbus_send('org.chromium.Atrusctl', 'org.chromium.Atrusctl', '/org/chromium/Atrusctl', 'ForceFirmwareUpgrade', args=args, timeout_seconds=90, tolerate_failures=True) return result.response
def AddAccessPoint(self, dev_path, ap_name, ssid, hw_address, mode, frequency, rate, strength, security): '''Add an access point to an existing WiFi device. You have to specify WiFi Device path, Access Point object name, ssid, hw_address, mode, frequency, rate, strength and security. For valid access point property values, please visit http://projects.gnome.org/NetworkManager/developers/api/09/spec.html#org.freedesktop.NetworkManager.AccessPoint Please note that this does not set any global properties. Returns the new object path. ''' dev_obj = dbusmock.get_object(dev_path) ap_path = '/org/freedesktop/NetworkManager/AccessPoint/' + ap_name if ap_path in dev_obj.access_points: raise dbus.exceptions.DBusException( 'Access point %s on device %s already exists' % (ap_name, dev_path), name=MAIN_IFACE + '.AlreadyExists') flags = NM80211ApFlags.NM_802_11_AP_FLAGS_PRIVACY if security == NM80211ApSecurityFlags.NM_802_11_AP_SEC_NONE: flags = NM80211ApFlags.NM_802_11_AP_FLAGS_NONE self.AddObject(ap_path, ACCESS_POINT_IFACE, {'Ssid': dbus.ByteArray(ssid.encode('UTF-8')), 'HwAddress': dbus.String(hw_address), 'Flags': dbus.UInt32(flags), 'LastSeen': dbus.Int32(1), 'Frequency': dbus.UInt32(frequency), 'MaxBitrate': dbus.UInt32(rate), 'Mode': dbus.UInt32(mode), 'RsnFlags': dbus.UInt32(security), 'WpaFlags': dbus.UInt32(security), 'Strength': dbus.Byte(strength)}, []) dev_obj.access_points.append(ap_path) aps = dev_obj.Get(WIRELESS_DEVICE_IFACE, 'AccessPoints') aps.append(ap_path) dev_obj.Set(WIRELESS_DEVICE_IFACE, 'AccessPoints', aps) dev_obj.EmitSignal(WIRELESS_DEVICE_IFACE, 'AccessPointAdded', 'o', [ap_path]) return ap_path
def __init__(self, service, sender, prompt_name=None, delay=0, dismiss=False, action=None): self.sender = sender self.service = service self.delay = 0 self.dismiss = False self.result = dbus.String("", variant_level=1) self.action = action self.completed = False if prompt_name: self.path = "/org/freedesktop/secrets/prompts/%s" % prompt_name else: self.path = "/org/freedesktop/secrets/prompts/%s" % next_identifier('p') dbus.service.Object.__init__(self, service.bus_name, self.path) service.add_prompt(self) assert self.path not in objects objects[self.path] = self
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)
def _get_all_buddies(self): interface = _create_dbus_connection() if interface is None: return accounts = interface.PurpleAccountsGetAllActive() show_offline = __kupfer_settings__["show_offline"] for account in accounts: buddies = interface.PurpleFindBuddies(account, dbus.String('')) protocol = interface.PurpleAccountGetProtocolName(account) for buddy in buddies: if not (show_offline or interface.PurpleBuddyIsOnline(buddy)): continue self.all_buddies[buddy] = self._get_pidgin_contact(interface, buddy, protocol=protocol, account=account)
def suppress() -> bool: """ uint32 Suppress (readwrite) 变化量抑制等级,xy坐标变化大于这个值才有效,取值0~100 :return:uint32 """ result = get_properties_value(dbus.String('Suppress')) if isinstance(result, dbus.UInt32): logging.info(f'Suppress:{result}') if 0 <= int(result) <= 100: return True else: logging.info('数据超出界限0-100') return False else: logging.info('返回数据类型不匹配') return False
def _vg_create(self, pv_paths=None): if not pv_paths: pv_paths = [self.objs[PV_INT][0].object_path] vg_name = vg_n() vg_path = self.handle_return( self.objs[MANAGER_INT][0].Manager.VgCreate( dbus.String(vg_name), dbus.Array(pv_paths, signature=dbus.Signature('o')), dbus.Int32(g_tmo), EOD)) self._validate_lookup(vg_name, vg_path) self.assertTrue(vg_path is not None and len(vg_path) > 0) return ClientProxy(self.bus, vg_path, interfaces=(VG_INT, ))
def setNTP(enabled, message): """ 设置系统时钟是否和网络时钟同步 :param enabled:true为系统时钟和网络时钟同步, false为系统时钟和网络时钟不同步 :param message:关于设置系统时钟的认证信息 :return:True or False """ property_obj = systemCommon.system_bus(dbus_name, dbus_path, iface_name) result = property_obj.SetNTP(dbus.Boolean(enabled), dbus.String(message)) time.sleep(6) logging.info(result) if not result: logging.info(f'设置系统时钟和网络时钟状态为{enabled}成功') return True else: logging.info("设置参数失败") return False
def test_gtk_modules(self): # Turn off event sounds self.settings_sound['event-sounds'] = False time.sleep(2) # Verify that only the PackageKit plugin is enabled self.assertEqual(self.obj_xsettings_props.Get('org.gtk.Settings', 'Modules'), dbus.String('pk-gtk-module', variant_level=1)) # Turn on sounds self.settings_sound['event-sounds'] = True time.sleep(2) # Check that both PK and canberra plugin are enabled retval = self.obj_xsettings_props.Get('org.gtk.Settings', 'Modules') values = sorted(str(retval).split(':')) self.assertEqual(values, ['canberra-gtk-module', 'pk-gtk-module'])
def get_dbus_property(self, prop): if prop == "name": return dbus.String(self.get_property(prop)) elif prop == "DEFAULTS": ret = dbus.Dictionary(signature="sv") for x in self._role._DEFAULTS: try: ret[x] = self._role.get_dbus_property(self._role, x) except Exception as e: log.error("{}.DEFAULTS: Failed to get/convert " "property '{}': {}".format( self._log_prefix, x, e)) return ret raise dbus.exceptions.DBusException( "org.freedesktop.DBus.Error.AccessDenied: " "Property '%s' isn't exported (or may not exist)" % prop)
def gajim_remote(self, command, args=[]): self.log.debug("gajim_remote: %s, %s" % (command, str(args))) if self._gajim_svc is None: self._gajim_svc = self._get_gajim_service() if self._gajim_svc is None: return False args = [a.decode('utf-8') for a in args] args = [dbus.String(a) for a in args] method = self._gajim_svc.__getattr__(command) try: result = method(*args) except dbus.DBusException, ex: self.log.warn(str(ex)) self._gajim_svc = None return None
def start_gpupdate_user(): ''' Make gpupdate-user.service "runtime-enabled" and start it. This function is needed in order to perform user service start in case pam_systemd.so is not present in PAM stack. ''' unit_name = 'gpupdate-user.service' session_bus = dbus.SessionBus() systemd_user_bus = session_bus.get_object('org.freedesktop.systemd1', '/org/freedesktop/systemd1') systemd_user_interface = dbus.Interface( systemd_user_bus, dbus_interface='org.freedesktop.systemd1.Manager') gpupdate_user_unit = systemd_user_interface.GetUnit(dbus.String(unit_name)) job = systemd_user_interface.StartUnit(unit_name, 'replace')
def create_update_connections(self, interest_interfaces, prefered_hostname, dnsmasq_via_carrier, dnsmasq_via_autoconnect): for interface in interest_interfaces: # Test if static ip exists in network # Case which doesn't work: User had set .10 manual and .10 is owned by another pc, # arping always fail so we can't catch the conflict. if interface.page.method_entry.get_active() == 2 and \ interface.carrier == 1 and self.netman.get_active_connections(): test_ip = interface.page.ip_entry.get_text() if test_ip != interface.existing_info.ip_add: sample = common.run_command(['arping', '-f', '-w1', '-I', interface.interface, test_ip], True) while sample.poll() is None: while Gtk.events_pending(): Gtk.main_iteration() if sample.returncode == 0: interface.page.ip_entry.set_icon_from_stock(1, Gtk.STOCK_DIALOG_WARNING) interface.page.ip_entry.set_icon_tooltip_text(1, MSG_PC_CONFLICT_IP.format(test_ip)) title = MSG_PC_CONFLICT_IP.format(test_ip) err_dialog = dialogs.ErrorDialog(title, TITLE_ERROR) err_dialog.set_transient_for(self.main_dlg) if err_dialog.showup() != Gtk.ResponseType.OK: self.main_dlg.set_sensitive(True) self.main_dlg.show() return if interface.conflict is not None: interface.conflict.interface.Update(interface.connection) if interface.carrier == 1 and interface.page.auto_checkbutton.get_active(): self.netman.interface.ActivateConnection(interface.conflict.object_path, interface.device_path, '/') else: object_path = self.settings.interface.AddConnection(interface.connection) if interface.carrier == 1 and interface.page.auto_checkbutton.get_active(): self.netman.interface.ActivateConnection(object_path, interface.device_path, '/') for connection_settings in interface.interface_connections: settings = connection_settings.get_settings() settings['connection'][dbus.String('autoconnect')] = dbus.Boolean('false') connection_settings.interface.Update(settings) if dnsmasq_via_carrier and dnsmasq_via_autoconnect: GObject.timeout_add(1000, self.watch_nm, interest_interfaces, prefered_hostname) else: success_dialog = dialogs.InfoDialog(MSG_TITLE_CONNECTIONS_CREATE, TITLE_SUCCESS) success_dialog.set_transient_for(self.main_dlg) success_dialog.showup() self.main_dlg.destroy()
def show(self, summary, message, icon, actions={}): """ [es] Metodo para mostrar una informacion emergente en el area de usuario ------------------------------------------------------------------- [en] Method to show up information on the user Desktop """ if actions != {}: timeout = 12000 (notify_actions, action_handlers) = self.__process_actions(actions) def action_invoked(nid, action_id): if action_handlers.has_key(action_id) and res == nid: # [es] Se ejecuta el manejador de acciones # [en] Execute the action handler thread.start_new_thread(action_handlers[action_id], ()) self.iface.CloseNotification(dbus.UInt32(nid)) condition = False while not condition: try: self.logger.debug(_("Trying to connect to ActionInvoked")) self.iface.connect_to_signal("ActionInvoked", action_invoked) condition = True except: logmsg = _("ActionInvoked handler not configured.") logmsg += _("Trying to run notification-daemon.") self.logger.warning(logmsg) os.system( '/usr/lib/notification-daemon/notification-daemon &') time.sleep(0.2) else: timeout = 7000 notify_actions = [] # [es] Incluimos el nombre de HERMES en el titulo de la notificacion # emergente # [en] Include HERMES name on the notification title summary = "HERMES: " + summary res = self.iface.Notify("Hermes", dbus.UInt32(0), dbus.String(icon), summary, message, notify_actions, {}, dbus.UInt32(timeout)) return res
def do_get_dbus_property(x, prop): # Cover additional settings and return a proper dbus type. if prop in [ "domain_name", "realm_name", "host_name", "admin_password", "dm_password", "root_ca_file", "primary_ip" ]: return dbus.String(x.get_property(x, prop)) elif prop in ["reverse_zone"]: return dbus.Array(x.get_property(x, prop), "s") elif prop in ["serve_dns"]: return dbus.Boolean(x.get_property(x, prop)) elif prop in ["id_start", "id_max"]: return dbus.Int32(x.get_property(x, prop)) elif prop in ["dns_forwarders"]: return dbus.Dictionary(x.get_property(x, prop), "sas") raise RolekitError(INVALID_PROPERTY, prop)
def _delete_component(self, component): """ Delete filter component via dbus API @param component: name of component """ if component not in self._loaded_components: return dbus_send.dbus_send('org.chromium.ComponentUpdaterService', 'org.chromium.ComponentUpdaterService', '/org/chromium/ComponentUpdaterService', 'UnloadComponent', timeout_seconds=20, user='******', args=[dbus.String(component)]) self._loaded_components.remove(component)
def SendMessage(self, message, flags): headers = message.pop(0) message_type = int(headers.get('message-type', telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL)) if message_type != telepathy.CHANNEL_TEXT_MESSAGE_TYPE_NORMAL: raise telepathy.NotImplemented("Unhandled message type") text = None #TODO html for part in message: if part.get("content-type", None) == "text/plain": text = part['content'] break if text is None: raise telepathy.NotImplemented("Unhandled message type") message_id = self._send_text_message(self._handle.name, text) return dbus.String(message_id)
def set_ipv4(self, Netmask, Gateway, Method, Address, net_name): cnt, list_services_info = self.get_services_info() for i in range(cnt): if (list_services_info[i * 8 + 3] == net_name): service_py = pyconnman.ConnService(list_services_info[i * 8 + 0]) name = "IPv4.Configuration" value22 = { dbus.String(u'Netmask'): dbus.String(Netmask, variant_level=1), dbus.String(u'Gateway'): dbus.String(Gateway, variant_level=1), dbus.String(u'Method'): dbus.String(Method, variant_level=1), dbus.String(u'Address'): dbus.String(Address, variant_level=1) } service_py.set_property(name, value22)
def parse_connection_settings(args): """Parses position arguments for connection settings Format is in the form of [[token] <value>, ...] where the value may be optional for some boolean options. Any problems are raised as a ValueError with a user-friendly message. """ options = {"auto": True} pos = 0 # ip-based options (for static config, mostly) ipv4_opts = ('ip','mask','gw','dns',) # Options passed with direct values. # Currently used with CDMA string_opts = ('num','user','pass',) # Auto is the 'default' option allowed_opts = ['auto',] allowed_opts.extend(ipv4_opts) allowed_opts.extend(string_opts) while pos < len(args): opt = args[pos] if not opt in allowed_opts: raise ValueError("Invalid option '%s'" % (opt)) if opt != "auto": pos += 1 # The rest of these require a value in the next position if pos == len(args): raise ValueError("Missing value for option '%s'" % (opt)) value = args[pos] try: if opt in ipv4_opts: options[opt] = IPAddress(value,version=4) except IPv4IpValidationError, e: raise ValueError("Invalid value for '%s': %s" % (opt, e)) if opt in string_opts: options[opt] = dbus.String(value) if 'ip' in options: options['auto'] = False pos += 1