Exemplo n.º 1
0
def gnss_task():
    sd_mounted = False

    with thread_list_mutex:
        thread_list[_thread.get_ident()] = 'GNSS'

    # Mount SD if possible
    sd = SD()
    try:
        os.mount(sd, '/sd')
        os.listdir('/sd')
        sd_mounted = True
    except OSError:
        pass
    
    gnss = L76GNSS(py, timeout=5)

    while True:
        coord = gnss.rmc()
        printt(coord)

        # if sd_mounted:
        #     logfile = open('/sd/gnss.txt', 'a')
        #     logfile.write(logstring)
        #     logfile.close()

        time.sleep(2)
Exemplo n.º 2
0
 def __init__(self,
              spi,
              reset,
              dreq,
              xdcs,
              xcs,
              sdcs=None,
              mp=None,
              cancb=lambda: False):
     self._reset = reset
     self._dreq = dreq  # Data request
     self._xdcs = xdcs  # Data CS
     self._xcs = xcs  # Register CS
     self._mp = mp
     self._spi = spi
     self._cbuf = bytearray(4)  # Command buffer
     self._cancb = cancb  # Cancellation callback
     self._slow_spi = True  # Start on low baudrate
     self._overrun = 0  # Recording
     self.reset()
     if ((sdcs is not None) and (mp is not None)):
         import sdcard
         import os
         sd = sdcard.SDCard(spi, sdcs)
         vfs = os.VfsFat(sd)
         os.mount(vfs, mp)
     self._spi.init(baudrate=_DATA_BAUDRATE)
Exemplo n.º 3
0
def run():
    # some SD cards won't work in 4-bit mode unless freq() is explicitely set
    freq(240 * 1000 * 1000)  # 80/160/240 MHz, faster CPU = faster SD card
    #sd=SDCard(slot=3) # 1-bit mode
    sd = SDCard()  # 4-bit mode
    mount(sd, "/sd")
    print(listdir("/sd"))
    f = open("/sd/long_file.bin", "rb")  # any 1-10 MB long file
    b = bytearray(16 * 1024)
    i = 0
    t1 = ticks_ms()
    while f.readinto(b):
        i += 1
    t2 = ticks_ms()
    print("%d KB in %d ms => %d KB/s file read" %
          (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 //
           (t2 - t1)))
    f.close()
    umount("/sd")
    i = 0
    t1 = ticks_ms()
    while i < 256:
        sd.readblocks(i, b)
        i += 1
    t2 = ticks_ms()
    print("%d KB in %d ms => %d KB/s raw sector read" %
          (i * len(b) // 1024, t2 - t1, 1000 * i * len(b) // 1024 //
           (t2 - t1)))
    sd.deinit()
Exemplo n.º 4
0
    def __init__(self, debug=False):
        self.cfg = None
        self.rtc = RTC()
        self.debug = debug
        self.battery = Battery()

        # use this pin for debug
        self.wifi_pin = Pin("GP24", mode=Pin.IN, pull=Pin.PULL_UP)

        # Empty WDT object
        self.wdt = None

        if not debug:
            if not self.wifi_pin():
                self.wdt = WDT(timeout=20000)
            self.sd = None
        else:
            from machine import SD
            try:
                self.sd = SD()
                mount(self.sd, '/sd')
                self.logfile = open("/sd/display.log", "a")
            except OSError:
                self.sd = None
                self.logfile = None

        self.epd = EPD()

        self.log("Time left on the alarm: %dms" % self.rtc.alarm_left())

        # Don't flash when we're awake outside of debug
        heartbeat(self.debug)
