def start_session(self, host, port, session, username, password, wait):
        """ Start a session using x2go """

        # Start in the background and attach a watch for when it exits
        cmd = [os.path.join(softwarecenter.paths.datadir,
            softwarecenter.paths.X2GO_HELPER)]
        (self.helper_pid, stdin, stdout, stderr) = GObject.spawn_async(
            cmd, standard_input=True, standard_output=True,
            standard_error=True, flags=GObject.SPAWN_DO_NOT_REAP_CHILD)
        self.helper_stdin = os.fdopen(stdin, "w")
        self.helper_stdout = os.fdopen(stdout)
        self.helper_stderr = os.fdopen(stderr)

        # Add a watch for when the process exits
        GObject.child_watch_add(self.helper_pid, self._on_x2go_exit)

        # Add a watch on stdout
        GObject.io_add_watch(self.helper_stdout, GObject.IO_IN,
            self._on_x2go_activity)

        # Start the connection
        self.state = "connecting"
        self.helper_stdin.write(
            "CONNECT: \"%s\" \"%s\" \"%s\" \"%s\" \"%s\"\n" %
            (host, port, username, password, session))
        self.helper_stdin.flush()
Ejemplo n.º 2
0
def run():
    """ Run the UI. """
    global loop
    loop = gobject.MainLoop()

    ui.set_mouse_tracking()
    app = appGUI()

    # Connect signals and whatnot to UI screen control functions
    bus.add_signal_receiver(app.dbus_scan_finished, 'SendEndScanSignal',
                            'org.wicd.daemon.wireless')
    bus.add_signal_receiver(app.dbus_scan_started, 'SendStartScanSignal',
                            'org.wicd.daemon.wireless')
    # I've left this commented out many times.
    bus.add_signal_receiver(app.update_netlist, 'StatusChanged',
                            'org.wicd.daemon')
    # Update the connection status on the bottom every 2 s.
    gobject.timeout_add(2000, app.update_status)

    # Get input file descriptors and add callbacks to the ui-updating function
    fds = ui.get_input_descriptors()
    for fd in fds:
        gobject.io_add_watch(fd, gobject.IO_IN, app.call_update_ui)
    app.update_ui()
    loop.run()
Ejemplo n.º 3
0
 def notify_read(self, func):
     """ This function can be called when the callsite must know when data
     is coming from the serial port.   It is necessary that a gobject main
     loop is already running before calling this method.
     """
     GObject.io_add_watch(self.get_port().fd, GObject.IO_IN,
                          lambda fd, cond: func(self, cond))
Ejemplo n.º 4
0
Archivo: pmpd.py Proyecto: an146/pmpd
 def listen_to_port(self):
     self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.socket.bind((config.host, config.port))
     self.socket.setblocking(0)
     self.socket.listen(5)
     conds = GObject.IO_IN | GObject.IO_ERR | GObject.IO_HUP
     GObject.io_add_watch(self.socket, conds, self.socket_callback)
Ejemplo n.º 5
0
def got_input(source, data, *port):
    '''Asynchronous connection listener. Starts a handler for each connection.'''
    conn, temp = source.accept()
    print( "mpdserver connected from " + str(conn.getsockname()))
    GObject.io_add_watch(conn, GObject.IO_IN, handle_input)
    conn.send('OK MPD 0.16.0\n')
    return True
Ejemplo n.º 6
0
    def __init__(self, cmd, resultHandler, prio=GObject.PRIORITY_LOW):
        self.lineSplitter = LineSplitter(resultHandler)

        #print("executing command: %s" % cmd)
        self.proc = subprocess.Popen(cmd,
                                     stdout=subprocess.PIPE,
                                     close_fds=True)
        self.pipe = self.proc.stdout

        # make pipe non-blocking:
        fl = fcntl.fcntl(self.pipe, fcntl.F_GETFL)
        fcntl.fcntl(self.pipe, fcntl.F_SETFL, fl | os.O_NONBLOCK)

        #print "(add watch)"
        if GObject.pygobject_version < (3, 7, 2):
            GObject.io_add_watch(self.pipe,
                                 GObject.IO_IN | GObject.IO_ERR
                                 | GObject.IO_HUP,
                                 self.onPipeReadable,
                                 priority=prio)
        else:
            # avoid deprecation warning in newer versions of PyGObject:
            GLib.io_add_watch(self.pipe, prio,
                              GLib.IO_IN | GLib.IO_ERR | GLib.IO_HUP,
                              self.onPipeReadable)
