def dformat(data, indent=0):
    padding = ' ' * indent
    from uio import StringIO
    buffer = StringIO()
    for key in sorted(data.keys()):
        value = data[key]
        buffer.write('{}{}: {}\n'.format(padding, key, value))
    return buffer.getvalue()
    def print_bootscreen(self):
        """
        Print bootscreen.

        This contains important details about your device
        and the operating system running on it.
        """

        if not self.settings.get('main.logging.enabled', False):
            return

        # Todo: Maybe refactor to TerkinDatalogger.
        from uio import StringIO
        buffer = StringIO()

        def add(item=''):
            buffer.write(item)
            buffer.write('\n')

        # Program name and version.
        title = '{} {}'.format(self.name, self.version)

        add()
        add('=' * len(title))
        add(title)
        add('=' * len(title))

        # Machine runtime information.
        add('CPU freq     {} MHz'.format(machine.freq() / 1000000))
        add('Device id    {}'.format(self.device_id))
        add()

        # System memory info (in bytes)
        if hasattr(machine, 'info'):
            machine.info()
            add()

        # TODO: Python runtime information.
        add('{:8}: {}'.format('Python', sys.version))
        """
        >>> import os; os.uname()
        (sysname='FiPy', nodename='FiPy', release='1.20.0.rc7', version='v1.9.4-2833cf5 on 2019-02-08', machine='FiPy with ESP32', lorawan='1.0.2', sigfox='1.0.1')
        """
        runtime_info = os.uname()
        for key in dir(runtime_info):
            if key == '__class__':
                continue
            value = getattr(runtime_info, key)
            #print('value:', value)
            add('{:8}: {}'.format(key, value))
        add()
        add()

        # Todo: Add program authors, contributors and credits.

        log.info('\n' + buffer.getvalue())
Beispiel #3
0
def ddformat(data, indent=0):
    padding = ' ' * indent
    from uio import StringIO
    buffer = StringIO()
    for key in sorted(data.keys()):
        item = data[key]
        value = item['value']
        text = item.get('description', '')
        buffer.write('{}{:<40}{:>10}    {}\n'.format(padding, key, value, text))
    return buffer.getvalue()
Beispiel #4
0
 def packtabs(self, s):
     sb = StringIO()
     for i in range(0, len(s), 8):
         c = s[i:i + 8]
         cr = c.rstrip(" ")
         if (len(c) - len(cr)) > 1:
             sb.write(cr + "\t")
         else:
             sb.write(c)
     return sb.getvalue()
Beispiel #5
0
def checkError(type_msg, message):
    try:
        s = StringIO()
        err = sys.print_exception(message, s)
        msg_complete = str(type_msg) + " - " + str(s.getvalue())
        print("Error control: " + str(msg_complete))
        saveErrorInFlash(str(type_msg) + str(msg_complete))
        utime.sleep(5)
        if 'I2C bus error' in str(msg_complete):
            #TODO Sometimes when reading the battery level it says I2C Bus Error. Check solution
            pass
            # machine.reset()
        if 'memory' in str(msg_complete):
            machine.reset()
    except BaseException as e:
        err = sys.print_exception(e, s)
        saveErrorInFlash("Error managing error issuer: " + str(s.getvalue()))
        utime.sleep(5)
        machine.reset()
Beispiel #6
0
    def exception_str(e):
        from uio import StringIO
        s = StringIO()
        sys.print_exception(e, s)
        s = s.getvalue().split('\n')
        l = len(s)
        line = s[l - 3].split(',')[1].strip()
        error = s[l - 2].strip()

        return "Error in " + line + "\n" + error
 def packtabs(self, s):
     sb = StringIO()
     for i in range(0, len(s), 8):
         c = s[i:i + 8]
         cr = c.rstrip(" ")
         if (len(c) - len(cr)) > 1:
             sb.write(cr + "\t") 
         else:
             sb.write(c)
     return sb.getvalue()
    def packtabs(self, s):

        try: from uio import StringIO
        except: from _io import StringIO

        sb = StringIO()
        for i in range(0, len(s), 8):
            c = s[i:i + 8]
            cr = c.rstrip(" ")
            if (len(c) - len(cr)) > 1:
                sb.write(cr + "\t") ## Spaces at the end of a section
            else: sb.write(c)
        return sb.getvalue()
