Esempio n. 1
0
    def get_id_hash(self):
        # hash over card config and serial # details
        # - stupidly it's over the repr of a functions' result
        import ngu

        info = pyb.SDCard().info()
        assert info 

        if len(info) == 3:
            # expected in v4
            csd_cid = pyb.SDCard().ident()
            info = tuple(list(info) + list(csd_cid))

        return ngu.hash.sha256s(repr(info))
Esempio n. 2
0
def wipe_microsd_card():
    import ckcc, pyb
    from main import dis

    try:
        os.umount('/sd')
    except:
        pass

    sd = pyb.SDCard()
    assert sd

    if not sd.present(): return

    # power cycle so card details (like size) are re-read from current card
    sd.power(0)
    sd.power(1)

    dis.fullscreen('Part Erase...')
    cutoff = 1024  # arbitrary
    blk = bytearray(512)

    for bnum in range(cutoff):
        ckcc.rng_bytes(blk)
        sd.writeblocks(bnum, blk)
        dis.progress_bar_show(bnum / cutoff)

    dis.fullscreen('Formating...')

    # remount, with newfs option
    os.mount(sd, '/sd', readonly=0, mkfs=1)
Esempio n. 3
0
def _try_microsd(bad_fs_ok=False):
    # Power up, mount the SD card, return False if we can't for some reason.
    #
    # If we're about to reformat, we don't need a working filesystem

    sd = pyb.SDCard()

    if not sd.present():
        return False

    if ckcc.is_simulator():
        return True

    try:
        # already mounted and ready?
        st = os.statvfs('/sd')
        return True
    except OSError:
        pass

    try:
        sd.power(1)
        os.mount(sd, '/sd', readonly=0, mkfs=0)
        st = os.statvfs('/sd')

        return True

    except OSError as exc:
        # corrupt or unformated SD card (or something)
        if bad_fs_ok: return True
        #sys.print_exception(exc)
        return False
Esempio n. 4
0
    def check_sd(self):

        try:
            os.listdir('/sd')
            print("/sd Mounted")
        except:
            print("SD not found")
            try:
                if pyb.SDCard().present():
                    os.mount(pyb.SDCard(), '/sd')
                    sys.path[1:1] = ['/sd', '/sd/lib']
                    sleep(1)
            except:
                print("Give up on SD")
                return False
        print("SD Mounted")
        return True
Esempio n. 5
0
def wipe_microsd_card():
    # Erase and re-format SD card. Not secure erase, because that is too slow.
    import callgate
    import pyb
    from common import dis

    try:
        os.umount('/sd')
    except:
        pass

    sd = pyb.SDCard()
    assert sd

    if not sd.present():
        return

    # power cycle so card details (like size) are re-read from current card
    sd.power(0)
    sd.power(1)

    dis.fullscreen('Part Erase...')
    cutoff = 1024  # arbitrary
    blk = bytearray(512)

    for bnum in range(cutoff):
        callgate.fill_random(blk)
        sd.writeblocks(bnum, blk)
        dis.progress_bar_show(bnum / cutoff)

    dis.fullscreen('Formating...')

    # remount, with newfs option
    os.mount(sd, '/sd', readonly=0, mkfs=1)

    # done, cleanup
    os.umount('/sd')

    # important: turn off power
    sd = pyb.SDCard()
    sd.power(0)
Esempio n. 6
0
    def recover(self):

        self.active = False

        try:
            os.umount('/sd')
        except:
            pass

        # important: turn off power so touch can work again
        sd = pyb.SDCard()
        sd.power(0)
Esempio n. 7
0
    def recover(self):
        # done using the microSD -- unpower it
        self.active_led.off()

        self.active = False

        try:
            os.umount('/sd')
        except: pass

        # important: turn off power so touch can work again
        sd = pyb.SDCard()
        sd.power(0)
Esempio n. 8
0
    def recover(self):
        # done using the microSD -- unpower it
        from main import numpad

        self.active = False

        try:
            os.umount('/sd')
        except: pass

        # important: turn off power so touch can work again
        sd = pyb.SDCard()
        sd.power(0)

        numpad.start()
pyb.country('GB')  # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU


