Exemple #1
0
 def action_state(method, loc, params, headers, conn, addr):
     return httpsrv.response(
         200,
         ujson.dumps(
             {
                 "unique_id": ubinascii.hexlify(
                     machine.unique_id()
                 ).decode().upper(),
                 "micropython_version": uos.uname().version[
                     1:uos.uname().version.index(" ")
                 ],
                 "firmware_version": __version__,
                 "color_id": _color_id,
                 "free_memory": gc.mem_free(),
                 "free_flash": uos.statvfs("/")[0] * uos.statvfs("/")[3],
                 "run_state": [
                     "ERROR {}".format(runner.get_error()[0])
                     if runner.get_error() is not None
                     else "",
                     "STOPPED",
                     "CODE.PY MISSING",
                     "CODE.PY IMPORTED",
                     "CODE.PY MAIN",
                 ][runner.get_state()],
                 "error_traceback": [
                     line.strip()
                     for line in runner.get_error()[1].split("\n")
                     if line and "Traceback" not in line
                 ]
                 if runner.get_error() is not None
                 else None,  # noqa
             }
         ),
         httpsrv.CT_JSON,
     )
Exemple #2
0
 def save_rk(self, rkid, user_id, key_handle):
     try:
         stat = statvfs('/flash')
         if stat[0] * stat[3] < 100000:  # bsize * bfree
             # if actual number of free bytes too low exit
             return False
         dir = listdir()
         if KS_CTAP2.RK_DIR not in dir:
             mkdir(KS_CTAP2.RK_DIR)
         dir = listdir(KS_CTAP2.RK_DIR)
         fn = hexlify(user_id).decode('utf-8')
         with open(KS_CTAP2.RK_DIR + '/' + fn, 'wb') as fout:
             fout.write(key_handle)
         if rkid in self.RKS:
             if fn in self.RKS[rkid]:
                 self.RKS[rkid].remove(fn)
             self.RKS[rkid].append(fn)  # most recent ones at the end
         else:
             self.RKS[rkid] = [fn]
         self.save_keystore()
     except OSError:
         return False
     except ValueError:
         return False
     return True
Exemple #3
0
def check():
    fs_stat = uos.statvfs('/')
    fs_size = fs_stat[0] * fs_stat[2]
    fs_free = fs_stat[0] * fs_stat[3]
    response = "File System Size {:,} - Free Space {:,}".format(
        fs_size, fs_free)
    return response
Exemple #4
0
def log_mem_usage(_ticks_now):
    #pylint: disable=global-statement
    global _mem_used
    global _stack_used
    global _fs_used
    global _counter

    mem_used = gc.mem_alloc()
    mem_free = gc.mem_free()
    stack_used = micropython.stack_use()
    fs_data = uos.statvfs('/')
    fs_size = fs_data[1] * fs_data[2]  # f_frsize * f_blocks
    fs_avail = fs_data[0] * fs_data[4]  # f_bsize * f_bavail
    fs_used = fs_size - fs_avail

    if mem_used == _mem_used and stack_used == _stack_used and fs_used == _fs_used:
        _counter += 1
        if _counter >= 60:
            _counter = 0
    else:
        _counter = 0

    if _counter == 0:
        _mem_used = mem_used
        _stack_used = stack_used
        _fs_used = fs_used
        _logger.debug("{},{},{},{},{}", mem_used, mem_free, stack_used,
                      fs_used, fs_avail)
def core():
    from core.core import uCore
    from core.mbus.mbus import MbusManager
    from core.config.config import ConfigManager

    # VFS SIZE
    fs_stat = uos.statvfs('/')
    fs_size = fs_stat[0] * fs_stat[2]
    fs_free = fs_stat[0] * fs_stat[3]
    print("File System Size {:,} - Free Space {:,}".format(fs_size, fs_free))

    part_name = uos.getcwd()
    print(part_name)

    # MBUS
    log.info("MBUS START")
    _mbus = MbusManager()

    # CONF
    log.info("CONF START")
    _conf = ConfigManager("./u_config")

    # CORE
    log.info("CORE: init")
    _core = uCore(_mbus, _conf)
    _core.part_name = part_name
