Example #1
0
def _on_enter_recovery_mode_():
    try:
        if update_framework():
            machine.reset()
    except Exception as e:
        usys.print_exception(e)
    start_ftp()
Example #2
0
def __save_dict():
    if __boot_dict == None:
        return
    try:
        with open(DICT_FILE_PATH, 'w') as f:
            ujson.dump(__boot_dict, f)
    except Exception as e:
        usys.print_exception(e)
Example #3
0
def main():
    do_connect()
    timer = RelayTimer()
    try:
        uasyncio.run(timer.main())
    except (Exception, KeyboardInterrupt) as e:
        timer.all_off()
        led.on()  # OFF
        usys.print_exception(e)
Example #4
0
def main(app_name, *args, **kws):
    screen.init()
    keypad.init()
    network_helper.deactive_all()
    screen.get_framebuffer().fill(0)
    screen.get_framebuffer().text("FTP MODE", 0, 0, COLOR_WHITE)
    screen.refresh()
    utime.sleep_ms(1000)
    try:
        ap = network_helper.ap("Play32AP", "12345678")
        wlan = network_helper.connect()
    except Exception as e:
        import usys
        usys.print_exception(e)
        screen.get_framebuffer().fill(0)
        screen.get_framebuffer().text("Error...", 0, 0, COLOR_WHITE)
        screen.get_framebuffer().text("Restart...", 0, 16, COLOR_WHITE)
        screen.refresh()
        utime.sleep_ms(2000)
        return
    wlan_connected = wlan.isconnected()

    def start():
        frame = screen.get_framebuffer()
        frame.fill(0)
        frame.text("\"B\" EXIT", 0, 0, COLOR_WHITE)
        frame.text("-WIFI:", 0, 8, COLOR_WHITE)
        frame.text("Play32AP", 0, 16, COLOR_WHITE)
        frame.text("-PASSWD:", 0, 24, COLOR_WHITE)
        frame.text("12345678", 0, 32, COLOR_WHITE)
        frame.text("-Port 21", 0, 40, COLOR_WHITE)
        frame.text(ap.ifconfig()[0], 0, 48, COLOR_WHITE)
        if wlan.isconnected():
            frame.text(wlan.ifconfig()[0], 0, 56, COLOR_WHITE)
        screen.refresh()
        # uftpd.restart()

    start()
    _loop = True
    while _loop:
        for event in keypad.get_key_event():
            event_type, key = keypad.parse_key_event(event)
            if event_type == keypad.EVENT_KEY_PRESS:
                if key == keypad.KEY_B:
                    # uftpd.stop()
                    wlan.disconnect()
                    wlan.active(False)
                    ap.active(False)
                    _loop = False  # exit
        if wlan.isconnected() != wlan_connected:
            wlan_connected = wlan.isconnected()
            start()
        utime.sleep_ms(100)
    network_helper.deactive_all()
Example #5
0
def f():
    micropython.heap_lock()
    try:
        raise ValueError(1)
    except ValueError as er:
        exc = er
    micropython.heap_unlock()

    # print the exception
    buf = uio.StringIO()
    usys.print_exception(exc, buf)
    for l in buf.getvalue().split("\n"):
        if l.startswith("  File "):
            print(l.split('"')[2])
        else:
            print(l)
Example #6
0
 def _timer_callback(self, _=None):
     if len(self.__irqs) <= 0:
         return
     irq = self.__irqs[0]
     irq_id, callback, target_time_ms, mode, priod = irq
     try:
         self.__irqs.remove(irq)
     except: pass
     if callback:
         try:
             callback(self)
         except Exception as e:
             print_exception(e)
     if mode == PERIODIC:
         self._insert_irq((irq_id, callback, ticks_add(target_time_ms, priod), mode, priod))
     self._set_timer()