Ejemplo n.º 7
0
Archivo: ari.py Proyecto: sumchege/ari
 def serial_write(self, data):
     l = len(self.serial_write_pending_)
     self.serial_write_pending_ += data
     if l == 0 and len(self.serial_write_pending_) > 0:
         dev = self.serial_device_
         GObject.io_add_watch(dev.fileno(), GObject.IO_OUT,
                              self.on_serial_data_write, dev)
Ejemplo n.º 8
0
def start_listening(handler):
    '''Start listening to socket or named pipe for new commandline
	calls. Also sets current process to be the main process.
	@param handler: the method to call when new commands are recieveds
	'''
    set_in_main_process(True)

    logger.debug('Start listening on: %s', SERVER_ADDRESS)
    try:
        if SERVER_ADDRESS_FAMILY == 'AF_UNIX' \
        and os.path.exists(SERVER_ADDRESS):
            # Clean up old socket (someone should already have checked
            # before whether or not it is functional)
            os.unlink(SERVER_ADDRESS)
        listener = Listener(SERVER_ADDRESS, SERVER_ADDRESS_FAMILY)
    except:
        logger.exception('Error setting up Listener')
        return False
    else:
        socket = _get_socket_for_listener(listener)
        if socket is not None:
            # Unix file descriptor
            GObject.io_add_watch(socket.fileno(), GObject.IO_IN,
                                 partial(_do_accept, listener, handler))
        else:
            # Win32 pipe
            t = threading.Thread(target=_listener_thread_main,
                                 args=(listener, handler))
            t.daemon = True
            t.start()
        return True
Ejemplo n.º 9
0
 def __init__(self, bus, index, service, queue):
     Characteristic.__init__(self, bus, index, UART_TX_CHARACTERISTIC_UUID,
                             ['notify'], service)
     self.notifying = False
     self.queue = queue
     GObject.io_add_watch(self.queue._reader, GObject.IO_IN,
                          self.on_console_input)
Ejemplo n.º 10
0
def enterNonblockingMode():
    global conn, log

    log.debug('entering nonblocking-mode')
    conn.setblocking(False)
    GObject.io_add_watch(conn, GObject.IO_IN, on_data, [''])
    GObject.idle_add(on_loop)
Ejemplo n.º 11
0
    def run(self):
        """Launch the clipboard manager daemon.
        Listen for clipboard events & client socket connections."""

        # Set up socket, pid file etc
        self.prepare_files()
        # We need to get the display instance from the window
        # for use in obtaining mouse state.
        # POPUP windows can do this without having to first show the window
        self.window = Gtk.Window(type=Gtk.WindowType.POPUP)

        # Handle clipboard changes
        self.c_id = self.clipboard.connect('owner-change', self.owner_change)
        # Handle socket connections
        GObject.io_add_watch(self.sock, GObject.IO_IN, self.socket_accept)
        # Handle unix signals
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGINT, self.exit)
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGTERM, self.exit)
        GLib.unix_signal_add(GLib.PRIORITY_HIGH, signal.SIGHUP, self.exit)
        GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGUSR1,
                             self.fdbquery.signal_handler)

        # Timeout for flushing history to disk
        # Do nothing if timeout is 0, or write_on_change is set in config
        history_timeout = self.config.getint('clipster',
                                             'history_update_interval')
        if history_timeout and not self.config.getboolean(
                'clipster', 'write_on_change'):
            logging.debug("Writing history file every %s seconds",
                          history_timeout)
            GObject.timeout_add_seconds(history_timeout,
                                        self.write_history_file)

        Gtk.main()
Ejemplo n.º 12
0
  def __init__(self, maxConcurrentThreads=10):
    ThreadManager.__init__(self, maxConcurrentThreads)

    # watch the queue for updates
    _fd = self.queue_in._reader.fileno()

    GObject.io_add_watch(_fd, GObject.IO_IN, self._on_cb)
Ejemplo n.º 13
0
    def run(self):
        signal.signal(signal.SIGTERM, self.shutdown)
        if self.proc_title:
            setproctitle.setproctitle(self.proc_title)

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        signals = (
            ('NewPlaybackStream', 'org.PulseAudio.Core1.{}',
                self.on_new_playback_stream),
            ('PlaybackStreamRemoved', 'org.PulseAudio.Core1.{}',
                self.on_playback_stream_removed),
            ('FallbackSinkUpdated', 'org.PulseAudio.Core1.{}',
                self.on_fallback_sink_updated),
            ('DeviceUpdated', 'org.PulseAudio.Core1.Stream.{}',
                self.on_device_updated),
        )
        self._connect(signals)
        self.update()
        self.default_sink = self.fallback_sink

        self.thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)

        mainloop = GObject.MainLoop()
        GObject.io_add_watch(
            self.pulse_queue._reader, GObject.IO_IN | GObject.IO_PRI,
            self._on_new_message)
        try:
            mainloop.run()
        except KeyboardInterrupt:
            self.shutdown()