Exemple #6
0
def root_info():
    info = uos.statvfs("/")
    block_size = info[0]
    fragment_size = info[1]
    fragment_count = info[2]
    free_block_count = info[3]

    print("Root FS size {} Free {}".format(fragment_size * fragment_count,
                                           block_size * free_block_count))
 def __init__(self, **kwargs):
     self.print(self.__class__, '__init__')
     s = statvfs('/')
     print('statvfs', round((s[2] - s[3]) / s[2] * 100), '%', 'of',
           round(s[1] * s[2] / pow(2, 20), 1), 'mb')
     self.activ = False
     self.obj = []
     for k, v in kwargs.items():
         setattr(self, k, v)
     self.mem_alloc()
Exemple #8
0
def fstest(format=False):
    fram = get_fram()
    if format:
        uos.VfsFat.mkfs(fram)
    vfs = uos.VfsFat(fram)
    try:
        uos.mount(vfs, '/fram')
    except OSError:  # Already mounted
        pass
    print('Contents of "/": {}'.format(uos.listdir('/')))
    print('Contents of "/fram": {}'.format(uos.listdir('/fram')))
    print(uos.statvfs('/fram'))
Exemple #9
0
def fstest(format=False):
    eep = get_eep()
    if format:
        uos.VfsFat.mkfs(eep)
    vfs = uos.VfsFat(eep)
    try:
        uos.mount(vfs, '/eeprom')
    except OSError:  # Already mounted
        pass
    print('Contents of "/": {}'.format(uos.listdir('/')))
    print('Contents of "/eeprom": {}'.format(uos.listdir('/eeprom')))
    print(uos.statvfs('/eeprom'))
Exemple #10
0
def fstest(format=False):
    eep = get_device()
    # ***** CODE FOR LITTLEFS *****
    if format:
        uos.VfsLfs2.mkfs(eep)
    try:
        uos.mount(eep, '/fl_ext')
    except OSError:  # Already mounted
        pass
    print('Contents of "/": {}'.format(uos.listdir('/')))
    print('Contents of "/fl_ext": {}'.format(uos.listdir('/fl_ext')))
    print(uos.statvfs('/fl_ext'))
def df():
    """Get free disk and memory"""
    st = uos.statvfs('/')
    _size = int(st[1] * st[2] / 1024)
    _free = int(st[1] * st[3] / 1024)
    _used = st[3] / st[2] * 100
    print('Flash  {:d} / {:d}kB ({:.1f}%)'.format(_free, _size, _used))

    gc.collect()
    _free = gc.mem_free() / 1024
    _size = _free + gc.mem_alloc() / 1024
    _used = 100 * _free / _size
    print('RAM    {:.1f} / {:.1f}kB ({:.1f}%)'.format(_free, _size, _used))
def mem_stats():
    from esp import flash_size
    from uos import statvfs
    import gc
    fs_stat = statvfs('/')
    fs_size = fs_stat[0] * fs_stat[2]
    fs_free = fs_stat[0] * fs_stat[3]
    print('Memory Information:')
    print('   RAM Size     {:5,}KB'.format(int((gc.mem_alloc() + gc.mem_free())/1024)))
    print()
    print('Flash Storage Information:')
    print('   Flash Size   {:5,}KB'.format(int(flash_size()/1024)))
    print('   User Space   {:5,}KB'.format(int(fs_size/1024)))
    print('   Free Space   {:5,}KB'.format(int(fs_free/1024)))
def main(ui):
    fs_stat = uos.statvfs('/')
    fs_size = fs_stat[0] * fs_stat[2]
    fs_free = fs_stat[0] * fs_stat[3]

    ui.cls()
    ui.center("System Size",0)
    ui.center("{:,}".format(fs_size), 1)

    ui.center("Free Space", 3)
    ui.center("{:,}".format(fs_free), 4)

    ui.center("Press to", 6)
    ui.wait("Continue", 7)
def cptest():  # Assumes pre-existing filesystem of either type
    eep = get_eep()
    if 'eeprom' in uos.listdir('/'):
        print('Device already mounted.')
    else:
        try:
            uos.mount(eep, '/eeprom')
        except OSError:
            print('Fail mounting device. Have you formatted it?')
            return
        print('Mounted device.')
    cp('eep_i2c.py', '/eeprom/')
    cp('eeprom_i2c.py', '/eeprom/')
    print('Contents of "/eeprom": {}'.format(uos.listdir('/eeprom')))
    print(uos.statvfs('/eeprom'))
