def GetAll(self, interface_name): if interface_name == self.MEDIA_PLAYER2_IFACE: return { 'CanQuit': True, 'CanRaise': True, 'HasTrackList': False, 'Identity': 'Pithos', 'DesktopEntry': 'pithos', 'SupportedUriSchemes': [''], 'SupportedMimeTypes': [''], } elif interface_name == self.MEDIA_PLAYER2_PLAYER_IFACE: return { 'PlaybackStatus': self._get_playback_status(), 'LoopStatus': "None", 'Rate': dbus.Double(1.0), 'Shuffle': False, 'Metadata': dbus.Dictionary(self._get_metadata(), signature='sv'), 'Volume': dbus.Double(self._get_volume()), 'Position': dbus.Int64(self._get_position()), 'MinimumRate': dbus.Double(1.0), 'MaximumRate': dbus.Double(1.0), 'CanGoNext': self.window.waiting_for_playlist is not True, 'CanGoPrevious': False, 'CanPlay': self.window.current_song is not None, 'CanPause': self.window.current_song is not None, 'CanSeek': False, 'CanControl': True, } else: raise dbus.exceptions.DBusException( 'org.mpris.MediaPlayer2.pithos', 'This object does not implement the %s interface' % interface_name)
def GetAll(self, interface): if interface == self.MPRIS_IFACE: return { 'CanQuit': True, 'CanRaise': True, 'HasTrackList': False, 'Identity': 'Lollypop', 'DesktopEntry': 'lollypop' } elif interface == self.MPRIS_PLAYER_IFACE: return { 'PlaybackStatus': self._get_status(), 'LoopStatus': 'Playlist', 'Rate': dbus.Double(1.0), 'Shuffle': True, 'Metadata': dbus.Dictionary(self._metadata, signature='sv'), 'Volume': dbus.Double(Lp().player.volume), 'Position': dbus.Int64(Lp().player.position / 60), 'MinimumRate': dbus.Double(1.0), 'MaximumRate': dbus.Double(1.0), 'CanGoNext': True, 'CanGoPrevious': True, 'CanPlay': True, 'CanPause': True, 'CanSeek': True, 'CanControl': True, } else: raise dbus.exceptions.DBusException( self.MPRIS_LOLLYPOP, "Lollypop doesn't handle %s interface" % interface)
def test_player(self): args = {"reply_handler": self._reply, "error_handler": self._error} piface = "org.mpris.MediaPlayer2.Player" props = { "PlaybackStatus": dbus.String("Stopped"), "LoopStatus": dbus.String("None"), "Rate": dbus.Double(1.0), "Shuffle": dbus.Boolean(False), "Volume": dbus.Double(1.0), "Position": dbus.Int64(0), "MinimumRate": dbus.Double(1.0), "MaximumRate": dbus.Double(1.0), "CanGoNext": dbus.Boolean(True), "CanGoPrevious": dbus.Boolean(True), "CanPlay": dbus.Boolean(True), "CanPause": dbus.Boolean(True), "CanSeek": dbus.Boolean(True), "CanControl": dbus.Boolean(True), } for key, value in props.items(): self._prop().Get(piface, key, **args) resp = self._wait(msg="for key '%s'" % key)[0] self.failUnlessEqual(resp, value) self.failUnless(isinstance(resp, type(value)))
def AddChargingBattery(self, device_name, model_name, percentage, seconds_to_full): '''Convenience method to add a charging battery object You have to specify a device name which must be a valid part of an object path, e. g. "mock_ac", an arbitrary model name, the charge percentage, and the seconds until the battery is full. Please note that this does not set any global properties such as "on-battery". Returns the new object path. ''' path = '/org/freedesktop/UPower/devices/' + device_name self.AddObject( path, DEVICE_IFACE, { 'PowerSupply': dbus.Boolean(True, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String(model_name, variant_level=1), 'Percentage': dbus.Double(percentage, variant_level=1), 'TimeToFull': dbus.Int64(seconds_to_full, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(percentage, variant_level=1), # UP_DEVICE_STATE_CHARGING 'State': dbus.UInt32(1, variant_level=1), # UP_DEVICE_KIND_BATTERY 'Type': dbus.UInt32(2, variant_level=1), }, []) self.EmitSignal(MAIN_IFACE, 'DeviceAdded', 'o', [path]) return path
def GetAll(self, interface): if interface == self.MPRIS_IFACE: return { "CanQuit": True, "CanRaise": True, "HasTrackList": False, "Identity": "Lollypop", "DesktopEntry": "org.gnome.Lollypop" } elif interface == self.MPRIS_PLAYER_IFACE: return { "PlaybackStatus": self._get_status(), "LoopStatus": "Playlist", "Rate": dbus.Double(1.0), "Shuffle": True, "Metadata": dbus.Dictionary(self._metadata, signature="sv"), "Volume": dbus.Double(Lp().player.volume), "Position": dbus.Int64(Lp().player.position / Gst.SECOND * (1000 * 1000)), "MinimumRate": dbus.Double(1.0), "MaximumRate": dbus.Double(1.0), "CanGoNext": True, "CanGoPrevious": True, "CanPlay": True, "CanPause": True, "CanSeek": True, "CanControl": True, } else: raise dbus.exceptions.DBusException( self.MPRIS_LOLLYPOP, "Lollypop doesn't handle %s interface" % interface)
def GetAll(self, interface_name): if interface_name == self.MEDIA_PLAYER2_IFACE: return { 'CanQuit': True, 'Fullscreen': False, 'CanSetFullscreen': False, 'CanRaise': True, 'HasTrackList': True, 'Identity': 'Music', 'DesktopEntry': 'gnome-music', 'SupportedUriSchemes': ['file'], 'SupportedMimeTypes': [ 'application/ogg', 'audio/x-vorbis+ogg', 'audio/x-flac', 'audio/mpeg' ], } elif interface_name == self.MEDIA_PLAYER2_PLAYER_IFACE: return { 'PlaybackStatus': self._get_playback_status(), 'LoopStatus': self._get_loop_status(), 'Rate': dbus.Double(1.0), 'Shuffle': self.player.repeat == RepeatType.SHUFFLE, 'Metadata': dbus.Dictionary(self._get_metadata(), signature='sv'), 'Volume': dbus.Double(self.player.get_volume()), 'Position': dbus.Int64(self.player.get_position()), 'MinimumRate': dbus.Double(1.0), 'MaximumRate': dbus.Double(1.0), 'CanGoNext': self.player.has_next(), 'CanGoPrevious': self.player.has_previous(), 'CanPlay': self.player.currentTrack is not None, 'CanPause': self.player.currentTrack is not None, 'CanSeek': True, 'CanControl': True, } elif interface_name == self.MEDIA_PLAYER2_TRACKLIST_IFACE: return { 'Tracks': self._get_track_list(), 'CanEditTracks': False, } elif interface_name == self.MEDIA_PLAYER2_PLAYLISTS_IFACE: return { 'PlaylistCount': len(self.playlists), 'Orderings': ['Alphabetical'], 'ActivePlaylist': self._get_active_playlist(), } else: raise dbus.exceptions.DBusException( 'org.mpris.MediaPlayer2.GnomeMusic', 'This object does not implement the %s interface' % interface_name)
def test_action_multiple_device_batteries(self): '''critical actions for multiple device batteries''' # add a fake battery to upower bat1_path = self.obj_upower.AddDischargingBattery('mock_BAT1', 'Bat0', 30.0, 1200) obj_bat1 = self.system_bus_con.get_object('org.freedesktop.UPower', bat1_path) self.obj_upower.EmitSignal('', 'DeviceAdded', 'o', [bat1_path], dbus_interface='org.freedesktop.DBus.Mock') bat2_path = '/org/freedesktop/UPower/devices/' + 'mock_MOUSE_BAT1' self.obj_upower.AddObject(bat2_path, 'org.freedesktop.UPower.Device', { 'PowerSupply': dbus.Boolean(False, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String('Bat1', variant_level=1), 'Percentage': dbus.Double(40.0, variant_level=1), 'TimeToEmpty': dbus.Int64(1600, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(40.0, variant_level=1), # UP_DEVICE_STATE_DISCHARGING 'State': dbus.UInt32(2, variant_level=1), # UP_DEVICE_KIND_BATTERY 'Type': dbus.UInt32(2, variant_level=1), }, dbus.Array([], signature='(ssss)')) obj_bat2 = self.system_bus_con.get_object('org.freedesktop.UPower', bat2_path) self.obj_upower.EmitSignal('', 'DeviceAdded', 'o', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') time.sleep(1) # now change the mouse battery to critical charge obj_bat2.Set('org.freedesktop.UPower.Device', 'TimeToEmpty', dbus.Int64(30, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.Set('org.freedesktop.UPower.Device', 'Energy', dbus.Double(0.5, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock') self.obj_upower.EmitSignal('', 'DeviceChanged', 'o', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') # wait long enough to ensure it didn't do anything (as we still have # the second battery) self.check_no_suspend(5) # now change the main battery to critical charge as well obj_bat1.Set('org.freedesktop.UPower.Device', 'TimeToEmpty', dbus.Int64(25, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat1.Set('org.freedesktop.UPower.Device', 'Energy', dbus.Double(0.4, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat1.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock') self.obj_upower.EmitSignal('', 'DeviceChanged', 'o', [bat1_path], dbus_interface='org.freedesktop.DBus.Mock') self.check_for_suspend(5)
def user_build_state(user): """Returns a generated state dictionary. State is a map of opaque backup keys to property maps. See the documentation for com.canonical.keeper.User's State() method for more information. """ tasks_states = {} for uuid in user.all_tasks: task_state = {} # action td = user.task_data[uuid] action = td.action task_state[KEY_ACTION] = dbus.String(action) # display-name choice = user.backup_choices.get(uuid, None) if not choice: choice = user.restore_choices.get(uuid, None) if not choice: fail("couldn't find a choice for uuid %s" % (uuid)) display_name = choice.get(KEY_NAME, None) task_state[KEY_NAME] = dbus.String(display_name) # error if action == ACTION_FAILED: task_state[KEY_ERROR] = dbus.String(td.error) # percent-done if td.n_bytes: p = dbus.Double((td.n_bytes - td.n_left) / td.n_bytes) else: p = dbus.Double(0.0) task_state[KEY_PERCENT_DONE] = p # speed if uuid == user.current_task: n_secs = 2 n_bytes = 0 too_old = time.time() - n_secs for key in td.bytes_per_second: if key > too_old: n_bytes += td.bytes_per_second[key] bytes_per_second = n_bytes / n_secs else: bytes_per_second = 0 task_state[KEY_SPEED] = dbus.Int32(bytes_per_second) # uuid tasks_states[uuid] = dbus.Dictionary(task_state) return dbus.Dictionary(tasks_states, signature='sa{sv}', variant_level=1)
def test_dbus_unwrap_dict(self): dbus_value = dbus.Dictionary( { dbus.String('a', variant_level=1): dbus.Double(3.2, variant_level=1), dbus.String('b', variant_level=1): dbus.Double(3.7, variant_level=1) }, variant_level=1) value = dbus_mqtt.unwrap_dbus_value(dbus_value) self.assertIsInstance(value, dict) self.assertEqual({'a': 3.2, 'b': 3.7}, value)
def volume(self, vol=None): cur = dbus.Double(self._get_property("Volume")) print("Current volume is {}".format(cur)) if vol == 0: #if self._player_interface_property('Volume') self.play_iface.Mute() self.play_iface.Unmute() else: #target = dbus.Double(10**(vol / 2000.0)) target = dbus.Double(10**((vol or 0) / 20.0)) #self._player_interface_property('Volume', target) self._set_property("Volume", target)
def test_notify_device_battery(self): '''critical power level notification for device batteries''' # Set internal battery to discharging self.set_composite_battery_discharging() # Add a device battery bat2_path = '/org/freedesktop/UPower/devices/' + 'mock_MOUSE_BAT1' self.obj_upower.AddObject(bat2_path, 'org.freedesktop.UPower.Device', { 'PowerSupply': dbus.Boolean(False, variant_level=1), 'IsPresent': dbus.Boolean(True, variant_level=1), 'Model': dbus.String('Bat1', variant_level=1), 'Percentage': dbus.Double(40.0, variant_level=1), 'TimeToEmpty': dbus.Int64(1600, variant_level=1), 'EnergyFull': dbus.Double(100.0, variant_level=1), 'Energy': dbus.Double(40.0, variant_level=1), 'State': dbus.UInt32(UPowerGlib.DeviceState.DISCHARGING, variant_level=1), 'Type': dbus.UInt32(UPowerGlib.DeviceKind.MOUSE, variant_level=1), 'WarningLevel': dbus.UInt32(UPowerGlib.DeviceLevel.NONE, variant_level=1), }, dbus.Array([], signature='(ssss)')) obj_bat2 = self.system_bus_con.get_object('org.freedesktop.UPower', bat2_path) self.obj_upower.EmitSignal('', 'DeviceAdded', 'o', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') time.sleep(1) # now change the mouse battery to critical charge obj_bat2.Set('org.freedesktop.UPower.Device', 'TimeToEmpty', dbus.Int64(30, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.Set('org.freedesktop.UPower.Device', 'Energy', dbus.Double(0.5, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.Set('org.freedesktop.UPower.Device', 'WarningLevel', dbus.UInt32(UPowerGlib.DeviceLevel.CRITICAL, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock') self.obj_upower.EmitSignal('', 'DeviceChanged', 'o', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') self.check_plugin_log('EMIT: charge-critical', 2) time.sleep(0.5) # we should have gotten a notification by now notify_log = self.p_notify.stdout.read() # verify notification self.assertRegex(notify_log, b'[0-9.]+ Notify "Power" 0 ".*" ".*Wireless mouse .*low.* power.*"')
def GetAll(self, interface_name): if interface_name == 'ch.bbv.brightness': return {'scaled': dbus.Double(self.brightness)} elif interface_name == 'ch.bbv.moisture': return {'scaled': dbus.Double(self.moisture)} elif interface_name == 'ch.bbv.proximity': return {'scaled': dbus.Double(self.proximity)} elif interface_name == 'ch.bbv.luminosity': return {'scaled': dbus.Double(self.luminosity)} elif interface_name == 'ch.bbv.warning': return {'phrase': dbus.String(self.warning)} else: raise dbus.exceptions.DBusException('Unknown interface: ' + interface_name)
def load(mock, parameters): mock.AddMethods(MAIN_IFACE, [ ('EnumerateDevices', '', 'ao', 'ret = [k for k in objects.keys() ' 'if "/devices" in k and not k.endswith("/DisplayDevice")]'), ]) props = dbus.Dictionary( { 'DaemonVersion': parameters.get('DaemonVersion', '0.99'), 'OnBattery': parameters.get('OnBattery', False), 'LidIsPresent': parameters.get('LidIsPresent', True), 'LidIsClosed': parameters.get('LidIsClosed', False), 'LidForceSleep': parameters.get('LidForceSleep', True), 'IsDocked': parameters.get('IsDocked', False), }, signature='sv') mock.AddMethods( MAIN_IFACE, [('GetCriticalAction', '', 's', 'ret = "%s"' % parameters.get('GetCriticalAction', 'HybridSleep')), ('GetDisplayDevice', '', 'o', 'ret = "/org/freedesktop/UPower/devices/DisplayDevice"')]) mock.p_display_dev = '/org/freedesktop/UPower/devices/DisplayDevice' # add Display device; for defined properties, see # http://cgit.freedesktop.org/upower/tree/src/org.freedesktop.UPower.xml mock.AddObject( mock.p_display_dev, DEVICE_IFACE, { 'Type': dbus.UInt32(0, variant_level=1), 'State': dbus.UInt32(0, variant_level=1), 'Percentage': dbus.Double(0.0, variant_level=1), 'Energy': dbus.Double(0.0, variant_level=1), 'EnergyFull': dbus.Double(0.0, variant_level=1), 'EnergyRate': dbus.Double(0.0, variant_level=1), 'TimeToEmpty': dbus.Int64(0, variant_level=1), 'TimeToFull': dbus.Int64(0, variant_level=1), 'IsPresent': dbus.Boolean(False, variant_level=1), 'IconName': dbus.String('', variant_level=1), # LEVEL_NONE 'WarningLevel': dbus.UInt32(1, variant_level=1), }, [ ('Refresh', '', '', ''), ]) mock.AddProperties(MAIN_IFACE, props)
def DBusWrap(val): if isinstance(val, str): val = dbus.String(val) elif isinstance(val, (list, tuple)): val = dbus.Array([DBusWrap(x) for x in val], signature='v') elif isinstance(val, bool): val = dbus.Boolean(val) elif isinstance(val, int): val = dbus.Int64(val) elif isinstance(val, float): val = dbus.Double(val) # Turn 'None' into 'False' to avoid errors elif val == None: val = dbus.Boolean(False) elif isinstance(val, dict): val = dbus.Dictionary({x: DBusWrap(val[x]) for x in val}, signature='sv') return val
def update_values(self, newvalues): vebus_service = newvalues.get('/VebusService') current_written = 0 if vebus_service is not None: # Writing the extra charge current to the Multi serves two purposes: # 1) Also take the charge current from the MPPT into account in the VE.Bus SOC algorithm. # 2) The bulk timer in the Multi only runs when the battery is being charged, ie charge-current # is positive. And in ESS Optimize mode, the Multi itself is not charging. # So without knowing that the MPPT is charging, the bulk timer will never run, and absorption # will then be very short. # # Always write the extra current, even if there is no solarcharger present. We need this because # once an SoC is written to the vebus service, the vebus device will stop adjusting its SoC until # an extra current is written. total_charge_current = newvalues.get('/Dc/Pv/Current', 0) try: charge_current_item = self._dbusmonitor.get_item( vebus_service, '/ExtraBatteryCurrent') if charge_current_item.get_value() != None: charge_current_item.set_value( dbus.Double(total_charge_current, variant_level=1)) current_written = 1 except dbus.exceptions.DBusException: pass newvalues['/Control/ExtraBatteryCurrent'] = current_written
def step_impl(context, value): bus = dbus.SessionBus() streetlightd = bus.get_object('ch.bbv.streetlight', '/ch/bbv/streetlight') streetlightd.Set('ch.bbv.proximity', 'scaled', dbus.Double(value), dbus_interface=dbus.PROPERTIES_IFACE)
def wrap_dbus_value(value): if value is None: return VEDBUS_INVALID 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, unicode): return dbus.String(value, variant_level=1) if isinstance(value, list): if len(value) == 0: # If the list is empty we cannot infer the type of the contents. So assume unsigned integer. # A (signed) integer is dangerous, because an empty list of signed integers is used to encode # an invalid value. return dbus.Array([], signature=dbus.Signature('u'), variant_level=1) 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): # Wrapping the keys of the dictionary causes D-Bus errors like: # 'arguments to dbus_message_iter_open_container() were incorrect, # assertion "(type == DBUS_TYPE_ARRAY && contained_signature && # *contained_signature == DBUS_DICT_ENTRY_BEGIN_CHAR) || (contained_signature == NULL || # _dbus_check_is_valid_signature (contained_signature))" failed in file ...' return dbus.Dictionary( {(k, wrap_dbus_value(v)) for k, v in value.items()}, variant_level=1) return value
def sinkSetFade(value): """ 设置前后声道平衡值 :return:None """ dbus_path = getDefaultSinkPath() property_obj = sessionCommon.session_bus(dbus_name, dbus_path, iface_name) property_obj.SetFade(dbus.Double(value))
def GetAll(self, interface): if interface == MAIN_IFACE: return { 'HasAccelerometer': dbus.Boolean(self.has_accelerometer), 'AccelerometerOrientation': dbus.String(self.accelerometer_orientation), 'HasAmbientLight': dbus.Boolean(self.has_ambient_light), 'LightLevelUnit': dbus.String(self.light_level_unit), 'LightLevel': dbus.Double(self.light_level), 'HasProximity': dbus.Boolean(self.has_proximity), 'ProximityNear': dbus.Boolean(self.proximity_near), } if interface == COMPASS_IFACE: return { 'HasCompass': dbus.Boolean(self.has_compass), 'CompassHeading': dbus.Double(self.compass_heading), } return dbus.Dictionary({}, signature='sv')
def volume(self, vol): """Set the volume and return the current volume.""" self.__assertConnected() try: if vol: return float(self.__iface_props.Volume(dbus.Double(vol))) else: return float(self.__iface_props.Volume()) except dbus.exceptions.DBusException: pass
def rate(self, r): """Set the playback rate and return the current playback rate""" self.__assertConnected() try: if r: return float(self.__iface_props.Rate(dbus.Double(r))) else: return float(self.__iface_props.Rate()) except dbus.exceptions.DBusException: pass
def set_property(self, prop, value): try: val = self.iface_props.Set('org.mpris.MediaPlayer2.Player', prop, dbus.Double(value)) #self.log ('property',prop,val) return True, val except dbus.exceptions.DBusException as ex: self.log('Failed set_property - dbus exception: {}'.format( ex.get_dbus_message())) return False, -1
def sinkSetVolume(value, isPlay): """ 设置音量大小 :param value:音量大小 :param isPlay:是否播放声音反馈 :return:None """ dbus_path = getDefaultSinkPath() property_obj = sessionCommon.session_bus(dbus_name, dbus_path, iface_name) property_obj.SetVolume(dbus.Double(value), dbus.Boolean(isPlay))
def sourceSetBalance(value, isPlay): """ 设置左右声道平衡 :param value:声道平衡值 :param isPlay:是否播放声音反馈 :return:None """ dbus_path = getDefaultSourcePath() property_obj = sessionCommon.session_bus(dbus_name, dbus_path, iface_name) property_obj.SetBalance(dbus.Double(value), dbus.Boolean(isPlay))
def test_action_multiple_batteries(self): '''critical actions for multiple batteries''' # add two fake batteries to upower bat1_path = self.obj_upower.AddDischargingBattery('mock_BAT1', 'Bat0', 30.0, 1200) obj_bat1 = self.system_bus_con.get_object('org.freedesktop.UPower', bat1_path) self.obj_upower.EmitSignal('', 'DeviceAdded', 's', [bat1_path], dbus_interface='org.freedesktop.DBus.Mock') bat2_path = self.obj_upower.AddDischargingBattery('mock_BAT2', 'Bat2', 40.0, 1600) obj_bat2 = self.system_bus_con.get_object('org.freedesktop.UPower', bat2_path) self.obj_upower.EmitSignal('', 'DeviceAdded', 's', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') time.sleep(1) # now change one battery to critical charge obj_bat1.Set('org.freedesktop.UPower.Device', 'TimeToEmpty', dbus.Int64(30, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat1.Set('org.freedesktop.UPower.Device', 'Energy', dbus.Double(0.5, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat1.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock') self.obj_upower.EmitSignal('', 'DeviceChanged', 's', [bat1_path], dbus_interface='org.freedesktop.DBus.Mock') # wait long enough to ensure it didn't do anything (as we still have # the second battery) self.check_no_suspend(5) # now change the other battery to critical charge as well obj_bat2.Set('org.freedesktop.UPower.Device', 'TimeToEmpty', dbus.Int64(25, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.Set('org.freedesktop.UPower.Device', 'Energy', dbus.Double(0.4, variant_level=1), dbus_interface=dbus.PROPERTIES_IFACE) obj_bat2.EmitSignal('', 'Changed', '', [], dbus_interface='org.freedesktop.DBus.Mock') self.obj_upower.EmitSignal('', 'DeviceChanged', 's', [bat2_path], dbus_interface='org.freedesktop.DBus.Mock') self.check_for_suspend(5)
def apply_monitors_config(self, display_name, mode, scale=1.0): """Set the selected display to the desired resolution""" transform = dbus.UInt32(0) is_primary = True monitors = [[ 0, 0, dbus.Double(scale), transform, is_primary, [[dbus.String(str(display_name)), dbus.String(str(mode)), {}]] ]] self.interface.ApplyMonitorsConfig(self.config_serial, self.TEMPORARY_METHOD, monitors, {})
def apply_monitors_config(self, display_configs): """Set the selected display to the desired resolution""" monitors_config = [[ config.position[0], config.position[1], dbus.Double(config.scale), dbus.UInt32(config.transform), config.primary, [[dbus.String(str(display_name)), dbus.String(str(mode)), {}] for display_name, mode in config.monitors] ] for config in display_configs] self.interface.ApplyMonitorsConfig(self.current_state.serial, self.TEMPORARY_METHOD, monitors_config, {})
def _update_metadata(self): if self._get_status() == 'Stopped': self._metadata = {} else: if Lp().player.current_track.id >= 0: self._metadata['mpris:trackid'] = dbus.ObjectPath( '/org/lollypop/%s' % Lp().player.current_track.id) else: # MPRIS SUX track_id = randint(10000000, 90000000) self._metadata['mpris:trackid'] = dbus.ObjectPath( '/org/lollypop/%s' % track_id) track_number = Lp().player.current_track.number if track_number is None: track_number = 1 self._metadata['xesam:trackNumber'] = track_number self._metadata['xesam:title'] = Lp().player.current_track.name self._metadata['xesam:album'] = Lp( ).player.current_track.album.name self._metadata['xesam:artist'] = Lp().player.current_track.artists self._metadata['xesam:albumArtist'] = \ ", ".join(Lp().player.current_track.album_artists) self._metadata['mpris:length'] = dbus.Int64( Lp().player.current_track.duration * 1000000) self._metadata['xesam:genre'] = Lp().player.current_track.genres\ or "Web" self._metadata['xesam:url'] = Lp().player.current_track.uri rate = Lp().player.current_track.get_rate() if rate == Type.NONE: rate = Lp().player.current_track.get_popularity() self._metadata["xesam:userRating"] = dbus.Double(rate / 5) if Lp().player.current_track.id == Type.RADIOS: cover_path = Lp().art.get_radio_cache_path( ", ".join(Lp().player.current_track.artists), ArtSize.MONSTER) elif Lp().player.current_track.id == Type.EXTERNALS: cover_path = "/tmp/lollypop_mpris.jpg" pixbuf = Lp().art.pixbuf_from_tags( GLib.filename_from_uri(Lp().player.current_track.uri)[0], ArtSize.MONSTER) if pixbuf is not None: pixbuf.savev(cover_path, "jpeg", ["quality"], ["90"]) else: cover_path = Lp().art.get_album_cache_path( Lp().player.current_track.album, ArtSize.MONSTER) if cover_path is not None: self._metadata['mpris:artUrl'] = "file://" + cover_path elif 'mpris:artUrl' in self._metadata: self._metadata['mpris:artUrl'] = ''
def launch_guidance(route): g_mapmatchedposition_interface.SetSimulationMode( dbus.UInt32(g_navigationcore_session_handle), dbus.Boolean(True)) g_guidance_interface.StartGuidance( dbus.UInt32(g_navigationcore_session_handle), dbus.UInt32(route)) g_mapviewercontrol_interface.SetFollowCarMode( dbus.UInt32(g_navigationcore_session_handle), dbus.UInt32(g_mapviewer_maphandle), True) g_mapviewercontrol_interface.SetMapViewScale( dbus.UInt32(g_mapviewer_sessionhandle), dbus.UInt32(g_mapviewer_maphandle), ZOOM_GUIDANCE) g_mapviewercontrol_interface.SetTargetPoint(dbus.UInt32(g_mapviewer_sessionhandle),\ dbus.UInt32(g_mapviewer_maphandle),\ dbus.Struct((\ dbus.Double(locations[routes[g_current_route].getElementsByTagName("start")[0].childNodes[0].data][0]),\ dbus.Double(locations[routes[g_current_route].getElementsByTagName("start")[0].childNodes[0].data][1]),\ dbus.Double(0)\ ))) g_mapmatchedposition_interface.StartSimulation( dbus.UInt32(g_navigationcore_session_handle)) g_mapmatchedposition_interface.SetSimulationSpeed( dbus.UInt32(g_navigationcore_session_handle), dbus.Byte(SPEED_FACTOR_SLOW))
def test_dbus_wrap_dict(self): value = {'a': 3, 'b': 7.0} dbus_value = dbus_mqtt.wrap_dbus_value(value) print(dbus_value) self.assertIsInstance(dbus_value, dbus.Dictionary) self.assertEqual( dbus.Dictionary( { dbus.String('a', variant_level=1): dbus.Int32(3, variant_level=1), dbus.String('b', variant_level=1): dbus.Double(7.0, variant_level=1) }, variant_level=1), dbus_value)