Ejemplo n.º 14
0
 def __init__(self, bus, index, service):
     Characteristic.__init__(self, bus, index, UART_TX_CHARACTERISTIC_UUID,
                             ['notify'], service)
     self.notifying = False
     # GObject.io_add_watch(sys.stdin, GObject.IO_IN, self.on_console_input)
     # Sposto il watcher sul Character Device Driver
     GObject.io_add_watch(dev_tx, GObject.IO_IN, self.on_cdev_input)
Ejemplo n.º 15
0
 def notify_read(self, func):
     """ This function can be called when the callsite must know when data
     is coming from the serial port.   It is necessary that a gobject main
     loop is already running before calling this method.
     """
     GObject.io_add_watch(self.get_port().fd, GObject.IO_IN,
                          lambda fd, cond: func(self, cond))
Ejemplo n.º 16
0
    def run(self):
        signal.signal(signal.SIGTERM, self.shutdown)
        if self.proc_title:
            setproctitle.setproctitle(self.proc_title)

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        signals = (
            ('NewPlaybackStream', 'org.PulseAudio.Core1.{}',
             self.on_new_playback_stream),
            ('PlaybackStreamRemoved', 'org.PulseAudio.Core1.{}',
             self.on_playback_stream_removed),
            ('FallbackSinkUpdated', 'org.PulseAudio.Core1.{}',
             self.on_fallback_sink_updated),
            ('DeviceUpdated', 'org.PulseAudio.Core1.Stream.{}',
             self.on_device_updated),
        )
        self._connect(signals)
        self.update()
        self.default_sink = self.fallback_sink

        self.thread_pool = concurrent.futures.ThreadPoolExecutor(max_workers=1)

        mainloop = GObject.MainLoop()
        GObject.io_add_watch(self.pulse_queue._reader,
                             GObject.IO_IN | GObject.IO_PRI,
                             self._on_new_message)
        try:
            mainloop.run()
        except KeyboardInterrupt:
            self.shutdown()
Ejemplo n.º 17
0
    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address,
                                        RequestHandlerClass)
        self.socket.setblocking(0)  # Set nonblocking

        # Watch the listener socket for data
        GObject.io_add_watch(self.socket, GObject.IO_IN, self._handle_accept)
Ejemplo n.º 18
0
    def run(self, line=1, column=1):
        dirname = os.path.dirname(self.filename)
        filename = os.path.basename(self.filename)

        self.ret = None

        try:
            self.pipe = subprocess.Popen(
                ['cdn-context', filename, '-l',
                 str(line), '-c',
                 str(column)],
                cwd=dirname,
                stdout=subprocess.PIPE)
        except Exception as (e):
            sys.stderr.write('Failed to execute cdn-context: %s\n' % (e, ))
            self.pipe = None
            return False

        self.read_buffer = ''

        flags = fcntl.fcntl(self.pipe.stdout.fileno(),
                            fcntl.F_GETFL) | os.O_NONBLOCK
        fcntl.fcntl(self.pipe.stdout.fileno(), fcntl.F_SETFL, flags)

        GObject.io_add_watch(self.pipe.stdout, GObject.IO_IN | GObject.IO_HUP,
                             self.on_output)
        GObject.child_watch_add(self.pipe.pid, self.on_parser_end)
Ejemplo n.º 19
0
	def listener(self, sock, *args):
		'''Asynchronous connection listener. Starts a handler for each connection.'''
		self.conn, temp = sock.accept()
		loggy.log( "mpdserver connected from " + str(self.conn.getsockname()))
		GObject.io_add_watch(self.conn, GObject.IO_IN, self.handler)
		self.conn.send('OK MPD 0.16.0\n')
		return True
Ejemplo n.º 20
0
def register(controller=None):
    # The BrailleInput event has a 'cursor' parameter, which is the
    # cursor position, available through the request/cursor TALES
    # expression
    controller.register_event('BrailleInput', _("Input from the braille table."))
    method=controller.message_log

    if brlapi is None:
        controller.log(_("BrlTTY not installed. There will be no braille support."))
    else:
        engine=BrlEngine(controller)
        try:
            engine.init_brlapi()
            if engine.brlconnection is not None:
                GObject.io_add_watch(engine.brlconnection.fileDescriptor,
                                     GObject.IO_IN,
                                     engine.input_handler)
                method=engine.action_brldisplay
                engine.brldisplay("Advene connected")
        except:
            controller.log(_("Could not initialize BrlTTY. No braille support."))

    # Register the Braille action even if the API is not available.
    controller.register_action(RegisteredAction(
            name="Braille",
            method=method,
            description=_("Display a message in Braille"),
            parameters={'message': _("Message to display.")},
            defaults={'message': 'annotation/content/data'},
            predefined={'message': (
                    ( 'annotation/content/data', _("The annotation content") ),
                    )},
            category='external',
            ))
