Beispiel #1
0
 def test_idle_method_callback_no_data(self):
     self.loop = GLib.MainLoop()
     GLib.idle_add(self.cb_no_data)
     self.loop.run()
Beispiel #2
0
def main():
    SearchPassService()
    GLib.MainLoop().run()
Beispiel #3
0
import gi
gi.require_version('NM', '1.0')
from gi.repository import GLib, NM  # pylint: disable=wrong-import-position

try:
    import configparser as configparser
except ImportError:
    import ConfigParser as configparser

ENV = os.environ.copy()
ENV['LC_ALL'] = 'C'
ENC = locale.getpreferredencoding()

CLIENT = NM.Client.new(None)
LOOP = GLib.MainLoop()
CONNS = CLIENT.get_connections()

if sys.version_info.major < 3:
    str = unicode

def dmenu_cmd(num_lines, prompt="Networks", active_lines=None):  # pylint: disable=too-many-branches
    """Parse config.ini if it exists and add options to the dmenu command

    Args: args - num_lines: number of lines to display
                 prompt: prompt to show
    Returns: command invocation (as a list of strings) for
                dmenu -l <num_lines> -p <prompt> -i ...

    """
    dmenu_command = "dmenu"
Beispiel #4
0
 def __init__(self, timeout):
     self._mainloop = GLib.MainLoop()
     self._cancellable = Gio.Cancellable.new()
     self._timeout = timeout
     self._timeout_id = None
Beispiel #5
0
    @dbus.service.method("com.example.SampleInterface",
                         in_signature='',
                         out_signature='(ss)')
    def GetTuple(self):
        return ("Hello Tuple", " from example-service.py")

    @dbus.service.method("com.example.SampleInterface",
                         in_signature='',
                         out_signature='a{ss}')
    def GetDict(self):
        return {"first": "Hello Dict", "second": " from example-service.py"}

    @dbus.service.method("com.example.SampleInterface",
                         in_signature='',
                         out_signature='')
    def Exit(self):
        mainloop.quit()


if __name__ == '__main__':
    dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

    session_bus = dbus.SessionBus()
    name = dbus.service.BusName("com.example.SampleService", session_bus)
    object = SomeObject(session_bus, '/SomeObject')

    mainloop = GLib.MainLoop()
    print "Running example service."
    print usage
    mainloop.run()
Beispiel #6
0
        )
    except Exception as e:
        sys.stderr.write("Error: %s\n" % e)
    main_loop.quit()


if __name__ == "__main__":
    # parse arguments
    persistent = False
    if len(sys.argv) != 2 and len(sys.argv) != 3:
        sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0])
    if len(sys.argv) == 3:
        if sys.argv[2] in "persistent" and sys.argv[2][:1] == "p":
            persistent = True
        else:
            sys.exit('Usage: %s <connection name> [persistent]' % sys.argv[0])
    profile_name = sys.argv[1]

    main_loop = GLib.MainLoop()

    # create Client object
    client = NM.Client.new(None)

    # create a connection profile for NM
    con = create_profile(profile_name)

    # send the connection to NM
    client.add_connection_async(con, persistent, None, added_cb, None)

    main_loop.run()
