Пример #1
0
async def reader(sock):
    try:
        print('Reader start')
        last = -1
        while True:
            line = await readline(sock)
            message = uio.StringIO(line)
            preheader = bytearray(ubinascii.unhexlify(message.read(10)))
            try:
                data = json.load(message)
            except Exception:
                data = message.read()
            finally:
                message.close()
                del message
            mid = preheader[0]
            print('Got', data)
            if last >= 0 and data[0] - last - 1:
                raise OSError('Missed message')
            last = data[0]
    except Exception as e:
        raise e
    finally:
        print("Reader stopped")
        try:
            print("Closing socket")
            sock.close()
        except:
            pass
Пример #2
0
def run_loop():
    # Wrapper for better error handling/recovery at top level.
    try:
        # This keeps all async tasks alive, including the main task created above
        from common import loop
        loop.run_forever()
    except BaseException as exc:
        import sys
        sys.print_exception(exc)
        # if isinstance(exc, KeyboardInterrupt):
        #     # preserve GUI state, but want to see where we are
        #     print("KeyboardInterrupt")
        #     raise
        if isinstance(exc, SystemExit):
            # Ctrl-D and warm reboot cause this, not bugs
            raise
        else:
            print("Exception:")
            # show stacktrace for debug photos
            try:
                import uio
                import ux
                tmp = uio.StringIO()
                sys.print_exception(exc, tmp)
                msg = tmp.getvalue()
                del tmp
                print(msg)
                ux.show_fatal_error(msg)
            except Exception as exc2:
                sys.print_exception(exc2)
Пример #3
0
    def test_start_callback_is_called(self):
        start = TestStartEnd.Start()

        data = uio.StringIO("ciao")
        sjson.loads(data, start)

        self.assertTrue(start.is_called)
Пример #4
0
    def test_list_parsing(self):
        lis = TestLists.JListObject()

        data = uio.StringIO('[{"key":null}, 1]')
        sjson.loads(data, lis)
        self.assertTrue(lis.is_started)
        self.assertTrue(lis.is_ended)
Пример #5
0
    def test_object_with_a_negative_float(self):
        num = TestObject.JNumObject()

        data = uio.StringIO('{"key":-42.11}')
        sjson.loads(data, num)
        self.assertEqual(num.last_number, -42.11)
        self.assertTrue(num.end)
Пример #6
0
    def test_object_with_a_positive_integer(self):
        num = TestObject.JNumObject()

        data = uio.StringIO('{"key":42}')
        sjson.loads(data, num)
        self.assertEqual(num.last_number, 42)
        self.assertTrue(num.end)
Пример #7
0
    def test_end_callback_is_called(self):
        end = TestStartEnd.End()

        data = uio.StringIO("ciao")
        sjson.loads(data, end)

        self.assertTrue(end.is_called)
Пример #8
0
    def render_warnings(self):
        with uio.StringIO() as msg:
            # # mention warning at top
            # wl = len(self.psbt.warnings)
            # if wl == 1:
            #     msg.write('(1 warning below)\n\n')
            # elif wl >= 2:
            #     msg.write('(%d warnings below)\n\n' % wl)

            # gc.collect()

            fee = self.psbt.calculate_fee()
            if fee is not None:
                msg.write("Network Fee:\n%s %s" %
                            self.chain.render_value(fee))

            # # NEW: show where all the change outputs are going
            # self.render_change_text(msg)
            # gc.collect()

            if self.psbt.warnings and len(self.psbt.warnings) > 0:
                msg.write('\n\nWarnings:')
                for label, m in self.psbt.warnings:
                    msg.write('\n%s: %s\n' % (label, m))
            
            return msg.getvalue()
Пример #9
0
def run_class(c, test_result):
    o = c()
    set_up = getattr(o, "setUp", lambda: None)
    tear_down = getattr(o, "tearDown", lambda: None)
    for name in dir(o):
        if name.startswith("test"):
            print("%s (%s) ..." % (name, c.__qualname__), end="")
            m = getattr(o, name)
            set_up()
            try:
                test_result.testsRun += 1
                m()
                print(" ok")
            except SkipTest as e:
                print(" skipped:", e.args[0])
                test_result.skippedNum += 1
            except Exception as e:
                print(" FAIL")
                test_result.failuresNum += 1
                with uio.StringIO() as s:
                    sys.print_exception(e, s)
                    print(s.getvalue())
                #raise
                continue
            finally:
                tear_down()