Exemplo n.º 5
0
def ConnectSDcardFile():
    global spi, sdfile, sd
    spi = SPI(sck=Pin(5), mosi=Pin(22), miso=Pin(27))  
    
    try:
        sd = sdcard.SDCard(spi, Pin(23))
        os.mount(sd, '/sd')
    except OSError as e:
        return ("SD card", str(e.args[0]))
    
    if not sum((f[0]=="LOG")  for f in os.ilistdir("sd")):
        os.mkdir("sd/LOG")
    fnum = 1+max((int(f[0][:3])  for f in os.ilistdir("sd/LOG")  if f[3]>10), default=0)
    fname = "sd/LOG/{:03d}.TXT".format(fnum)
    print("Opening file", fname)
    sdfile = open(fname, "w")
    sdfile.write("Logfile: {}\n".format(fname))
    sdfile.write("Device number: 3\n")
    sdfile.write("Rt[ms]d\"[isodate]\"e[latdE]n[latdN]f[lngdE]o[lngdN] GPS cooeffs\n") 
    sdfile.write("Qt[ms]u[ms midnight]y[lat600000]x[lng600000]a[alt] GPS\n") 
    sdfile.write("Vt[ms]v[kph100]d[deg100] GPS velocity\n") 
    sdfile.write("Ft[ms]p[milibars] bluefly pressure\n") 
    sdfile.write("Gt[ms]r[rawhumid]a[rawtemp] si7021Humidity meter\n") 
    sdfile.write("Nt[ms]r[rawadc]s[resistance] nickel wire sensor\n") 
    sdfile.write("Zt[ms]xyz[linacc]abc[gravacc]wxyz[quat]s[calibstat] orient\n"); 
    sdfile.write("Yt[ms]s\"calibconsts\" orient calib\n"); 
    sdfile.write("\n")
    sdfile.flush()
    return (["SDfile", fname[:6], fname[6:]])
Exemplo n.º 6
0
 def mount_sd_card(self):
     if not self.sd_mounted:
         _logger.info("Mounting SD card")
         os.mount(self.sdcard, self.SDCARD_MOUNT_POINT)
     else:
         _logger.debug("SD card already mounted")
     self.sd_mounted = True
Exemplo n.º 7
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)
    def __init__(self, rtc):
        self.rtc = rtc

        # Try to access the SD card and make the new path
        try:
            sd = SD()
            os.mount(sd, '/sd')
            self.sensor_file = "/sd/{0}".format(SENSOR_DATA)
            print("INFO: Using SD card for data.")
        except:
            print("ERROR: cannot mount SD card, reverting to flash!")
            self.sensor_file = SENSOR_DATA
        print("Data filename = {0}".format(self.sensor_file))

        # Setup the dictionary for each soil moisture sensor
        adc = ADC(0)
        soil_moisture1 = {
            'sensor': adc.channel(pin='P13', attn=3),
            'power': Pin('P19', Pin.OUT),
            'location': 'Green ceramic pot on top shelf',
            'num': 1,
        }
        soil_moisture2 = {
            'sensor': adc.channel(pin='P14', attn=3),
            'power': Pin('P20', Pin.OUT),
            'location': 'Fern on bottom shelf',
            'num': 2,
        }
        # Setup a list for each sensor dictionary
        self.sensors = [soil_moisture1, soil_moisture2]
        # Setup the alarm to read the sensors
        a = Timer.Alarm(handler=self._read_sensors,
                        s=UPDATE_FREQ,
                        periodic=True)
        print("Plant Monitor class is ready...")
Exemplo n.º 9
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
Exemplo n.º 10
0
    def __init__(self,
                 spi=None,
                 cs=None,
                 telegramToken=None,
                 chatId=None,
                 name="unnamed"):
        self.spi = spi
        self.cs = cs
        self.telegramToken = telegramToken
        self.chatId = chatId
        self.name = name
        self.tgramActive = False
        self.rStatusActive = False

        try:
            self.sd = sdcard.SDCard(spi, cs)  # Compatible with PCB
            self.vfs = VfsFat(self.sd)
            mount(self.vfs, Logger.PARTITION)
            self.initialized = True
            print("SD inicializada")

        except Exception as e:
            print("No se pudo montar micro SD")
            self.vfs = None
            self.initialized = False
            print_exception(e)
            print(repr(e))
Exemplo n.º 11
0
 def mount(self):
     try:
         os.mount(self.sdcard, self.sd_path)
         self.mounted = True
     except Exception as e:
         sys.print_exception(e)
         print('sd mount failure')