Beispiel #7
0
def main():
    from gi.repository import GLib
    from xpra.platform import program_context
    with program_context("Sound-Record"):
        args = sys.argv
        log.enable_debug()
        import os.path
        if len(args) not in (2, 3):
            print("usage: %s [-v|--verbose] filename [codec]" % sys.argv[0])
            return 1
        filename = args[1]
        if not os.path.exists(filename):
            print("file %s does not exist" % filename)
            return 2
        decoders = get_decoders()
        if len(args) == 3:
            codec = args[2]
            if codec not in decoders:
                print("invalid codec: %s" % codec)
                print("only supported: %s" % str(decoders.keys()))
                return 2
            codecs = [codec]
        else:
            codec = None
            parts = filename.split(".")
            if len(parts) > 1:
                extension = parts[-1]
                if extension.lower() in codecs:
                    codec = extension.lower()
                    print("guessed codec %s from file extension %s" %
                          (codec, extension))
            if codec is None:
                print("assuming this is an mp3 file...")
                codec = MP3
            codecs = [codec]

        log.enable_debug()
        with open(filename, "rb") as f:
            data = f.read()
        print("loaded %s bytes from %s" % (len(data), filename))
        #force no leak since we push all the data at once
        global QUEUE_LEAK, QUEUE_SILENT
        QUEUE_LEAK = GST_QUEUE_NO_LEAK
        QUEUE_SILENT = True
        ss = SoundSink(codecs=codecs)

        def eos(*args):
            print("eos%s" % (args, ))
            GLib.idle_add(glib_mainloop.quit)

        ss.connect("eos", eos)
        ss.start()

        glib_mainloop = GLib.MainLoop()

        import signal

        def deadly_signal(*_args):
            GLib.idle_add(ss.stop)
            GLib.idle_add(glib_mainloop.quit)

            def force_quit(_sig, _frame):
                sys.exit()

            signal.signal(signal.SIGINT, force_quit)
            signal.signal(signal.SIGTERM, force_quit)

        signal.signal(signal.SIGINT, deadly_signal)
        signal.signal(signal.SIGTERM, deadly_signal)

        def check_for_end(*_args):
            qtime = ss.queue.get_property("current-level-time") // MS_TO_NS
            if qtime <= 0:
                log.info("underrun (end of stream)")
                start_thread(ss.stop, "stop", daemon=True)
                GLib.timeout_add(500, glib_mainloop.quit)
                return False
            return True

        GLib.timeout_add(1000, check_for_end)
        GLib.idle_add(ss.add_data, data)

        glib_mainloop.run()
        return 0
Beispiel #8
0
 def setUp(self):
     self.loop = GLib.MainLoop()
     self._error = []
     self._success = []
Beispiel #9
0
import gi
from gi.repository import GLib
from gi.repository import Gio

PYTHONPATH = os.path.join(os.environ["TOPSRCDIR"], "logger")
sys.path.append(PYTHONPATH)

import fleet_commander_logger as FleetCommander

# Set logging level to debug
log = logging.getLogger()
level = logging.getLevelName("DEBUG")
log.setLevel(level)

# Get mainloop
ml = GLib.MainLoop()

# Test helpers


def mainloop_quit_callback(*args, **kwargs):
    logging.error(
        "Timed out waiting for file update notification. Test probably failed")
    ml.quit()


class MockConnectionManager(object):
    """
    Connection Manager mock class
    """
    def __init__(self):
    # start logging
    logger = logging.getLogger("bt_auto_loader")
    logger.setLevel(LOG_LEVEL)
    logger.addHandler(logging.handlers.SysLogHandler(address = LOG_FILE))
    logger.info("Starting to monitor Bluetooth/A2DP connections")

    # Get the system bus
    try:
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SystemBus()
    except Exception as ex:
        logger.error("Unable to get the system dbus: '{0}'. Exiting. Is dbus running?".format(ex.message))
        sys.exit(1)

    # listen for signals on the Bluez bus
    bus.add_signal_receiver(interface_change, bus_name="org.bluez", signal_name="InterfacesAdded", member_keyword="member")
    bus.add_signal_receiver(interface_change, bus_name="org.bluez", signal_name="InterfacesRemoved", member_keyword="member")

    try:
        mainloop = gobject.MainLoop()
        mainloop.run()
    except KeyboardInterrupt:
        pass
    except:
        logger.error("Unable to run the gobject main loop")
        sys.exit(1)

    logger.info("Shutting down")
    sys.exit(0)
Beispiel #11
0
    if 'xesam:artist' in keys and 'xesam:title' in keys:
        print('{} - {}'.format(metadata['xesam:artist'][0],
                               metadata['xesam:title']))


def init_player(name):
    # choose if you want to manage the player based on the name
    if name.name in ['vlc', 'cmus']:
        player = Playerctl.Player.new_from_name(name)
        player.connect('playback-status::playing', on_play, manager)
        player.connect('metadata', on_metadata, manager)
        manager.manage_player(player)


def on_name_appeared(manager, name):
    init_player(name)