# https://pybd.io/hw/pybd_sfxw.html
# The CPU frequency can be set to any multiple of 2MHz between 48MHz and 216MHz, via machine.freq(<freq>).
# By default the SF2 model runs at 120MHz and the SF6 model at 144MHz in order to conserve electricity.
# It is possible to go below 48MHz but then the WiFi cannot be used.
# From: https://github.com/micropython/micropython/issues/4662
# This sometimes causes problems with USB and possibly SDCard if done later.
# Best done in boot before usb and sdcard are initialised.
# machine.freq(48000000)  # Set to lowest usable frequency

# https://pybd.io/hw/pybd_sfxw.html
# The board has a built-in micro SD card slot. If an SD card is inserted, by default it will not be automatically
# mount in the board's filesystem but it will be exposed as a mass storage device if USB is used. To automatically
# mount the SD card if it is inserted, put the following in your boot.py:
# Enable power supply to sdcard
pyb.Pin.board.EN_3V3.on()
utime.sleep_ms(10)

if pyb.SDCard().present():
    # Extra delay to let the SDCard start up before mounting.
    utime.sleep_ms(500)
    os.mount(pyb.SDCard(), '/sd')
    pyb.usb_mode('VCP+MSC', msc=(pyb.Flash(), pyb.SDCard()))  # act as a serial and a storage device
else:
    pyb.usb_mode('VCP+MSC')  # act as a serial and a storage device

pyb.main('main.py')  # main script to run after this one run after this one

Esempio n. 10
0
async def test_microsd():
    if ckcc.is_simulator(): return

    async def wait_til_state(want):
        dis.clear()
        dis.text(None, 10, 'MicroSD Card:')
        dis.text(None, 34, 'Remove' if sd.present() else 'Insert', font=FontLarge)
        dis.show()

        while 1:
            if want == sd.present(): return
            await sleep_ms(100)
            if ux_poll_once():
                raise RuntimeError("MicroSD test aborted")

    try:
        import pyb
        sd = pyb.SDCard()
        sd.power(0)

        # test presence switch
        for ph in range(7):
            await wait_til_state(not sd.present())

            if ph >= 2 and sd.present():
                # debounce
                await sleep_ms(100)
                if sd.present(): break
                if ux_poll_once():
                    raise RuntimeError("MicroSD test aborted")

        dis.clear()
        dis.text(None, 10, 'MicroSD Card:')
        dis.text(None, 34, 'Testing', font=FontLarge)
        dis.show()

        # card inserted
        assert sd.present()     #, "SD not present?"

        # power up?
        sd.power(1)
        await sleep_ms(100)

        try:
            blks, bsize, *unused = sd.info()
            assert bsize == 512
        except:
            assert 0        # , "card info"

        # just read it a bit, writing would prove little
        buf = bytearray(512)
        msize = 256*1024
        for addr in range(0, msize, 1024):
            sd.readblocks(addr, buf)
            dis.progress_bar_show(addr/msize)

            if addr == 0:
                assert buf[-2:] == b'\x55\xaa'      # "Bad read"

        # force removal, so cards don't get stuck in finished units
        await wait_til_state(False)

    finally:
        # CRTICAL: power it back down
        sd.power(0)
Esempio n. 11
0
def fpath(fname):
    """A small function to avoid % storage_root everywhere"""
    return "%s%s" % (config.storage_root, fname)


# path to store #reckless entropy
if simulator:
    # create folders for simulator
    maybe_mkdir(config.storage_root)
    maybe_mkdir(fpath("/flash"))
    maybe_mkdir(fpath("/qspi"))
    maybe_mkdir(fpath("/sd"))
else:
    storage_root = ""
    sdcard = pyb.SDCard()
    sdled = pyb.LED(4)
    sdled.off()


def get_version() -> str:
    # version is coming from boot.py if running on the hardware
    try:
        ver = version.split(">")[1].split("</")[0]
        major = int(ver[:2])
        minor = int(ver[2:5])
        patch = int(ver[5:8])
        rc = int(ver[8:])
        ver = "%d.%d.%d" % (major, minor, patch)
        if rc != 99:
            ver += "-rc%d" % rc
Esempio n. 12
0
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import pyb
import os, sys

#pyb.main('main.py') # main script to run after this one
#pyb.usb_mode('CDC+MSC') # act as a serial and a storage device
#pyb.usb_mode('CDC+HID') # act as a serial device and a mouse