Beispiel #9
0
def expandtabs(s, tab_size=8):
    if '\t' in s:
        sb = StringIO()
        pos = 0
        for c in s:
            if c == '\t': ## tab is seen
                sb.write(" " * (tab_size - pos % tab_size)) ## replace by space
                pos += tab_size - pos % tab_size
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue(), True
    else:
        return s, False
Beispiel #10
0
def expandtabs(s):
    if '\t' in s:
        sb = StringIO()
        pos = 0
        for c in s:
            if c == '\t': 
                sb.write(" " * (8 - pos % 8)) 
                pos += 8 - pos % 8
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue(), True
    else:
        return s, False
Beispiel #11
0
def expandtabs(s):
    if '\t' in s:
        sb = StringIO()
        pos = 0
        for c in s:
            if c == '\t':
                sb.write(" " * (8 - pos % 8))
                pos += 8 - pos % 8
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue(), True
    else:
        return s, False
Beispiel #12
0
 def expandtabs(self, s):
     if '\t' in s:
         self.write_tabs = True
         sb = StringIO()
         pos = 0
         for c in s:
             if c == '\t': ## tab is seen
                 sb.write(" " * (8 - pos % 8)) ## replace by space
                 pos += 8 - pos % 8
             else:
                 sb.write(c)
                 pos += 1
         return sb.getvalue()
     else:
         return s
Beispiel #13
0
def expandtabs(s):
    if '\t' in s:
        Editor.tab_seen = 'y'
        sb = StringIO()
        pos = 0
        for c in s:
            if c == '\t':  ## tab is seen
                sb.write(" " * (8 - pos % 8))  ## replace by space
                pos += 8 - pos % 8
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue()
    else:
        return s
Beispiel #14
0
def ddformat(data, indent=0):
    """

    :param data: 
    :param indent:  (Default value = 0)

    """
    padding = ' ' * indent
    from uio import StringIO
    buffer = StringIO()
    for key in sorted(data.keys()):
        item = data[key]
        value = item['value']
        text = item.get('description', '')
        buffer.write('{}{:<35}{:>25} {:>25}\n'.format(padding, key, value, text))
    return buffer.getvalue()
Beispiel #15
0
def expandtabs(s):
    from uio import StringIO

    if '\t' in s:
        sb = StringIO()
        pos = 0
        for c in s:
            if c == '\t':  ## tab is seen
                sb.write(" " * (8 - pos % 8))  ## replace by space
                pos += 8 - pos % 8
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue()
    else:
        return s
Beispiel #16
0
def expandtabs(s):
    try:
        from uio import StringIO
    except:
        from _io import StringIO
    if '\t' in s:
        sb = StringIO()
        pos = 0
        for c in s:
            if c == '\t':
                sb.write(" " * (8 - pos % 8))
                pos += 8 - pos % 8
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue()
    else:
        return s
Beispiel #17
0
def expandtabs(s):
    try:
        from uio import StringIO
    except:
        from _io import StringIO
    if "\t" in s:
        Editor.tab_seen = "y"
        sb = StringIO()
        pos = 0
        for c in s:
            if c == "\t":
                sb.write(" " * (8 - pos % 8))
                pos += 8 - pos % 8
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue()
    else:
        return s
Beispiel #18
0
def expandtabs(s):
    try: from uio import StringIO
    except: from _io import StringIO

    if '\t' in s:
#ifndef BASIC
        Editor.tab_seen = 'y'
#endif
        sb = StringIO()
        pos = 0
        for c in s:
            if c == '\t': ## tab is seen
                sb.write(" " * (8 - pos % 8)) ## replace by space
                pos += 8 - pos % 8
            else:
                sb.write(c)
                pos += 1
        return sb.getvalue()
    else:
        return s