def on_player_vanished(manager, player):
    print('player has exited: {}'.format(player.props.player_name))


manager.connect('name-appeared', on_name_appeared)
manager.connect('player-vanished', on_player_vanished)

for name in manager.props.player_names:
    init_player(name)

main = GLib.MainLoop()
main.run()
Beispiel #12
0
    def show(self):
        self._init_player()

        # Wait for events
        main = GLib.MainLoop()
        main.run()
Beispiel #13
0
    def run(self):
        logger.info(f"Monitoring Services : {self.services_to_monitor}")
        try:
            # Register all the services to signal of 'PropertiesChanged' and
            # raise an alert if some service is not active on initially or if
            # Unit is not found for the service
            services_to_monitor_copy = copy.deepcopy(self.services_to_monitor)
            for service in services_to_monitor_copy:
                err = self.connect_to_prop_changed_signal(service)
                if err:
                    self.raise_alert(service, "N/A", "N/A", "N/A", "N/A",
                                     "N/A", "N/A", 0)
                    logger.error(
                        f"{service} is not active initially. \n Error {err}")
                else:
                    self.services_to_monitor.remove(service)

            logger.debug(f"failed_services : {self.failed_services}")
            logger.debug(f"services_to_monitor : {self.services_to_monitor}")

            # Retrieve the main loop which will be called in the run method
            self._loop = GLib.MainLoop()

            # Initialize the gobject threads and get its context
            GLib.threads_init()
            context = self._loop.get_context()

            time_to_check_lists = self.current_time() + self.polling_frequency

            # WHILE LOOP FUNCTION : every second we check for
            # properties change event if any generated (using context
            # iteration) and after a delay of polling frequency we
            # check for inactive processes.
            while self.is_running():
                # At interval of 'thread_sleep' check for events occured for
                # registered services and process them(call on_pro_changed())
                context.iteration(False)
                time.sleep(self.thread_sleep)

                # At interval of 'polling_freqency' process unregistered
                # services and services with not-active (intermidiate) state.
                if time_to_check_lists <= self.current_time():
                    time_to_check_lists = self.current_time() + \
                                            self.polling_frequency

                    # Try to bind the enabled services on the node to the
                    # signal whose Unit was earlier not found. On successfully
                    # registering for service state change signal, remove from
                    # local list as monitoring enabled through SystemD
                    # and to avoid re-registration.
                    services_to_monitor_copy = copy.deepcopy(
                        self.services_to_monitor)
                    for service in services_to_monitor_copy:
                        if not self.connect_to_prop_changed_signal(service):
                            self.services_to_monitor.remove(service)

                    # Check for services in intermidiate state(not active)
                    self.check_notactive_services()


            logger.info("ServiceMonitor gracefully breaking out " +\
                                "of dbus Loop, not restarting.")
        except GLib.Error as err:
            raise ThreadException(
                self.SENSOR_NAME,
                "Ungrecefully breaking out of GLib.MainLoop() with error: %s" %
                err)
        except DBusException as err:
            raise ThreadException(
                self.SENSOR_NAME,
                "Ungracefully breaking out of dbus loop with error: %s" % err)
        except Exception as err:
            raise ThreadException(self.SENSOR_NAME,
                "Ungracefully breaking out of ServiceMonitor:run() "\
                "with error: %s" % err)
Beispiel #14
0
 def _create_mainloop(self):
     '''
         Create GLibMainLoop
     '''
     if not self.mainloop:
         self.mainloop = GLib.MainLoop()
Beispiel #15
0
 def test_idle_method_callback_with_data(self):
     self.loop = GLib.MainLoop()
     data = {}
     GLib.idle_add(self.cb_with_data, data)
     self.loop.run()
     self.assertTrue(data['called'])
Beispiel #16
0
 def __init__(self, port=8309):
     Gst.init(None)
     self.loop = GLib.MainLoop()
     self.pipe = Gst.Pipeline()
     self.port = port
