示例#1
0
def distributer(inchans, outchans, delay_max=0.5):
    inchans = inchans[:]  # Copy.  Will remove closed chans
    while True:
        try:
            _, value = chanselect(inchans, [])
            time.sleep(random.random() * delay_max)
        except ChanClosed as ex:
            inchans.remove(ex.which)
            continue
        _, _ = chanselect([], [(chan, value) for chan in outchans])
示例#2
0
def distributer(inchans, outchans, delay_max=0.5):
    inchans = inchans[:]  # Copy.  Will remove closed chans
    while True:
        try:
            _, value = chanselect(inchans, [])
            time.sleep(random.random() * delay_max)
        except ChanClosed as ex:
            inchans.remove(ex.which)
            continue
        _, _ = chanselect([], [(chan, value) for chan in outchans])
示例#3
0
    def _run(self):
        next_time = time.time()
        pending = []  # First is most recent.  Should be a deque
        err = None

        while True:
            start_fetch = timeout_after(max(0.0, next_time - time.time()))

            # Does or doesn't wait on updates_chan depending on if we have
            # items ready.
            if pending:
                outchans = [(self.updates_chan, pending[0])]
            else:
                outchans = []

            ch, value = chanselect([self.quit, start_fetch], outchans)
            if ch == self.quit:
                errc = value
                self.updates_chan.close()
                errc.put(err)
                return
            elif ch == start_fetch:
                try:
                    err = None
                    item_list, next_time = self.fetcher.fetch()
                except Exception as ex:
                    err = ex
                    next_time = time.time() + 10.0
                    continue
                pending.extend(item_list)
            else:  # self.updates_chan
                pending.pop(0)  # Pops the sent item
示例#4
0
    def _run(self):
        next_time = time.time()
        pending = []  # First is most recent.  Should be a deque
        err = None

        while True:
            start_fetch = timeout_after(max(0.0, next_time - time.time()))

            # Does or doesn't wait on updates_chan depending on if we have
            # items ready.
            if pending:
                outchans = [(self.updates_chan, pending[0])]
            else:
                outchans = []

            ch, value = chanselect([self.quit, start_fetch], outchans)
            if ch == self.quit:
                errc = value
                self.updates_chan.close()
                errc.put(err)
                return
            elif ch == start_fetch:
                try:
                    err = None
                    item_list, next_time = self.fetcher.fetch()
                except Exception as ex:
                    err = ex
                    next_time = time.time() + 10.0
                    continue
                pending.extend(item_list)
            else:  # self.updates_chan
                pending.pop(0)  # Pops the sent item
示例#5
0
def setup_and_dispatch(server_chan,
                       terminal_url,
                       use_pty,
                       cmd,
                       start_clojurescript_repl=False,
                       initial_request=None):

    # client process (pty or plain process)
    client = terminalio.AsyncResettableTerminal(
        use_pty=use_pty,
        cmd=cmd,
    )

    # terminal
    term = terminal.Terminal(client,
                             url=terminal_url,
                             start_clojurescript_repl=start_clojurescript_repl)

    if initial_request:
        term.request(initial_request)

    channels = [client.out, server_chan]

    while True:
        res = True

        try:
            ch, val = chan.chanselect(consumers=channels, producers=[])
            closed = False
        except chan.ChanClosed, co:
            ch = co.which
            val = None
            closed = True

        if ch == client.out:
            assert not closed

            # output from the terminal process
            res = term.input(val)

        elif ch == server_chan:
            assert not closed
            msgtype = val[0]
            if msgtype == 'request':
                res = term.request(val[1])
            elif msgtype == 'websocket_connect':
                res = term.websocket_connect(val[1])
            elif msgtype == 'websocket_receive':
                res = term.websocket_receive(val[1], val[2])
            else:
                assert 'unknown msgtype: %r' % (msgtype, )

        else:
            assert False

        # deal with the returnvalue
        if res == 'reload':
            return 'reload', val[1] # the initial request
        elif res is False:
            return False, None
示例#6
0
        def sender():
            i = 0
            while True:
                time.sleep(1.0 * random.random())

                chan, _ = chanselect([quit], [(c, "%s: %d" % (msg, i))])
                if chan == quit:
                    quit.put("See you!")
                i += 1
示例#7
0
    def _run(self):
        subchans = [sub.updates() for sub in self.subscriptions]
        while True:
            c, value = chanselect(subchans + [self.quit], [])
            if c == self.quit:
                value.put(self._close_subs_collect_errs())
                self.updates_chan.close()
                return
            else:
                item = value

            c, _ = chanselect([self.quit], [(self.updates_chan, item)])
            if c == self.quit:
                value.put(self._close_subs_collect_errs())
                self.updates_chan.close()
                return
            else:
                pass  # Send successful
示例#8
0
 def fanin_until_closed(inchans, outchan):
     inchans = inchans[:]
     while inchans:
         try:
             _, val = chanselect(inchans, [])
             out.put(val)
         except ChanClosed as ex:
             inchans.remove(ex.which)
     out.close()