Example #7
0
def check_update_file():
    try:
        with open(FRAMEMEWORK_PACK_HASH_PATH, "rb") as f:
            sha256_checksum = f.read()
        hasher = uhashlib.sha256()
        with open(FRAMEMEWORK_PACK_PATH, "rb") as f:
            part = f.read(4096)
            while len(part) > 0:
                hasher.update(part)
                part = f.read(4096)
        generated_checksum = hasher.digest()
        if sha256_checksum == generated_checksum:
            return True
        print(sha256_checksum, generated_checksum)
    except Exception as e:
        usys.print_exception(e)
    return False
Example #8
0
def dump_exception(msg, e):
    print(msg)
    print_exception(e)
    
    if EXCEPTION_DUMP > 0:
        pos = _log.tell()
        
        if pos < EXCEPTION_DUMP :
            dt  = RTC().datetime()
            _log.write(f'\n{dt[2]}.{dt[1]}.{dt[0]} {dt[4]}:{dt[5]:02} :: ')
            _log.write(msg)
            _log.write('\n')
            print_exception(e, _log)
            _log.flush()
    
    if alert.error_beep:
        play((200, 500), (100, 500))
Example #9
0
    async def on_connection(self, reader, writer):
        try:
            # Read and keep request method, path and HTTP version
            method, path, httpv = (await reader.readline()).decode().split(' ')

            # Refuse wrong HTTP methods
            if method != 'GET':
                return await self.http_response(reader, writer,
                                                '405 Method Not Allowed',
                                                '405 Method not allowed')

            if path.startswith('/?run='):
                # Run with provided timeout
                time = utime.ticks_ms()
                run_for = int(path.split('=')[1].strip())
                self.run_until = time + run_for * 1000
                return await self.http_response(reader, writer,
                                                '303 See Other',
                                                ['Location: /'])
            elif path.strip() == '/':
                # Just show the page
                return await self.http_response(reader, writer, '200 OK', [],
                                                self.get_web_page())
            elif path.strip() == '/off':
                # Trigger turn off in mainloop
                self.run_until = 1
                return await self.http_response(reader, writer,
                                                '303 See Other',
                                                ['Location: /'])
            elif path.strip() == '/incr':
                # Perform incremenent the same way the button would
                self.increment()
                return await self.http_response(reader, writer,
                                                '303 See Other',
                                                ['Location: /'])

            return await self.http_response(reader, writer, '404 Not Found',
                                            [], '404 Not Found')

        except Exception as e:
            await self.http_response(reader, writer,
                                     '500 Internal Server Error', [],
                                     '500 Internal Server Error')
            print("Exception while handling HTTP request")
            usys.print_exception(e)
Example #10
0
 async def render_once(self, root_view, screen):
     s_w, s_h = screen.get_size()
     frame = screen.get_framebuffer()
     target_duration = 1000 // self.__context[C.CONTEXT_FRAME_RATE]
     now = time_ms()
     if now - self.__lasttime < target_duration:
         await asyncio.sleep(0.0)
         return
     self.__context[C.CONTEXT_FRAME_DURATION] = now - self.__lasttime
     self.__lasttime = now
     # print(self.__context[CONTEXT_FRAME_DURATION])
     try:
         if root_view.need_render(self.__context):
             effect_area = await root_view.render(self.__context, frame,
                                                  (0, 0, s_w, s_h))
             await screen.refresh(self.__context, effect_area)
     except Exception as e:
         if is_debug:
             print_exception(e)
             self.stop()
             return