Пример #10
0
 def run(self):
     try:
         self.run_inner()
     except Exception as e:
         import uio
         string_io = uio.StringIO()
         sys.print_exception(e, string_io)
         s = string_io.getvalue()
         print("showing blue screen:", s)
         lcd.clear(lcd.BLUE)
         msg = "** " + str(e)
         chunks, chunk_size = len(msg), 29
         msg_lines = [
             msg[i:i + chunk_size] for i in range(0, chunks, chunk_size)
         ]
         # "A problem has been detected and windows has been shut down to prevent damange to your m5stickv :)"
         lcd.draw_string(1, 1, "A problem has been detected and windows",
                         lcd.WHITE, lcd.BLUE)
         lcd.draw_string(1, 1 + 5 + 16, "Technical information:", lcd.WHITE,
                         lcd.BLUE)
         current_y = 1 + 5 + 16 * 2
         for line in msg_lines:
             lcd.draw_string(1, current_y, line, lcd.WHITE, lcd.BLUE)
             current_y += 16
             if current_y >= lcd.height():
                 break
         lcd.draw_string(1, current_y, s, lcd.WHITE, lcd.BLUE)
         lcd.draw_string(1,
                         lcd.height() - 17,
                         "Will reboot after 10 seconds..", lcd.WHITE,
                         lcd.BLUE)
         time.sleep(10)
         machine.reset()
Пример #11
0
def error_view(exc):
    """
    Return an HTTP 500 response with a JSON body of the error detail.

    This function may be monkey-patched to override the default error response. It must
    return a dict assembled by `send_response`.
    """

    exc_details = uio.StringIO()
    sys.print_exception(exc, exc_details)

    if isinstance(exc, OSError):
        exc_msg = (uerrno.errorcode[exc.args[0]] if len(exc.args) > 0
                   and exc.args[0] in uerrno.errorcode else "")  # noqa
    else:
        exc_msg = exc.args[0] if len(exc.args) > 0 else ""

    return response(
        500,
        ujson.dumps({
            "error":
            "{}: {}".format(exc.__class__.__name__, exc_msg),
            "traceback": [
                line.strip() for line in exc_details.getvalue().split("\n")
                if line and "Traceback" not in line  # noqa
                and exc.__class__.__name__ not in line  # noqa
            ],
        }),
        CT_JSON,
    )
Пример #12
0
    def log_stop(self, stop_exception):
        if stop_exception:
            stop_out = uio.StringIO()

            print(">" * 80, file=stop_out)
            print(" Stopped at " + str(time.localtime()[:6]), file=stop_out)
            print("-" * 80, file=stop_out)

            if stop_exception:
                print("Exception: ", file=stop_out)
                sys.print_exception(stop_exception, stop_out) # pylint: disable=E1101
                print("-" * 80, file=stop_out)

            print(str(self.gps_poller), end='', file=stop_out)
            print("<" * 80, file=stop_out)

            stop_msg = stop_out.getvalue()

            try:
                with open("/sd/stoplog.txt", "a+") as fh:
                    print(stop_msg, file=fh)
            except:
                pass

            if self.stdout_echo:
                print(stop_msg)

        try:
            os.unmount("/sd") # pylint: disable=E1101
            print("** Unmounted /sd")
        except:
            pass
Пример #13
0
    def test_object_key(self):
        obj = TestObject.JObjectKey()

        data = uio.StringIO('{"key":True}')
        sjson.loads(data, obj)

        self.assertEqual(obj.last_key, "key")
Пример #14
0
def die_with_debug(exc):
    from usb import is_vcp_active
    is_debug = is_vcp_active()

    if is_debug and isinstance(exc, KeyboardInterrupt):
        # preserve GUI state, but want to see where we are
        print("KeyboardInterrupt")
        raise exc
    elif isinstance(exc, SystemExit):
        # Ctrl-D and warm reboot cause this, not bugs
        raise exc
    else:
        # show stacktrace for debug photos
        try:
            import uio, ux
            tmp = uio.StringIO()
            sys.print_exception(exc, tmp)
            msg = tmp.getvalue()
            del tmp
            print(msg)
            ux.show_fatal_error(msg)
        except:
            pass

        # securely die (wipe memory)
        if not is_debug:
            try:
                import callgate
                callgate.show_logout(1)
            except:
                pass
Пример #15
0
def sub_cb(topic, msg):
    """Received messages from subscriptions will be delivered to this callback."""
    try:

        if (msg is not None):
            img = ujson.loads(
                msg
            )  # parse the given message stream, interpreting it as a JSON string and deserialising the data to a Python object

            if (img is not None) and (img["height"] <= cols) and (img["width"]
                                                                  <= rows):
                for i in range(n):
                    pixel = [(img["data"][i][0] >> 1),
                             (img["data"][i][1] >> 1),
                             (img["data"][i][2] >> 1)]
                    np[i] = pixel  # set every pixels to the colour of the imagepixels in the JSON object

            np.write()  # write data to all pixels

            print(topic + '\t' + ujson.dumps(msg))

    except ValueError as e:

        buf = uio.StringIO()
        sys.print_exception(e, buf)
        print("JSON string is not correctly formed")