示例#9
0
 def fanin_until_closed(inchans, outchan):
     inchans = inchans[:]
     while inchans:
         try:
             _, val = chanselect(inchans, [])
             out.put(val)
         except ChanClosed as ex:
             inchans.remove(ex.which)
     out.close()
示例#10
0
    def _run(self):
        subchans = [sub.updates() for sub in self.subscriptions]
        while True:
            c, value = chanselect(subchans + [self.quit], [])
            if c == self.quit:
                value.put(self._close_subs_collect_errs())
                self.updates_chan.close()
                return
            else:
                item = value

            c, _ = chanselect([self.quit], [(self.updates_chan, item)])
            if c == self.quit:
                value.put(self._close_subs_collect_errs())
                self.updates_chan.close()
                return
            else:
                pass  # Send successful
示例#11
0
        def sender():
            i = 0
            while True:
                time.sleep(1.0 * random.random())

                chan, _ = chanselect([quit], [(c, "%s: %d" % (msg, i))])
                if chan == quit:
                    quit.put("See you!")
                i += 1
示例#12
0
def brain_loop(args):
    sock_node = Socket(BUS)
    sock_node.bind('tcp://*:%s' % BRAIN_PORT)
    sock_node.recv_timeout = 250
    #sock_node.send_buffer_size = 1000
    sock_node.send_timeout = 200
    seq = 0

    timer = set_mode(args.mode)
    server = Server(args)

    while True:
        ch, value = chanselect([timer.chan, server.chan], [])

        #print 'AFTER chanselect', ch is timer.chan, time.time()
        if ch is timer.chan:
            lights.only(*value)
            #print "LIGHTS", value
            try:
                seq += 1
                sock_node.send(
                    '%i %s %s' %
                    (seq, CMD_LIGHTS, ' '.join(lights.rev_lookup[led_pin]
                                               for led_pin in value)))
            except Exception as ex:
                #print ex
                pass
        elif ch is server.chan:
            if value[0] == 'status':
                node = None
                try:
                    seq += 1
                    sock_node.send('%i PING' % seq)
                    while True:
                        node_msg = sock_node.recv().split()
                        if int(node_msg[0]) == seq:
                            node = 'ok'
                            break
                        elif int(node_msg[0]) > seq:
                            raise Exception('Skipped ping message')
                except Exception as ex:
                    node = repr(ex)
                value[1].put({'loop': 'ok', 'node': node})
            elif value[0] == 'set_period':
                timer.period = value[1]
            elif value[0] == 'trip':
                timer.trip = True
            elif value[0] == 'mode':
                mode = value[1]
                print("new mode tho %s" % mode)
                timer = set_mode(mode)
            else:
                print "UNKNOWN COMMAND:", value

    time.sleep(2)
示例#13
0
def master_loop():
    sock_slave = Socket(PAIR)
    sock_slave.bind('tcp://*:%s' % MASTER_PORT)
    sock_slave.recv_timeout = 250
    #sock_slave.send_buffer_size = 1000
    sock_slave.send_timeout = 200
    seq = 0

    timer = LightTimer()
    server = Server()

    while True:
        ch, value = chanselect([timer.chan, server.chan], [])
        #print 'AFTER chanselect', ch is timer.chan, time.time()
        if ch is timer.chan:
            lights.only(*value)
            #print "LIGHTS", value
            try:
                seq += 1
                sock_slave.send('%i %s %s' % (
                    seq,
                    CMD_LIGHTS,
                    ' '.join(lights.rev_lookup[led_pin] for led_pin in value)))
            except Exception as ex:
                #print ex
                pass
        elif ch is server.chan:
            if value[0] == 'status':
                slave = None
                try:
                    seq += 1
                    sock_slave.send('%i PING' % seq)
                    while True:
                        slave_msg = sock_slave.recv().split()
                        if int(slave_msg[0]) == seq:
                            slave = 'ok'
                            break
                        elif int(slave_msg[0]) > seq:
                            raise Exception('Skipped ping message')
                except Exception as ex:
                    slave = repr(ex)
                value[1].put({'loop': 'ok', 'slave': slave})
            elif value[0] == 'set_period':
                timer.period = value[1]
            elif value[0] == 'trip':
                timer.trip = True
            else:
                print "UNKNOWN COMMAND:", value
    time.sleep(2)
示例#14
0
def example_timeout():
    def boring(msg):
        c = Chan()

        def sender():
            i = 0
            while True:
                c.put("%s: %d" % (msg, i))
                time.sleep(1.5 * random.random())
                i += 1
        quickthread(sender)
        return c

    c = boring("Joe")
    while True:
        chan, value = chanselect([c, timer(1.0)], [])
        if chan == c:
            print value
        else:
            print "You're too slow."
            return