Ejemplo n.º 21
0
    def __init__(self, server_address, RequestHandlerClass):
        SocketServer.TCPServer.__init__(self, server_address,
                                        RequestHandlerClass)
        self.socket.setblocking(0)  # Set nonblocking

        # Watch the listener socket for data
        GObject.io_add_watch(self.socket, GObject.IO_IN, self._handle_accept)
Ejemplo n.º 22
0
def run():
    mask = None

    opts, args = getopt.getopt(sys.argv[1:], "hdWk:")

    for opt in opts:
        if opt[0] == '-h':
            print('Snaptile.py')
            print('-W use Windows key')
            print('-h this help text')
            sys.exit()
        elif opt[0] == '-d':
            isDualMonitor = True
        elif opt[0] == '-W':
            mask = 'Windows'

    global disp, root, lastkey_state, posmap, posmapLeft
    disp, root, lastkey_state, posmap = global_inital_states()

    initkey0(disp, root)
    initkeys(keymap, disp, root)

    for _ in range(0, root.display.pending_events()):
        root.display.next_event()
    GObject.io_add_watch(root.display, GObject.IO_IN, checkevt)
    print('Snaptile running. Press CTRL+C to quit.')
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    Gtk.main()
Ejemplo n.º 23
0
    def _schedule_write(self, conn, message):
        queue = self.currentConnections[conn]

        self.log.debug('re-starting on_write[%u] scheduling', conn.fileno())
        GObject.io_add_watch(conn, GObject.IO_OUT, self.on_write)

        queue.put(message)
Ejemplo n.º 24
0
def run():
    mask = None

    opts, args = getopt.getopt(sys.argv, "hdW")
    
    for opt in args:
        if opt == '-h':
            print ('Snaptile.py')
            print ('-d expanded dual-monitor keybinds')
            print ('-W use Windows key')
            print ('-h this help text')
            sys.exit()
        elif opt == '-d':
            global keymap;
            keymap = [
                ['Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I'],
                ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K'],
                ['Z', 'X', 'C', 'V', 'B', 'N', 'M', 'comma']
            ]
        elif opt == '-W':
            mask = 'Windows'

    global disp, root, lastkey_state, posmap
    disp, root, lastkey_state, posmap = global_inital_states()

    initkeys(keymap, disp, root, mask)
    for _ in range(0, root.display.pending_events()):
        root.display.next_event()
    GObject.io_add_watch(root.display, GObject.IO_IN, checkevt)
    print('Snaptile running. Press CTRL+C to quit.')
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    Gtk.main()
Ejemplo n.º 25
0
Archivo: net.py Proyecto: gkfabs/remuco
 def __init__(self, sock, addr, clients, pinfo_msg, msg_handler_fn, c_type):
     
     self.__sock = sock
     self.__addr = addr
     self.__clients = clients
     self.__pinfo_msg = pinfo_msg
     self.__msg_handler_fn = msg_handler_fn
     self.__conn_type = c_type
     
     # client info
     self.info = ClientInfo()
     self.__psave = False
     
     # the following fields are used for iterative receiving on message data
     # see io_recv() and io_recv_buff()
     self.__rcv_buff_header = ReceiveBuffer()
     self.__rcv_buff_data = ReceiveBuffer()
     self.__rcv_msg_id = message.IGNORE
     self.__rcv_msg_size = 0
     
     self.__snd_buff = b'' # buffer for outgoing data
     
     # source IDs for various events
     self.__sids = [
         GObject.io_add_watch(self.__sock, GObject.IO_IN, self.__io_recv),
         GObject.io_add_watch(self.__sock, GObject.IO_ERR, self.__io_error),
         GObject.io_add_watch(self.__sock, GObject.IO_HUP, self.__io_hup)
         ]
     self.__sid_out = 0
     
     log.debug("send 'hello' to %s" % self)
     
     self.send(ClientConnection.IO_HELLO)
Ejemplo n.º 26
0
def enterNonblockingMode():
    global conn, log

    log.debug("entering nonblocking-mode")
    conn.setblocking(False)
    GObject.io_add_watch(conn, GObject.IO_IN, on_data, [""])
    GObject.idle_add(on_loop)