Пример #16
0
def problem_file_line(exc):
    # return a string of just the filename.py and line number where
    # an exception occured. Best used on AssertionError.
    import uio, sys, ure

    tmp = uio.StringIO()
    sys.print_exception(exc, tmp)
    lines = tmp.getvalue().split('\n')[-3:]
    del tmp

    # convert:
    #   File "main.py", line 63, in interact
    #    into just:
    #   main.py:63
    #
    # on simulator, huge path is included, remove that too

    rv = None
    for ln in lines:
        mat = ure.match(r'.*"(/.*/|)(.*)", line (.*), ', ln)
        if mat:
            try:
                rv = mat.group(2) + ':' + mat.group(3)
            except:
                pass

    return rv or str(exc) or 'Exception'
Пример #17
0
    def test_format_with_error(self):
        msg = 'Hello'
        level = 'info'
        now = 'now'
        err = Exception('Some error')
        try:
            raise err
        except Exception as e:
            err = e

        err_data = None
        if err != None:
            err_data = uio.StringIO()
            sys.print_exception(err, err_data)
            err_data.seek(0)
            err_data = err_data.read().strip().split('\n')

        want_payload = {
            'msg': msg,
            'time': now,
            'level': level,
            'v': 1,
        }
        want_payload['err'] = err_data[-1]
        want_payload['trace'] = err_data[:-1]
        got_message = logger.json_formatter(msg=msg,
                                            level=level,
                                            now=now,
                                            err=err)
        self.assertEqual(got_message, ujson.dumps(want_payload))
Пример #18
0
def go():
    # Wrapper for better error handling/recovery at top level.
    #
    try:
        loop.run_forever()
    except BaseException as exc:
        from usb import is_vcp_active
        is_debug = is_vcp_active()

        if is_debug and isinstance(exc, KeyboardInterrupt):
            # preserve GUI state, but want to see where we are
            print("KeyboardInterrupt")
            raise
        elif isinstance(exc, SystemExit):
            # Ctrl-D and warm reboot cause this, not bugs
            raise
        else:
            # show stacktrace for debug photos
            try:
                import uio, ux
                tmp = uio.StringIO()
                sys.print_exception(exc, tmp)
                msg = tmp.getvalue()
                del tmp
                print(msg)
                ux.show_fatal_error(msg)
            except: pass

            # securely die (wipe memory)
            if not is_debug:
                try:
                    import callgate
                    callgate.show_logout(1)
                except: pass
Пример #19
0
async def ms_wallet_detail(menu, label, item):
    # show details of single multisig wallet, offer to delete
    import chains

    ms = item.arg
    msg = uio.StringIO()

    msg.write('''
Policy: {M} of {N}
Blockchain: {ctype}
Addresses:
  {at}
Derivation:
  m/{der}

'''.format(M=ms.M,
           N=ms.N,
           ctype=ms.chain_type,
           der=ms.common_prefix or "?'",
           at=MultisigWallet.render_addr_fmt(ms.addr_fmt)))

    # concern: the order of keys here is non-deterministic
    for idx, (xfp, xpub) in enumerate(ms.xpubs):
        if idx:
            msg.write('\n')
        msg.write('%s:\n%s\n' % (xfp2str(xfp), xpub))

    await ux_show_story(msg, title=ms.name)
Пример #20
0
def do_usb_command(cmd, args):
    # TESTING commands!
    # - only to be implemented on the simulator!!
    # - pleaes don't freak out, stay calm
    # - if you can trick us into running this, can run anything worse directly
    # - and we don't ship this code on the real product, only part of simulator

    if cmd == 'XKEY':
        from main import numpad
        try:
            numpad.inject(str(args, 'ascii'))
        except: pass
        return

    try:
        if cmd == 'EVAL':
            return b'biny' + repr(eval(str(args, 'utf8'))).encode()

        if cmd == 'EXEC':
            RV = uio.BytesIO()
            exec(str(args, 'utf8'), None, dict(RV=RV))
            return b'biny' + RV.getvalue()

    except BaseException as exc:
        tmp = uio.StringIO()
        sys.print_exception(exc, tmp)
        return b'biny' + tmp.getvalue().encode()

    return b'err_Unknown SIMULATOR cmd'
    async def show_detail(self, verbose=True):
        # Show the xpubs; might be 2k or more rendered.
        msg = uio.StringIO()

        if verbose:
            msg.write('''
Policy: {M} of {N}
Blockchain: {ctype}
Addresses:
  {at}\n\n'''.format(M=self.M, N=self.N, ctype=self.chain_type,
            at=self.render_addr_fmt(self.addr_fmt)))

        # concern: the order of keys here is non-deterministic
        for idx, (xfp, deriv, xpub) in enumerate(self.xpubs):
            if idx:
                msg.write('\n---===---\n\n')

            msg.write('%s:\n  %s\n\n%s\n' % (xfp2str(xfp), deriv, xpub))

            if self.addr_fmt != AF_P2SH:
                # SLIP-132 format [yz]pubs here when not p2sh mode.
                # - has same info as proper bitcoin serialization, but looks much different
                node = self.chain.deserialize_node(xpub, AF_P2SH)
                xp = self.chain.serialize_public(node, self.addr_fmt)

                msg.write('\nSLIP-132 equiv:\n%s\n' % xp)

        return await ux_show_story(msg, title=self.name)