Exemplo n.º 12
0
def ConnectSDcardFile():
    global sdfile
    try:
        os.mount(sd, '/sd')
    except OSError as e:
        oledshowfattext(["SD card", "failed"])
        time.sleep_ms(5000)

    if not sum((f[0] == "LOG") for f in os.ilistdir("sd")):
        os.mkdir("sd/LOG")
    fnum = 1 + max(
        (int(f[0][:3]) for f in os.ilistdir("sd/LOG") if f[3] > 10), default=0)
    fname = "sd/LOG/{:03d}.TXT".format(fnum)
    oledshowfattext(["SDfile", fname[:6], fname[6:]])
    print("Opening file", fname)
    sdfile = open(fname, "w")
    sdfile.write("Logfile: {}".format(fname))
    sdfile.write("Device number: 3")
    sdfile.write(
        "Rt[ms]d\"[isodate]\"e[latdE]n[latdN]f[lngdE]o[lngdN] GPS cooeffs\n")
    sdfile.write("Qt[ms]u[ms midnight]y[lat600000]x[lng600000]a[alt] GPS\n")
    sdfile.write("Vt[ms]v[kph100]d[deg100] GPS velocity\n")
    sdfile.write("Ft[ms]p[milibars] bluefly pressure\n")
    sdfile.write("Gt[ms]r[rawhumid]a[rawtemp] si7021Humidity meter\n")
    sdfile.write("Nt[ms]r[rawadc]s[resistance] nickel wire sensor\n")
    sdfile.write("\n")
    return sdfile
Exemplo n.º 13
0
 def __check_file(self, file_path, debug=False):
     if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
         if file_path[
                 0] == '/' and not 'flash' in file_path and not file_path.split(
                     '/')[1] in os.listdir('/'):
             if self.__sdpath is None:
                 self.__sdpath = file_path.split('/')[1]
                 try:
                     sd = SD()
                     time.sleep(0.5)
                     os.mount(sd, '/{}'.format(self.__sdpath))
                 except Exception as ex:
                     print('Unable to mount SD card!')
                     return False
             else:
                 print('SD card already mounted on {}!'.format(
                     self.__sdpath))
                 return False
     try:
         size = os.stat(file_path)[6]
         if debug: print('File {} has size {}'.format(file_path, size))
         return True
     except Exception as ex:
         print('Exception when checking file {}... wrong file name?'.format(
             file_path))
         print('{}'.format(ex))
         return False
     return False
Exemplo n.º 14
0
def mount_sdcard():
    spisd = SoftSPI(-1, miso=Pin(13), mosi=Pin(12), sck=Pin(14))

    sd = SDCard(spisd, Pin(27))

    vfs = os.VfsFat(sd)
    os.mount(vfs, '/sd')
Exemplo n.º 15
0
def mount_sdcard() -> bool:
    """Mounts SD card"""
    if not is_sd_present():
        raise RuntimeError("SD card is not present")
    if sdcard is not None:
        sdled.on()
        sdcard.power(True)
        os.mount(sdcard, "/sd")
Exemplo n.º 16
0
def mountsd():
    try:
        spisd = SPI(-1, sck=Pin(14), mosi=Pin(13), miso=Pin(12))
        sd = sdcard.SDCard(spisd, machine.Pin(15))
        os.mount(sd, '/sd')
        return 1
    except:
        return 0