def main():
    parser = argparse.ArgumentParser(description='Pravega to screen')
    parser.add_argument('--controller', default='127.0.0.1:9090')
    parser.add_argument('--log_level', type=int, default=logging.INFO, help='10=DEBUG,20=INFO')
    parser.add_argument('--scope', default='examples')
    parser.add_argument('--stream', default='hls3')
    args = parser.parse_args()

    logging.basicConfig(level=args.log_level)
    logging.info('args=%s' % str(args))

    # Set GStreamer plugin path.
    script_dir = os.path.dirname(os.path.abspath(__file__))
    pravega_plugin_dir = os.path.join(script_dir, '..', 'gst-plugin-pravega', 'target', 'debug')
    logging.info('pravega_plugin_dir=%s' % pravega_plugin_dir)
    python_plugin_dir = os.path.join(script_dir, 'plugins')
    logging.info('python_plugin_dir=%s' % python_plugin_dir)
    plugin_path = ':'.join([python_plugin_dir, pravega_plugin_dir, os.environ['GST_PLUGIN_PATH']])
    logging.debug('plugin_path=%s' % plugin_path)
    os.environ['GST_PLUGIN_PATH'] = plugin_path

    # Set GStreamer log level.
    if not 'GST_DEBUG' in os.environ:
        os.environ['GST_DEBUG'] = 'pravegasrc:DEBUG,python:LOG,identity:TRACE'
        logging.info('GST_DEBUG=%s' % os.environ['GST_DEBUG'])

    # Standard GStreamer initialization.
    Gst.init(None)
    logging.info(Gst.version_string())

    # Create Pipeline element that will form a connection of other elements.
    # pipeline_description = 'videotestsrc name=src ! videoconvert ! autovideosink name=sink'
    # pipeline_description = 'videotestsrc name=src ! identity_py ! fakesink'
    # pipeline_description = 'videotestsrc name=src num-buffers=2000 ! example_python_transform_tensorflow ! identity silent=false dump=true ! autovideosink'
    pipeline_description = ('pravegasrc name=src ! tsdemux ! h264parse ! avdec_h264 ! videoconvert ! ' +
                            'example_python_transform_tensorflow ! autovideosink')
    logging.info('Creating pipeline: ' +  pipeline_description)
    pipeline = Gst.parse_launch(pipeline_description)

    pravegasrc = pipeline.get_by_name('src')
    pravegasrc.set_property('controller', args.controller)
    pravegasrc.set_property('stream', '%s/%s' % (args.scope, args.stream))

    # Create an event loop and feed GStreamer bus messages to it.
    loop = GLib.MainLoop()
    bus = pipeline.get_bus()
    bus.add_signal_watch()
    bus.connect('message', bus_call, loop)

    # Start play back and listen to events.
    logging.info('Starting pipeline')
    pipeline.set_state(Gst.State.PLAYING)
    try:
        loop.run()
    except:
        logging.error(traceback.format_exc())
        # Cleanup GStreamer elements.
        pipeline.set_state(Gst.State.NULL)
        raise

    pipeline.set_state(Gst.State.NULL)
    logging.info('END')
