Ejemplo n.º 1
0
def main():
    if os.geteuid() != 0:
        exit("Comitup requires root privileges")

    args = parse_args()

    log = deflog()
    log.info("Starting comitup")

    (conf, data) = load_data()

    if args.check:
        if wificheck.run_checks():
            sys.exit(1)
        else:
            sys.exit(0)
    else:
        wificheck.run_checks(verbose=False)

    webmgr.init_webmgr(conf.web_service)
    iptmgr.init_iptmgr()

    statemgr.init_state_mgr(
        conf,
        data,
        [
            webmgr.state_callback,
            iptmgr.state_callback,
            cdns.state_callback,
        ],
    )

    loop = MainLoop()
    loop.run()
Ejemplo n.º 2
0
def pydbus_server():
    loop = MainLoop()
    bus = pydbus.SessionBus()
    try:
        bus.get('pydbus.unittest',timeout=1)
    except:
        with bus.publish("pydbus.unittest", PyDbusUnitTestService(loop)):
            loop.run()
Ejemplo n.º 3
0
class RoficationDbusService:
    def __init__(self, queue: NotificationQueue) -> None:
        # preserve D-Bus object reference
        self._object = RoficationDbusObject(queue)
        # create GLib mainloop, this is needed to make D-Bus work and takes care of catching signals.
        self._loop = MainLoop()

    def run(self) -> None:
        self._loop.run()
Ejemplo n.º 4
0
    def ObjListUpdater(self):
        self.system_bus = pydbus.SystemBus()
        self.system_bus.subscribe(sender='org.bluez',
                                  signal='PropertiesChanged',
                                  signal_fired=self.Update_obj_list)

        loop = MainLoop()
        timeout_add(100, self.checkTerminate, loop)
        loop.run()
Ejemplo n.º 5
0
    def initialize_bus(self, bus=None, loop=None):
        if bus is None:
            self.bus = SessionBus()
        else:
            self.bus = bus
        if loop is None:
            self.loop = MainLoop()
        else:
            self.loop = loop

        self.bus.publish(self.INTERFACE_NAME, self)
Ejemplo n.º 6
0
def main():
    global log

    if os.geteuid() != 0:
        exit("Comitup requires root privileges")

    args = parse_args()

    (conf, data) = config.load_data()

    log = deflog(args.verbose or conf.getboolean("verbose"))
    log.info("Starting comitup")

    if args.info:
        for (key, val) in statemgr.get_info(conf, data).items():
            print("{}: {}".format(key, val))
        sys.exit(0)

    if args.check:
        if wificheck.run_checks():
            sys.exit(1)
        else:
            sys.exit(0)
    else:
        wificheck.run_checks(verbose=False)

    check_environment(log)

    webmgr.init_webmgr(conf.web_service)
    iptmgr.init_iptmgr()

    statemgr.init_state_mgr(
        conf,
        data,
        [
            webmgr.state_callback,
            iptmgr.state_callback,
            cdns.state_callback,
        ],
    )

    nuke.init_nuke()

    signal.signal(signal.SIGTERM, handle_term)

    loop = MainLoop()

    try:
        loop.run()
    except Exception:
        log.error("Terminal exception encountered")
        raise
    finally:
        cleanup()
Ejemplo n.º 7
0
def main():
    handler = logging.StreamHandler(stream=None)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)

    log.info('starting')

    init_state_mgr('comitup.local', 'comitup-1111.local')
    states.set_state('HOTSPOT', timeout=5)

    loop = MainLoop()
    loop.run()
Ejemplo n.º 8
0
def main():
    handler = logging.StreamHandler(stream=None)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)

    log.info("starting")

    init_state_mgr("comitup.local", "comitup-1111.local")
    states.set_state("HOTSPOT", timeout=5)

    loop = MainLoop()
    loop.run()
Ejemplo n.º 9
0
def on_message(bus: Gst.Bus, message:Gst.Message, loop: GLib.MainLoop):
    mtype = message.type
    if mtype == Gst.MessageType.EOS:
        print('End Of Stream')
        loop.quit()
    elif mtype == Gst.MessageType.ERROR:
        err, debug = message.parse_error()
        print(err, debug)
        loop.quit()
    elif mtype == Gst.MessageType.WARNING:
        err, debug = message.parse_warning()
        print(err, debug)
    
    return True