Beispiel #19
0
    def to_line_protocol(self):
        from uio import StringIO
        stream = StringIO()

        stream.write(self.name)
        stream.write(',')

        def formatDict(dict):
            first = True
            for key, value in dict.items():
                if not first:
                    stream.write(',')
                else:
                    first = False

                arg = '{0}={1}'.format(key, value)
                stream.write(arg)

        formatDict(self.tags)
        stream.write(' ')
        formatDict(self.fields)

        return stream.getvalue()
Beispiel #20
0
def generate_public_contents():
    # Generate public details about wallet.
    #
    # simple text format:
    #   key = value
    # or #comments
    # but value is JSON
    from main import settings
    from public_constants import AF_CLASSIC

    num_rx = 5

    chain = chains.current_chain()

    with stash.SensitiveValues() as sv:

        yield ('''\
# Coldcard Wallet Summary File
## For wallet with master key fingerprint: {xfp}

Wallet operates on blockchain: {nb}

For BIP44, this is coin_type '{ct}', and internally we use
symbol {sym} for this blockchain.

## IMPORTANT WARNING

Do **not** deposit to any address in this file unless you have a working
wallet system that is ready to handle the funds at that address!

## Top-level, 'master' extended public key ('m/'):

{xpub}

What follows are derived public keys and payment addresses, as may
be needed for different systems.


'''.format(nb=chain.name,
           xpub=chain.serialize_public(sv.node),
           sym=chain.ctype,
           ct=chain.b44_cointype,
           xfp=xfp2str(sv.node.my_fingerprint())))

        for name, path, addr_fmt in chains.CommonDerivations:

            if '{coin_type}' in path:
                path = path.replace('{coin_type}', str(chain.b44_cointype))

            if '{' in name:
                name = name.format(core_name=chain.core_name)

            show_slip132 = ('Core' not in name)

            yield ('''## For {name}: {path}\n\n'''.format(name=name,
                                                          path=path))
            yield (
                '''First %d receive addresses (account=0, change=0):\n\n''' %
                num_rx)

            submaster = None
            for i in range(num_rx):
                subpath = path.format(account=0, change=0, idx=i)

                # find the prefix of the path that is hardneded
                if "'" in subpath:
                    hard_sub = subpath.rsplit("'", 1)[0] + "'"
                else:
                    hard_sub = 'm'

                if hard_sub != submaster:
                    # dump the xpub needed

                    if submaster:
                        yield "\n"

                    node = sv.derive_path(hard_sub, register=False)
                    yield ("%s => %s\n" %
                           (hard_sub, chain.serialize_public(node)))
                    if show_slip132 and addr_fmt != AF_CLASSIC and (
                            addr_fmt in chain.slip132):
                        yield (
                            "%s => %s   ##SLIP-132##\n" %
                            (hard_sub, chain.serialize_public(node, addr_fmt)))

                    submaster = hard_sub
                    node.blank()
                    del node

                # show the payment address
                node = sv.derive_path(subpath, register=False)
                yield ('%s => %s\n' % (subpath, chain.address(node, addr_fmt)))

                node.blank()
                del node

            yield ('\n\n')

    from multisig import MultisigWallet
    if MultisigWallet.exists():
        yield '\n# Your Multisig Wallets\n\n'
        from uio import StringIO

        for ms in MultisigWallet.get_all():
            fp = StringIO()

            ms.render_export(fp)
            print("\n---\n", file=fp)

            yield fp.getvalue()
            del fp