Beispiel #18
0
    def __init__(self):
        window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
        window.set_title("Short-cutting the pipeline")
        window.set_default_size(300, -1)
        window.connect("destroy", Gtk.main_quit, "WM destroy")
        vbox = Gtk.VBox()
        window.add(vbox)
        self.button = Gtk.Button("Start")
        self.button.connect("clicked", self.start_stop)
        vbox.add(self.button)
        window.show_all()

        self.data = CustomData()
        # Initialize custom data structure
        self.data.a = 0.0
        self.data.b = 1.0
        self.data.c = 0.0
        self.data.d = 1.0

        # Create the elements
        self.data.app_source = Gst.ElementFactory.make("appsrc", "app_source")
        self.data.tee = Gst.ElementFactory.make("tee", "tee")
        self.data.audio_queue = Gst.ElementFactory.make("queue", "audio_queue")
        self.data.audio_convert1 = Gst.ElementFactory.make(
            "audioconvert", "audio_convert1")
        self.data.audio_resample = Gst.ElementFactory.make(
            "audioresample", "audio_resample")
        self.data.audio_sink = Gst.ElementFactory.make("autoaudiosink",
                                                       "audio_sink")

        self.data.video_queue = Gst.ElementFactory.make("queue", "video_queue")
        self.data.audio_convert2 = Gst.ElementFactory.make(
            "audioconvert", "audio_convert2")
        self.data.visual = Gst.ElementFactory.make("wavescope", "visual")
        self.data.video_convert = Gst.ElementFactory.make(
            "videoconvert", "csp")
        self.data.video_sink = Gst.ElementFactory.make("glimagesink",
                                                       "video_sink")

        self.data.app_queue = Gst.ElementFactory.make("queue", "app_queue")
        self.data.app_sink = Gst.ElementFactory.make("appsink", "app_sink")

        self.data.pipeline = Gst.Pipeline.new("test-pipeline")

        if not (self.data.app_source and self.data.tee
                and self.data.audio_queue and self.data.audio_convert1
                and self.data.audio_resample and self.data.audio_sink
                and self.data.video_queue and self.data.audio_convert2
                and self.data.visual and self.data.video_convert
                and self.data.video_sink and self.data.app_queue
                and self.data.app_sink and self.data.pipeline):
            print("Not all elements could be created.", file=sys.stderr)
            sys.exit(-1)

        # Configure wavescope
        self.data.visual.set_properties({"shader": 0, "style": 0})

        # Configure appsrc
        audio_caps = Gst.caps_from_string(AUDIO_CAPS)
        self.data.app_source.set_property("caps", audio_caps)
        self.data.app_source.connect("need-data", self.start_feed, self.data)
        self.data.app_source.connect("enough-data", self.stop_feed, self.data)

        # Configure appsink
        self.data.app_sink.set_properties({
            "emit-signals": True,
            "caps": audio_caps
        })
        self.data.app_sink.connect("new-sample", self.new_sample, self.data)

        # Link all elements that can be automatically linked because they have "Always" pads
        [
            self.data.pipeline.add(k) for k in [
                self.data.app_source, self.data.tee, self.data.audio_queue,
                self.data.audio_convert1, self.data.audio_resample, self.data.
                audio_sink, self.data.video_queue, self.data.audio_convert2,
                self.data.visual, self.data.video_convert,
                self.data.video_sink, self.data.app_queue, self.data.app_sink
            ]
        ]

        if not (self.data.app_source.link(self.data.tee) and
                (self.data.audio_queue.link(self.data.audio_convert1)
                 and self.data.audio_convert1.link(self.data.audio_resample)
                 and self.data.audio_resample.link(self.data.audio_sink)) and
                (self.data.video_queue.link(self.data.audio_convert2)
                 and self.data.audio_convert2.link(self.data.visual)
                 and self.data.visual.link(self.data.video_convert)
                 and self.data.video_convert.link(self.data.video_sink))
                and self.data.app_queue.link(self.data.app_sink)):
            print("Elements could not be linked.", file=sys.stderr)
            sys.exit(-1)

        # print('data.audio_convert2.parse_context()', data.audio_convert2.parse_context())

        # Manually link the Tee, which has "Request" pads
        tee_audio_pad = self.data.tee.get_request_pad("src_%u")
        print("Obtained request pad {0} for audio branch".format(
            tee_audio_pad.get_name()))
        queue_audio_pad = self.data.audio_queue.get_static_pad("sink")

        tee_video_pad = self.data.tee.get_request_pad("src_%u")
        print("Obtained request pad {0} for video branch".format(
            tee_video_pad.get_name()))
        queue_video_pad = self.data.video_queue.get_static_pad("sink")

        tee_app_pad = self.data.tee.get_request_pad("src_%u")
        print("Obtained request pad {0} for app branch".format(
            tee_app_pad.get_name()))
        queue_app_pad = self.data.app_queue.get_static_pad("sink")

        if (tee_audio_pad.link(queue_audio_pad) != Gst.PadLinkReturn.OK
                or tee_video_pad.link(queue_video_pad) != Gst.PadLinkReturn.OK
                or tee_app_pad.link(queue_app_pad) != Gst.PadLinkReturn.OK):
            print("Tee could not be linked.", file=sys.stderr)
            sys.exit(-1)

        # Instruct the bus to emit signals for each received message, and connect to the interesting signals
        bus = self.data.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect("message", self.bus_message)
        # bus.connect("message::error", self.error_cb, self.data)
        # bus.connect("message::eos", self.eos_cb, self.data)

        # Start playing the pipeline
        # data.pipeline.set_state(Gst.State.PLAYING)

        # Create a GLib Mainloop and set it to run
        self.data.main_loop = GLib.MainLoop()
        self.data.main_loop.run()