Exemple #15
0
def cptest():
    eep = get_device()
    if 'fl_ext' in uos.listdir('/'):
        print('Device already mounted.')
    else:
        try:
            uos.mount(eep, '/fl_ext')
        except OSError:
            print('Fail mounting device. Have you formatted it?')
            return
        print('Mounted device.')
    cp('flash_test.py', '/fl_ext/')
    cp('flash_spi.py', '/fl_ext/')
    print('Contents of "/fl_ext": {}'.format(uos.listdir('/fl_ext')))
    print(uos.statvfs('/fl_ext'))
Exemple #16
0
def cptest():
    fram = get_fram()
    if 'fram' in uos.listdir('/'):
        print('Device already mounted.')
    else:
        vfs = uos.VfsFat(fram)
        try:
            uos.mount(vfs, '/fram')
        except OSError:
            print('Fail mounting device. Have you formatted it?')
            return
        print('Mounted device.')
    cp('fram_test.py', '/fram/')
    cp('fram_i2c.py', '/fram/')
    print('Contents of "/fram": {}'.format(uos.listdir('/fram')))
    print(uos.statvfs('/fram'))
    def system_status_string(self):
        try:
            svfs = uos.statvfs("/sd/")
            self._error_string = None
        except OSError as e:
            self._error_string = str(e)
            svfs = (None, None, "ERR", "ERR")

        return "v_vbat=%.1f v_temp=%.1f v_ichg=%.1f v_idcg=%.1f v_vusb=%.1f v_iusb=%.1f v_vaps=%.1f v_vex=%.1f v_iex=%.1f v_wbat=%.1f v_warn=%d v_blocks=%s v_bfree=%s" % (
            self._axp192.getVbatVoltage(), self._axp192.getTemperature(),
            self._axp192.getBatteryChargeCurrent(),
            self._axp192.getBatteryDischargeCurrent(),
            self._axp192.getUSBVoltage(), self._axp192.getUSBInputCurrent(),
            self._axp192_getApsVoltage(), self._axp192.getConnextVoltage(),
            self._axp192.getConnextInputCurrent(),
            self._axp192.getBatteryInstantWatts(),
            self._axp192_getWarningLeve(), svfs[2], svfs[3])
def fstest(format=False):
    eep = get_eep()
    try:
        uos.umount('/eeprom')
    except OSError:
        pass
    # ***** CODE FOR FATFS *****
    #if format:
    #os.VfsFat.mkfs(eep)
    # ***** CODE FOR LITTLEFS *****
    if format:
        uos.VfsLfs2.mkfs(eep)
    # General
    try:
        uos.mount(eep, '/eeprom')
    except OSError:
        raise OSError("Can't mount device: have you formatted it?")
    print('Contents of "/": {}'.format(uos.listdir('/')))
    print('Contents of "/eeprom": {}'.format(uos.listdir('/eeprom')))
    print(uos.statvfs('/eeprom'))
Exemple #19
0
def main():

    loop = asyncio.get_event_loop()

    #WDT

    loop.create_task(run_wdt())

    _ = _thread.stack_size(8 * 1024)
    _thread.start_new_thread(loop.run_forever, ())


    fs_stat = uos.statvfs('/')
    fs_size = fs_stat[0] * fs_stat[2]
    fs_free = fs_stat[0] * fs_stat[3]
    print("File System Size {:,} - Free Space {:,}".format(fs_size, fs_free))


    board_id = ubinascii.hexlify(machine.unique_id())
    print("BOARD ID: {}".format(board_id))

    # MBUS
    from core.mbus.mbus import MbusManager

    g_mbus = MbusManager()
    g_mbus.start()
    print("MBUS START")

    # MOD
    from core.umod.umod import ModManager
    g_umod = ModManager()
    #g_umod = ModManager("./{}/u_db".format(runnin_gpart_name))
    print("MOD START")

    from utime import sleep
    print("Wait 5s")
    sleep(5)

    loop.create_task(loader(g_mbus, g_umod, board_id))