示例#15
0
def example_timeout():
    def boring(msg):
        c = Chan()

        def sender():
            i = 0
            while True:
                c.put("%s: %d" % (msg, i))
                time.sleep(1.5 * random.random())
                i += 1

        quickthread(sender)
        return c

    c = boring("Joe")
    while True:
        chan, value = chanselect([c, timer(1.0)], [])
        if chan == c:
            print value
        else:
            print "You're too slow."
            return
示例#16
0
def setup_and_dispatch(server_chan,
                       terminal_url,
                       use_pty,
                       cmd,
                       start_clojurescript_repl=False,
                       initial_request=None,
                       window_control=None):

    # client process (pty or plain process)
    client = terminalio.AsyncResettableTerminal(
        use_pty=use_pty,
        cmd=cmd,
    )

    # terminal
    term = terminal.Terminal(client,
                             url=terminal_url,
                             start_clojurescript_repl=start_clojurescript_repl,
                             window_control=window_control)

    if initial_request:
        term.request(initial_request)

    channels = [client.out, server_chan]

    while True:
        res = True

        try:
            ch, val = chan.chanselect(consumers=channels, producers=[])
            closed = False
        except chan.ChanClosed, co:
            ch = co.which
            val = None
            closed = True

        if ch == client.out:
            assert not closed

            # output from the terminal process
            res = term.input(val)

        elif ch == server_chan:
            assert not closed
            msgtype = val[0]
            if msgtype == 'request':
                res = term.request(val[1])
            elif msgtype == 'websocket_connect':
                res = term.websocket_connect(val[1])
            elif msgtype == 'websocket_receive':
                res = term.websocket_receive(val[1], val[2])
            else:
                assert 'unknown msgtype: %r' % (msgtype, )

        else:
            assert False

        # deal with the returnvalue
        if res == 'reload':
            return 'reload', val[1] # the initial request
        elif res is False:
            return False, None
示例#17
0
    def book_keeper(self, init):
        new_song = self.manager.register("preload_new_song")
        preload_next = self.manager.register("preload_next")
        push = self.manager.register("preload_push")
        self.exit = exit = self.manager.register("preload_exit")
        start = self.manager.register("metadata")

        # We are done setting up, so push the init and close it.
        init.put(True)
        init.close()

        channels = [new_song, preload_next, push, exit, start]

        # State variables
        first_song = True
        last_preload_index = 0
        while True:
            action, value = chan.chanselect(channels, [])

            audiofile = None

            # This is entered whenever a new song needs to be added from
            # the queue.
            if action is new_song:
                # Find the index in the queue we want
                index = len(self.preloaded)
                song = self.queue.peek(index=index)

                # Make sure we didn't reach the end of the queue.
                if song is None:
                    logger.debug("Empty source queue found.")
                    continue

                logger.debug("Adding new track: %s", song.metadata)

                audiofile = PreloadedAudioFile(song,
                                               self.manager,
                                               self.options)

                self.preloaded.append(audiofile)

                if len(self.preloaded) <= self.preload_full_amount:
                    self.manager.emit("preload_next", True)

                # If this is the first song, we need to push it so that
                # there is something ready right away.
                if first_song:
                    self.manager.emit("preload_push", True)
                    first_song = False

            elif action is preload_next:
                try:
                    audiofile = self.preloaded[last_preload_index]
                except IndexError:
                    # No more songs? just do nothing.
                    logging.debug("Empty queue, failed to start preload.")
                    continue

                logger.debug("Starting preload on: %s", audiofile.metadata)
                start_thread(audiofile.preload)

                last_preload_index += 1

            elif action is push:
                # Get the left most item, the next one to play
                audiofile = self.preloaded[0]

                # Make sure the song has been preloaded fully
                if not audiofile.finished.is_set():
                    # The file hasn't been fully loaded, ditch it
                    # for one that doesn't preload at all.
                    logger.debug("Song hasn't preloaded yet, giving out non-preload.")
                    audiofile = audiofile.non_preload()

                logger.debug("Pushing audiofile: %s", audiofile.metadata)
                # And push it away!
                self.manager.emit("audiofile", audiofile)
                # Don't forget to add a new song to replace the old one.
                self.manager.emit("preload_new_song", True)

            elif action is start:
                # Pop the song from the actual queue first
                song = self.queue.pop()
                # Then pop it from our internal one.
                self.preloaded.popleft()

                # Make sure to update our index of preloadness
                last_preload_index -= 1
                # And limit it to 0 so we don't go negative
                last_preload_index = (last_preload_index if
                                      last_preload_index > 0 else 0)

                logger.debug("Starting audiofile: %s", song.metadata)

            elif action is exit:
                # We are wanted to exit, lets do so
                # First cleanup our files
                for audiofile in self.preloaded:
                    audiofile.close()
                # Then break out.
                break

            # Delete our references.
            del audiofile

        for c in channels:
            c.close()
示例#18
0
 def forward():
     while True:
         chan, value = chanselect([input1, input2], [])
         c.put(value)
示例#19
0
 def forward():
     while True:
         chan, value = chanselect([input1, input2], [])
         c.put(value)