Ejemplo n.º 10
0
def bus_call(bus: Gst.Bus, message: Gst.Message, loop: GLib.MainLoop):
    t = message.type
    if t == Gst.MessageType.EOS:
        sys.stdout.write("End-of-stream\n")
        loop.quit()
    elif t == Gst.MessageType.ERROR:
        err, debug = message.parse_error()
        sys.stderr.write("Error: %s: %s\n" % (err, debug))
        loop.quit()
    elif t == Gst.MessageType.WARNING:
        # Handle warnings
        err, debug = message.parse_warning()
        sys.stderr.write("Warning: %s: %s\n" % (err, debug))
    return True
Ejemplo n.º 11
0
def main():

    args = cli_aruments()
    try:
        hci = Adapter(args.adapter)
    except BluezError as e:
        print(str(e), file=sys.stderr)
        sys.exit(1)

    loop = MainLoop.new(None, False)

    if args.scan_duration:
        timeout_add_seconds(args.scan_duration, scan_timeout, loop)

    hci.onPropertiesChanged(adapter_changed, loop)
    hci.onDeviceAdded(device_found, args.properties, init=True, some="Foo")
    # hci.onDeviceRemoved(device_removed, args.properties)
    # hci.scan()

    # for d in hci.devices():
    #     device_found(d, d.properties, args.properties)

    try:
        loop.run()
    except (KeyboardInterrupt, SystemExit):
        pass
    finally:
        try:
            hci.onDeviceAdded(None)
            hci.onPropertiesChanged(None)
            hci.scan(enable=False)
            hci.clear()
        except:
            pass
Ejemplo n.º 12
0
def run():
    loop = MainLoop()
    bus = SystemBus(mainloop=dglib.DBusGMainLoop())
    dglib.threads_init()

    bat_object = bus.get_object(
        'org.freedesktop.UPower',
        '/org/freedesktop/UPower/devices/battery_BAT1')
    bat = Interface(bat_object, 'org.freedesktop.DBus.Properties')

    lemonbar = Feeder(i3, bat, bus, bar, display_title)
    lemonbar.render_all()

    pulse = Pulse('event-printer')
    pulse.event_mask_set('sink', 'server')
    pulse.event_callback_set(lemonbar.on_volume_event)
    pulse_thread = Thread(target=pulse.event_listen, args=[0])
    pulse_thread.daemon = True
    pulse_thread.start()

    bat_object.connect_to_signal(
        "PropertiesChanged",
        lemonbar.on_battery_event,
        dbus_interface='org.freedesktop.DBus.Properties')
    bat_thread = Thread(target=loop.run)
    bat_thread.daemon = True
    bat_thread.start()

    sched = BackgroundScheduler(daemon=True)
    sched.add_job(lemonbar.on_timedate_event, 'cron', second=0)
    sched.start()

    def shutdown(caller, e):
        bar.stop_bar(wbak, bar_pid)
        print(e.change)
        exit(0)

    def reload_bar(caller, data):
        global bar_pid
        bar.stop_bar(wbak, bar_pid)
        #print("reloading...")
        bar_pid = bar.start_bar()
        lemonbar.set_outputs()
        lemonbar.render_all(caller=caller, e=data)

    i3.on('workspace::urgent', lemonbar.on_workspace_event)
    i3.on('workspace::empty', lemonbar.on_workspace_event)
    if display_title:
        i3.on('window::title', lemonbar.on_window_title_change)
        i3.on('window::close', lemonbar.on_window_close)
        i3.on('window::focus', lemonbar.on_window_title_change)
        i3.on('workspace::focus', lemonbar.on_workspace_focus)
    else:
        i3.on('workspace::focus', lemonbar.on_workspace_event)
    i3.on('mode', lemonbar.on_binding_mode_change)
    i3.on('output', reload_bar)
    i3.on('shutdown', shutdown)
    i3.main()
Ejemplo n.º 13
0
def main():
    handler = logging.StreamHandler(stream=None)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)

    log.info('starting')

    init_nmmon()

    def up():
        print("wifi up")

    def down():
        print("wifi down")

    enable(modemgr.get_ap_device(), up, down)

    loop = MainLoop()
    loop.run()
