Beispiel #1
0
 def call_at(self, time, callback, *args):
     # Including self.cnt is a workaround per heapq docs
     if __debug__:
         log.debug("Scheduling %s", (time, self.cnt, callback, args))
     heapq.heappush(self.q, (time, self.cnt, callback, args))
     #        print(self.q)
     self.cnt += 1
Beispiel #2
0
def test_heappush():
    n = 1000
    a = []
    for i in range(n):
        heappush(a, randrange(1000))
    assert len(a) == n
    assert_heap_ordered(a)
Beispiel #3
0
 def push(self, _):
     global i_pum, i_snd, i_data, sub_flag
     if -35 < (i_pum - i_snd) < 61:
         try:
             kT = sensor_k.measure()
             kTr = '%f' % (kT)
             if kTr == 'nan':
                 kTr = 'null'
         except:
             kTr = 'null'
             pass
         try:
             aT, aH = sensor3.measure()
             aTr = '%f' % (aT)
             aHr = '%f' % (aH)
             if aTr == 'nan':
                 aTr = 'null'
             if aHr == 'nan':
                 aHr = 'null'
         except:
             aTr = 'null'
             aHr = 'null'
             pass
         atemp = '[{"id":%d,"kT":%s,"aT":%s,"aH":%s}]' % (i_pum, kTr, aTr,
                                                          aHr)
         uheapq.heappush(i_data, atemp)
     else:
         pass
     i_pum += 1
     if i_pum > 43200:
         sub_flag = 404
Beispiel #4
0
def on_message(topic, message):
    if topic == b"configuration":
        print("Receive configuration message : " + str(message))
        print()

        configuration = json.loads(message)
        uheapq.heappush(heap, configuration)
Beispiel #5
0
    def call_at(self, time, callback, *args):
        # Including self.cnt is a workaround per heapq docs
        if __debug__:
            log.debug("Scheduling %s", (time, self.cnt, callback, args))
        heapq.heappush(self.q, (time, self.cnt, callback, args))
#        print(self.q)
        self.cnt += 1
Beispiel #6
0
 def call_at(self, time, callback, *args):
     # Including self.cnt is a workaround per heapq docs
     # Returning it provides a handle for locating a queue entry
     if __debug__:
         log.debug("Scheduling %s", (time, self.cnt, callback, args))
     self.cnt += 1
     heapq.heappush(self.q, (time, self.cnt, callback, args))
     self.max_qlen = max(self.max_qlen, len(self.q))
     return self.cnt
Beispiel #7
0
def move_blue_train():
    global head, tail
    if head == 0:
        print(f'move = {time.monotonic()}')
    PIXELS[head] = BLUE
    PIXELS[tail] = BLACK
    head = (head + DIRECTION) % 10
    tail = (tail + DIRECTION) % 10
    uheapq.heappush(EVENT_QUEUE, (time.monotonic() + 0.1, move_blue_train))
Beispiel #8
0
def move_train(t):
    global head, tail
    if head == 0:
        print(f'move = {time.monotonic():.2f}')
    PIXELS[head] = BLUE
    PIXELS[tail] = BLACK
    head = (head + DIRECTION) % 10
    tail = (tail + DIRECTION) % 10
    uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, move_train))
Beispiel #9
0
    def recv_audio(self):
        # set receive timeout
        self.handle.settimeout(CONFIG_RECV_TIMEOUT_MS)

        # receive the size of audio segment
        try:
            val = self.handle.recv(4)
            if not val:
                print("Recv size ERROR")
                return False
            total_size = int(struct.unpack('I', val[:])[0])
        except OSError:
            return True
        except:
            print("Recv size ERROR2")
            return False

        want_recv = CONFIG_BUFFER_RECV_SIZE
        total_recv = 0
        print("streaming {} bytes".format(total_size))

        # receive the audio segment
        while total_recv < total_size:
            if total_size - total_recv < want_recv:
                want_recv = total_size - total_recv

            # receive audio segment
            self.handle.settimeout(CONFIG_RECV_TIMEOUT_MS_2)
            try:
                data = self.handle.recv(want_recv)
                if not data:
                    print("Recv size ERROR3")
                    return False
                total_recv += len(data)
                #print(total_recv)
            except OSError:
                return True
            except MemoryError:
                print("Recv size ERRORX")
                return True
            except:
                print("Recv size ERROR4")
                return False

            # queue the data
            try:
                heapq.heappush(self.queue_data, data)
                print("push {}".format(len(data)))
                #time.sleep(0.010)
            except:
                print("push {} failed!".format(len(data)))
                return False

        print("streamed  {} bytes".format(total_recv))
        return True