Beispiel #19
0
 def run(self):
     self.mainloop = GLib.MainLoop()
     self.show()
     self.mainloop.run()
Beispiel #20
0
def main():
    global args

    if os.geteuid() != 0:
        print('[E] No root no party. Try again with sudo.')
        sys.exit(1)

    parser = argparse.ArgumentParser()
    parser.add_argument('--debug',
                        action='store_true',
                        help='add some debug info and additional checks')
    parser.add_argument('--config',
                        default='/etc/lenovo_fix.conf',
                        help='override default config file path')
    args = parser.parse_args()

    config = load_config()
    power['source'] = 'BATTERY' if is_on_battery(config) else 'AC'

    platform_info = get_cpu_platform_info()
    if args.debug:
        for key, value in platform_info.items():
            print('[D] cpu platform info: {} = {}'.format(
                key.replace("_", " "), value))
    regs = calc_reg_values(platform_info, config)

    if not config.getboolean('GENERAL', 'Enabled'):
        return

    exit_event = Event()
    thread = Thread(target=power_thread, args=(config, regs, exit_event))
    thread.daemon = True
    thread.start()

    undervolt(config)

    # handle dbus events for applying undervolt on resume from sleep/hybernate
    def handle_sleep_callback(sleeping):
        if not sleeping:
            undervolt(config)

    def handle_ac_callback(*args):
        try:
            power['source'] = 'BATTERY' if args[1]['Online'] == 0 else 'AC'
            power['method'] = 'dbus'
        except:
            power['method'] = 'polling'

    DBusGMainLoop(set_as_default=True)
    bus = dbus.SystemBus()

    # add dbus receiver only if undervolt is enabled in config
    if any(
            config.getfloat('UNDERVOLT', plane) != 0
            for plane in VOLTAGE_PLANES):
        bus.add_signal_receiver(handle_sleep_callback, 'PrepareForSleep',
                                'org.freedesktop.login1.Manager',
                                'org.freedesktop.login1')
    bus.add_signal_receiver(
        handle_ac_callback,
        signal_name="PropertiesChanged",
        dbus_interface="org.freedesktop.DBus.Properties",
        path="/org/freedesktop/UPower/devices/line_power_AC")

    try:
        loop = GLib.MainLoop()
        loop.run()
    except (KeyboardInterrupt, SystemExit):
        pass

    exit_event.set()
    loop.quit()
    thread.join(timeout=1)
    def test_add_update_settings(self):
        connection = {
            'connection': {
                'timestamp': 1441979296,
                'type': 'vpn',
                'id': 'a',
                'uuid': '11111111-1111-1111-1111-111111111111'
            },
            'vpn': {
                'service-type': 'org.freedesktop.NetworkManager.openvpn',
                'data': dbus.Dictionary({
                    'connection-type': 'tls'
                }, signature='ss')
            },
            'ipv4': {
                'routes': dbus.Array([], signature='o'),
                'never-default': True,
                'addresses': dbus.Array([], signature='o'),
                'dns': dbus.Array([], signature='o'),
                'method': 'auto'
            },
            'ipv6': {
                'addresses': dbus.Array([], signature='o'),
                'ip6-privacy': 0,
                'dns': dbus.Array([], signature='o'),
                'never-default': True,
                'routes': dbus.Array([], signature='o'),
                'method': 'auto'
            }
        }

        connectionA = self.settings.AddConnection(connection)
        self.assertEqual(self.settings.ListConnections(), [connectionA])

        connectionA_i = dbus.Interface(
            self.dbus_con.get_object(MANAGER_IFACE, connectionA), CSETTINGS_IFACE)
        connection['connection']['id'] = 'b'

        def do_update():
            connectionA_i.Update(connection)

        caught = []
        ml = GLib.MainLoop()

        def catch(*args, **kwargs):
            if (kwargs['interface'] == 'org.freedesktop.NetworkManager.Settings.Connection' and
                    kwargs['member'] == 'Updated'):
                caught.append(kwargs['path'])
                ml.quit()

        self.dbus_con.add_signal_receiver(catch,
                                          interface_keyword='interface',
                                          path_keyword='path',
                                          member_keyword='member')

        GLib.timeout_add(200, do_update)
        # ensure that the loop quits even when we don't catch anything
        GLib.timeout_add(3000, ml.quit)
        ml.run()

        self.assertEqual(connectionA_i.GetSettings(), connection)
        self.assertEqual(caught, [connectionA])