Exemple #20
0
def main():
    gc.collect()
    print("Memory Info:")
    micropython.mem_info()
    fs_info = uos.statvfs('/')
    print("FS Stats:")
    print("  FS Used: {} MiB".format((fs_info[2] * fs_info[1]) / 1024 / 1024))
    print("  FS Free: {} MiB".format((fs_info[3] * fs_info[1]) / 1024 / 1024))

    print("Configuring CPU...")
    configure_cpu()

    print("Connecting to WIFI...")
    net.connect_to_wifi()

    try:
        loop = LoopState()
        loop.loop_forever()
    except Exception as ex:
        print(str(ex))
        panic_handler.send_exception_message(ex)
        utime.sleep_ms(10000)
        machine.reset()
Exemple #21
0
        print(self.id, "open", file, mode)


# first we umount any existing mount points the target may have
try:
    uos.umount("/")
except OSError:
    pass
for path in uos.listdir("/"):
    uos.umount("/" + path)

# stat root dir
print(uos.stat("/"))

# statvfs root dir; verify that f_namemax has a sensible size
print(uos.statvfs("/")[9] >= 32)

# getcwd when in root dir
print(uos.getcwd())

# basic mounting and listdir
uos.mount(Filesystem(1), "/test_mnt")
print(uos.listdir())

# ilistdir
i = uos.ilistdir()
print(next(i))
try:
    next(i)
except StopIteration:
    print("StopIteration")
Exemple #22
0
from uos import statvfs
from logging import basicConfig, getLogger, DEBUG, debug
from gc import enable, collect, threshold, mem_free, mem_alloc

from common import utils

# Logger config
basicConfig(level=DEBUG)
main_logger = getLogger(None)
main_logger.setLevel(DEBUG)

# Info about start
debug("=== BOOT START ===")
utils.print_reset_wake_state()