def on_message(bus: Gst.Bus, message: Gst.Message, loop: GLib.MainLoop):
    mtype = message.type
    """
        Gstreamer Message Types and how to parse
        https://lazka.github.io/pgi-docs/Gst-1.0/flags.html#Gst.MessageType
    """
    if mtype == Gst.MessageType.EOS:
        print("End of stream")
        loop.quit()

    elif mtype == Gst.MessageType.ERROR:
        err, debug = message.parse_error()
        print(err, debug)
        loop.quit()
    elif mtype == Gst.MessageType.WARNING:
        err, debug = message.parse_warning()
        print(err, debug)

    return True
Ejemplo n.º 15
0
def main():
    handler = logging.StreamHandler(stream=None)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)

    log.info('starting')

    init_nmmon()

    def up():
        print("wifi up")

    def down():
        print("wifi down")

    set_device_callbacks('HOTSPOT', up, down)

    loop = MainLoop()
    loop.run()
Ejemplo n.º 16
0
    def do_notify_single(self, arg):
        "enable notifications on char and print changed values"
        args = _parse_args_simple(arg)
        timeout_seconds = None
        if len(args) > 1:
            try:
                timeout_seconds = int(args[1])
            except Exception as e:
                print(str(e))
                return
        else:
            print("To few arguments (char, [timeout[)")
            return

        g_char = self.find_char_or_desc_obj(args[0])
        if not g_char:
            print(
                "get:",
                str(g_char),
                "Not valid in GATT database or not resolved",
                file=sys.stderr,
            )
            return

        c = g_char
        try:
            flags = c.flags
            if "notify" in flags or "indicate" in flags:
                c.onValueChanged(generic_notify)
                c.notifyOn()
            elif "read" in flags:
                c.onValueChanged(generic_notify)

        except bluez.BluezDoesNotExistError as e:
            print(c.name, str(e), file=sys.stderr)

        loop = MainLoop.new(None, False)

        self.gatt.dev.onPropertiesChanged(dev_connected_changed)
        timeout = None
        if timeout_seconds:
            timeout = CmdTimeout(timeout_seconds, loop)
        try:
            if timeout_seconds:
                print("Notifying for {} seconds".format(timeout_seconds),
                      file=sys.stderr)
            else:
                print("Notifiying, CTRL+C to end", file=sys.stderr)

            loop.run()
        except (KeyboardInterrupt, bluez.BluezError) as e:
            print("aborted:", self.gatt.dev.name, str(e), file=sys.stderr)
            loop.quit()
            if timeout:
                timeout.canceled = True
Ejemplo n.º 17
0
def main():
    if os.geteuid() != 0:
        exit("Comitup requires root privileges")

    args = parse_args()

    log = deflog()
    log.info("Starting comitup")

    (conf, data) = config.load_data()

    if args.info:
        for (key, val) in statemgr.get_info(conf, data).items():
            print("{}: {}".format(key, val))
        sys.exit(0)

    if args.check:
        if wificheck.run_checks():
            sys.exit(1)
        else:
            sys.exit(0)
    else:
        wificheck.run_checks(verbose=False)

    check_environment(log)

    webmgr.init_webmgr(conf.web_service)
    iptmgr.init_iptmgr()

    statemgr.init_state_mgr(
        conf,
        data,
        [
            webmgr.state_callback,
            iptmgr.state_callback,
            cdns.state_callback,
        ],
    )

    loop = MainLoop()
    loop.run()