Ejemplo n.º 27
0
   def __init__(self,gyotoytop):
      GObject.set_application_name("Gyotoy")
      GObject.set_prgname("Gyotoy")

      self.gyotoytop = gyotoytop
      self._pyk_blocked=0
      self.length_unit="geometrical"

      # read GUI definition
      self.builder = Gtk.Builder()
      self.builder.add_from_file(os.path.join(self.gyotoytop,'gyotoy.xml'))
      
      # handle destroy event (so that we can kill the window through window bar)
      self.window = self.builder.get_object('window1')
      if (self.window):
         self.window.connect('destroy', self.destroy)

      # autoconnect to callback functions
      # this will automatically connect the event handler "on_something_event"
      # to the here-defined function of the same name. This avoid defining a
      # long dictionary that serves the same purpose
      self.builder.connect_signals(self)

      # set stdin non blocking, this will prevent readline to block
      # stdin is coming from yorick (yorick spawned this python process)
      fd = sys.stdin.fileno()
      flags = fcntl.fcntl(fd, fcntl.F_GETFL)
      fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
      
      # ... and add stdin to the event loop (yorick input pipe by spawn)
      GObject.io_add_watch(sys.stdin,GObject.IO_IN|GObject.IO_HUP,self.yo2py,None)

      # run: realize the interface, start event management
      Gtk.main()
Ejemplo n.º 28
0
    def _schedule_write(self, conn, message):
        queue = self.currentConnections[conn]

        self.log.debug('re-starting on_write[%u] scheduling', conn.fileno())
        GObject.io_add_watch(conn, GObject.IO_OUT, self.on_write)

        queue.put(message)
Ejemplo n.º 29
0
  def __init__(self, maxConcurrentThreads=10):
    ThreadManager.__init__(self, maxConcurrentThreads)

    # watch the queue for updates
    _fd = self.queue_in._reader.fileno()

    GObject.io_add_watch(_fd, GObject.IO_IN, self._on_cb)
Ejemplo n.º 30
0
 def listener(self, sock, *args):
     '''Asynchronous connection listener. Starts a handler for each connection.'''
     self.conn, self.addr = self.sock.accept()
     print _("Connected")
     GObject.io_add_watch(self.conn, GObject.IO_IN, self.handler)
     self.conn.send(self.msg_banner())
     return True
Ejemplo n.º 31
0
def run():
    """ Run the UI. """
    global loop
    loop = gobject.MainLoop()

    ui.set_mouse_tracking()
    app = appGUI()

    # Connect signals and whatnot to UI screen control functions
    bus.add_signal_receiver(app.dbus_scan_finished, 'SendEndScanSignal',
                            'org.wicd.daemon.wireless')
    bus.add_signal_receiver(app.dbus_scan_started, 'SendStartScanSignal',
                            'org.wicd.daemon.wireless')
    # I've left this commented out many times.
    bus.add_signal_receiver(app.update_netlist, 'StatusChanged',
                            'org.wicd.daemon')
    # Update the connection status on the bottom every 2 s.
    gobject.timeout_add(2000, app.update_status)

    # Get input file descriptors and add callbacks to the ui-updating function
    fds = ui.get_input_descriptors()
    for fd in fds:
        gobject.io_add_watch(fd, gobject.IO_IN, app.call_update_ui)
    app.update_ui()
    loop.run()
Ejemplo n.º 32
0
	def __init__(self):
		self.mainloop = GObject.MainLoop()
		self.source_pipeline = None

		self.sink_pipeline = Gst.parse_launch("""
			intervideosrc channel=video !
				queue !
				video/x-raw,width=800,height=450,format=I420,framerate=25/1 !
				textoverlay halignment=left valignment=top ypad=50 text=intervideosrc !
				timeoverlay halignment=left valignment=top ypad=50 xpad=400 !
				tee name=vtee

			interaudiosrc blocksize=4096 channel=audio !
				queue !
				audio/x-raw,format=S16LE,layout=interleaved,rate=48000,channels=2 !
				tee name=atee


			vtee. !
				queue !
				videoconvert !
				textoverlay halignment=left valignment=top ypad=75 text=avenc_mpeg2video !
				timeoverlay halignment=left valignment=top ypad=75 xpad=400 !
				avenc_mpeg2video bitrate=50000 max-key-interval=0 !
				queue !
				mux.

			atee. !
				queue !
				avenc_mp2 bitrate=192000 !
				queue !
				mux.

			mpegtsmux name=mux !
				filesink location=foo.ts


			vtee. !
				queue !
				textoverlay halignment=left valignment=top ypad=75 text=xvimagesink !
				timeoverlay halignment=left valignment=top ypad=75 xpad=400 !
				videoconvert !
				xvimagesink

			atee. !
				queue !
				audioconvert !
				alsasink
		""")

		# Create the server, binding to localhost on port 5000
		sock = socket.socket(socket.AF_INET6)
		sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False)
		sock.bind(('::', 10000))
		sock.listen(1)

		# register socket for callback inside the GTK-Mainloop
		GObject.io_add_watch(sock, GObject.IO_IN, self.on_connect)