if pyb.SDCard().present():
    pyb.usb_mode('VCP+MSC', msc=(pyb.SDCard(), ))  # expose SD card to the PC

    os.mount(pyb.SDCard(), '/sd')
    sys.path[1:1] = ['/sd', '/sd/lib']
    print("SD Mounted")

if pyb.SDCard().present():
    # Try starting from the SD card
    pyb.main('/sd/smain.py')  # main script to run after this one
    print("Started /sd/smain.py")
else:
    # If that fails (no SD card), start the flash
    pyb.main('/flash/main.py')  # main script to run after this one
    print("Started /flash/main.py")
Esempio n. 13
0
    def make_menu(self):
        from menu import MenuItem, MenuSystem
        from actions import goto_top_menu
        from ux import ux_show_story
        from seed import set_bip39_passphrase
        import pyb

        # Very quick check for card not present case.
        if not pyb.SDCard().present():
            return None

        # Read file, decrypt and make a menu to show; OR return None
        # if any error hit.
        try:
            with CardSlot() as card:

                self._calc_key(card)
                if not self.key: return None

                data = self._read(card)

                if not data: return None

        except CardMissingError:
            # not an error: they just aren't using feature
            return None

        # We have a list of xfp+pw fields. Make a menu.

        # Challenge: we need to hint at which is which, but don't want to
        # show the password on-screen.
        # - simple algo: 
        #   - show either first N or last N chars only
        #   - pick which set which is all-unique, if neither, try N+1
        #
        pws = []
        for i in data:
            p = i.get('pw') 
            if p not in pws:
                pws.append(p)

        for N in range(1, 8):
            parts = [i[0:N] + ('*'*(len(i)-N if len(i) > N else 0)) for i in pws]
            if len(set(parts)) == len(pws): break
            parts = [('*'*(len(i)-N if len(i) > N else 0)) + i[-N:] for i in pws]
            if len(set(parts)) == len(pws): break
        else:
            # give up: show it all!
            parts = pws

        async def doit(menu, idx, item):
            # apply the password immediately and drop them at top menu
            set_bip39_passphrase(data[idx]['pw'])

            from nvstore import settings
            from utils import xfp2str
            xfp = settings.get('xfp')

            # verification step; I don't see any way for this to go wrong
            assert xfp == data[idx]['xfp']

            # feedback that it worked
            await ux_show_story("Passphrase restored.", title="[%s]" % xfp2str(xfp))

            goto_top_menu()


        return MenuSystem((MenuItem(label or '(empty)', f=doit) for label in parts))
Esempio n. 14
0
import machine
from machine import Pin
import time
import utime
from scd30 import SCD30
from machine import I2C

errled = LED(1)
led = LED(2)

# Get Sensor, should be scannable here...
i2c = I2C(1)
scd30 = SCD30(i2c, 0x61)

# Make sure we have a SD card!
sd = pyb.SDCard()

if sd.present() != 1:
    errled.on()
    machine.deepsleep()

# Power off the board...
sd.power(0)

en_3v3 = Pin('EN_3V3')
en_3v3.value(0)

while True:
    data = {}
    en_3v3.value(1)
    led.on()
Esempio n. 15
0
 def get_id_hash(self):
     # hash over card config and serial # details
     import tcc
     info = pyb.SDCard().info()
     assert info and len(info) >= 5  # need micropython changes
     return tcc.sha256(repr(info)).digest()
Esempio n. 16
0
# Mount the SD card
import pyb
import os
sd = pyb.SDCard()
os.mount(sd, '/sd')
os.chdir('/sd')
Esempio n. 17
0
async def test_microsd():
    if ckcc.is_simulator(): return

    from main import numpad
    numpad.stop()

    try:
        import pyb
        sd = pyb.SDCard()
        sd.power(0)

        # test presence switch
        for ph in range(7):
            want = not sd.present()

            dis.clear()
            dis.text(None, 10, 'MicroSD Card:')
            dis.text(None,
                     34,
                     'Remove' if sd.present() else 'Insert',
                     font=FontLarge)
            dis.show()

            while 1:
                if want == sd.present(): break
                await sleep_ms(100)
                if ux_poll_once():
                    raise RuntimeError("MicroSD test aborted")

            if ph >= 2 and sd.present():
                # debounce
                await sleep_ms(100)
                if sd.present(): break
                if ux_poll_once():
                    raise RuntimeError("MicroSD test aborted")

        dis.clear()
        dis.text(None, 10, 'MicroSD Card:')
        dis.text(None, 34, 'Testing', font=FontLarge)
        dis.show()

        # card inserted
        assert sd.present(), "SD not present?"

        # power up?
        sd.power(1)
        await sleep_ms(100)

        try:
            blks, bsize, ctype = sd.info()
            assert bsize == 512, "wrong block size"
        except:
            assert 0, "unable to get card info"

        # just read it a bit, writing would prove little
        buf = bytearray(512)
        msize = 1024 * 1024
        for addr in range(0, msize, 1024):
            sd.readblocks(addr, buf)
            dis.progress_bar_show(addr / msize)

            if addr == 0:
                assert buf[-2:] == b'\x55\xaa', "Bad read"

    finally:
        # CRTICAL: power it back down
        sd.power(0)
        numpad.start()