Example #11
0
def start_ftp():
    ap = network_helper.ap("Play32AP", "12345678")
    utime.sleep(1.0)
    ip = ap.ifconfig()[0]
    ftp = microftpd.FTPServer(ip)
    ftp.init()
    print("Connect to WIFI: Play32AP")
    console.log("Connect to WIFI: Play32AP")
    print("with password: 12345678")
    console.log("with password: 12345678")
    print("FTP started at {}:21".format(ip))
    console.log("FTP started at {}:21".format(ip))
    print("")
    console.log("")
    print("Put framework.pack and sha256 file into /tmp .")
    console.log("Put framework.pack and sha256 file into /tmp .")
    print("Press A+B to update.")
    console.log("Press A+B to update.")
    is_key_pressed = hal_keypad.is_key_pressed
    KEY_A = hal_keypad.KEY_A
    KEY_B = hal_keypad.KEY_B
    while True:
        # key event
        if is_key_pressed(KEY_A) and is_key_pressed(KEY_B):
            try:
                if update_framework():
                    machine.reset()
            except:
                print("update failed. Please check your framework pack.")
                console.log("update failed. Please check your framework pack.")
        # serve ftp
        try:
            ftp.loop()
        except KeyboardInterrupt:
            return
        except Exception as e:
            usys.print_exception(e)
Example #12
0
 def play_next_note(self, play_next_note=False):
     try:
         try:
             time, frame_type, padding, frame_data = parse_bee_frame(self.__buzz_file.file.read(8))
         except:
             return
         time = time * self.__tempo // self.__buzz_file.ticks_per_beat // 1000 # us -> ms
         # play next note
         self.__frame_pointer += 1
         if self.__frame_pointer < self.__buzz_file.frame_count and play_next_note and time > 0:
             # set timer event as soon as possible
             self.__target_note_time = ticks_add(self.__target_note_time, time)
             target_period = ticks_diff(self.__target_note_time, ticks_ms())
             self.__timer_id = self.__timer.init(mode=ONE_SHOT, period=target_period, callback=self._timer_callback)
         # deal with frame
         if frame_type == TYPE_SET_TEMPO:
             self.__tempo = int.from_bytes(frame_data, 'big')
         elif frame_type == TYPE_NOTE_OFF:
             self.note_off()
         elif frame_type == TYPE_NOTE_ON:
             self.note_on(frame_data[0], self.__volume)
         elif frame_type == TYPE_EMIT_EVENT and self.__event_callback != None:
             self.__event_callback(frame_data, padding)
         # control next note
         if self.__frame_pointer < self.__buzz_file.frame_count and play_next_note and time <= 0:
             self.play_next_note(True)
             return time
         if self.__frame_pointer >= self.__buzz_file.frame_count:
             if self.__loop:
                 self.start(True)
             else:
                 self.stop()
         return time
     except Exception as e:
         import usys
         usys.print_exception(e)
try:
    raise global_exc
except:
    pass


def test():
    micropython.heap_lock()
    global global_exc
    global_exc.__traceback__ = None
    try:
        raise global_exc
    except StopIteration:
        print("StopIteration")
    micropython.heap_unlock()


# call test() with heap allocation disabled
test()

# print the exception that was raised
buf = uio.StringIO()
usys.print_exception(global_exc, buf)
for l in buf.getvalue().split("\n"):
    # uPy on pyboard prints <stdin> as file, so remove filename.
    if l.startswith("  File "):
        l = l.split('"')
        print(l[0], l[2])
    else:
        print(l)
Example #14
0
    print('MQTT start')
    c = MQTTClient(clientID, usocket.getaddrinfo(server, 1883)[0][4][0], user="******", password="******")
    c.set_callback(sub_cb)
    c.connect()
    c.subscribe(b"prayers/out")
    time.sleep(1)
    print("MQTT connected")
    print("Boo")
    while True:
        c.check_msg()
        if(button.value() == 0):
            print('Publishing prayer')
            c.publish(b'prayers/in', clientID)
            time.sleep(1)
        time.sleep_ms(50)

c = 'asf'
relay = Pin(5, Pin.OUT)
button = Pin(4, Pin.IN, Pin.PULL_UP)

if __name__ == "__main__":
    while True:
        try:
            do_connect() 
            main()
            print("Main exited, restarting")
        except OSError as e:
            usys.print_exception(e)
            time.sleep(5)
#         machine.reset()