Ejemplo n.º 33
0
 def input_add(self, source, condition, callback):
     if hasattr(source, 'fileno'):
         # handle python objects
         def wrapper(source, condition, real_s=source, real_cb=callback):
             return real_cb(real_s, condition)
         return gobject.io_add_watch(source.fileno(), condition, wrapper)
     else:
         return gobject.io_add_watch(source, condition, callback)
Ejemplo n.º 34
0
    def socket_accept(self, sock, _):
        """Accept a connection and 'select' it for readability."""

        conn, _ = sock.accept()
        self.client_msgs[conn.fileno()] = []
        GObject.io_add_watch(conn, GObject.IO_IN, self.socket_recv)
        logging.debug("Client connection received.")
        return True
Ejemplo n.º 35
0
def run():
    initkeys(keymap, disp, root)
    for _ in range(0, root.display.pending_events()):
        root.display.next_event()
    GObject.io_add_watch(root.display, GObject.IO_IN, checkevt)
    print('Snaptile running. Press CTRL+C to quit.')
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    Gtk.main()
Ejemplo n.º 36
0
 def server(self, host, port):
     '''Initialize server and start listening.'''
     self.sock = socket.socket()
     self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     self.sock.bind((host, port))
     self.sock.listen(1)
     print _("Listening on port %i...") % (port)
     GObject.io_add_watch(self.sock, GObject.IO_IN, self.listener)
Ejemplo n.º 37
0
 def __init__(self, bus, index, service):
     global pty
     Characteristic.__init__(self, bus, index, UART_TX_CHARACTERISTIC_UUID,
                             ['notify'], service)
     self.notifying = False
     #GObject.io_add_watch(sys.stdin, GObject.IO_IN, self.on_console_input)
     GObject.io_add_watch(pty.fileno(), GObject.IO_IN,
                          self.on_console_input)
Ejemplo n.º 38
0
def init_mqtt():
    global MQTT_CLIENT
    MQTT_CLIENT = mqtt.Client( client_id='d:quickstart:mosquitto:019283hb' )
    MQTT_CLIENT.connect( MQTT_SERVER )

    MQTT_CLIENT.on_connect = on_connect
    MQTT_CLIENT.on_message = on_message

    GObject.io_add_watch(MQTT_CLIENT.socket().makefile(), GObject.IO_IN | GObject.IO_OUT, on_message_received)
Ejemplo n.º 39
0
 def accept_interrupt(self, source, cond):
     self.interrupt_channel, cinfo = self.interrupt_socket.accept()
     gobject.io_add_watch(self.interrupt_channel.fileno(),
                          gobject.IO_ERR | gobject.IO_HUP,
                          self.close_interrupt)
     gobject.io_add_watch(self.interrupt_channel.fileno(),
                          gobject.IO_IN | gobject.IO_PRI, self.callback,
                          self.interrupt_channel)
     return False
Ejemplo n.º 40
0
 def accept_control(self, source, cond):
     self.control_channel, cinfo = self.control_socket.accept()
     gobject.io_add_watch(self.control_channel.fileno(),
                          gobject.IO_ERR | gobject.IO_HUP,
                          self.close_control)
     gobject.io_add_watch(self.control_channel.fileno(),
                          gobject.IO_IN | gobject.IO_PRI, self.callback,
                          self.control_channel)
     return False  # Stop watching, we only accept one connection
Ejemplo n.º 41
0
    def input_add(self, source, condition, callback):
        if hasattr(source, 'fileno'):
            # handle python objects
            def wrapper(source, condition, real_s=source, real_cb=callback):
                return real_cb(real_s, condition)

            return gobject.io_add_watch(source.fileno(), condition, wrapper)
        else:
            return gobject.io_add_watch(source, condition, callback)
Ejemplo n.º 42
0
 def start(self):
     """ Write config if not found and watch for keyboard events. """
     self._get_config()
     self.root.change_attributes(event_mask=X.KeyPressMask)
     self._bind_keys()
     for event in range(0, self.root.display.pending_events()):
         self.root.display.next_event()
     GObject.io_add_watch(self.root.display, GObject.IO_IN, self._check_event)
     print('PyGrid running. Press CTRL+C to cancel.')
     Gtk.main()