# boot.py -- run on boot-up
# can run arbitrary Python, but best to keep it minimal

import machine
import pyb
import os
import utime
pyb.country('GB')  # ISO 3166-1 Alpha-2 code, eg US, GB, DE, AU

# https://pybd.io/hw/pybd_sfxw.html
# The board has a built-in micro SD card slot. If an SD card is inserted, by default it will not be automatically
# mount in the board’s filesystem but it will be exposed as a mass storage device if USB is used. To automatically
# mount the SD card if it is inserted, put the following in your boot.py:
# Enable power supply to sdcard
pyb.Pin.board.EN_3V3.on()
utime.sleep_ms(10)

if pyb.SDCard().present():
    # Extra delay to let the SDCard start up before mounting.
    utime.sleep_ms(500)
    os.mount(pyb.SDCard(), '/sd')
    pyb.usb_mode('VCP+MSC',
                 msc=(pyb.Flash(),
                      pyb.SDCard()))  # act as a serial and a storage device
else:
    pyb.usb_mode('VCP+MSC')  # act as a serial and a storage device

pyb.main('main.py')  # main script to run after this one
Esempio n. 19
0
# boot.py
# MIT license; Copyright (c) 2020 Andrea Corbo

import os
import pyb

pyb.freq(84000000)  # Sets main clock to reduce power consumption.

pyb.usb_mode(
    "VCP+MSC")  # Sets usb device to act only as virtual com port, needed
# to map pyboard to static dev on linux systems.
try:
    os.mount(pyb.SDCard(), "/sd")  # Mounts SD card.
except:
    print("UNABLE TO MOUNT SD")
Esempio n. 20
0
# - the WAV file will play continuously in a loop until
#   a keyboard interrupt is detected or the board is reset
#
# Blocking version
# - the write() method blocks until the entire sample buffer is written to I2S

import uos
from machine import I2S
from machine import Pin

if uos.uname().machine.find("PYBv1") == 0:
    pass
elif uos.uname().machine.find("PYBD") == 0:
    import pyb
    pyb.Pin("EN_3V3").on()  # provide 3.3V on 3V3 output pin
    uos.mount(pyb.SDCard(), "/sd")
elif uos.uname().machine.find("ESP32") == 0:
    from machine import SDCard
    sd = SDCard(slot=3, sck=Pin(18), mosi=Pin(23), miso=Pin(19), cs=Pin(5))
    uos.mount(sd, "/sd")
else:
    print("Warning: program not tested with this board")

# ======= AUDIO CONFIGURATION =======
WAV_FILE = "music-16k-32bits-stereo.wav"
WAV_SAMPLE_SIZE_IN_BITS = 32
FORMAT = I2S.STEREO
SAMPLE_RATE_IN_HZ = 16000
# ======= AUDIO CONFIGURATION =======

# ======= I2S CONFIGURATION =======
Esempio n. 21
0
import led36
from lsm9ds1 import LSM9DS1

import uasyncio
from uasyncio.websocket.server import WSReader, WSWriter
from uasyncio.queues import Queue

import picoweb

import os

measurement_queue = Queue()


if pyb.SDCard().present():
    os.mount(pyb.SDCard(), '/sd')
    print("Mounted SD Card")
    print("/sd:", os.listdir("/sd/"))
    print("/sd/web:", os.listdir("/sd/web"))
else:
    print("No SD Card present!")


def init_led_tile():
    led36.brightness(100)
    led36.illu(0, 0, 0)


def init_inertia_module():
    i2c_y = pyb.I2C(2, pyb.I2C.MASTER, baudrate=100000)