Ejemplo n.º 18
0
    def do_notify(self, arg):
        "enable all notifications and print changed values"
        args = _parse_args_simple(arg)
        timeout_seconds = None
        if len(args) > 0:
            try:
                timeout_seconds = int(args[0])
            except Exception as e:
                print(str(e))
                return

        if not self.gatt:
            print("Disconnected", file=sys.stderr)
            return

        for s in self.gatt.services:
            for c in s.chars:
                try:
                    flags = c.flags
                    if "notify" in flags or "indicate" in flags:
                        c.onValueChanged(generic_notify)
                        c.notifyOn()
                    elif "read" in flags:
                        c.onValueChanged(generic_notify)

                except bluez.BluezDoesNotExistError as e:
                    print(c.name, str(e), file=sys.stderr)
                except bluez.BluezError as e:
                    print(str(e), file=sys.stderr)

        loop = MainLoop.new(None, False)

        self.gatt.dev.onPropertiesChanged(dev_connected_changed)
        timeout = None
        if timeout_seconds:
            timeout = CmdTimeout(timeout_seconds, loop)
        try:
            if timeout_seconds:
                print("Notifying for {} seconds".format(timeout_seconds),
                      file=sys.stderr)
            else:
                print("Notifiying, CTRL+C to end", file=sys.stderr)

            loop.run()
        except (KeyboardInterrupt, bluez.BluezError) as e:
            print("aborted:", self.gatt.dev.name, str(e), file=sys.stderr)
            loop.quit()
            if timeout:
                timeout.canceled = True
Ejemplo n.º 19
0
    def __init__(self, adapter_name, peripheral_addresses, logger,
                 gatt_description):
        self.adapter_name = adapter_name
        self.peripheral_addresses = peripheral_addresses
        self.logger = logger
        self.scan_filters = {'Transport': 'le'}

        self.mainloop = MainLoop.new(None, False)
        # Use same gatt description for all peripherals (matching uuids to names/formats)
        self.gatt_description = gatt_description

        # state information for all peripherals we want to interact with, dictionary with addr as key
        self.peripherals = {}
        for idx, p_addr in enumerate(self.peripheral_addresses):
            # use upper case addresses
            self.peripheral_addresses[idx] = p_addr.upper()
            self.peripherals[p_addr.upper()] = None

        try:
            self.init_adapter()
        except bluez.BluezError as e:
            logger.error(str(e))
            bluez.ObjectManager.get().onAdapterAdded(adapter_added,
                                                     self.adapter_name, self)
Ejemplo n.º 20
0
 def __init__(self, batn, design):
     self.bus = SystemBus()
     self.loop = MainLoop()
     self.bat = self.upower = None
     self.use_design_capacity = design
     self.bat_path = f'/org/freedesktop/UPower/devices/battery_BAT{batn}'
Ejemplo n.º 21
0
    set_hosts(*hosts)

    for callback in callbacks:
        add_state_callback(callback)

    hotspot_name = dns_to_conn(hosts[0])

    assure_hotspot(hotspot_name, modemgr.get_ap_device())


def add_state_callback(callback):
    global state_callbacks

    state_callbacks.append(callback)


if __name__ == '__main__':
    handler = logging.StreamHandler(stream=None)
    log.addHandler(handler)
    log.setLevel(logging.DEBUG)

    log.info("Starting")

    init_states('comitup.local', 'comitup-1111.local')

    set_state('HOTSPOT')
    # set_state('CONNECTING', candidate_connections())

    loop = MainLoop()
    loop.run()
Ejemplo n.º 22
0
 def main(self):
     main_loop = MainLoop()
     self.connect('ipc_shutdown', lambda self: main_loop.quit())
     main_loop.run()
Ejemplo n.º 23
0
def create_main_loop():
    """Create GLib main loop.

    :returns: GLib.MainLoop instance.
    """
    return MainLoop()
Ejemplo n.º 24
0
class Daemon(ManagesProcesses):
    INTERFACE_NAME = "pro.wizardsoftheweb.pyrofibus.daemon"
    dbus = """
    <node>
        <interface name='{}'>
            <method name='is_running'>
                <arg type='b' name='response' direction='out'/>
            </method>
            <method name='start'>
            </method>
            <method name='stop'>
            </method>
            <method name='load_apps'>
                <arg type='i' name='response' direction='out'/>
            </method>
        </interface>
    </node>
    """.format(INTERFACE_NAME)

    _is_running = False

    def __init__(self, bus=None, loop=None, *args, **kwargs):
        super(Daemon, self).__init__(*args, **kwargs)
        self.initialize_bus(bus, loop)

    def initialize_bus(self, bus=None, loop=None):
        if bus is None:
            self.bus = SessionBus()
        else:
            self.bus = bus
        if loop is None:
            self.loop = MainLoop()
        else:
            self.loop = loop

        self.bus.publish(self.INTERFACE_NAME, self)

    def start(self):
        if not self._is_running:
            try:
                self._is_running = True
                self.loop.run()
            except KeyboardInterrupt:
                self.loop.quit()
                self._is_running = False

    def is_running(self):
        return self._is_running

    def stop(self):
        self.loop.quit()
        self._is_running = False

    def load_apps(self):
        old_length = len(self.managed_processes)
        new_scripts = self.check_for_new_scripts()
        self.load_new_scripts(new_scripts)
        new_length = len(self.managed_processes)
        return new_length - old_length

    @classmethod
    def bootstrap(cls):
        daemon = cls()
        daemon.start()