Beispiel #10
0
    import uheapq as heapq
except:
    try:
        import heapq
    except ImportError:
        import sys
        print("SKIP")
        sys.exit()

try:
    heapq.heappop([])
except IndexError:
    print("IndexError")

try:
    heapq.heappush((), 1)
except TypeError:
    print("TypeError")


def pop_and_print(h):
    l = []
    while h:
        l.append(str(heapq.heappop(h)))
    print(' '.join(l))


h = []
heapq.heappush(h, 3)
heapq.heappush(h, 1)
heapq.heappush(h, 2)
Beispiel #11
0
def blink_off(t):
    RED_LED.value = False
    uheapq.heappush(EVENT_QUEUE, (t + 900 * MILLISECOND, blink_on))
Beispiel #12
0
def blink_on(t):
    print(f'blink_on: {time.monotonic():.2f}')
    RED_LED.value = True
    uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, blink_off))
Beispiel #13
0
def move_train(t):
    global head, tail
    if head == 0:
        print(f'move = {time.monotonic():.2f}')
    PIXELS[head] = BLUE
    PIXELS[tail] = BLACK
    head = (head + DIRECTION) % 10
    tail = (tail + DIRECTION) % 10
    uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, move_train))


def blink_on(t):
    print(f'blink_on: {time.monotonic():.2f}')
    RED_LED.value = True
    uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, blink_off))


def blink_off(t):
    RED_LED.value = False
    uheapq.heappush(EVENT_QUEUE, (t + 900 * MILLISECOND, blink_on))


start = time.monotonic_ns()
uheapq.heappush(EVENT_QUEUE, (start + SECOND, move_train))
uheapq.heappush(EVENT_QUEUE, (start + SECOND + 1, blink_on))

while EVENT_QUEUE:
    t, fn = uheapq.heappop(EVENT_QUEUE)
    time.sleep(max((t - time.monotonic_ns()) / SECOND, 0))
    fn(t)
Beispiel #14
0
def add(h, v):
    heapq.heappush(h, (v, None), True)
Beispiel #15
0
DEBUG = 0

MAX = ticks_add(0, -1)
MODULO_HALF = MAX // 2 + 1

if DEBUG:
    def dprint(*v):
        print(*v)
else:
    def dprint(*v):
        pass

# Try not to crash on invalid data
h = []
heapq.heappush(h, 1)
try:
    heapq.heappush(h, 2, True)
    assert False
except TypeError:
    pass

heapq.heappush(h, 2)
try:
    heapq.heappop(h, True)
    assert False
except TypeError:
    pass


def pop_all(h):
Beispiel #16
0
 def call_at_(self, time, callback, args=()):
     if __debug__ and DEBUG:
         log.debug("Scheduling %s", (time, callback, args))
     heapq.heappush(self.q, (time, callback, args), True)
Beispiel #17
0
MAX = ticks_add(0, -1)
MODULO_HALF = MAX // 2 + 1

if DEBUG:

    def dprint(*v):
        print(*v)
else:

    def dprint(*v):
        pass


# Try not to crash on invalid data
h = []
heapq.heappush(h, 1)
try:
    heapq.heappush(h, 2, True)
    assert False
except TypeError:
    pass

heapq.heappush(h, 2)
try:
    heapq.heappop(h, True)
    assert False
except TypeError:
    pass


def pop_all(h):
Beispiel #18
0
def add(h, v):
    heapq.heappush(h, (v, None), True)
Beispiel #19
0
try:
    import uheapq as heapq
except:
    try:
        import heapq
    except ImportError:
        print("SKIP")
        raise SystemExit

try:
    heapq.heappop([])
except IndexError:
    print("IndexError")

try:
    heapq.heappush((), 1)
except TypeError:
    print("TypeError")

def pop_and_print(h):
    l = []
    while h:
        l.append(str(heapq.heappop(h)))
    print(' '.join(l))

h = []
heapq.heappush(h, 3)
heapq.heappush(h, 1)
heapq.heappush(h, 2)
print(h)
pop_and_print(h)
Beispiel #20
0
import board
import digitalio
import time
import uheapq

RED_LED = digitalio.DigitalInOut(board.D13)
RED_LED.direction = digitalio.Direction.OUTPUT
NANOSECOND = 1
MICROSECOND = 1000 * NANOSECOND
MILLISECOND = 1000 * MICROSECOND
SECOND = 1000 * MILLISECOND
EVENT_QUEUE = []


def blink_on(t):
    print(f'blink = {time.monotonic()}')
    RED_LED.value = True
    uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, blink_off))


def blink_off(t):
    RED_LED.value = False
    uheapq.heappush(EVENT_QUEUE, (t + 900 * MILLISECOND, blink_on))