Exemplo n.º 17
0
def setup():
    global logger, rtc, sd, iCAM, iACC, CTLR_IPADDRESS, logfile, filename
    global wdt, ow, temp, py, sensor

    gc.enable()

    # HW Setup
    wdt = WDT(timeout=wdt_timeout)
    sd = SD()
    rtc = RTC()
    os.mount(sd,'/sd')
    # Enable WiFi Antenna
    Pin('P12', mode=Pin.OUT)(True)

    # TEMPERATURE SENSORS: DS18B20 and SI7006A20
    ow = OneWire(Pin('P10'))
    temp = DS18X20(ow)
    py = Pysense()
    sensor = SI7006A20(py)


    # SYSTEM VARIABLES
    iCAM = pycom.nvs_get('iCAM') # pycom.nvs_set('iCAM',1)
    iACC = pycom.nvs_get('iACC') # pycom.nvs_set('iACC',1)

    logfile='/sd/log/{}.log'.format(datetime_string(time.time()))
    logging.basicConfig(level=logging.DEBUG,filename=logfile)
    logger = logging.getLogger(__name__)

    # # NETWORK VARIABLES
    # pbconf = pybytes.get_config()
    # AP = pbconf['wifi']['ssid']
    # if AP == 'wings':
    #     CTLR_IPADDRESS = '192.168.1.51'
    # elif AP == 'RUT230_7714':
    #     CTLR_IPADDRESS = '192.168.1.100'
    #     # CONNECT TO AP
    #     wlan = WLAN(mode=WLAN.STA)
    #     while not wlan.isconnected():
    #         nets = wlan.scan()
    #         for net in nets:
    #             if net.ssid == 'RUT230_7714':
    #                 pybytes.connect_wifi()
    #
        # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)
        # while not wlan.isconnected():
        #     machine.idle() # save power while waiting
    socket_client.CTLR_IPADDRESS = CTLR_IPADDRESS

    # GREETING
    logger.info('--------------------')
    logger.info(' Starting CAM{}-ACC{}'.format(iCAM, iACC))
    logger.info('--------------------')
    logger.info('AP={}'.format(AP))
    gc.collect()

    return
Exemplo n.º 18
0
def sdtest2():
    spi = machine.SPI(1)
    spi.init()  # Ensure right baudrate
    sd = sdcard.SDCard(spi, machine.Pin(15))  # Compatible with PCB
    # vfs = os.VfsLfs2(sd)
    vfs = os.VfsFat(sd)
    os.mount(vfs, "/fc")
    print("Filesystem check")
    print(os.listdir("/fc"))

    line = "abcdefghijklmnopqrstuvwxyz\n"
    lines = line * 200  # 5400 chars
    short = "1234567890\n"

    fn = "/fc/rats.txt"
    print()
    print("Multiple block read/write")
    with open(fn, "w") as f:
        n = f.write(lines)
        print(n, "bytes written")
        n = f.write(short)
        print(n, "bytes written")
        n = f.write(lines)
        print(n, "bytes written")

    with open(fn, "r") as f:
        result1 = f.read()
        print(len(result1), "bytes read")

    fn = "/fc/rats1.txt"
    print()
    print("Single block read/write")
    with open(fn, "w") as f:
        n = f.write(short)  # one block
        print(n, "bytes written")

    with open(fn, "r") as f:
        result2 = f.read()
        print(len(result2), "bytes read")

    os.umount("/fc")

    print()
    print("Verifying data read back")
    success = True
    if result1 == "".join((lines, short, lines)):
        print("Large file Pass")
    else:
        print("Large file Fail")
        success = False
    if result2 == short:
        print("Small file Pass")
    else:
        print("Small file Fail")
        success = False
    print()
    print("Tests", "passed" if success else "failed")