Ejemplo n.º 25
0
class BatteryMonitor:
    ''' Class for Battery Monitoring '''
    def __init__(self, batn, design):
        self.bus = SystemBus()
        self.loop = MainLoop()
        self.bat = self.upower = None
        self.use_design_capacity = design
        self.bat_path = f'/org/freedesktop/UPower/devices/battery_BAT{batn}'

    def run(self):
        ''' Run the event loop '''
        self.upower = self.bus.get('org.freedesktop.UPower',
                                   '/org/freedesktop/UPower')

        if self.bat_path in self.upower.EnumerateDevices():
            self.add_battery(self.bat_path)
        else:
            self.upower.onDeviceAdded = self.add_battery

        # Handle SIGTERM and SIGINT signal
        endloop = lambda signum, fname: self.loop.quit()
        signal.signal(signal.SIGINT, endloop)
        signal.signal(signal.SIGTERM, endloop)

        self.loop.run()
        return 0

    def add_battery(self, dev_path):
        ''' Add the battery when the battery exists '''
        if dev_path == self.bat_path:
            self.upower.onDeviceRemoved = self.remove_battery
            if self.upower.onDeviceAdded is not None:
                self.upower.onDeviceAdded = None

            self.bat = self.bus.get('org.freedesktop.UPower', self.bat_path)
            self.bat.onPropertiesChanged = self.update_battery
            self.update_battery()

    def remove_battery(self, dev_path):
        ''' Remove the battery when the battery not exists '''
        if dev_path == self.bat_path:
            self.upower.onDeviceAdded = self.add_battery
            self.upower.onDeviceRemoved = None

            self.bat.onPropertiesChanged = None
            self.bat = None
            self.update_battery()

    def update_battery(self,
                       ifname=None,
                       changed_props=None,
                       invalid_props=None):
        ''' Print the updated battery info '''
        del ifname, invalid_props
        if (changed_props is None) or (('Energy' in changed_props) or
                                       ('State' in changed_props)):
            text = ''
            css_class = ''

            if self.bat is not None:
                bat_state = BAT_STATE[self.bat.State]
                bat_energy_empty = self.bat.EnergyEmpty
                bat_energy_full = self.bat.EnergyFullDesign if \
                    self.use_design_capacity else self.bat.EnergyFull

                # Calculate the battery capacity percentage
                bat_capacity = 100 * (self.bat.Energy - bat_energy_empty) \
                    / (bat_energy_full - bat_energy_empty)

                # Find the battery capacity label
                for key, value in BAT_LEVEL.items():
                    if bat_capacity <= key:
                        bat_level = value
                        break

                if bat_state['class'] == BAT_STATE[2]['class']:
                    if bat_capacity <= BAT_STATE[2]['crit']['level']:
                        css_class = BAT_STATE[2]['crit']['class']
                    elif bat_capacity <= BAT_STATE[2]['warn']['level']:
                        css_class = BAT_STATE[2]['warn']['class']

                if css_class == '':
                    css_class = bat_state['class']

                text = f"{bat_state['label']}{bat_level}{bat_capacity:.2f}%"

            print(f'{{"text": "{text}", "class": "{css_class}"}}', flush=True)