Beispiel #22
0
 def start():
     loop = GLib.MainLoop()
     loop.run()
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop
from gi.repository import GLib

import paths
from kano_peripherals.paths import CK2_PRO_HAT_OBJECT_PATH, SERVICE_API_IFACE, \
    BUS_NAME as CK2_PRO_HAT_BUS_NAME


def power_pressed_cb():
    print 'Power button pressed'


if __name__ == '__main__':
    DBusGMainLoop(set_as_default=True)
    '''
    Connect to DBus signal:
        Bus: System
        Bus Name: me.kano.boards
        Interface: me.kano.boards.PiHat
        Object Path: /me/kano/boards/PiHat
        Signal: power_button_pressed
    '''
    dbus.SystemBus().add_signal_receiver(power_pressed_cb,
                                         'power_button_pressed',
                                         SERVICE_API_IFACE,
                                         CK2_PRO_HAT_BUS_NAME,
                                         CK2_PRO_HAT_OBJECT_PATH)

    GLib.MainLoop().run()
Beispiel #24
0
    def __init__(self):
        ################ INSTANCES ################
        # self.buoydetector = BuoyDetector.BuoyDetector()
        self.gatedetector = GateDetector.GateDetector()
        self.pathdetector = PathDetector.PathDetector()
        self.pathfollowdetector = PathFollowDetector.PathFollowDetector()
        self.dicedetector = DiceDetector.DiceDetector()
        # self.chipdetector = ChipDetector.ChipDetector()
        self.roulettedetector = RouletteDetector.RouletteDetector()
        # self.slotsdetector = SlotsDetector.SlotsDetector()
        # self.pingerdetector = PingerDetector.PingerDetector()
        # self.cashindetector = CashInDetector.CashInDetector()

        ################ FPS COUNTER ################
        self.fps_output = 15

        ################ CAMERA FRAME ################
        self.current_raw_frame = None
        self.current_processed_frame = None

        ################ DICTIONARIES ################
        self.tasks = {
            'gate': self.gatedetector,
            'path': self.pathdetector,
            'path_follow': self.pathfollowdetector,
            'dice': self.dicedetector,
            'roulette': self.roulettedetector
        }
        # 'chip': self.chipdetector,
        # 'slots': self.slotsdetector,
        # 'pinger_b': self.pingerdetector,
        # 'pinger_a': self.pingerdetector,
        # 'cash_in': self.cashindetector

        # set.models = {

        # }

        self.camera_start_dictionary = {
            0: self.opencv_camera_start,
            1: self.sub_driver_camera_start
        }

        self.camera_detect = {
            0: self.opencv_camera_detect,
            1: self.sub_driver_camera_detect
        }

        ################ VIDEOCAMERA INSTANCES ################
        ################ SUB CAMERA DRIVER AND OPENCV ################
        ##### DO NOT CHANGE #########
        self.camera_serials = {'forward': '07714031', 'down': '35710219'}
        # self.camera_serials = {
        #     'down' : '07714031',
        #     'forward' : '35710219'
        # }
        #############################
        self.sample = {'forward': None, 'down': None}
        self.pipeline = {'forward': None, 'down': None}
        self.display_pipeline = {'forward': None, 'down': None}
        self.display_input = {'forward': None, 'down': None}
        self.display_buffers = {'forward': None, 'down': None}
        self.camera_callbacks = {
            'forward': self.camera_forward_callback,
            'down': self.camera_down_callback
        }

        self.time_delay = 1.0
        self.camera_direction = 'forward'
        self.cap = None

        try:
            self.loop = GLib.MainLoop()
            self.thread = None
            self.sub_camera_found = 1
            print '*******initialize Glib.MainLoop() successful*******'
        except:
            self.sub_camera_found = 0
            print '*******unable to initialize Glib.MainLoop()*******'