uheapq.heappush(EVENT_QUEUE, (time.monotonic_ns(), blink_on))
while EVENT_QUEUE:
    t, fn = uheapq.heappop(EVENT_QUEUE)
    time.sleep(max((t - time.monotonic_ns()) / SECOND, 0))
    fn(t)
Beispiel #21
0
PIXELS = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=0.2, auto_write=True)
BLUE = (0, 0, 100)
BLACK = (0, 0, 0)
NANOSECOND = 1
MICROSECOND = 1000 * NANOSECOND
MILLISECOND = 1000 * MICROSECOND
SECOND = 1000 * MILLISECOND
EVENT_QUEUE = []
DIRECTION = 1

head, tail = 0, DIRECTION * (-4) % 10


def move_blue_train(t):
    global head, tail
    if head == 0:
        print(f'move = {time.monotonic()}')
    PIXELS[head] = BLUE
    PIXELS[tail] = BLACK
    head = (head + DIRECTION) % 10
    tail = (tail + DIRECTION) % 10
    uheapq.heappush(EVENT_QUEUE, (t + 100 * MILLISECOND, move_blue_train))


uheapq.heappush(EVENT_QUEUE, (time.monotonic_ns(), move_blue_train))
while EVENT_QUEUE:
    t, fn = uheapq.heappop(EVENT_QUEUE)
    time.sleep(max((t - time.monotonic_ns()) / SECOND, 0))
    fn(t)
Beispiel #22
0
    def cmd_post_callback(self, handler, req):
        # try to fetch body
        try:
            buffer = bytearray(req.content_len);
            req.recv(buffer, len(buffer))
            parsed = ujson.loads(buffer);
            
        except Exception as e:
            print("Exception while reading post data:", e);
            self.send_error(req, 400, e)
            return -1  # ESP_FAIL

        print("Parsed:", parsed);

        if not "cmd" in parsed:
            self.send_error(req, 400, "Missing command")
            return -1  # ESP_FAIL

        # check for project files
        pfiles = [ ]
        if "project" in parsed:
            # get projects base name (prepent / if missing
            prjbase = self.unquote(parsed["project"])
            if not prjbase[0] == "/": prjbase = "/" + prjbase
            for i in [ ".py", ".xml" ]:
                fname = prjbase+i
                print("Checking for", fname);
                try:
                    if uos.stat(fname)[0] & 0x8000:
                        pfiles.append(prjbase+i)
                except:
                    pass
                
            print("Files:", pfiles)

            if not len(pfiles):
                req.resp_set_status("404 Project not found");
                req.resp_sendstr("Project not found");
                return -1  # ESP_FAIL            
            
        if parsed["cmd"] == "delete":
            print("Delete command");
            try:
                for i in pfiles:
                    uos.remove(i)
            except Exception as e:
                self.send_error(req, 400, "Delete failed " + e);
                return -1  # ESP_FAIL                            
            
        elif parsed["cmd"] == "copy":
            print("Copy command");
            try:
                for i in pfiles:
                    # copy from /sd/xyz to /xyz or from
                    # /xyz to /sd/xyz
                    if i.startswith("/sd"): dstname = i[3:]
                    else:                   dstname = "/sd"+i
                    print("copy", i, "to", dstname);
                    self.copyfile(i, dstname)
            except Exception as e:
                self.send_error(req, 400, "Copy failed "+e);
                return -1  # ESP_FAIL                            
            
        elif parsed["cmd"] == "rename":
            print("Rename command");

            # rename needs a "new" entry
            if not "new" in parsed:
                self.send_error(req, 400, "New name not specified");
                return -1  # ESP_FAIL            

            newbase = self.unquote(parsed["new"])
            if not newbase[0] == "/": newbase = "/" + newbase
            try:
                for i in pfiles:
                    newname = newbase + "." + i.split(".")[-1]
                    print("rename", i, "to", newname);
                    uos.rename(i, newname)
            except Exception as e:
                print("Error", e);
                self.send_error(req, 400, "Rename failed "+e);
                return -1  # ESP_FAIL
            
        elif parsed["cmd"] == "run":
            if not "name" in parsed or not "sd" in parsed:                
                self.send_error(req, 400, "Incomplete run request");
                return -1  # ESP_FAIL
            
            # push command into queue to be read by lvgl task
            uheapq.heappush(self.queue, ( "run", parsed["sd"], parsed["name"]));
            
        else:
            self.send_error(req, 400, "Unknown command " + parsed["cmd"]);
            return -1  # ESP_FAIL
            
        req.resp_sendstr("Command ok")
        return 0