Ejemplo n.º 26
0
def main():
    parser = ArgumentParser(description="bluetooth tester")
    parser.add_argument(
        "-i",
        "--adapter",
        metavar="hciX",
        default=def_adapter,
        help="bluetooh adapter to use (default={})".format(def_adapter),
    )

    parser.add_argument(
        "-a",
        "--device",
        metavar="addr",
        default=None,
        help="device address to connect to",
    )

    parser.add_argument(
        "-p",
        "--pair",
        default=False,
        action="store_true",
        help="Send pairing request to device, if not paired (Needs an agent)",
    )

    parser.add_argument("-k",
                        "--keep",
                        default=False,
                        action="store_true",
                        help="keep connection alive")

    parser.add_argument(
        "-l",
        "--loop",
        default=False,
        action="store_true",
        help="loop requesting info (sleeps 1s)",
    )

    parser.add_argument(
        "-w",
        "--wait",
        metavar="sec",
        default=1,
        type=int,
        help="time to wait before starting to read",
    )

    args = parser.parse_args()

    print("Scanning on: {}".format(args.adapter))

    try:
        adapter = Adapter(args.adapter)
    except BluezDoesNotExistError as e:
        print(str(e))
        sys.exit(2)

    devs = adapter.devices()
    dev = None

    for d in devs:
        da = d.address()
        if da and da.upper() == args.device.upper():
            print("Found {}: {}".format(args.device, d))
            dev = d

    if not dev:
        adapter.scan()

        sleep(3)
        sr = adapter.devices()

        for d in sr:
            da = d.address()
            if da and da.upper() == args.device.upper():
                print("Found {}: {}".format(args.device, d))
                dev = d

        if not dev:
            print("Could not find device nearby: {}".format(args.device))
            adapter.scan(enable=False)
            sys.exit(1)

        adapter.scan(enable=False)

    if dev.connected():
        print("Already connected: {}".format(dev))
    else:
        if args.pair:
            if not dev.paired():
                print("Device is not paired")
                print("Connecting/pairing to: {}".format(str(dev)))
                dev.pair()
                # waait for paring-agent
                wait_secs = 60
                while wait_secs > 0 and not dev.paired():
                    wait_secs -= 1
                    sleep(1)
                if not dev.paired():
                    print("Pairing failed")
                    sys.exit(1)

                if not dev.trusted():
                    dev.trust(True)
                    print("Device is now trusted")

        if not dev.connect():
            print("Connecting failed")
            sys.exit(1)

    gatt = Gatt(dev, [device_information])

    gatt.resolve()
    if not dev.services_resolved:
        print(
            "Waited not long enough for service resolving, did not find uuids")
        sys.exit(1)

    print("Service UUIDs resolved")

    dev_info = gatt.device_information  # pylint: disable=no-member

    for dinfo in dev_info.chars:
        if dinfo.obj:
            print(dinfo.name, ":", dinfo.read(options={"timeout": 4}))

    if args.wait > 0:
        sleep(args.wait)

    if args.loop:
        loop = MainLoop.new(None, False)

        for dinfo_char in dev_info.chars:
            if dinfo_char.obj:
                # add callback for printing if new value is avalable
                dinfo_char.onPropertiesChanged(print_char)

                # add cyclic read every 1 sec
                timeout_add_seconds(1, read_char, dinfo_char)

        try:
            loop.run()
        except (KeyboardInterrupt, SystemExit) as e:
            print("Interupted:", str(e))

    if not args.keep:
        dev.disconnect()
Ejemplo n.º 27
0
        if signal != 'ActiveChanged':
            logging.debug("Not what we are looking for, ignored")
            return

        logging.debug("START OF SIGNAL PROCESSING")

        if signal_msg is True:
            logging.debug("Screensaver now active")
        else:
            logging.info("Running 'on 0\\nas\\nquit' to turn on TV")
            proc = subprocess.Popen(['/usr/bin/cec-client'], stdin=subprocess.PIPE)
            results = proc.communicate(input='on 0\nas\nquit\n'.encode())
            time.sleep(3)
            logging.debug(results[0])
            logging.debug(results[1])
            proc.terminate()
            proc.kill()

        logging.debug("END OF SIGNAL PROCESSING")


    BUS.subscribe(iface=DBUS_INTERFACE, signal_fired=signal_recieved)

    # loop forever, until CTRL+C, or something goes wrong
    try:
        MainLoop().run()
    except KeyboardInterrupt:
        logging.debug('Got CTRL+C, exiting cleanly')
        raise SystemExit