Beispiel #25
0
    def test_signals(self):
        '''emitting signals'''
        def do_emit():
            self.dbus_mock.EmitSignal('', 'SigNoArgs', '', [])
            self.dbus_mock.EmitSignal('org.freedesktop.Test.Sub', 'SigTwoArgs',
                                      'su', ['hello', 42])
            self.dbus_mock.EmitSignal(
                'org.freedesktop.Test.Sub', 'SigTypeTest', 'iuvao',
                [-42, 42,
                 dbus.String('hello', variant_level=1), ['/a', '/b']])

        caught = []
        ml = GLib.MainLoop()

        def catch(*args, **kwargs):
            if kwargs['interface'].startswith('org.freedesktop.Test'):
                caught.append((args, kwargs))
            if len(caught) == 3:
                # we caught everything there is to catch, don't wait for the
                # timeout
                ml.quit()

        self.dbus_con.add_signal_receiver(catch,
                                          interface_keyword='interface',
                                          path_keyword='path',
                                          member_keyword='member')

        GLib.timeout_add(200, do_emit)
        # ensure that the loop quits even when we catch fewer than 2 signals
        GLib.timeout_add(3000, ml.quit)
        ml.run()

        # check SigNoArgs
        self.assertEqual(caught[0][0], ())
        self.assertEqual(caught[0][1]['member'], 'SigNoArgs')
        self.assertEqual(caught[0][1]['path'], '/')
        self.assertEqual(caught[0][1]['interface'],
                         'org.freedesktop.Test.Main')

        # check SigTwoArgs
        self.assertEqual(caught[1][0], ('hello', 42))
        self.assertEqual(caught[1][1]['member'], 'SigTwoArgs')
        self.assertEqual(caught[1][1]['path'], '/')
        self.assertEqual(caught[1][1]['interface'], 'org.freedesktop.Test.Sub')

        # check data types in SigTypeTest
        self.assertEqual(caught[2][1]['member'], 'SigTypeTest')
        self.assertEqual(caught[2][1]['path'], '/')
        args = caught[2][0]
        self.assertEqual(args[0], -42)
        self.assertEqual(type(args[0]), dbus.Int32)
        self.assertEqual(args[0].variant_level, 0)

        self.assertEqual(args[1], 42)
        self.assertEqual(type(args[1]), dbus.UInt32)
        self.assertEqual(args[1].variant_level, 0)

        self.assertEqual(args[2], 'hello')
        self.assertEqual(type(args[2]), dbus.String)
        self.assertEqual(args[2].variant_level, 1)

        self.assertEqual(args[3], ['/a', '/b'])
        self.assertEqual(type(args[3]), dbus.Array)
        self.assertEqual(args[3].variant_level, 0)
        self.assertEqual(type(args[3][0]), dbus.ObjectPath)
        self.assertEqual(args[3][0].variant_level, 0)

        # check correct logging
        with open(self.mock_log.name) as f:
            log = f.read()
        self.assertRegex(log,
                         '[0-9.]+ emit org.freedesktop.Test.Main.SigNoArgs\n')
        self.assertRegex(
            log,
            '[0-9.]+ emit org.freedesktop.Test.Sub.SigTwoArgs "hello" 42\n')
        self.assertRegex(
            log, '[0-9.]+ emit org.freedesktop.Test.Sub.SigTypeTest -42 42')
        self.assertRegex(
            log,
            r'[0-9.]+ emit org.freedesktop.Test.Sub.SigTypeTest -42 42 "hello" \["/a", "/b"\]\n'
        )
Beispiel #26
0
 def __init__(self):
     self.main_loop = GLib.MainLoop()