def quick_test_hw(hw):
    _logger.info("Starting quick self test...")
    pycom_util.reset_rgbled()

    _logger.info("Starting hardware quick check")
    chrono = machine.Timer.Chrono()
    chrono.start()

    with CheckStep(FLAG_MOSFET_PIN, suppress_exception=True):
        if hw.mosfet_pin:
            _logger.info("Mosfet pin state: %s", hw.mosfet_pin())
        wdt.feed()

    with CheckStep(FLAG_SD_CARD, suppress_exception=True):
        import os
        mountpoint = "/co2_sd_card_test"
        os.mount(hw.sdcard, mountpoint)
        contents = os.listdir(mountpoint)
        os.umount(mountpoint)
        _logger.info("SD card OK. Contents: %s", contents)
        wdt.feed()

    with CheckStep(FLAG_ERTC, suppress_exception=True):
        ertc = hw.ertc
        time_tuple = ertc.get_time()
        _logger.info("External RTC ok. Current time: %s", time_tuple)
        wdt.feed()

    with CheckStep(FLAG_CO2, suppress_exception=True):
        import explorir
        co2 = hw.co2
        co2.set_mode(explorir.MODE_POLLING)
        reading = co2.read_co2()
        _logger.info("CO2 sensor ok. Current level: %d ppm", reading)
        wdt.feed()

    with CheckStep(FLAG_ETEMP, suppress_exception=True):
        etemp = hw.etemp
        _logger.debug("Starting external temp read. Can take up to 750ms.")
        etemp.start_conversion()
        chrono.reset()
        while True:
            reading = etemp.read_temp_async()
            if reading: break
            if chrono.read_ms() > 1000:
                raise TimeoutError(
                    "Timeout reading external temp sensor after %d ms" %
                    chrono.read_ms())
        _logger.info("External temp sensor ok. Current temp: %s C", reading)
        wdt.feed()

    show_boot_flags()
    _logger.info("Failures after quick hardware check: 0x%04x", failures)
    display_errors_led()
    wdt.feed()

    pycom.rgbled(0x0)
Exemplo n.º 20
0
def init_sd_card():

    # First we would like to bount the SD card
    try:
        spibus = SPI(1, sck=Pin(18), mosi=Pin(23), miso=Pin(19))
        sd = sdcard.SDCard(spibus, Pin(4))  # <- chipselect 4 on WEMOS D32 Pro
        os.mount(sd, SD_ROOT)
    except:
        failure()
Exemplo n.º 21
0
def sdtest():
    spi = machine.SPI(1)
    spi.init()  # Ensure right baudrate
    sd = sdcard.SDCard(spi, machine.Pin.board.X21) # Compatible with PCB
    vfs = os.VfsFat(sd)
    os.mount(vfs, '/fc')
    print('Filesystem check')
    print(os.listdir('/fc'))

    line = 'abcdefghijklmnopqrstuvwxyz\n'
    lines = line * 200 # 5400 chars
    short = '1234567890\n'

    fn = '/fc/rats.txt'
    print()
    print('Multiple block read/write')
    with open(fn,'w') as f:
        n = f.write(lines)
        print(n, 'bytes written')
        n = f.write(short)
        print(n, 'bytes written')
        n = f.write(lines)
        print(n, 'bytes written')

    with open(fn,'r') as f:
        result1 = f.read()
        print(len(result1), 'bytes read')

    fn = '/fc/rats1.txt'
    print()
    print('Single block read/write')
    with open(fn,'w') as f:
        n = f.write(short) # one block
        print(n, 'bytes written')

    with open(fn,'r') as f:
        result2 = f.read()
        print(len(result2), 'bytes read')

    os.umount('/fc')

    print()
    print('Verifying data read back')
    success = True
    if result1 == ''.join((lines, short, lines)):
        print('Large file Pass')
    else:
        print('Large file Fail')
        success = False
    if result2 == short:
        print('Small file Pass')
    else:
        print('Small file Fail')
        success = False
    print()
    print('Tests', 'passed' if success else 'failed')
Exemplo n.º 22
0
 def mount(path):
     """
         Mount the SD card.
     """
     if path not in os.listdir("/"):
         try:
             os.mount(SD(), "/" + path)
         except:
             return False
     return True
 def __init__(self):
     try:
         os.mount(
             SDCard(slot=3,
                    miso=Pin(12),
                    mosi=Pin(13),
                    sck=Pin(14),
                    cs=Pin(15)), "/sd")
     except:
         print("Sd card could not be read")
Exemplo n.º 24
0
def start():
    # FIXME
    lcd.erase()

    # mount SD card to filesystem
    sd = SDCard()
    os.mount(sd, '/sd')

    # navigate to first screen
    SeedChoiceScreen().visit()
Exemplo n.º 25
0
def fstest():
    ram = get_spiram()
    os.VfsLfs2.mkfs(ram)  # Format littlefs
    try:
        os.mount(ram, '/ram')
    except OSError:  # Already mounted
        pass
    print('Contents of "/": {}'.format(os.listdir('/')))
    print('Contents of "/ram": {}'.format(os.listdir('/ram')))
    print(os.statvfs('/ram'))