Пример #22
0
def exception_output(e):
    global lang, interface_strings

    lang = product_lang()

    if lang == 'zh-cn':
        image.font_load(image.UTF8, 16, 16, 0x753000)
        lang = 'zh'

    pic_path = '/flash/error_' + lang + '.jpg'

    string_io = uio.StringIO()
    sys.print_exception(e, string_io)
    s = string_io.getvalue()

    print(s)

    if str(e) == "[Errno 5] EIO" and 'File "maix_motor.py"' in s:
        draw_on_image(pic_path, interface_strings[lang]["EIO Error - please turn on the power switch and reboot MARK"], 10, 10 , space = (lang == 'zh') )
        sys.exit()
    elif str(e) == "[Errno 5] EIO":
        restore_backup(filename='user.py')
    try:
        img = image.Image(pic_path)
    except:
        img = image.Image()

    image.font_free()

    a = img.draw_string(5, 5, s, scale=1, color=(255,0,0), x_spacing=1, mono_space=0)
    lcd.display(img)
    del(img)

    time.sleep(2)
Пример #23
0
 def run():
     nonlocal output
     for _ in range(loops):
         stream = io.StringIO()
         solve_file(board, strategy, order, stream)
         output = stream.getvalue()
         stream = None
Пример #24
0
    def render_change_text(self):
        # Produce text report of what the "change" outputs are (based on our opinion).
        # - we don't really expect all users to verify these outputs, but just in case.
        # - show the total amount, and list addresses
        with uio.StringIO() as msg:
            msg.write('Change Amount:')
            total = 0
            addrs = []
            for idx, tx_out in self.psbt.output_iter():
                outp = self.psbt.outputs[idx]
                if not outp.is_change:
                    continue
                total += tx_out.nValue
                addrs.append(self.chain.render_address(tx_out.scriptPubKey))

            if not addrs:
                msg.write('\nNo change')
                return msg.getvalue()

            total_val = ' '.join(self.chain.render_value(total))

            msg.write("\n%s\n" % total_val)

            if len(addrs) == 1:
                msg.write('\nChange Address:\n%s\n' % addrs[0])
            else:
                msg.write('\nChange Addresses:\n\n')
                for a in addrs:
                    msg.write('%s\n\n' % a)

            return msg.getvalue()
Пример #25
0
    def test_object_with_a_boolean_False(self):
        obj = TestObject.JBoolObject()

        data = uio.StringIO('{"key":false}')
        sjson.loads(data, obj)

        self.assertEqual(obj.last_bool, False)
Пример #26
0
def lcd_show_except(e):
    import uio
    err_str = uio.StringIO()
    sys.print_exception(e, err_str)
    err_str = err_str.getvalue()
    img = image.Image(size=(224, 224))
    img.draw_string(0, 10, err_str, scale=1, color=(0xff, 0x00, 0x00))
    lcd.display(img)
Пример #27
0
    def test_object(self):
        obj = TestObject.JObject()

        data = uio.StringIO('{"ciao"}')
        sjson.loads(data, obj)

        self.assertTrue(obj.is_start_called)
        self.assertTrue(obj.is_end_called)
Пример #28
0
    def test_object_key_with_value_sting(self):
        obj = TestObject.JObjectKey()

        data = uio.StringIO('{"key":"value"}')
        sjson.loads(data, obj)

        self.assertEqual(obj.last_key, "key")
        self.assertEqual(obj.last_string, "value")
Пример #29
0
    def test_object_with_two_string_keys(self):
        obj = TestObject.JObjectKey()

        data = uio.StringIO('{"key1":"value1", "key2": "value2"}')
        sjson.loads(data, obj)

        self.assertEqual(obj.last_key, "key2")
        self.assertEqual(obj.last_string, "value2")
Пример #30
0
    def test_object_no_obj(self):
        obj = TestObject.JObject()

        data = uio.StringIO("ciao")
        sjson.loads(data, obj)

        self.assertFalse(obj.is_start_called)
        self.assertFalse(obj.is_end_called)