def __init__(self): self.prefix = 'W:' self.suffix = ' ' self.tooltip_heading = 'Wireless LAN Status:\n' self.iface = None # Set to interface name to override interface selection self.build_ui() # Needed by wpa_supplicant.core self.reactor = SelectReactor() thread = threading.Thread(target=self.reactor.run, kwargs={'installSignalHandlers': 0}) thread.daemon = True thread.start() time.sleep(0.1) # let reactor start self.wpasup = None self.wpasup_running = False self.wlan = None self.wlan_signal = None # Monitor the availability of wpa_supplicant via DBus self.dbus = SystemBus() # watch_name() fires an event as soon as GLib.MainLoop() starts, so we don't need to explicitly # call get_wpa_supplicant() here self.dbus.watch_name(BUS_NAME, 0, self.get_wpa_supplicant, self.get_wpa_supplicant) self.start_watch_thread()
def __init__(self): self.ostree_remote_attributes = None self.logger = logging.getLogger('fullmetalupdate_container_updater') self.mark_os_successful() bus = SystemBus() self.systemd = bus.get('.systemd1') self.sysroot = OSTree.Sysroot.new_default() self.sysroot.load(None) self.logger.info("Cleaning the sysroot") self.sysroot.cleanup(None) [_, repo] = self.sysroot.get_repo() self.repo_os = repo self.remote_name_os = None self.repo_containers = OSTree.Repo.new(Gio.File.new_for_path(PATH_REPO_APPS)) if os.path.exists(PATH_REPO_APPS): self.logger.info("Preinstalled OSTree for containers, we use it") self.repo_containers.open(None) else: self.logger.info("No preinstalled OSTree for containers, we create " "one") self.repo_containers.create(OSTree.RepoMode.BARE_USER_ONLY, None)
def __init__(self): self.object = None self.bus = SystemBus() self.udev = GUdev.Client(subsystems=["usb/usb_device"]) self.udev.connect("uevent", self.uevent) self.loop = GLib.MainLoop() self.busname = self.bus.publish(BUSNAME, self)
def loop(): bus = SystemBus() bus.own_name('net.lvht.btk') obj_path = '/net/lvht/btk/HIDProfile' sock = bt.BluetoothSocket(bt.L2CAP) sock.setblocking(False) try: sock.bind(('', PSM_INTR)) except: print("For bluez5 add --noplugin=input to the bluetoothd commandline") print("Else there is another application running that has it open.") sys.exit(errno.EACCES) sock.listen(1) profile = HIDProfile(bus.con, obj_path, sock) opts = { "PSM": GLib.Variant.new_uint16(PSM_CTRL), "ServiceRecord": GLib.Variant.new_string(open('./sdp_record.xml', 'r').read()), "RequireAuthentication": GLib.Variant.new_boolean(True), "RequireAuthorization": GLib.Variant.new_boolean(False), } manager = bus.get('org.bluez')['.ProfileManager1'] manager.RegisterProfile(obj_path, str(uuid.uuid4()), opts) profile.run()
def start(self, median_path, config_path, db_path): # Always start in standby self.set_state(State.STANDBY) # Start up camera self.snapper = Snapper(logger) # Start up solver self.solver = Solver(logger) self.solver.startup(median_path, config_path, db_path) # Start solver thread self.s_thread.start() logger.info("Started solver thread.") # Start up D-Bus server bus = SystemBus() loop = GLib.MainLoop() bus.publish(self.interface_name, self) try: logger.info("Starting D-Bus loop.") loop.run() except KeyboardInterrupt as e: loop.quit() logger.info("Ended D-Bus loop.") self.end()
def run(self): self.logger.info("Starting Signal Interface") bus = SystemBus() self.signal = bus.get('org.asamk.Signal') self.signal.onMessageReceived = self.handle_message self.loop = GLib.MainLoop() #self.timer = GObject.idle_add(self.run_loop) self.logger.debug("Signal Interface Running") ps.subscribe(self.handle_panel_event, "events") ps.subscribe(self.handle_notify, "notifications") try: self.loop.run() except (KeyboardInterrupt, SystemExit): self.logger.debug("Signal loop stopping") if self.alarm is not None: self.loop.quit() self.alarm.disconnect() except Exception: self.logger.exception("Signal loop")
def start(self, median_path, config_path, db_path, sample_dir=None): if (DEBUG_ENABLED): global STACK_LAYERS print(f"{STACK_LAYERS * ' '}Inside Server.start") STACK_LAYERS = STACK_LAYERS + 1 # Start up star tracker self.st.startup(median_path, config_path, db_path, sample_dir=sample_dir) time.sleep(20) self.st_thread.start() logger.info("Started worker thread") # Start up D-Bus server bus = SystemBus() loop = GLib.MainLoop() bus.publish(self.interface_name, self) try: logger.info("Starting D-Bus loop...") loop.run() except KeyboardInterrupt as e: loop.quit() logger.info("Ended D-Bus loop") self.end() if (DEBUG_ENABLED): STACK_LAYERS = STACK_LAYERS - 1 print(f"{STACK_LAYERS * ' '}End Server.start")
def run_event_loop(): bus = SystemBus() logger.debug('Publishing interface %s on DBus', constants.DEPUTY_DBUS_NAME) config = get_config() bus.publish(constants.DEPUTY_DBUS_NAME, HadesDeputyService(bus, config)) loop = GLib.MainLoop() loop.run()
def __init__(self): GObject.GObject.__init__(self) self.interface = None self.welcomed_ok = False try: self.bus = SystemBus() self.dbus_proxy = self.bus.get(WelcomedClient._name, WelcomedClient._object_path) if not self.dbus_proxy: self.welcomed_ok = False else: self.dbus_proxy.PropertiesChanged.connect( self.on_properties_changed) self.welcomed_ok = self.dbus_proxy.is_alpm_on() except Exception as err: print(err) finally: if not self.welcomed_ok: msg = _( "Can't find Welcome d-bus service. Is it really installed?" ) Notify.init("antergos-welcome") Notify.Notification.new(_("ERROR!"), msg, 'dialog-error').show()
def startDbus(self): self.bus = SystemBus() self.manager = self.bus.get("org.freedesktop.ModemManager1") for s in self.getAllModems(): self.buildModem(s) self.manager.InterfacesAdded.connect( lambda path, x: self.buildModem(path) ) self.manager.InterfacesRemoved.connect( lambda path, x: self.removeModem(path) )
def get_dbus_interface(fallback=True): """Get an interface to start and stop injecting keystrokes. Parameters ---------- fallback : bool If true, returns an instance of the daemon instead if it cannot connect """ msg = ('The daemon "key-mapper-service" is not running, mapping keys ' 'only works as long as the window is open. ' 'Try `sudo systemctl start key-mapper`') if not is_service_running(): if not fallback: logger.error('Service not running') return None logger.warning(msg) return Daemon() bus = SystemBus() try: interface = bus.get(BUS_NAME) except GLib.GError as error: logger.debug(error) if not fallback: logger.error('Failed to connect to the running service') return None logger.warning(msg) return Daemon() return interface
def main(): # parse arguments parser = argparse.ArgumentParser() parser.add_argument("-a", "--add", dest="file", help="path to file to install") parser.add_argument("-u", "--update", action="store_true", help="start update") parser.add_argument("-s", "--status-archive", action="store_true", help="make status archive file") args = parser.parse_args() # set up bus connection bus = SystemBus() updater = bus.get(IFACE) if args.file: ret = updater.AddUpdateArchive(os.path.abspath(args.file)) print("AddUpdateArchive returned: " + str(ret)) elif args.update: ret = updater.Update() print("Update returned: " + str(ret)) elif args.status_archive: ret = updater.MakeStatusArchive() print("MakeStatusArchive returned: " + str(ret))
def post_config_hook(self): try: self._logind_proxy = SystemBus().get( bus_name="org.freedesktop.login1", object_path="/org/freedesktop/login1/session/self", ) except NameError: self._logind_proxy = None if not self.device: self.device = get_device() elif "/" not in self.device: self.device = f"/sys/class/backlight/{self.device}" if self.device is None: if self.hide_when_unavailable: return else: raise Exception(STRING_NOT_AVAILABLE) self.format = self.py3.update_placeholder_formats( self.format, {"level": ":.0f"}) # check for an error code and an output self.command_available = False try: output = self.py3.command_output(self._command_get()) try: float(output) self.command_available = True except ValueError: pass except self.py3.CommandError: pass if self.brightness_initial: self._set_backlight_level(self.brightness_initial)
def main(): """The main for the oresat linux updater daemon""" ret = 0 pid_file = "/run/oresat-linux-updaterd.pid" parser = ArgumentParser() parser.add_argument("-d", "--daemon", action="store_true", help="daemonize the process") parser.add_argument("-v", "--verbose", action="store_true", help="enable debug log messaging") parser.add_argument("-w", "--work-dir", dest="work_dir", default=WORK_DIR, help="override the working directory") parser.add_argument("-c", "--cache-dir", dest="cache_dir", default=CACHE_DIR, help="override the update archive cache directory") args = parser.parse_args() if args.daemon: _daemonize(pid_file) log_handler = SysLogHandler(address="/dev/log") else: log_handler = logging.StreamHandler(sys.stderr) # turn on logging for debug messages if args.verbose: level = logging.DEBUG else: level = logging.INFO logging.basicConfig(level=level, handlers=[log_handler]) log = logging.getLogger('oresat-linux-updater') # make updater updater = DBusServer(args.work_dir, args.cache_dir, log) # set up dbus wrapper bus = SystemBus() bus.publish(DBUS_INTERFACE_NAME, updater) loop = GLib.MainLoop() try: updater.run() loop.run() except KeyboardInterrupt: updater.quit() loop.quit() except Exception as exc: # this should not happen log.critical(exc) updater.quit() loop.quit() ret = 1 if args.daemon: os.remove(pid_file) # clean up daemon return ret
def __init__(self, interface, path=None): self._interface = interface if path is None: self._path = '/org/freedesktop/ModemManager1' self._dbus = SystemBus().get('.ModemManager1') else: self._path = path self._dbus = SystemBus().get('.ModemManager1', self._path)
def restart_nginx(self): """ Restarts the nginx-1.12.2 service with DBUS """ self._logger.info("Restarting NGINX") bus = SystemBus() systemd = bus.get(".systemd1") systemd.RestartUnit("nginx.service", "fail")
def __init__(self, battery_name="BAT0"): self.loop = GLib.MainLoop() self.bat_name = battery_name self.dbus = SystemBus() self.upower = self.dbus.get('org.freedesktop.UPower', '/org/freedesktop/UPower') self.bat_obj_path = '/org/freedesktop/UPower/devices/battery_{}'\ .format(self.bat_name)
def publish(self): """Make the dbus interface available.""" bus = SystemBus() try: bus.publish(BUS_NAME, self) except RuntimeError as error: logger.error('Is the service is already running? %s', str(error)) sys.exit(1)
def __init__(self, name): self.bus = SystemBus() self.systemd = SystemBus().get('.systemd1') self.name = name self.unit = self.bus.get('.systemd1', self.systemd.GetUnit(self.name)) self.connection = self.unit['org.freedesktop.DBus.Properties'].PropertiesChanged.connect(self.callback) self.og = OpsGenieApi() self.notify(True)
def __init__(self, **kwargs): self.available = False super().__init__(**kwargs) self.loop = GLib.MainLoop() self.bus = SystemBus() # ID used to cancel the scan timer and to find out whether it is running # Will be None whenever the timer isn't running self.scan_timer_id = None self.new_connection_subscription = None self.access_points = [] self.saved_ssids = [] # Register kivy events self.register_event_type('on_access_points') self.register_event_type('on_connect_failed') # Get proxy objects try: self.nm = self.bus.get(_NM, "/org/freedesktop/NetworkManager") except GLib.GError as e: # Occurs when NetworkManager was not installed if "org.freedesktop.DBus.Error.ServiceUnknown" in e.message: return # Leaves self.available = False raise self.settings = self.bus.get(_NM, "/org/freedesktop/NetworkManager/Settings") devices = self.nm.Devices # Type: ao self.eth_dev = self.wifi_dev = None for dev in devices: dev_obj = self.bus.get(_NM, dev) if dev_obj.Capabilities & 0x1: # NetworkManager supports this device if dev_obj.DeviceType == 1: # a wired ethernet device self.eth_dev = dev_obj elif dev_obj.DeviceType == 2: # an 802.11 Wi-Fi device self.wifi_dev = dev_obj # For simplicity require both devices to be available if not(self.eth_dev and self.wifi_dev): return # Leaves self.available = False #UNUSED Does the wifi device support 5gGHz (flag 0x400) #self.freq_5ghz = bool(self.wifi_dev.WirelessCapabilities & 0x400) # Connect DBus signals to their callbacks # Pick out the .DBus.Properties interface because the .NetworkManager # interface overwrites that with a less functioning one. nm_prop = self.nm['org.freedesktop.DBus.Properties'] nm_prop.PropertiesChanged.connect(self._handle_nm_props) wifi_prop = self.wifi_dev['org.freedesktop.DBus.Properties'] wifi_prop.PropertiesChanged.connect(self._handle_wifi_dev_props) # Initiate the values handled by signal handlers by simply # sending all the properties that are being listened to. self._handle_nm_props(None, self.nm.GetAll('org.freedesktop.NetworkManager'), None) self._handle_wifi_dev_props(None, self.wifi_dev.GetAll(_NM + ".Device"), None) self._handle_wifi_dev_props(None, self.wifi_dev.GetAll(_NM + ".Device.Wireless"), None) self.available = True
def __init__(self): self.bus = SystemBus() self.networkmanager = self.bus.get( "org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager" ) self.use_alt_text = False signal.signal(signal.SIGUSR1, self.sigusr1_handler)
def signal_cleanup(timeout: int = 1) -> None: """Signal the deputy to perform a cleanup.""" logger.debug("Signaling cleanup on DBus: %s.%s", constants.DEPUTY_DBUS_NAME, 'Cleanup') with typed_glib_error(): bus = SystemBus() deputy = bus.get(constants.DEPUTY_DBUS_NAME, timeout=timeout) deputy_interface = deputy[constants.DEPUTY_DBUS_NAME] deputy_interface.Cleanup(timeout=timeout)
def stop_start_systemd_unit(name="ssh.service"): """Stop and restart a systemd unit""" bus = SystemBus() # systemd is now a proxy for the .systemd1 remote object systemd = bus.get(".systemd1") job1 = systemd.StopUnit(name, "fail") job2 = systemd.StartUnit(name, "fail")
def __init__(self): self._logger = get_logger('uchroma.power') self._name_watchers = [] self._running = False self._sleeping = False self._session_bus = SessionBus() self._system_bus = SystemBus() self._dm = UChromaDeviceManager() #singleton
def quit(bus=None): if bus is None: bus = SystemBus() try: bts = bus.get(BTSDBusService.interface_name) bts.Quit() except GLib.Error: return -1
def __init__(self, config): """Constructor. config: Dictionary containing BatWatch configuration details. """ self.logger = logging.getLogger(__name__) self.system_bus = SystemBus() self.upower_bus = SystemBus().get(UPOWER_BUS_NAME) self.config = config
def signal_refresh(timeout: int = 1) -> None: """Signal the deputy to perform a refresh.""" logger.debug("Signaling refresh on DBus: %s.%s", constants.DEPUTY_DBUS_NAME, 'Refresh') with typed_glib_error(): bus = SystemBus() deputy = bus.get(constants.DEPUTY_DBUS_NAME, timeout=timeout) deputy_interface = deputy[constants.DEPUTY_DBUS_NAME] deputy_interface.Refresh(timeout=timeout)
def watch_for_new_systemd_jobs(): """Wait for new systemd units and when they are created, print them out""" bus = SystemBus() # systemd is now a proxy for the .systemd1 remote object systemd = bus.get(".systemd1") systemd.JobNew.connect(print) GLib.MainLoop().run()
class Controller: def __init__(self, adapter_int=0): adapter_path = '/org/bluez/hci{}'.format(adapter_int) self.dbus = SystemBus() self.adapter = self.dbus.get('org.bluez', adapter_path) self.controller = self.dbus.get('org.bluez', '/org/bluez/hci0/dev_DC_0C_2D_20_DA_E8') print('Waiting for connection from DC:0C:2D:20:DA:E8') self.controller.Connect() while not self.controller.Connected: sleep(1) print('Connected') sleep(2) self.device = evdev.InputDevice('/dev/input/event2') self.max_value = 0 self.min_value = 255 self.max_throttle = 1 self.min_throttle = -1 self.right_steering = 1 self.left_steering = -1 def map_throttle(self, value): input_range = self.max_value - self.min_value output_range = self.max_throttle - self.min_throttle input_percentage = (value - self.min_value) / input_range output_value = (output_range * input_percentage) + self.min_throttle return round(output_value, 2) def map_steering(self, value): input_range = self.max_value - self.min_value output_range = self.right_steering - self.left_steering input_percentage = (value - self.min_value) / input_range output_value = (output_range * input_percentage) + self.left_steering return round(output_value, 2) def get_events(self): for event in self.device.read_loop(): ly = None rx = None btn = None if event.type == evdev.ecodes.EV_ABS: if event.code == 1: # print('Left:', event.value) ly = self.map_throttle(event.value) if event.code == 3: # print('Right:', event.value) rx = self.map_steering(event.value) if event.type == evdev.ecodes.EV_KEY: if event.code == evdev.ecodes.BTN_SOUTH and event.value == 0: btn = 'BTN_SOUTH' elif event.code == evdev.ecodes.BTN_WEST and event.value == 0: btn = 'BTN_WEST' elif event.code == evdev.ecodes.BTN_NORTH and event.value == 0: btn = 'BTN_NORTH' elif event.code == evdev.ecodes.BTN_EAST and event.value == 0: btn = 'BTN_EAST' yield ly, rx, btn
def _start_loop(self): """Starts main event handler loop, run in handler thread t.""" # Create our main loop, get our bus, and add the signal handler loop = GObject.MainLoop() bus = SystemBus() manager = bus.get(".NetworkManager") manager.onPropertiesChanged = self._vpn_signal_handler # Loop forever loop.run()
def inject(mail, bus=None): if bus is None: bus = SystemBus() mail = base64.b64encode(mail).decode('ascii') try: bts = bus.get(BTSDBusService.interface_name) return bts.Inject(mail) except GLib.Error: return -1
def _get_vpn_status(self): """Returns None if no VPN active, Id if active.""" # Sleep for a bit to let any changes in state finish sleep(0.3) # Check if any active connections are a VPN bus = SystemBus() for name in self.active: conn = bus.get(".NetworkManager", name) if conn.Vpn: return conn.Id # No active VPN return None
def get_unit_status(unit_name: str) -> Dict[str, Any]: bus = SystemBus() systemd = bus.get('org.freedesktop.systemd1') path = systemd.GetUnit(unit_name) unit = bus.get('org.freedesktop.systemd1', path) properties = dict_from_attributes(unit['org.freedesktop.systemd1.Unit'], unit_properties) if unit_name.endswith('.service'): properties.update(dict_from_attributes( unit['org.freedesktop.systemd1.Service'], service_properties)) elif unit_name.endswith('.timer'): properties.update(dict_from_attributes( unit['org.freedesktop.systemd1.Timer'], timer_properties)) return properties
def __init__(self): threading.Thread.__init__(self) self.bus = SystemBus() try: self.dev = self.bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/drives/TSSTcorp_CDDVDW_SE_S084C_SATASLIM00003008cae') #self.dev = self.bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks/devices/sr0') except KeyError: print "CD LW not connected" quit() self.media = self.dev.MediaAvailable
def dbus_main(): global sysbus, avahi, dbus_loop dbg('Connecting to system DBus') sysbus = SystemBus() dbg('Subscribing to .Avahi.RecordBrowser signals') sysbus.con.signal_subscribe('org.freedesktop.Avahi', 'org.freedesktop.Avahi.RecordBrowser', None, None, None, 0, signal_dispatcher) avahi = sysbus.get('.Avahi', '/') dbg("Connected to Avahi Daemon: %s (API %s) [%s]" % (avahi.GetVersionString(), avahi.GetAPIVersion(), avahi.GetHostNameFqdn())) dbg('Starting DBus main loop') dbus_loop = GLib.MainLoop() dbus_loop.run()
def __init__(self): self.prefix = 'B:' self.separator = '/' self.suffix = ' ' self.tooltip_heading = 'Battery Status:\n' self.low_battery_alarm_threshold = 5 self.low_battery_alarm_visible = False self.build_ui() self.dbus = SystemBus() self.upower = self.dbus.get('.UPower', '/org/freedesktop/UPower') self.battery_subscriptions = [] self.upower.DeviceAdded.connect(lambda name, vals, a: self.get_upower_batteries()) self.upower.DeviceRemoved.connect(lambda name, vals, a: self.get_upower_batteries()) self.get_upower_batteries() self.start_signal_thread()
class MediaDeviceThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.bus = SystemBus() try: self.dev = self.bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/drives/TSSTcorp_CDDVDW_SE_S084C_SATASLIM00003008cae') #self.dev = self.bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks/devices/sr0') except KeyError: print "CD LW not connected" quit() self.media = self.dev.MediaAvailable def _print(*a): print a def run(self): with self.dev.PropertiesChanged.connect(self._print) as d: if self.media: print "Media still inserted..." # self.dev.Eject() GObject.MainLoop().run()
def __init__(self): GObject.GObject.__init__(self) self.interface = None self.welcomed_ok = False try: self.bus = SystemBus() self.dbus_proxy = self.bus.get( WelcomedClient._name, WelcomedClient._object_path) if not self.dbus_proxy: self.welcomed_ok = False else: self.dbus_proxy.PropertiesChanged.connect( self.on_properties_changed) self.welcomed_ok = self.dbus_proxy.is_alpm_on() except Exception as err: print(err) finally: if not self.welcomed_ok: msg = _("Can't find Welcome d-bus service. Is it really installed?") Notify.init("antergos-welcome") Notify.Notification.new( _("ERROR!"), msg, 'dialog-error').show()
stream_handler.setLevel(log_level) stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) def setup_gettext(): # This allows to translate all py texts (not the glade ones) gettext.textdomain(APP_NAME) gettext.bindtextdomain(APP_NAME, LOCALE_DIR) locale_code, encoding = locale.getdefaultlocale() lang = gettext.translation(APP_NAME, LOCALE_DIR, locale_code, None, True) lang.install() # With this we can use _("string") to translate gettext.install(APP_NAME, localedir=LOCALE_DIR, codeset=None, names=locale_code) if __name__ == '__main__': setup_gettext() argv_options, argv_args = parse_argv() setup_logging(argv_options) mainloop = GLib.MainLoop() bus = SystemBus() logging.debug(_("Connected to the system bus")) bus.publish("com.antergos.welcome", service.DBusService(mainloop)) mainloop.run()
#!/usr/bin/python3 # Based on http://stackoverflow.com/questions/22390064/use-dbus-to-just-send-a-message-in-python # Python script to call the methods of the DBUS Test Server from pydbus import SystemBus import sys #get the session bus bus = SystemBus() o2 = bus.get("org.freedesktop.DBus") pat = "it.pook.DelcomClock." if len(sys.argv) > 1: name = pat + sys.argv[1] else: for n in o2.ListNames(): if n.startswith("it.pook.DelcomClock."): name = n break else: sys.exit("no delcom") print("anme", name) #get the object the_object = bus.get(name) #call the methods and print the results reply = the_object.Hello()
class Py3status: """ """ # available configuration parameters cache_timeout = 5 format = ('\?color=state WW: [\?if=state_name=connected ' '({signal_quality_0}% at {m3gpp_operator_name}) ' '[{format_ipv4}[\?soft ]{format_ipv6}]' '|{state_name}][ SMS {messages} [{format_message}]]') format_ipv4 = u'[{address}]' format_ipv6 = u'[{address}]' format_message = u'\?if=index<2 {number} [\?max_length=10 {text}...]' format_message_separator = u' ' format_notification = None format_stats = u'{duration_hms}' modem = None thresholds = [(0, 'bad'), (11, 'good')] def post_config_hook(self): modem_manager = ['ModemManager', '/usr/sbin/ModemManager'] network_manager = ['NetworkManager', '/usr/sbin/NetworkManager'] for command in (modem_manager, network_manager): if not self.py3.check_commands(command): raise Exception('%s %s' % (command[0], STRING_NOT_INSTALLED)) # search: modemmanager flags and enumerations # enum 1: #MMModemState # enum 2: #MMModemAccessTechnology # enum 3: #MMModem3gppRegistrationState # enum 4: #MMModemBand # enum 1: network states self.network_states = { -1: 'failed', 0: 'unknown', 1: 'initializing', 2: 'locked', 3: 'disabled', 4: 'disabling', 5: 'enabling', 6: 'enabled', 7: 'searching', 8: 'registered', 9: 'disconnecting', 10: 'connecting', 11: 'connected' } # enum 2: network speed self.network_speed = { 0: 'Unknown', 1 << 0: 'POTS', # 2 1 << 1: 'GSM', 1 << 2: 'GSM Compact', 1 << 3: 'GPRS', 1 << 4: 'EDGE', 1 << 5: 'UMTS', # 32 1 << 6: 'HSDPA', 1 << 7: 'HSUPA', 1 << 8: 'HSPA', 1 << 9: 'HSPA+', # 512 1 << 10: '1XRTT', 1 << 11: 'EVDO0', 1 << 12: 'EVDOA', 1 << 13: 'EVDOB', 1 << 14: 'LTE' # 16384 } # enum 3: network registration state self.registration_states = { 0: 'IDLE', 1: 'HOME', 2: 'SEARCHING', 3: 'DENIED', 4: 'UNKNOWN', 5: 'ROAMING' } # enum 4: modem bands self.modem_bands = { 0: 'Unknown or invalid band', 1: 'GSM/GPRS/EDGE 900 MHz', 2: 'GSM/GPRS/EDGE 1800 MHz', 3: 'GSM/GPRS/EDGE 1900 MHz', 4: 'GSM/GPRS/EDGE 850 MHz', 5: 'WCDMA 2100 MHz (Class I)', 6: 'WCDMA 3GPP 1800 MHz (Class III)', 7: 'WCDMA 3GPP AWS 1700/2100 MHz (Class IV)', 8: 'WCDMA 3GPP UMTS 800 MHz (Class VI)', 9: 'WCDMA 3GPP UMTS 850 MHz (Class V)', 10: 'WCDMA 3GPP UMTS 900 MHz (Class VIII)', 11: 'WCDMA 3GPP UMTS 1700 MHz (Class IX)', 12: 'WCDMA 3GPP UMTS 1900 MHz (Class II)', 13: 'WCDMA 3GPP UMTS 2600 MHz (Class VII, internal)', 31: 'E-UTRAN band I', 32: 'E-UTRAN band II', 33: 'E-UTRAN band III', 34: 'E-UTRAN band IV', 35: 'E-UTRAN band V', 36: 'E-UTRAN band VI', 37: 'E-UTRAN band VII', 38: 'E-UTRAN band VIII', 39: 'E-UTRAN band IX', 40: 'E-UTRAN band X', 41: 'E-UTRAN band XI', 42: 'E-UTRAN band XII', 43: 'E-UTRAN band XIII', 44: 'E-UTRAN band XIV', 47: 'E-UTRAN band XVII', 48: 'E-UTRAN band XVIII', 49: 'E-UTRAN band XIX', 50: 'E-UTRAN band XX', 51: 'E-UTRAN band XXI', 52: 'E-UTRAN band XXII', 53: 'E-UTRAN band XXIII', 54: 'E-UTRAN band XXIV', 55: 'E-UTRAN band XXV', 56: 'E-UTRAN band XXVI', 63: 'E-UTRAN band XXXIII', 64: 'E-UTRAN band XXXIV', 65: 'E-UTRAN band XXXV', 66: 'E-UTRAN band XXXVI', 67: 'E-UTRAN band XXXVII', 68: 'E-UTRAN band XXXVIII', 69: 'E-UTRAN band XXXIX', 70: 'E-UTRAN band XL', 71: 'E-UTRAN band XLI', 72: 'E-UTRAN band XLII', 73: 'E-UTRAN band XLIII', 128: 'CDMA Band Class 0 (US Cellular 850MHz)', 129: 'CDMA Band Class 1 (US PCS 1900MHz)', 130: 'CDMA Band Class 2 (UK TACS 900MHz)', 131: 'CDMA Band Class 3 (Japanese TACS)', 132: 'CDMA Band Class 4 (Korean PCS)', 134: 'CDMA Band Class 5 (NMT 450MHz)', 135: 'CDMA Band Class 6 (IMT2000 2100MHz)', 136: 'CDMA Band Class 7 (Cellular 700MHz)', 137: 'CDMA Band Class 8 (1800MHz)', 138: 'CDMA Band Class 9 (900MHz)', 139: 'CDMA Band Class 10 (US Secondary 800)', 140: 'CDMA Band Class 11 (European PAMR 400MHz)', 141: 'CDMA Band Class 12 (PAMR 800MHz)', 142: 'CDMA Band Class 13 (IMT2000 2500MHz Expansion)', 143: 'CDMA Band Class 14 (More US PCS 1900MHz)', 144: 'CDMA Band Class 15 (AWS 1700MHz)', 145: 'CDMA Band Class 16 (US 2500MHz)', 146: 'CDMA Band Class 17 (US 2500MHz Forward Link Only)', 147: 'CDMA Band Class 18 (US 700MHz Public Safety)', 148: 'CDMA Band Class 19 (US Lower 700MHz)', 256: 'auto' } self.bus = SystemBus() self.init = { 'ip': [], 'sms_message': [], 'thresholds': self.py3.get_color_names_list(self.format), } self.last_messages = 0 self.last_notification = self.py3.storage_get('notification') names = [ 'current_bands_name', 'access_technologies_name', 'm3gpp_registration_name', 'interface_name', 'ipv4', 'ipv6', 'stats', 'format_message', 'message' ] placeholders = [ 'current_bands_name', 'access_technologies_name', 'm3gpp_registration_name', 'interface_name', 'format_ipv4', 'format_ipv6', 'format_stats', 'format_message', 'message*' ] # init methods format_strings = [self.format, self.format_notification] for name, placeholder in zip(names, placeholders): self.init[name] = [] for format_string in format_strings: if format_string: # fails on None, [], '', etc if self.py3.format_contains(format_string, placeholder): self.init[name].append(format_string) if name in ['ipv4', 'ipv6']: if name not in self.init['ip']: self.init['ip'].append(name) if name in ['message', 'format_message']: if name not in self.init['sms_message']: self.init['sms_message'].append(name) def _get_modem_proxy(self): modemmanager_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS) modems = modemmanager_proxy.GetManagedObjects() for objects in modems.items(): modem_path = objects[0] modem_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, modem_path) eqid = modem_proxy.EquipmentIdentifier if self.modem is None or self.modem == eqid: return modem_proxy else: return {} def _get_modem_status_data(self, modem_proxy): modem_data = {} try: modem_data = modem_proxy.GetStatus() except: # noqa e722 pass return modem_data def _get_bearer(self, modem_proxy): bearer = {} try: bearer = modem_proxy.Bearers[0] except: # noqa e722 pass return bearer def _get_interface(self, bearer): return self.bus.get(STRING_MODEMMANAGER_DBUS, bearer).Interface def _get_message_data(self, modem_proxy): message_data = {} try: message_data = modem_proxy.Messages except: # noqa e722 pass return message_data def _count_messages(self, message_data): count_messages = len(message_data) count_message = max(0, count_messages - self.last_messages) self.last_messages = count_messages return count_message, count_messages def _manipulate_message(self, data): new_message = [] for index, msg in sorted(enumerate(data, 1), reverse=True): try: sms_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, msg) new_message.append( self.py3.safe_format( self.format_message, { 'index': index, 'number': sms_proxy.Number, 'text': sms_proxy.Text })) except: # noqa e722 break format_message_separator = self.py3.safe_format( self.format_message_separator ) format_message = self.py3.composite_join( format_message_separator, new_message ) return format_message def _get_network_config(self, bearer): bearer_proxy = self.bus.get(STRING_MODEMMANAGER_DBUS, bearer) return { 'ipv4': bearer_proxy.Ip4Config, 'ipv6': bearer_proxy.Ip6Config, } def _get_stats(self, bearer): return self.bus.get(STRING_MODEMMANAGER_DBUS, bearer).Stats def _organize(self, data): new_data = {} for key, value in data.items(): key = key.lower().replace('-', '_') if isinstance(value, (list, tuple)): if len(value) > 1: for i, v in enumerate(value): new_data['%s_%s' % (key, i)] = v elif len(value) == 1: new_data[key] = value[0] else: new_data[key] = None else: new_data[key] = value return new_data def wwan(self): urgent = False name = '_name' # get wwan data modem_proxy = self._get_modem_proxy() wwan_data = self._get_modem_status_data(modem_proxy) wwan_data = self._organize(wwan_data) # state and name key = 'state' wwan_data[key] = wwan_data.get(key, 0) wwan_data[key + name] = self.network_states[wwan_data[key]] # if state is -1, modem failed. stop here. report error. # if state is less than 8, we are not connected. skip. # if state is 8 or more, we are connected. start work. if wwan_data[key] == -1: self.py3.error(STRING_MODEM_ERROR) elif wwan_data[key] < 8: pass else: # access technologies and name if self.init['access_technologies_name']: key = 'access_technologies' if wwan_data[key]: bit = 1 << (wwan_data[key].bit_length() - 1) else: bit = 0 wwan_data[key + name] = self.network_speed[bit] # modem band if self.init['current_bands_name']: key = 'current_bands' wwan_data[key + name] = self.modem_bands[wwan_data[key]] # registration state and name if self.init['m3gpp_registration_name']: key = 'm3gpp_registration_state' new_key = key + name wwan_data[new_key] = self.registration_states[wwan_data[key]] # get bearer bearer = self._get_bearer(modem_proxy) if bearer: # interface name if self.init['interface_name']: wwan_data['interface_name'] = self._get_interface(bearer) # ipv4 and ipv6 network config if self.init['ip']: network_config = self._get_network_config(bearer) format_ip = { 'ipv4': self.format_ipv4, 'ipv6': self.format_ipv6, } for ip in self.init['ip']: wwan_data['format_' + ip] = self.py3.safe_format( format_ip[ip], network_config.get(ip, {})) # network connection statistics if self.init['stats']: stats = self._organize(self._get_stats(bearer)) if stats: stats['duration_hms'] = format( timedelta(seconds=stats['duration']) ) wwan_data['format_stats'] = self.py3.safe_format( self.format_stats, stats ) # message and format message if self.init['sms_message']: if wwan_data['state'] >= 1: message_data = self._get_message_data(modem_proxy) # count messages keys = ['message', 'messages'] wwan_data.update(zip(keys, self._count_messages(message_data))) if wwan_data['message']: urgent = True # format sms messages if self.init['format_message']: wwan_data['format_message'] = self._manipulate_message( message_data ) # thresholds for x in self.init['thresholds']: if x in wwan_data: self.py3.threshold_get_color(wwan_data[x], x) # notifications if self.format_notification: # get a notification format_notification = self.py3.safe_format( self.format_notification, wwan_data ) notification = self.py3.get_composite_string( format_notification ) if notification and notification != self.last_notification: self.last_notification = notification self.py3.storage_set('notification', notification) self.py3.notify_user(notification) response = { 'cached_until': self.py3.time_in(self.cache_timeout), 'full_text': self.py3.safe_format(self.format, wwan_data) } if urgent: response['urgent'] = True return response
def post_config_hook(self): modem_manager = ['ModemManager', '/usr/sbin/ModemManager'] network_manager = ['NetworkManager', '/usr/sbin/NetworkManager'] for command in (modem_manager, network_manager): if not self.py3.check_commands(command): raise Exception('%s %s' % (command[0], STRING_NOT_INSTALLED)) # search: modemmanager flags and enumerations # enum 1: #MMModemState # enum 2: #MMModemAccessTechnology # enum 3: #MMModem3gppRegistrationState # enum 4: #MMModemBand # enum 1: network states self.network_states = { -1: 'failed', 0: 'unknown', 1: 'initializing', 2: 'locked', 3: 'disabled', 4: 'disabling', 5: 'enabling', 6: 'enabled', 7: 'searching', 8: 'registered', 9: 'disconnecting', 10: 'connecting', 11: 'connected' } # enum 2: network speed self.network_speed = { 0: 'Unknown', 1 << 0: 'POTS', # 2 1 << 1: 'GSM', 1 << 2: 'GSM Compact', 1 << 3: 'GPRS', 1 << 4: 'EDGE', 1 << 5: 'UMTS', # 32 1 << 6: 'HSDPA', 1 << 7: 'HSUPA', 1 << 8: 'HSPA', 1 << 9: 'HSPA+', # 512 1 << 10: '1XRTT', 1 << 11: 'EVDO0', 1 << 12: 'EVDOA', 1 << 13: 'EVDOB', 1 << 14: 'LTE' # 16384 } # enum 3: network registration state self.registration_states = { 0: 'IDLE', 1: 'HOME', 2: 'SEARCHING', 3: 'DENIED', 4: 'UNKNOWN', 5: 'ROAMING' } # enum 4: modem bands self.modem_bands = { 0: 'Unknown or invalid band', 1: 'GSM/GPRS/EDGE 900 MHz', 2: 'GSM/GPRS/EDGE 1800 MHz', 3: 'GSM/GPRS/EDGE 1900 MHz', 4: 'GSM/GPRS/EDGE 850 MHz', 5: 'WCDMA 2100 MHz (Class I)', 6: 'WCDMA 3GPP 1800 MHz (Class III)', 7: 'WCDMA 3GPP AWS 1700/2100 MHz (Class IV)', 8: 'WCDMA 3GPP UMTS 800 MHz (Class VI)', 9: 'WCDMA 3GPP UMTS 850 MHz (Class V)', 10: 'WCDMA 3GPP UMTS 900 MHz (Class VIII)', 11: 'WCDMA 3GPP UMTS 1700 MHz (Class IX)', 12: 'WCDMA 3GPP UMTS 1900 MHz (Class II)', 13: 'WCDMA 3GPP UMTS 2600 MHz (Class VII, internal)', 31: 'E-UTRAN band I', 32: 'E-UTRAN band II', 33: 'E-UTRAN band III', 34: 'E-UTRAN band IV', 35: 'E-UTRAN band V', 36: 'E-UTRAN band VI', 37: 'E-UTRAN band VII', 38: 'E-UTRAN band VIII', 39: 'E-UTRAN band IX', 40: 'E-UTRAN band X', 41: 'E-UTRAN band XI', 42: 'E-UTRAN band XII', 43: 'E-UTRAN band XIII', 44: 'E-UTRAN band XIV', 47: 'E-UTRAN band XVII', 48: 'E-UTRAN band XVIII', 49: 'E-UTRAN band XIX', 50: 'E-UTRAN band XX', 51: 'E-UTRAN band XXI', 52: 'E-UTRAN band XXII', 53: 'E-UTRAN band XXIII', 54: 'E-UTRAN band XXIV', 55: 'E-UTRAN band XXV', 56: 'E-UTRAN band XXVI', 63: 'E-UTRAN band XXXIII', 64: 'E-UTRAN band XXXIV', 65: 'E-UTRAN band XXXV', 66: 'E-UTRAN band XXXVI', 67: 'E-UTRAN band XXXVII', 68: 'E-UTRAN band XXXVIII', 69: 'E-UTRAN band XXXIX', 70: 'E-UTRAN band XL', 71: 'E-UTRAN band XLI', 72: 'E-UTRAN band XLII', 73: 'E-UTRAN band XLIII', 128: 'CDMA Band Class 0 (US Cellular 850MHz)', 129: 'CDMA Band Class 1 (US PCS 1900MHz)', 130: 'CDMA Band Class 2 (UK TACS 900MHz)', 131: 'CDMA Band Class 3 (Japanese TACS)', 132: 'CDMA Band Class 4 (Korean PCS)', 134: 'CDMA Band Class 5 (NMT 450MHz)', 135: 'CDMA Band Class 6 (IMT2000 2100MHz)', 136: 'CDMA Band Class 7 (Cellular 700MHz)', 137: 'CDMA Band Class 8 (1800MHz)', 138: 'CDMA Band Class 9 (900MHz)', 139: 'CDMA Band Class 10 (US Secondary 800)', 140: 'CDMA Band Class 11 (European PAMR 400MHz)', 141: 'CDMA Band Class 12 (PAMR 800MHz)', 142: 'CDMA Band Class 13 (IMT2000 2500MHz Expansion)', 143: 'CDMA Band Class 14 (More US PCS 1900MHz)', 144: 'CDMA Band Class 15 (AWS 1700MHz)', 145: 'CDMA Band Class 16 (US 2500MHz)', 146: 'CDMA Band Class 17 (US 2500MHz Forward Link Only)', 147: 'CDMA Band Class 18 (US 700MHz Public Safety)', 148: 'CDMA Band Class 19 (US Lower 700MHz)', 256: 'auto' } self.bus = SystemBus() self.init = { 'ip': [], 'sms_message': [], 'thresholds': self.py3.get_color_names_list(self.format), } self.last_messages = 0 self.last_notification = self.py3.storage_get('notification') names = [ 'current_bands_name', 'access_technologies_name', 'm3gpp_registration_name', 'interface_name', 'ipv4', 'ipv6', 'stats', 'format_message', 'message' ] placeholders = [ 'current_bands_name', 'access_technologies_name', 'm3gpp_registration_name', 'interface_name', 'format_ipv4', 'format_ipv6', 'format_stats', 'format_message', 'message*' ] # init methods format_strings = [self.format, self.format_notification] for name, placeholder in zip(names, placeholders): self.init[name] = [] for format_string in format_strings: if format_string: # fails on None, [], '', etc if self.py3.format_contains(format_string, placeholder): self.init[name].append(format_string) if name in ['ipv4', 'ipv6']: if name not in self.init['ip']: self.init['ip'].append(name) if name in ['message', 'format_message']: if name not in self.init['sms_message']: self.init['sms_message'].append(name)
def __init__(self, irc): super().__init__(irc) self.irc = irc self.topic_lock = threading.Lock() self.mainloop = None self.mainloop_thread = None mainloop = GObject.MainLoop() if not mainloop.is_running(): log.info('Starting Glib main loop') mainloop_thread = threading.Thread(target=mainloop.run, name='Glib maing loop') mainloop_thread.start() self.mainloop_thread = mainloop_thread self.mainloop = mainloop self.requests_session = requests.Session() self.requests_session.verify = True self.queued_topics = {} self.last_n_messages = [] # data sources pseudo_packages.pp = PseudoPackages(self.requests_session) self.pseudo_packages = pseudo_packages.pp self.stable_rc_bugs = StableRCBugs(self.requests_session) self.testing_rc_bugs = TestingRCBugs(self.requests_session) self.new_queue = NewQueue(self.requests_session) self.dinstall = Dinstall(self.requests_session) self.rm_queue = RmQueue(self.requests_session) self.apt_archive = AptArchive( self.registryValue('apt_configuration_directory'), self.registryValue('apt_cache_directory')) self.data_sources = ( self.pseudo_packages, self.stable_rc_bugs, self.testing_rc_bugs, self.new_queue, self.dinstall, self.rm_queue, self.apt_archive ) # Schedule datasource updates def wrapper(source): def implementation(): try: source.update() except Exception as e: log.exception('Failed to update {}: {}'.format(source.NAME, e)) self._topic_callback() return implementation for source in self.data_sources: # schedule periodic events schedule.addPeriodicEvent(wrapper(source), source.INTERVAL, source.NAME, now=False) # and run them now once schedule.addEvent(wrapper(source), time.time() + 1) log.info('Starting D-Bus service') self.dbus_service = BTSDBusService(self._email_callback) self.dbus_bus = SystemBus() self.dbus_bus.publish(self.dbus_service.interface_name, self.dbus_service) self.dbus_service.start()
#! # server_test.py # Publish a string of data every second onto the System D-Bus # To check server is emitting data OK use the gdbus utility command... # $ gdbus monitor --system --dest org.example.ca.server # Importing import asyncio import random from pydbus import SystemBus from pydbus.generic import signal # Instantiation / Variables / Constants iface_name = "org.example.ca.server" # Note that server uses the System D-Bus (not Session D-Bus) bus = SystemBus() # Main event loop loop = asyncio.get_event_loop() class Server_XML(object): """ Server_XML definition. type='i' for integer, type='d' for double/float, type='s' for string type='ai' for list of 32-bit signed integers, type='as' for string list """ dbus = """ <node> <interface name="org.example.ca.server"> <signal name="app_signal"> <arg type='s'/>
# Client monitors for server applications System D-Bus signal emissions. # Client is a command line application. # GLib.MainLoop is used to provide the loop # TODO: Change code to use asyncio loop? # To Demo: # From one console terminal launch server_test.py # From another console terminal launch client_test.py import sys from gi.repository import GLib from pydbus import SystemBus # Instantiation / Variables / Constants # Note that server uses the System D-Bus (not Session D-Bus) iface_name = "org.example.ca.server" bus = SystemBus() loop = GLib.MainLoop() bus_name = "org.example.ca.server" dbus_filter = "/" + "/".join(bus_name.split(".")) # print(dbus_filter) # /org/example/ca/server def cb_server_signal_emission(*args): """ Callback on emitting signal from server Emitted signal is the value of the counter Data is in args[4]. The first item in a tuple.args[4][0] """ data = args[4][0] print("Client:", data)
class WlanApp: def __init__(self): self.prefix = 'W:' self.suffix = ' ' self.tooltip_heading = 'Wireless LAN Status:\n' self.iface = None # Set to interface name to override interface selection self.build_ui() # Needed by wpa_supplicant.core self.reactor = SelectReactor() thread = threading.Thread(target=self.reactor.run, kwargs={'installSignalHandlers': 0}) thread.daemon = True thread.start() time.sleep(0.1) # let reactor start self.wpasup = None self.wpasup_running = False self.wlan = None self.wlan_signal = None # Monitor the availability of wpa_supplicant via DBus self.dbus = SystemBus() # watch_name() fires an event as soon as GLib.MainLoop() starts, so we don't need to explicitly # call get_wpa_supplicant() here self.dbus.watch_name(BUS_NAME, 0, self.get_wpa_supplicant, self.get_wpa_supplicant) self.start_watch_thread() def build_ui(self): self.tray = tray = Gtkti.TrayIcon() self.eventbox = eventbox = Gtk.EventBox() eventbox.set_tooltip_text(self.tooltip_heading+'WPA Supplicant not running') tray.add(eventbox) self.tray_label = tray_label = Gtk.Label(self.prefix+'_'+self.suffix) eventbox.add(tray_label) tray.show_all() menu = Gtk.Menu() item_quit = Gtk.MenuItem('Quit') def quit(menu_item): if sys.version_info < (3, 0): os.kill(os.getpid(), signal.SIGINT) else: Gtk.main_quit() item_quit.connect('activate', quit) menu.append(item_quit) menu.show_all() def button_pressed(eventbox, event, menu=menu): if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3: menu.popup(None, None, None, None, event.button, event.time) eventbox.connect('button-press-event', button_pressed) # Update the UI (thread-safe) def update_ui(self): GLib.idle_add(self.gtk_update_ui) # Update the UI (within the GTK main thread ; not thread-safe) def gtk_update_ui(self): if not self.wpasup_running: display_str = '_' tooltip_str = 'WLAN Interface is down (WPA Supplicant is not running)' elif not self.wlan: display_str = '_' tooltip_str = 'WLAN Interface not found via WPA Supplicant' else: try: ifname = self.wlan.get_ifname() tooltip_str = ifname state = self.wlan.get_state() tooltip_str += ' '+state.title() if state == 'interface_disabled': display_str = '_' elif state == 'disconnected' or state == 'inactive': display_str = '-' elif state == 'scanning': display_str = '?' elif state == 'authenticating' or state == 'associating' or state == 'associated' or \ state == '4way_handshake' or state == 'group_handshake': display_str = '@' elif state == 'completed': display_str = '' tooltip_str += ' Connected' elif state == 'unknown': display_str = '!' else: display_str = '!' print >> sys.stderr, 'Unknown wpa_supplicant state: '+state+' to '+self.wlan.get_current_bss().get_ssid() bss = self.wlan.get_current_bss() if bss: display_str += bss.get_ssid() tooltip_str += ' to '+bss.get_ssid() except: # This is expected if another thread sets self.wlan to None while the above code is # executing, or if wpa_supplicant shuts down while the above code is executing. In either # case, another UI update should happen momentarily. display_str = '!' tooltip_str = 'Unknown (Exception Thrown)' self.tray_label.set_text(self.prefix+display_str+self.suffix) self.eventbox.set_tooltip_text(self.tooltip_heading+tooltip_str) # Return false to unregister this method as a GLib idle handler return False def select_wlan_interface(self, interfaces): if self.wlan_signal: wlan_signal = self.wlan_signal # To avoid race conditions self.wlan_signal = None wlan_signal.cancel() self.wlan = None if interfaces: if self.iface: for interface in interfaces: if interface.get_ifname() == self.iface: self.wlan = interface break else: self.wlan = interfaces[0] self.wlan_signal = \ self.wlan.register_signal('PropertiesChanged', lambda args: self.update_ui()) self.update_ui() def scan_wpa_interfaces(self, args=None): self.wpa_interfaces = self.wpasup.get_interfaces() self.select_wlan_interface(self.wpa_interfaces) def wlan_interface_removed(self, path): # wpa_supplicant sends InterfaceRemoved just before shutting down, and get_interfaces() may # throw an exception if it is called while wpa_supplicant is shutting down. So, instead of # calling scan_wpa_interfaces on InterfaceRemoved, it is probably better to keep a cache of the # list of interfaces and just delete the relevant interface from the cache. self.wpa_interfaces[:] = [i for i in self.wpa_interfaces if not i.get_path() == path] self.select_wlan_interface(self.wpa_interfaces) def get_wpa_supplicant(self, dbus_name_owner = None): if dbus_name_owner: self.wpasup_running = True if not self.wpasup: # Connect to wpa_supplicant self.wpasup = WpaSupplicantDriver(self.reactor).connect() self.wpasup.register_signal('InterfaceAdded', self.scan_wpa_interfaces) self.wpasup.register_signal('InterfaceRemoved', self.wlan_interface_removed) self.scan_wpa_interfaces() else: # If we don't do anything when wpa_supplicant vanishes, then our signals seem to remain # registered when wpa_supplicant re-appears. However, wpa_supplicant doesn't seem to send # InterfaceAdded signals when it comes up, so we must explicitly re-scan the interfaces. self.scan_wpa_interfaces() else: self.wpasup_running = False self.select_wlan_interface([]) def start_watch_thread(self): thread = threading.Thread(target=GLib.MainLoop().run) thread.daemon = True thread.start()
def post_config_hook(self): bus = SystemBus() systemd = bus.get('org.freedesktop.systemd1') self.systemd_unit = bus.get('.systemd1', systemd.LoadUnit(self.unit))
class WelcomedClient(GObject.GObject): _name = 'com.antergos.welcome' _object_path = '/com/antergos/welcome' _interface_name = 'com.antergos.welcome' __gsignals__ = { 'command-finished': (GObject.SignalFlags.RUN_FIRST, None, (str, str, GObject.TYPE_PYOBJECT)) } def __init__(self): GObject.GObject.__init__(self) self.interface = None self.welcomed_ok = False try: self.bus = SystemBus() self.dbus_proxy = self.bus.get( WelcomedClient._name, WelcomedClient._object_path) if not self.dbus_proxy: self.welcomed_ok = False else: self.dbus_proxy.PropertiesChanged.connect( self.on_properties_changed) self.welcomed_ok = self.dbus_proxy.is_alpm_on() except Exception as err: print(err) finally: if not self.welcomed_ok: msg = _("Can't find Welcome d-bus service. Is it really installed?") Notify.init("antergos-welcome") Notify.Notification.new( _("ERROR!"), msg, 'dialog-error').show() def refresh(self): """ pacman -Sy """ return self.dbus_proxy.refresh_alpm() def on_properties_changed(self, *params): """ A d-bus server property has changed """ (sender, prop, not_used) = params # print("PARAMS:", params) if sender == WelcomedClient._name and 'command_finished' in prop.keys(): (uid, command, pkgs) = prop['command_finished'] self.emit("command-finished", uid, command, pkgs) def install_package(self, pkg): """ pacman -S pkg """ return self.dbus_proxy.install_package(pkgs) def install_packages(self, pkgs): """ pacman -S pkgs """ return self.dbus_proxy.install_packages(pkgs) def remove_package(self, package): """ pacman -R pkg """ return self.dbus_proxy.remove_package(package) def remove_packages(self, pkgs): """ pacman -R pkgs """ for pkg in pkgs: self.remove_package(pkg) def check_updates(self): return self.dbus_proxy.check_updates() def system_upgrade(self): return self.dbus_proxy.system_upgrade()
class DebianDevelChanges(supybot.callbacks.Plugin): threaded = True def __init__(self, irc): super().__init__(irc) self.irc = irc self.topic_lock = threading.Lock() self.mainloop = None self.mainloop_thread = None mainloop = GObject.MainLoop() if not mainloop.is_running(): log.info('Starting Glib main loop') mainloop_thread = threading.Thread(target=mainloop.run, name='Glib maing loop') mainloop_thread.start() self.mainloop_thread = mainloop_thread self.mainloop = mainloop self.requests_session = requests.Session() self.requests_session.verify = True self.queued_topics = {} self.last_n_messages = [] # data sources pseudo_packages.pp = PseudoPackages(self.requests_session) self.pseudo_packages = pseudo_packages.pp self.stable_rc_bugs = StableRCBugs(self.requests_session) self.testing_rc_bugs = TestingRCBugs(self.requests_session) self.new_queue = NewQueue(self.requests_session) self.dinstall = Dinstall(self.requests_session) self.rm_queue = RmQueue(self.requests_session) self.apt_archive = AptArchive( self.registryValue('apt_configuration_directory'), self.registryValue('apt_cache_directory')) self.data_sources = ( self.pseudo_packages, self.stable_rc_bugs, self.testing_rc_bugs, self.new_queue, self.dinstall, self.rm_queue, self.apt_archive ) # Schedule datasource updates def wrapper(source): def implementation(): try: source.update() except Exception as e: log.exception('Failed to update {}: {}'.format(source.NAME, e)) self._topic_callback() return implementation for source in self.data_sources: # schedule periodic events schedule.addPeriodicEvent(wrapper(source), source.INTERVAL, source.NAME, now=False) # and run them now once schedule.addEvent(wrapper(source), time.time() + 1) log.info('Starting D-Bus service') self.dbus_service = BTSDBusService(self._email_callback) self.dbus_bus = SystemBus() self.dbus_bus.publish(self.dbus_service.interface_name, self.dbus_service) self.dbus_service.start() def die(self): log.info('Stopping D-Bus service') self.dbus_service.stop() if self.mainloop is not None: log.info('Stopping Glib main loop') self.mainloop.quit() self.mainloop_thread.join(timeout=1.0) if self.mainloop_thread.is_alive(): log.warn('Glib main loop thread is still alive.') self.mainloop = None self.mainloop_thread = None for source in self.data_sources: try: schedule.removePeriodicEvent(source.NAME) except KeyError: pass super().die() def _email_callback(self, fileobj): try: emailmsg = parse_mail(fileobj) msg = get_message(emailmsg, new_queue=self.new_queue) if not msg: return txt = colourise(msg.for_irc()) # Simple flood/duplicate detection if txt in self.last_n_messages: return self.last_n_messages.insert(0, txt) self.last_n_messages = self.last_n_messages[:20] maintainer_info = None if hasattr(msg, 'maintainer'): maintainer_info = (split_address(msg.maintainer), ) else: maintainer_info = [] for package in msg.package.split(','): package = package.strip() try: maintainer_info.append(self.apt_archive.get_maintainer(package)) except NewDataSource.DataError as e: log.info("Failed to query maintainer for {}.".format(package)) for channel in self.irc.state.channels: package_regex = self.registryValue( 'package_regex', channel, ) or 'a^' # match nothing by default package_match = re.search(package_regex, msg.package) maintainer_match = False maintainer_regex = self.registryValue( 'maintainer_regex', channel) if maintainer_regex and maintainer_info is not None and len(maintainer_info) >= 0: for mi in maintainer_info: maintainer_match = re.search(maintainer_regex, mi['email']) if maintainer_match: break if not package_match and not maintainer_match: continue distribution_regex = self.registryValue( 'distribution_regex', channel, ) if distribution_regex: if not hasattr(msg, 'distribution'): # If this channel has a distribution regex, don't # bother continuing unless the message actually has a # distribution. This filters security messages, etc. continue if not re.search(distribution_regex, msg.distribution): # Distribution doesn't match regex; don't send this # message. continue send_privmsg = self.registryValue('send_privmsg', channel) # Send NOTICE per default and if 'send_privmsg' is set for the # channel, send PRIVMSG instead. if send_privmsg: ircmsg = supybot.ircmsgs.privmsg(channel, txt) else: ircmsg = supybot.ircmsgs.notice(channel, txt) self.irc.queueMsg(ircmsg) except Exception as e: log.exception('Uncaught exception: %s ' % e) def _topic_callback(self): sections = { self.testing_rc_bugs.get_number_bugs: 'RC bug count', self.stable_rc_bugs.get_number_bugs: 'stable RC bug count', self.new_queue.get_size: 'NEW queue', self.new_queue.get_backports_size: 'backports NEW queue', self.rm_queue.get_size: 'RM queue', self.dinstall.get_status: 'dinstall' } channels = set() with self.topic_lock: values = {} for callback, prefix in sections.items(): new_value = callback() if new_value is not None: values[prefix] = new_value for channel in self.irc.state.channels: new_topic = topic = self.irc.state.getTopic(channel) for prefix, value in values.items(): new_topic = rewrite_topic(new_topic, prefix, value) if topic != new_topic: self.queued_topics[channel] = new_topic if channel not in channels: log.info("Queueing change of topic in #%s to '%s'" % (channel, new_topic)) channels.add(channel) for channel in channels: event_name = '{}_topic'.format(channel) try: schedule.removeEvent(event_name) except KeyError: pass def update_topic(channel=channel): self._update_topic(channel) schedule.addEvent(update_topic, time.time() + 60, event_name) def _update_topic(self, channel): with self.topic_lock: try: new_topic = self.queued_topics[channel] log.info("Changing topic in #%s to '%s'" % (channel, new_topic)) self.irc.queueMsg(supybot.ircmsgs.topic(channel, new_topic)) except KeyError: pass def rc(self, irc, msg, args): """Link to UDD RC bug overview.""" num_bugs = self.testing_rc_bugs.get_number_bugs() if type(num_bugs) is int: irc.reply( "There are %d release-critical bugs in the testing distribution. " "See https://udd.debian.org/bugs.cgi?release=buster¬main=ign&merged=ign&rc=1" % num_bugs) else: irc.reply("No data at this time.") rc = wrap(rc) bugs = wrap(rc) def update(self, irc, msg, args): """Trigger an update.""" if not ircdb.checkCapability(msg.prefix, 'owner'): irc.reply("You are not authorised to run this command.") return for source in self.data_sources: source.update() irc.reply("Updated %s." % source.NAME) self._topic_callback() update = wrap(update) def madison(self, irc, msg, args, package): """List packages.""" try: lines = madison(package) if not lines: irc.reply('Did not get a response -- is "%s" a valid package?' % package) return field_styles = ('package', 'version', 'distribution', 'section') for line in lines: out = [] fields = line.strip().split('|', len(field_styles)) for style, data in zip(field_styles, fields): out.append('[%s]%s' % (style, data)) irc.reply(colourise('[reset]|'.join(out)), prefixNick=False) except Exception as e: irc.reply("Error: %s" % e.message) madison = wrap(madison, ['text']) def get_pool_url(self, package): if package.startswith('lib'): return (package[:4], package) else: return (package[:1], package) def _maintainer(self, irc, msg, args, items): """Get maintainer for package.""" for package in items: info = self.apt_archive.get_maintainer(package) if info: display_name = format_email_address("%s <%s>" % (info['name'], info['email']), max_domain=18) login = info['email'] if login.endswith('@debian.org'): login = login.replace('@debian.org', '') msg = "[desc]Maintainer for[reset] [package]%s[reset] [desc]is[reset] [by]%s[reset]: " % (package, display_name) msg += "[url]https://qa.debian.org/developer.php?login=%s[/url]" % login else: msg = 'Unknown source package "%s"' % package irc.reply(colourise(msg), prefixNick=False) maintainer = wrap(_maintainer, [many('anything')]) maint = wrap(_maintainer, [many('anything')]) who_maintains = wrap(_maintainer, [many('anything')]) def _qa(self, irc, msg, args, items): """Get link to QA page.""" for package in items: url = "https://packages.qa.debian.org/%s/%s.html" % self.get_pool_url(package) msg = "[desc]QA page for[reset] [package]%s[reset]: [url]%s[/url]" % (package, url) irc.reply(colourise(msg), prefixNick=False) qa = wrap(_qa, [many('anything')]) overview = wrap(_qa, [many('anything')]) package = wrap(_qa, [many('anything')]) pkg = wrap(_qa, [many('anything')]) srcpkg = wrap(_qa, [many('anything')]) def _changelog(self, irc, msg, args, items): """Get link to changelog.""" for package in items: url = "https://packages.debian.org/changelogs/pool/main/%s/%s/current/changelog" % self.get_pool_url(package) msg = "[desc]debian/changelog for[reset] [package]%s[reset]: [url]%s[/url]" % (package, url) irc.reply(colourise(msg), prefixNick=False) changelog = wrap(_changelog, [many('anything')]) changes = wrap(_changelog, [many('anything')]) def _copyright(self, irc, msg, args, items): """Link to copyright files.""" for package in items: url = "https://packages.debian.org/changelogs/pool/main/%s/%s/current/copyright" % self.get_pool_url(package) msg = "[desc]debian/copyright for[reset] [package]%s[reset]: [url]%s[/url]" % (package, url) irc.reply(colourise(msg), prefixNick=False) copyright = wrap(_copyright, [many('anything')]) def _buggraph(self, irc, msg, args, items): """Link to bug graph.""" for package in items: msg = "[desc]Bug graph for[reset] [package]%s[reset]: [url]https://qa.debian.org/data/bts/graphs/%s/%s.png[/url]" % \ (package, package[0], package) irc.reply(colourise(msg), prefixNick=False) buggraph = wrap(_buggraph, [many('anything')]) bug_graph = wrap(_buggraph, [many('anything')]) def _buildd(self, irc, msg, args, items): """Link to buildd page.""" for package in items: msg = "[desc]buildd status for[reset] [package]%s[reset]: [url]https://buildd.debian.org/pkg.cgi?pkg=%s[/url]" % \ (package, package) irc.reply(colourise(msg), prefixNick=False) buildd = wrap(_buildd, [many('anything')]) def _popcon(self, irc, msg, args, package): """Get popcon data.""" try: msg = popcon(package, self.requests_session) if msg: irc.reply(colourise(msg.for_irc()), prefixNick=False) except Exception as e: irc.reply("Error: unable to obtain popcon data for %s" % package) popcon = wrap(_popcon, ['text']) def _testing(self, irc, msg, args, items): """Check testing migration status.""" for package in items: msg = "[desc]Testing migration status for[reset] [package]%s[reset]: [url]https://qa.debian.org/excuses.php?package=%s[/url]" % \ (package, package) irc.reply(colourise(msg), prefixNick=False) testing = wrap(_testing, [many('anything')]) migration = wrap(_testing, [many('anything')]) def _new(self, irc, msg, args): """Link to NEW queue.""" line = "[desc]NEW queue is[reset]: [url]%s[/url]. [desc]Current size is:[reset] %d" % \ ("https://ftp-master.debian.org/new.html", self.new_queue.get_size()) irc.reply(colourise(line)) new = wrap(_new) new_queue = wrap(_new) newqueue = wrap(_new)
from pydbus import SystemBus from gi.repository import GObject def print_state(a, b, c): print a print b.keys() print c bus = SystemBus() dev = bus.get('org.freedesktop.UDisks2', '/org/freedesktop/UDisks2/drives/TSSTcorp_CDDVDW_SE_S084C_SATASLIM00003008cae') dev.PropertiesChanged.connect(print_state) GObject.MainLoop().run()
#!/usr/bin/python3 from pydbus import SessionBus,SystemBus BATTERY_LEVELS = "" CHARGING_FULL = '' CHARGING = '' sys = SystemBus() power = sys.get('.UPower') all_capacity = 0 all_rate = 0 charge_time = 0 bat_no = 0 percentages = [] all_full = True for a in power.EnumerateDevices(): dev = sys.get('.UPower', a) # check if battery if dev.Type == 2: # change all full, if not all fully charged if dev.State != 4: all_full = False # check if battery is charging if dev.State == 1: charge_time += (dev.EnergyFull - dev.Energy) / dev.EnergyRate
<method name='EchoString'> <arg type='s' name='question' direction='in'/> <arg type='s' name='response' direction='out'/> </method> <method name='Quit'/> </interface> </node> """ def EchoString(self, s): """returns whatever is passed to it""" logging.debug("%s: EchoString %s" % (self.__class__.__name__, s)) return s def Quit(self): """removes the object from the DBUS connection and exits""" logging.debug("%s: Quit" % self.__class__.__name__) GLib.timeout_add_seconds(1, loop.quit) def initialize(self): """initialize boss before publishing""" logging.debug("%s: intialize started" % self.__class__.__name__) time.sleep(random.randrange(4)) logging.debug("%s: intialize finished" % self.__class__.__name__) bus = SystemBus() module = Timezone() module.initialize() bus.publish("org.freedesktop.Anaconda.Module.Timezone", module) loop.run()
<method name='EchoString'> <arg type='s' name='question' direction='in'/> <arg type='s' name='response' direction='out'/> </method> <method name='Quit'/> </interface> </node> """ def EchoString(self, s): """returns whatever is passed to it""" logging.debug("%s: EchoString %s" % (self.__class__.__name__, s)) return s def Quit(self): """removes the object from the DBUS connection and exits""" logging.debug("%s: Quit" % self.__class__.__name__) GLib.timeout_add_seconds(1, loop.quit) def initialize(self): """initialize boss before publishing""" logging.debug("%s: intialize started" % self.__class__.__name__) time.sleep(random.randrange(4)) logging.debug("%s: intialize finished" % self.__class__.__name__) bus = SystemBus() module = Pony() module.initialize() bus.publish("org.freedesktop.Anaconda.Addon.Pony", module) loop.run()
class BatteryApp: def __init__(self): self.prefix = 'B:' self.separator = '/' self.suffix = ' ' self.tooltip_heading = 'Battery Status:\n' self.low_battery_alarm_threshold = 5 self.low_battery_alarm_visible = False self.build_ui() self.dbus = SystemBus() self.upower = self.dbus.get('.UPower', '/org/freedesktop/UPower') self.battery_subscriptions = [] self.upower.DeviceAdded.connect(lambda name, vals, a: self.get_upower_batteries()) self.upower.DeviceRemoved.connect(lambda name, vals, a: self.get_upower_batteries()) self.get_upower_batteries() self.start_signal_thread() def build_ui(self): self.tray = tray = Gtkti.TrayIcon() self.eventbox = eventbox = Gtk.EventBox() eventbox.set_tooltip_text(self.tooltip_heading+'Unknown') tray.add(eventbox) self.tray_label = tray_label = Gtk.Label(self.prefix+'?'+self.suffix) eventbox.add(tray_label) tray.show_all() menu = Gtk.Menu() item_quit = Gtk.MenuItem('Quit') def quit(menu_item): if sys.version_info < (3, 0): os.kill(os.getpid(), signal.SIGINT) else: Gtk.main_quit() item_quit.connect('activate', quit) menu.append(item_quit) menu.show_all() def button_pressed(eventbox, event, menu=menu): if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3: menu.popup(None, None, None, None, event.button, event.time) eventbox.connect('button-press-event', button_pressed) # Update the UI (thread-safe) def update_ui(self): GLib.idle_add(self.gtk_update_ui) # Update the UI (within the GTK main thread ; not thread-safe) def gtk_update_ui(self): display_str = '' tooltip_str = '' max_percentage = 0 for battery in self.upower_batteries: if display_str: display_str += '/' tooltip_str += '\n' tooltip_str += battery.NativePath+': ' state = battery.State if state == 1 or state == 5: tooltip_str += 'Charging ('+str(battery.Percentage)+'%)' display_str += str(int(battery.Percentage))+'+' elif state == 2 or state == 3 or state == 6: tooltip_str += 'Discharging ('+str(battery.Percentage)+'%)' display_str += str(int(battery.Percentage))+'-' elif state == 4: tooltip_str += 'Full ('+str(battery.Percentage)+'%)' display_str += str(int(battery.Percentage)) else: tooltip_str += 'Unknown ('+str(battery.Percentage)+'%)' display_str += '?' if battery.TimeToFull: m, s = divmod(battery.TimeToFull, 60) h, m = divmod(m, 60) tooltip_str += ', Remaining Charge Time: '+('%dh %02dm %02ds' % (h, m, s)) if battery.TimeToEmpty: m, s = divmod(battery.TimeToEmpty, 60) h, m = divmod(m, 60) tooltip_str += ', Remaining Discharge Time: '+('%dh %02dm %02ds' % (h, m, s)) if battery.Percentage > max_percentage: max_percentage = battery.Percentage self.tray_label.set_text(self.prefix+display_str+self.suffix) self.eventbox.set_tooltip_text(self.tooltip_heading+tooltip_str) if max_percentage < self.low_battery_alarm_threshold and not self.low_battery_alarm_visible: self.low_battery_alarm_visible = True dialog = Gtk.Dialog() dialog.set_title('Warning') dialog.set_default_size(250, 100) label = Gtk.Label('Low Battery') dialog.get_content_area().add(label) dialog.add_button('_Close', -1) # GTK_RESPONSE_NONE == -1 def close_pressed(dialog, response_id, self=self): self.low_battery_alarm_visible = False dialog.destroy() dialog.connect('response', close_pressed) dialog.show_all() # Return false to unregister this method as a GLib idle handler return False def get_upower_batteries(self): paths = self.upower.EnumerateDevices() devices = map(lambda p: self.dbus.get('.UPower', p), paths) batteries = filter(lambda d: d.Type == 2, devices) for s in self.battery_subscriptions: s.disconnect() self.battery_subscriptions = [] for battery in batteries: s = battery.PropertiesChanged.connect(lambda name, vals, a: self.update_ui()) self.battery_subscriptions.append(s) self.upower_batteries = batteries self.update_ui() def start_signal_thread(self): thread = threading.Thread(target=GLib.MainLoop().run) thread.daemon = True thread.start()
from pydbus import SystemBus bus = SystemBus() systemd = bus.get(".systemd1") #systemd = bus.get("org.freedesktop.systemd1") manager = systemd[".Manager"] #manager = systemd["org.freedesktop.systemd1.Manager"] #manager = systemd # works but may break if systemd adds another interface import sys try: if len(sys.argv) < 2: for unit in manager.ListUnits(): print(unit) else: if sys.argv[1] == "--help": help(manager) else: command = sys.argv[1] command = "".join(x.capitalize() for x in command.split("-")) result = getattr(manager, command)(*sys.argv[2:]) for var in result: if type(var) == list: for line in var: print(line) else: print(var)