Exemplo n.º 26
0
def print_log(path='/sd/display.log'):
    sd = SD()
    os.mount(sd, '/sd')

    with open(path, 'r') as logfile:
        for line in logfile:
            print(line, end='')

    os.unmount('/sd')
    sd.deinit()
Exemplo n.º 27
0
    def mount_microSD(self):
        try:
            microSD = SD()
        except OSError:
            return False

        try:
            os.mount(microSD,'/microSD')
        except OSError:
            return False
        return True
Exemplo n.º 28
0
def initialize_sd_card():
    """Try to mount SD card and append /sd/lib to sys.path"""
    global sd
    try:
        sd = SD(pins=('GP10', 'GP11', 'GP15'))
        os.mount(sd, '/sd')
        sys.path.append('/sd/lib')
    except OSError:
        return False
    else:
        return True
Exemplo n.º 29
0
def mount_sd():
    try:
        sd = machine.SD()
        try:  # check if sd is already mounted
            os.stat('/sd')
            return True
        except:  # not mounted: continue    # todo except specific exception
            pass
        os.mount(sd, '/sd')
        return True
    except OSError:
        return False
Exemplo n.º 30
0
def cptest():
    ram = get_spiram()
    if 'ram' in os.listdir('/'):
        print('Device already mounted.')
    else:
        os.VfsLfs2.mkfs(ram)  # Format littlefs
        os.mount(ram, '/ram')
        print('Formatted and mounted device.')
    cp('/sd/spiram_test.py', '/ram/')
    cp('/sd/spiram.py', '/ram/')
    print('Contents of "/ram": {}'.format(os.listdir('/ram')))
    print(os.statvfs('/ram'))
def mount_sd():
    logger.info("mounting sd...")
    try:
        sd = sdcard.SDCard(machine.SPI(1), machine.Pin(15))
        os.mount(sd, "/sd")
    except Exception as e:
        logger.exc(e, "sd could not be mounted.")
        failed_mounts_count = increment_counter("failed_mounts")
        if failed_mounts_count == 1:
            print_error_msg("SD-Karte konnte nicht gelesen werden! Sag besser mal Fabian bescheid!")
    else:
        reset_counter("failed_mounts")
Exemplo n.º 32
0
    def __init__(self):
        self.debug('doing state init')
        #load (or create) a local file
        sd = SD()
        os.mount(sd, '/sd')

        #sigfox setup
        sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1)
        self.sig = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW)
        self.sig.setblocking(False)
        self.sig.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, False)

        #py = Pytrack()
        #self.gps = L76GNSS(py)

        self.debug('trying to get state from net...')
        try:
            data = {}
            data["order"] = '-createdAt'
            data["limit"] = '1'
            headers = {
                'X-Parse-Application-Id': PARSE_APPLICATION_ID,
                'X-Parse-REST-API-Key': PARSE_REST_API_KEY,
                'Content-Type': 'application/json'
            }
            self.debug('sending request.')
            resp = urequests.get(PARSE_BASE_URL + '/classes/ConfigObject',
                                 headers=headers,
                                 data=ujson.dumps(data))
            config = resp.json()
            resp.close()
            self.debug('got state from net:')
            self.debug(ujson.dumps(config))
            self.write_config(config["results"][0])

        except:
            self.debug('could not get state from net.')
            try:
                f = open('/sd/config.json', 'r')
                config = f.read()
                f.close()
                if config == '':
                    self.debug('found invalid local json file, writing...')
                    config = {}
                    config["state"] = 0
                    self.write_config(config)
                else:
                    self.debug('found valid local json file:')
                    self.debug(config)
                    self.config = ujson.loads(config)
            except:
                self.debug('ERROR - could not get/create a valid config file!')
                pass