Beispiel #21
0
def render_backup_contents():
    # simple text format:
    #   key = value
    # or #comments
    # but value is JSON
    from main import settings, pa

    rv = StringIO()

    def COMMENT(val=None):
        if val:
            rv.write('\n# %s\n' % val)
        else:
            rv.write('\n')

    def ADD(key, val):
        rv.write('%s = %s\n' % (key, ujson.dumps(val)))

    rv.write('# Coldcard backup file! DO NOT CHANGE.\n')

    chain = chains.current_chain()

    COMMENT('Private key details: ' + chain.name)

    with stash.SensitiveValues(for_backup=True) as sv:

        if sv.mode == 'words':
            ADD('mnemonic', tcc.bip39.from_data(sv.raw))

        if sv.mode == 'master':
            ADD('bip32_master_key', b2a_hex(sv.raw))

        ADD('chain', chain.ctype)
        ADD('xprv', chain.serialize_private(sv.node))
        ADD('xpub', chain.serialize_public(sv.node))

        # BTW: everything is really a duplicate of this value
        ADD('raw_secret', b2a_hex(sv.secret).rstrip(b'0'))

        if pa.has_duress_pin():
            COMMENT('Duress Wallet (informational)')
            dpk = sv.duress_root()
            ADD('duress_xprv', chain.serialize_private(dpk))
            ADD('duress_xpub', chain.serialize_public(dpk))

        if version.has_608:
            # save the so-called long-secret
            ADD('long_secret', b2a_hex(pa.ls_fetch()))

    COMMENT('Firmware version (informational)')
    date, vers, timestamp = version.get_mpy_version()[0:3]
    ADD('fw_date', date)
    ADD('fw_version', vers)
    ADD('fw_timestamp', timestamp)
    ADD('serial', version.serial_number())

    COMMENT('User preferences')

    # user preferences
    for k, v in settings.current.items():
        if k[0] == '_': continue  # debug stuff in simulator
        if k == 'xpub': continue  # redundant, and wrong if bip39pw
        if k == 'xfp': continue  # redundant, and wrong if bip39pw
        ADD('setting.' + k, v)

    if version.has_fatram:
        import hsm
        if hsm.hsm_policy_available():
            ADD('hsm_policy', hsm.capture_backup())

    rv.write('\n# EOF\n')

    return rv.getvalue()
Beispiel #22
0
try:
    from uio import StringIO
    import ujson as json
except:
    try:
        from io import StringIO
        import json
    except ImportError:
        print("SKIP")
        raise SystemExit

s = StringIO()
json.dump(False, s)
print(s.getvalue())

s = StringIO()
json.dump({"a": (2, [3, None])}, s)
print(s.getvalue())

# dump to a small-int not allowed
try:
    json.dump(123, 1)
except (AttributeError, OSError):  # CPython and uPy have different errors
    print('Exception')

# dump to an object not allowed
try:
    json.dump(123, {})
except (AttributeError, OSError):  # CPython and uPy have different errors
    print('Exception')
Beispiel #23
0
try:
    from uio import StringIO
    import ujson as json
except:
    try:
        from io import StringIO
        import json
    except ImportError:
        print("SKIP")
        raise SystemExit

s = StringIO()
json.dump(False, s)
print(s.getvalue())

s = StringIO()
json.dump({"a": (2, [3, None])}, s)
print(s.getvalue())
Beispiel #24
0
def ESP_init(cl_s=b'esp001data'):
    f_log = StringIO()
    f_log.write('{"ESP_init":{\n')
    atemp = '"DATA_topic":"%s",\n' % (cl_s.decode())
    print(atemp)
    f_log.write(atemp)
    try:
        if ds_tm.lost_time():
            atemp = '"DS3231":"lost_time",\n'
            print(atemp)
            f_log.write(atemp)
            raise
        else:
            ds_tm.settime()
            atemp = '"DS3231 SetTime":"OK",\n'
            print(atemp)
            f_log.write(atemp)
            try:
                ntptime_cn.time()
                utime.sleep_ms(200)
                ntptime_cn.settime()
                ds_tm.sync_rtc2ntp()
                ds_tm.settime()
                atemp = '"NTP & RTC SyncTime":"OK",\n'
                print(atemp)
                f_log.write(atemp)
            except:
                pass
    except:
        ntptime_cn.time()
        utime.sleep(3)
        ntptime_cn.settime()
        atemp = '"NTP SetTime":"OK",\n'
        print(atemp)
        f_log.write(atemp)
        try:
            ds_tm.sync_rtc2ntp()
            ds_tm.settime()
            atemp = '"NTP & RTC SyncTime":"OK",\n'
            print(atemp)
            f_log.write(atemp)
        except:
            pass
    finally:
        atemp = '"Time":"%d-%02d-%02d %02d:%02d:%02d GMT",\n"Day_W":%d,"Day_Y":%d,\n' % (
            utime.localtime())
        print(atemp)
        f_log.write(atemp)
    try:
        atemp = '"DS3231 SQW":"1Hz Out Start%d",\n' % (ds_tm.sqw_1hz())
        print(atemp)
        f_log.write(atemp)
    except:
        atemp = '"DS3231 SQW":"1Hz Out ERROR",\n'
        print(atemp)
        f_log.write(atemp)
    try:
        sensor3 = SHT30()
        temperature, humidity = sensor3.measure()
        del sensor3
        atemp = '"ambient Temperature":"%f ºC","ambient Humidity":"%f %%",\n' % (
            temperature, humidity)
        print(atemp)
        f_log.write(atemp)
        atemp = '"Sensor SHT30":"OK",\n'
        print(atemp)
        f_log.write(atemp)
    except:
        pass
    try:
        sensor_k = MAX6675()
        atemp = '"K Thermocouple":"%f ºC",\n"Sensor MAX6675":"OK"}}..' % (
            sensor_k.measure())
        del sensor_k
        print(atemp)
        f_log.write(atemp)
    except:
        pass
    f_str = f_log.getvalue()
    f_log.close()
    return f_str