Ejemplo n.º 43
0
def add_input_port(server, port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        sock.bind((server, port)) #TODO: check port empty first
    except:
        print ('Server failed to start on host %s port %s' % (server, port))
        return False
    sock.listen(1)
    print('Server Interface Running on ' + server + ':' + str(port) )
    GObject.io_add_watch(sock, GObject.IO_IN, got_input, port)
Ejemplo n.º 44
0
def add_listen_port (hostname,port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(2)
    try:
        sock.connect((hostname,port))
    except:
        print ('Could not connect to '+str(hostname)+'@'+str(port))
    listen_ports[port] = sock
    recent_text[port] = []
    #sock.send('GET /index.html HTTP/1.1\nHost: pygtk.org\n\n')
    GObject.io_add_watch(sock, GObject.IO_IN, handle_data, port)
Ejemplo n.º 45
0
    def stegcrack(self, widget):
        outguess = ("OFF", "ON")[self.checkoutguess.get_active()]
        jphide = ("OFF", "ON")[self.checkjph.get_active()]
        jsteg = ("OFF", "ON")[self.checkjsteg.get_active()]
        dictionary = self.dict.get_filename()
        self.sfile = self.file.get_text()
        tests = " -t "
        if outguess == "ON":
            tests += "o"
        if jphide == "ON":
            tests += "p"
        if jsteg == "ON":
            tests += "j"

        if self.sfile != '' and dictionary != None:
            self.buffer3.set_text("Please Wait \n")
            cmd = re.escape(
                execdir
            ) + "/programs/" + self.arch + "/stegbreak " + tests + " -r " + re.escape(
                execdir) + "/programs/noarch/rules.ini -f " + re.escape(
                    dictionary) + " " + self.sfile
            self.showprogress()
            p = Popen("exec " + cmd, shell=True, stdout=PIPE, stderr=PIPE)
            self.pid = p.pid

            def test_io_watch(f, cond):
                out = f.readline()
                if out == '':
                    return False
                end_iter = self.buffer3.get_end_iter()
                self.buffer3.insert(end_iter, out)
                adj = self.sw.get_vadjustment()
                adj.set_value(adj.get_upper() - adj.get_page_size())
                return True

            def tester():
                if p.poll() is None:
                    time.sleep(5)
                    GObject.timeout_add(2000, update)
                    return True

            GObject.io_add_watch(p.stderr, GObject.IO_IN | GObject.IO_HUP,
                                 test_io_watch)
            GObject.io_add_watch(p.stdout, GObject.IO_IN | GObject.IO_HUP,
                                 test_io_watch)

            def update():
                os.system("kill -s 2 " + str(self.pid))

            GObject.idle_add(tester)
        else:
            self.buffer1.set_text(
                "You must select a stego file and a dictionary file.")
            self.showdiag()
Ejemplo n.º 46
0
 def start(self):
     """ Write config if not found and watch for keyboard events. """
     self._get_config()
     self.root.change_attributes(event_mask=X.KeyPressMask)
     self._bind_keys()
     for event in range(0, self.root.display.pending_events()):
         self.root.display.next_event()
     GObject.io_add_watch(self.root.display, GObject.IO_IN,
                          self._check_event)
     print('PyGrid running. Press CTRL+C to cancel.')
     Gtk.main()
Ejemplo n.º 47
0
 def sniffThread(self):
     logging.info("Launching sniff process")
     self.stracePid = subprocess.Popen([
         "/usr/bin/strace", "-xx", "-s", "65536", "-e", "read,write", "-p",
         str(self.pid)
     ],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
     GObject.io_add_watch(self.stracePid.stderr,
                          GObject.IO_IN | GObject.IO_HUP,
                          self.handle_new_pkt)
Ejemplo n.º 48
0
 def create_lircd_socket(self, socket_path):
     try:
         os.remove(socket_path)
     except OSError:
         pass
     sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     sock.bind(socket_path)
     sock.listen(5)
     GObject.io_add_watch(sock, GObject.IO_IN, self.listener)
     print("created Lirc-Socket %s"%(socket_path))
     return sock
Ejemplo n.º 49
0
    def listener(self, sock, *args):
        '''Asynchronous connection listener. Starts a handler for each connection.'''
        conn, addr = sock.accept()
        f = conn.makefile(conn)
        self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)

        print(_("Connected"))
        GObject.io_add_watch(conn, GObject.IO_IN, self.handler)
        if self.shell.intro:
            self.shell.stdout.write(str(self.shell.intro)+"\n")
            self.shell.stdout.flush()
        return True
Ejemplo n.º 50
0
    def listener(self, sock, *args):
        '''Asynchronous connection listener. Starts a handler for each connection.'''
        conn, addr = sock.accept()
        f = conn.makefile(conn)
        self.shell = ShoebotCmd(self.bot, stdin=f, stdout=f, intro=INTRO)

        print(_("Connected"))
        GObject.io_add_watch(conn, GObject.IO_IN, self.handler)
        if self.shell.intro:
            self.shell.stdout.write(str(self.shell.intro) + "\n")
            self.shell.stdout.flush()
        return True
Ejemplo n.º 51
0
Archivo: btk.py Proyecto: timpuri/btk
    def NewConnection(self, path, fd, properties):
        print("new control connectin")
        self.conns[path] = HIDConnection(fd.take())

        def new_intr_conn(ssock, ip_type):
            sock, info = ssock.accept()
            print("interrput connection:", info)
            self.conns[path].register_intr_sock(sock)

            return False

        gobject.io_add_watch(self.sock, gobject.IO_IN, new_intr_conn)
Ejemplo n.º 52
0
 def run_command(self, command):
     try:
         p = subprocess.Popen(command,
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE,
                              stdin=subprocess.PIPE,
                              shell=True)
         self.io_id = GObject.io_add_watch(p.stdout, GObject.IO_IN, self.feed)
         GObject.io_add_watch(p.stdout, GObject.IO_HUP, self.command_finished)
     except Exception as err:
         message_dialog(self.win, 'error', _("An error has occured"),
                        str(err))
Ejemplo n.º 53
0
 def create_lircd_socket(self, socket_path):
     try:
         os.remove(socket_path)
     except OSError:
         pass
     sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
     sock.bind(socket_path)
     sock.listen(5)
     GObject.io_add_watch(sock, GObject.IO_IN, self.listener)
     print("created Lirc-Socket %s" % (socket_path))
     return sock
Ejemplo n.º 54
0
 def serve_forever(self, poll_interval=0.5):
     mainloop = GObject.MainLoop()
     if hasattr(self, 'socket'):
         GObject.io_add_watch(
             self, GObject.IO_IN | GObject.IO_PRI, self._on_new_request)
     if hasattr(self, 'stream_queue'):
         GObject.io_add_watch(
             self.stream_queue._reader, GObject.IO_IN | GObject.IO_PRI,
             self._on_new_message)
     try:
         mainloop.run()
     except KeyboardInterrupt:
         self.shutdown()
Ejemplo n.º 55
0
    def connect_callback(self, response):
        if "CONNECT" in response:
            dprint("Starting pppd")
            self.pppd = subprocess.Popen(
                ["/usr/sbin/pppd", "%s" % self.port, "115200", "defaultroute", "updetach", "usepeerdns"], bufsize=1,
                stdout=subprocess.PIPE)
            GObject.io_add_watch(self.pppd.stdout, GObject.IO_IN | GObject.IO_ERR | GObject.IO_HUP, self.on_pppd_stdout)
            GObject.timeout_add(1000, self.check_pppd)

            self.cleanup()
        else:
            self.cleanup()
            raise PPPException("Bad modem response %s, expected CONNECT" % response[0])
Ejemplo n.º 56
0
    def watch_debconf_fd(self, from_debconf, process_input):
        """Event loop interface to debconffilter.

        A frontend typically provides its own event loop. When a
        debconffiltered command is running, debconffilter must be given an
        opportunity to process input from that command as it arrives. This
        method will be called with from_debconf as a file descriptor reading
        from the filtered command and a process_input callback which should
        be called when input events are received."""

        GObject.io_add_watch(from_debconf,
                             GObject.IO_IN | GObject.IO_ERR | GObject.IO_HUP,
                             self.watch_debconf_fd_helper, process_input)
Ejemplo n.º 57
0
 def start(self):
     """ Write config if not found and watch for keyboard events. """
     self._get_config()
     self.root.change_attributes(event_mask=X.KeyPressMask)
     self.keys = {self.display.keysym_to_keycode(k):v for k,v in self.KEYS.items()}
     for keycode in self.keys:
         self.root.grab_key(keycode, X.ControlMask | X.Mod1Mask, 1, X.GrabModeAsync, X.GrabModeAsync)
         self.root.grab_key(keycode, X.ControlMask | X.Mod1Mask | X.Mod2Mask, 1, X.GrabModeAsync, X.GrabModeAsync)
     for event in range(0, self.root.display.pending_events()):
         self.root.display.next_event()
     GObject.io_add_watch(self.root.display, GObject.IO_IN, self._check_event)
     print('PyGrid running. Press CTRL+C to cancel.')
     Gtk.main()
Ejemplo n.º 58
0
	def startserver(self, host, port):
		self.host = host
		self.port = port
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
		try:
			self.sock.bind((self.host, self.port)) #TODO: check port empty first
		except:
			loggy.warn('mpdserver failed to start on host %s port %s' % (self.host, self.port))
			return False
		self.sock.listen(1)
		loggy.log('mpdserver Interface Running on ' + host + ':' + str(port) )
		GObject.io_add_watch(self.sock, GObject.IO_IN, self.listener)