# Garbage Collector
enable()
threshold(mem_free() // 4 + mem_alloc())

# Diagnostic info - not needed in production
collect()
debug("Free memory: " + str(mem_free()))
fs_stat = statvfs('//')
debug("Free flash: {} MB".format((fs_stat[0] * fs_stat[3]) / 1048576))
del fs_stat
Exemple #23
0
    def MQTT_Commands(self, Payload):

        # ++++++++++++++++++++++++++++++++++++++++ Reboot ++++++++++++++++++++++++++++++++++++++++
        # Reboots the device
        if Payload.lower() == 'reboot':
            # Run self.Reboot is will do the rest
            self.Reboot("MQTT Commands")

        # ++++++++++++++++++++++++++++++++++++++++ Find Me ++++++++++++++++++++++++++++++++++++++++
        # Blinks the indicator 20 times if configured
        elif Payload.lower() == 'find me':
            # Turn on FindMe blink
            self.Indicator.Add("Find me", 20, "0.5s", "0.75s")

        # ++++++++++++++++++++++++++++++++++++++++ Log level ++++++++++++++++++++++++++++++++++++++++
        # Reboots the device
        elif Payload.lower().startswith("log level ") == True:
            try:
                # remember to add one to range to get 0-5
                if int(Payload[10:]) in range(6):
                    self.Log_Level = int(Payload[10:])
            except:
                self.Log(2, "Commands", "Invalid log level: " + Payload[10:])
            else:
                self.Log(1, "Commands",
                         "Log level set to: " + str(self.Log_Level))
            return

        # ++++++++++++++++++++++++++++++++++++++++ Network ++++++++++++++++++++++++++++++++++++++++
        # # Pings a target
        # elif Payload.lower().startswith() == 'ping ':
        #     # Split payload into 'ping ' and target
        #     Payload = Payload.split(' ')
        #     # Payload not contains the target
        #     Payload = Payload[1]
        #     # Ping target and capture reply
        #     Resoult = uping.ping(Payload, timeout=500)
        #     print('Resoult')
        #     print(Resoult)
        #     # # Log resoult
        #     # self.Log(1, "Commands", "Ping: " + str(Resoult))

        # ++++++++++++++++++++++++++++++++++++++++ Memory ++++++++++++++++++++++++++++++++++++++++
        # Lists free memory
        # source - https://forum.micropython.org/viewtopic.php?t=3499
        elif Payload.lower() == 'free memory':
            # calc free memory
            gc.collect()
            F = gc.mem_free()
            A = gc.mem_alloc()
            T = F + A
            P = '{0:.2f}%'.format(F / T * 100)
            # Log free memory
            self.Log(
                1, "Commands", "Free memory: " + str(
                    ('Total:{0} Free:{1} ({2})'.format(T, F, P))))
            return

        # ++++++++++++++++++++++++++++++++++++++++ File system ++++++++++++++++++++++++++++++++++++++++
        # Free space
        # source - https://forum.micropython.org/viewtopic.php?t=3499
        elif Payload.lower() == 'free space':
            # calc free space
            s = uos.statvfs('//')
            # Log free space
            self.Log(
                1, "Commands", "Free space: " + str(('{0} MB'.format(
                    (s[0] * s[3]) / 1048576))))
            return

        # ++++++++++++++++++++++++++++++++++++++++ Push ++++++++++++++++++++++++++++++++++++++++
        # Sends a push message to id specified
        elif Payload.lower().startswith('push ') == True:
            # get id
            id = Payload.split(" ")[1]
            # Send a push with message "Test"
            self.Push_Send(id, "Push Test", "Test Message", Type="Test")
            # Log event
            self.Log(1, "Commands", "Message send to id: " + str(id))
            return

        # ++++++++++++++++++++++++++++++++++++++++ Config ++++++++++++++++++++++++++++++++++++++++
        elif Payload.lower() == 'config list':
            # publishes a list of all config files
            dir_String = uos.listdir('/conf')
            # Var to hold string we are returning
            Return_String = ' '
            # Convert list to string
            for Entry in dir_String:
                # split(".")[0] gives us the file name without the extention
                Return_String = Return_String + Entry.split(".")[0] + " "
            # Remove the last space added by the for loop
            Return_String = Return_String[:-1]
            # Log event
            self.Log(1, 'System', "Config list:" + Return_String)
            return

        elif Payload.lower().startswith('config show ') == True:

            # Only get the path
            Config_Path = Payload[12:]
            Config_Name = ""

            # Check if we got a / if so will asume we got the full path
            # if no .json at the end of full path then fail
            if "/" in Config_Path:
                # NO / in path, user gave a config name
                # Check if we got .json at the end
                if Config_Path.lower().endswith('.json') == False:
                    # No json at the end return and report unknown file
                    self.Log(1, 'System',
                             "Invalid full config path: " + Config_Path)
                    return

                # Generate config name
                Config_Name = Config_Path.split()
                Config_Name = Config_Name[-1]
                Config_Name = Config_Name.replace('json', "")

            # Config name only
            else:
                # Generate config name
                Config_Name = Config_Path
                # Add /confi/ to the beginning and .json to the end of Config_Path
                Config_Path = "/conf/" + Config_Path + ".json"

            # Read the content of the specified file
            try:
                f = open(Config_Path)
                Config_File = f.read()
                f.close()
            except OSError:
                self.Log(
                    2, 'System', "Unable to read config: " + Config_Name +
                    " path: " + Config_Path)
                return

            # Log event - aka publish config
            self.Log(
                1, 'System',
                "Config: " + Config_Name + "\nContent: " + str(Config_File))
            return

        else:
            self.Log(1, 'System', "Unknown command: " + Payload)
            return
Exemple #24
0
def send_df():
    f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax = uos.statvfs("/")

    collectd.send_value("df_complex", "free", f_bavail * f_bsize, plugin="df", plugin_instance="root")
    collectd.send_value("df_complex", "used", (f_blocks - f_bavail) * f_bsize, plugin="df", plugin_instance="root")
    collectd.send_value("df_complex", "reserved", (f_bfree - f_bavail) * f_bsize, plugin="df", plugin_instance="root")
Exemple #25
0
from esp import check_fw, flash_size
from uos import statvfs

print("\n\nmicro python 8266. FRIGO")
check_fw()
print('\nflash size in Mbytes: ', flash_size()/(1024.0*1024.0))

#esp.osdebug(None)

# display flash size
#import port_diag

# do not include for 512k port
# free file system
i= statvfs('/')
fs = i[1]*i[2]/(1024.0*1024.0)
free= i[0]*i[4]/(1024.0*1024.0)
per = (float(free)/float(fs))
print('file system size %0.1f, free %0.1f, used in percent %0.1f' %(fs, free, per))

#uos.dupterm(None, 1) # disable REPL on UART(0)

# start webrepl after wifi. will be on 192.168.1.4:8266 (connect to wemos ssid) 
# and on local IP on home router as well
#WebREPL daemon started on ws://192.168.4.1:8266
#WebREPL daemon started on ws://192.168.1.5:8266
#Started webrepl in #ormal mode


# does not work on 512K, no file system ?
Exemple #26
0
print("version: ", sys.version)
print("sys.path: ", sys.path)  # list
print("modules imported: ", sys.modules)  # dict

print('cpu frequency: %d Mhz' % (freq() / 1000000))
print('flash size in Mbytes: ', flash_size() / (1024.0 * 1024.0))
print('ESP32 internal temp %d' % (int(raw_temperature() - 32) * 5.0 / 9.0))

#esp.osdebug(None)
#to display flash size
#import port_diag

import uos
# do not include for 512k port, no file system
# free file system
i = uos.statvfs('/')
fs = i[1] * i[2] / (1024.0 * 1024.0)
free = i[0] * i[4] / (1024.0 * 1024.0)
per = (float(free) / float(fs))
print('file system size %0.1f, free %0.1f, free in percent %0.1f' %
      (fs, free, per))

#uos.dupterm(None, 1) # disable REPL on UART(0)


def start_repl():
    # need to import once webrepl_setup from a usb/ttl connection to set password
    # creates webrepl_cfg.py (not visible in uPyCraft, visible w: os.listdir()
    # cannot just browse to IP, need client http://micropython.org/webrepl/
    import webrepl
    print('import webrepl_setup once to set password')
Exemple #27
0
        print(self.id, 'open', file, mode)


# first we umount any existing mount points the target may have
try:
    uos.umount('/')
except OSError:
    pass
for path in uos.listdir('/'):
    uos.umount('/' + path)

# stat root dir
print(uos.stat('/'))

# statvfs root dir; verify that f_namemax has a sensible size
print(uos.statvfs('/')[9] >= 32)

# getcwd when in root dir
print(uos.getcwd())

# basic mounting and listdir
uos.mount(Filesystem(1), '/test_mnt')
print(uos.listdir())

# ilistdir
i = uos.ilistdir()
print(next(i))
try:
    next(i)
except StopIteration:
    print('StopIteration')
Exemple #28
0
def show_memory():
    fs_stat = uos.statvfs('/')
    fs_size = fs_stat[0] * fs_stat[2]
    fs_free = fs_stat[0] * fs_stat[3]
    print("File System Size {:,} - Free Space {:,}".format(fs_size, fs_free))
Exemple #29
0
        print(self.id, 'open', file, mode)


# first we umount any existing mount points the target may have
try:
    uos.umount('/')
except OSError:
    pass
for path in uos.listdir('/'):
    uos.umount('/' + path)

# stat root dir
print(uos.stat('/'))

# statvfs root dir; verify that f_namemax has a sensible size
print(uos.statvfs('/')[9] >= 32)

# getcwd when in root dir
print(uos.getcwd())

# basic mounting and listdir
uos.mount(Filesystem(1), '/test_mnt')
print(uos.listdir())

# ilistdir
i = uos.ilistdir()
print(next(i))
try:
    next(i)
except StopIteration:
    print('StopIteration')
Exemple #30
0
import gc

import uos
import logging

main_logger = logging.getLogger(None)
main_logger.setLevel(logging.DEBUG)
logging.debug("In BOOT.")

# Diagnostic info - not needed in production
gc.collect()
logging.debug('free memory: ' + str(gc.mem_free()))

fs_stat = uos.statvfs('//')
logging.info('Free flash: {0} MB'.format((fs_stat[0] * fs_stat[3]) / 1048576))
Exemple #31
0
def checkSpace():
    return os.statvfs('/')[0] * os.statvfs('/')[3]