Exemplo n.º 33
0
def initialize_sd_card():
    """Try to mount SD card and append /sd/lib to sys.path"""
    global sd
    log = ulog.Logger('SD: ')
    try:
        log.info('preparing SD card')
        sd = SD(pins=('GP10', 'GP11', 'GP15'))
        os.mount(sd, '/sd')
        sys.path.append('/sd/lib')
    except OSError:
        log.info('no card found!')
        return False
    else:
        log.info('mounted to /sd')
        return True
Exemplo n.º 34
0
def save_config(cfg):
    """
    Save out a configuration file
    :param Config cfg: config option
    :return: None
    """
    sd = SD()
    os.mount(sd, '/sd')

    with open("/sd/config.txt", "w") as cfgfile:
        cfgfile.write("Host:%s\n", cfg.host)
        cfgfile.write("WiFi:%s\n", cfg.wifi_ssid)
        cfgfile.write("Pass:%s\n", cfg.wifi_key)
        cfgfile.write("Port:%s\n", cfg.port)
        cfgfile.write("Image:%s\n", cfg.image_path)
        cfgfile.write("Meta:%s\n", cfg.metadata_path)
        if cfg.upload_path:
            cfgfile.write("Up:%s\n", cfg.upload_path)
    os.unmount(sd)
    sd.deinit()
Exemplo n.º 35
0
    def load(debug=False, sd=None):
        """
         Load off SD our AP, pw, and URL details
        :param debug: Logging
        :param sd: SD object if mounted already
        :return: Config object
        """
        from machine import SD
        cfg = None
        try:
            unmount = False
            if sd is None:
                sd = SD()
                os.mount(sd, '/sd')
                unmount = True

            cfg = Config.load_file(open(Config.SD_CONFIG_PATH,"r"), debug)

            if unmount:
                try:
                    os.unmount('/sd') # got renamed in upy 1.9
                except AttributeError:
                    os.umount('/sd')
                sd.deinit()
                del sd
        except OSError:
            print("Can't open config file SD card")

        if not cfg:
            cfg = Config.load_file(open(Config.FLASH_CONFIG_PATH, "r"), debug)
            if not cfg:
                raise ValueError("No config file!")
            print("Loaded from flash")
            cfg.src = "flash"
        else:
            print("Loaded from SD card")
            cfg.src = "sd"
        return cfg
Exemplo n.º 36
0
print

# Unpack the base yaOSp package

print
print "Installing yaOSp base package ..."

try :
    os.mkdir( "/media/install" )
except OSError, e :
    print "Failed to create /media/install directory!"
    sys.exit(0)

try :
    os.mount( partition[ "name" ], "/media/install", "ext2" )
except OSError, e :
    print "Failed to mount %s to /media/install" % ( partition[ "name" ] )
    sys.exit(0)

try :
    base = tarfile.open( "/yaosp/yaosp_base.tar.bz2" )
except IOError, e :
    print "The yaosp base package is not found!"
    sys.exit(0)

print

for entry in base :
    print "Extracting /media/install/%s" % ( entry.name )
    base.extract( entry, "/media/install" )
Exemplo n.º 37
0
def mnt():
    cs = Pin("P22", mode=Pin.OUT)
    sd = SDCard(SPI(0), cs)
    os.mount(sd, '/')
Exemplo n.º 38
0
from pyb import SD
import pyb
import os

machine = os.uname().machine
if 'LaunchPad' in machine:
    sd_pins = ('GP16', 'GP17', 'GP15')
elif 'WiPy' in machine:
    sd_pins = ('GP10', 'GP11', 'GP15')
else:
    raise Exception('Board not supported!')

sd = SD(pins=sd_pins)

os.mount(sd, '/sd')
os.mkfs('/sd')
os.chdir('/flash')
print(os.listdir())

os.chdir('/sd')
print(os.listdir())

# create a test directory in flash
os.mkdir('/flash/test')
os.chdir('/flash/test')
print(os.getcwd())
os.chdir('..')
print(os.getcwd())
os.chdir('test')
print(os.getcwd())
Exemplo n.º 39
0
def mount_tf(self, mount_point="/"):
    sd = SDCard(SPI(0), Pin("P15", mode=Pin.OUT))
    os.mount(sd, mount_point)