Пример #1
0
 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)
Пример #2
0
    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
Пример #3
0
    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 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()
Пример #5
0
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()
Пример #6
0
 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) )
Пример #7
0
    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)
Пример #8
0
    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()
Пример #9
0
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
Пример #10
0
    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")
Пример #11
0
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))
Пример #12
0
    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")
Пример #13
0
 def post_config_hook(self):
     if self.user:
         bus = SessionBus()
     else:
         bus = SystemBus()
     systemd = bus.get("org.freedesktop.systemd1")
     self.systemd_unit = bus.get(".systemd1", systemd.LoadUnit(self.unit))
Пример #14
0
 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)
Пример #15
0
    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)
Пример #16
0
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()
Пример #17
0
class Properties(MyBluez):

    interfaceName = "org.freedesktop.DBus.Properties"
    busName = "org.bluez"
    path = "/org/bluez/hci0"
    bus = SystemBus()
    objectsListArray = []

    def __init__(self):
        print "Object Manager's Init Called"

    def PowerOff(self):
        properties = self.bus.get(self.busName, self.path)
        iface = "org.bluez.Adapter1"
        name = "Powered"
        properties.Set(iface, name, GLib.Variant("b", False))

    def PowerOn(self):
        properties = self.bus.get(self.busName, self.path)
        iface = "org.bluez.Adapter1"
        name = "Powered"
        properties.Set(iface, name, GLib.Variant("b", True))

    def GetAll(self):
        properties = self.bus.get(self.busName, self.pathIPhone)
        iface = "org.bluez.Adapter1"
        allProps = properties.GetAll(iface)
        print allProps
Пример #18
0
    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()
Пример #19
0
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
Пример #20
0
 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)
Пример #21
0
 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)
Пример #22
0
 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")
Пример #23
0
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")
Пример #24
0
    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
Пример #25
0
def quit(bus=None):
    if bus is None:
        bus = SystemBus()

    try:
        bts = bus.get(BTSDBusService.interface_name)
        bts.Quit()
    except GLib.Error:
        return -1
Пример #26
0
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)
Пример #27
0
def main (args, app):
  for trigger in Trigger.FromConfig(app.config):
    if args.name == trigger.name:
      with SystemBus( ) as bus:
        path = PATH + '/EventSink/{name:s}'.format(name=trigger.name)
        event = bus.get(BUS, path)
        event.Fire( )
        props = event.GetAll(OWN_IFACE)
        print props
Пример #28
0
    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)
Пример #29
0
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)
Пример #30
0
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()