Beispiel #25
0
    def print_bootscreen(self):
        """Print bootscreen.
        
        This contains important details about your device
        and the operating system running on it.


        """

        if not self.settings.get('main.logging.enabled', False):
            return

        # Todo: Maybe refactor to TerkinDatalogger.
        from uio import StringIO
        buffer = StringIO()

        def add(item=''):
            """

            :param item:  (Default value = '')

            """
            buffer.write(item)
            buffer.write('\n')

        # Program name and version.
        title = '{} {}'.format(self.name, self.version)

        add()
        add('=' * len(title))
        add(title)
        add('=' * len(title))

        # Machine runtime information.
        frequency = machine.freq() / 1000000

        add('Device id    {}'.format(self.device_id))
        add()
        add('CPU freq     {}   MHz'.format(frequency))
        try:
            import pycom
            free_heap = pycom.get_free_heap()
            add('{:13}{:>7} {}'.format('Free heap', free_heap[0] / 1000.0,
                                       'kB'))
            add('{:13}{:>7} {}'.format('Free PSRAM', free_heap[1] / 1000.0,
                                       'kB'))
        except:
            pass
        add()

        # System memory info (in bytes).
        """
        if hasattr(machine, 'info'):
            machine.info()
            add()
        """

        # TODO: Python runtime information.
        add('{:8}: {}'.format('Python', sys.version.replace('\n', '')))
        add('{:8}: {}'.format('platform', sys.platform))
        """
        >>> import os; os.uname()
        (sysname='FiPy', nodename='FiPy', release='1.20.0.rc7', version='v1.9.4-2833cf5 on 2019-02-08', machine='FiPy with ESP32', lorawan='1.0.2', sigfox='1.0.1')
        """
        runtime_info = os.uname()
        #print(dir(runtime_info))
        for key in dir(runtime_info):
            if key.startswith('__') or key.startswith('n_'):
                continue
            value = getattr(runtime_info, key)
            if callable(value):
                continue
            #print('value:', value)
            add('{:8}: {}'.format(key, value))
        add()

        # Todo: Add program authors, contributors and credits.

        log.info('\n' + buffer.getvalue())
Beispiel #26
0
    ts1_value = t_scale1.raw_value()
    ts2_value = t_scale2.raw_value()

    # measure bottom
    bs1_value = b_scale1.raw_value()
    bs2_value = b_scale2.raw_value()

    if (serial_run % SERIAL_DEBUG_FRAC == 0):
        print('data:t:' +
              str((ts1_value + ts2_value) * t_calibration_factor / 1000))
        print('data:b:' +
              str((bs1_value + bs2_value) * b_calibration_factor / 1000))
        serial_run = 0

    try:
        # send ble data
        sendData((ts1_value + ts2_value) * t_calibration_factor / 1000,
                 (bs1_value + bs2_value) * b_calibration_factor / 1000)
    except Exception as e:
        import sys
        from uio import StringIO

        s = StringIO()
        sys.print_exception(e, s)

        print("an error occured \n " + s.getvalue())

        pass

    serial_run += 1