Exemplo n.º 1
0
 def get_esp_stats(self):
     import esp
     return {
         'flash_id': esp.flash_id(),
         'flash_size': esp.flash_size(),
         'free_mem': esp.freemem()
     }
Exemplo n.º 2
0
class FlashBdev:

    FS_SIZE = esp.flash_size()
    SEC_SIZE = esp.flash_sec_size()
    START_SEC = esp.flash_user_start() // SEC_SIZE

    def __init__(self, blocks):
        self.blocks = blocks

    def readblocks(self, n, buf):
        #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        esp.flash_read((n + self.START_SEC) * self.SEC_SIZE, buf)

    def writeblocks(self, n, buf):
        #print("writeblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        #assert len(buf) <= self.SEC_SIZE, len(buf)
        esp.flash_erase(n + self.START_SEC)
        esp.flash_write((n + self.START_SEC) * self.SEC_SIZE, buf)

    def ioctl(self, op, arg):
        #print("ioctl(%d, %r)" % (op, arg))
        if op == 4:  # BP_IOCTL_SEC_COUNT
            return self.blocks
        if op == 5:  # BP_IOCTL_SEC_SIZE
            return self.SEC_SIZE
Exemplo n.º 3
0
 def get_esp_stats(self):
     import esp
     return {
         'flash_id': esp.flash_id(),
         'flash_size': esp.flash_size(),
         'free_mem': esp.freemem()
     }
Exemplo n.º 4
0
def set_adc_vcc():
    sector_size = bdev.SEC_SIZE
    flash_size = esp.flash_size()
    init_sector = int(flash_size / sector_size - 4)
    data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
    data[107] = 255
    esp.flash_erase(init_sector)
    esp.flash_write(init_sector * sector_size, data)
    machine.reset()
Exemplo n.º 5
0
def flashinfo(display=True):
    """ Get flash informations """
    try:
        import esp
        result = b"Flash user=%s size=%s" % (sizeToBytes(
            esp.flash_user_start(), 1), sizeToBytes(esp.flash_size(), 1))
        if display:
            print(tostrings(result))
        else:
            return result
    except:
        return b"Flash unavailable"
Exemplo n.º 6
0
def set_adc_mode(mode):
    sector_size = bdev.SEC_SIZE
    flash_size = esp.flash_size()  # device dependent
    init_sector = int(flash_size / sector_size - 4)
    data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
    if data[107] == mode:
        return  # flash is already correct; nothing to do
    else:
        data[107] = mode  # re-write flash
        esp.flash_erase(init_sector)
        esp.flash_write(init_sector * sector_size, data)
        print("ADC mode changed in flash; restart to use it!")
        return
def search(offset, text):
    print('search for %r start with offset 0x%x' % (text, offset))

    offset_step = CHUNK_SIZE - len(text)

    if offset_step <= 0:
        raise AssertionError('Search text too large: increase CHUNK_SIZE!')

    def print_throughput():
        duration = utime.time() - start_time
        if duration == 0:
            throughput = -1
        else:
            throughput = (offset - start_offset) / duration / 1024
        print(
            '(Search duration: %i sec. - %i KBytes/sec' % (duration, throughput)
        )

    flash_size = esp.flash_size()
    start_offset = offset
    end_researched = False
    start_time = utime.time()
    next_update = start_time + 1
    while True:
        if offset + CHUNK_SIZE > flash_size:
            # Search to esp.flash_size(), but don't go beyond.
            offset = flash_size - CHUNK_SIZE
            end_researched = True

        try:
            esp.flash_read(offset, BUFFER)
        except OSError as e:
            print('Read flash error: %s at 0x%x - 0x%x' % (e, offset, offset + CHUNK_SIZE))
            return -1

        if text in BUFFER:
            print('Found in 0x%x !' % offset, end=' ')
            print_throughput()
            return offset

        if utime.time() >= next_update:
            print('Search: 0x%x ...' % offset, end=' ')
            print_throughput()
            next_update = utime.time() + 1

        if end_researched:
            print('Memory end researched, searched up to 0x%x' % (offset + CHUNK_SIZE))
            print_throughput()
            return -1

        offset += offset_step
Exemplo n.º 8
0
def main():
    print("Hello Welcome to SYDCA ESP OS")

    print("Flash_id:" + str(esp.flash_id()))
    machid = str(machine.unique_id())
    machid = ure.sub("\\\\x", "", machid)
    machid = ure.sub("b'", "", machid)
    machid = ure.sub("'", "", machid)
    print("Machine Id:" + str(machid))
    print("Flash Size:" + str(esp.flash_size()))
    boot_init()
    # print(initfile.readlines())
    print("Start Running Mode")
    load_init_file()
Exemplo n.º 9
0
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)))
Exemplo n.º 10
0
	def getMessage(self):
		""" This method is paring a measured values into json format """
		print("Prepare message for measurements")

		header = "HTTP/1.1 200 OK\nContent-Type: application/json\r\n\n"
		html1 = """<!DOCTYPE html>
<html>
    <head> <title>ESP8266 Pins</title> </head>
    <body>"""
		html2 = """</body>
</html>
"""
		msg = json.dumps({"version" : self.sysVersion, "flashSize:": str(esp.flash_size())})
		return header + msg
Exemplo n.º 11
0
    def display_info(self):
        gc.collect()
        output = dict(
            freq=int(machine.freq() / 1_000_000),
            flash=esp.flash_size(),
            hall=esp32.hall_sensor(),
            temp=int((esp32.raw_temperature() - 32) / 1.8),
            mac=self.network.mac,
            ip=self.network.ip,
            ram=gc.mem_free(),
        )

        output = ["%s: %s" % (key, val) for key, val in output.items()]

        self.screen.display_lines(output)
Exemplo n.º 12
0
 def get_flash_stats(self):
     stats = os.statvfs('/')
     frsize = stats[1]
     blocks = stats[2]
     bavail = stats[4]
     capacity = blocks * frsize
     free = bavail * frsize
     used = capacity - free
     return {
         'flash_id': esp.flash_id(),
         'flash_size': esp.flash_size(),
         'capacity': capacity,
         'used': used,
         'free': free
     }
Exemplo n.º 13
0
def set_adc_mode(mode):
    sector_size = bdev.SEC_SIZE
    flash_size = esp.flash_size() # device dependent
    init_sector = int(flash_size / sector_size - 4)
    data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
    if data[107] == mode:
        return  # flash is already correct; nothing to do
    else:
        print( "*** Going to adjust the ADC type in the flashed memory" );
        print( "*** You will need to hit the 'RST' button, near the USB port" );
        print( "*** when it's done" );
        data[107] = mode  # re-write flash
        esp.flash_erase(init_sector)
        esp.flash_write(init_sector * sector_size, data)
        print("*** ADC mode changed in flash; restart to use it!")
        return
Exemplo n.º 14
0
def adc_mode(mode=None):
    import flashbdev

    sector_size = flashbdev.bdev.SEC_SIZE
    flash_size = esp.flash_size()  # device dependent
    init_sector = int(flash_size / sector_size - 4)
    data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
    current_mode = data[107]
    if mode is None:  # Read adc mode
        return current_mode
    if current_mode == mode:
        print("ADC mode already {}.".format(mode))
    else:
        data[107] = mode  # re-write flash
        esp.flash_erase(init_sector)
        esp.flash_write(init_sector * sector_size, data)
        print("ADC mode is now {}. Reset to apply.".format(mode))
    return mode
Exemplo n.º 15
0
def set_adc_mode(adc=0):
    ADC_MODE_ADC = 0
    ADC_MODE_VCC = 255

    mode = {0: ADC_MODE_ADC, 1: ADC_MODE_VCC}
    sector_size = bdev.SEC_SIZE
    flash_size = esp.flash_size()  # device dependent
    init_sector = int(flash_size / sector_size - 4)
    data = bytearray(esp.flash_read(init_sector * sector_size, sector_size))
    if data[107] == mode[adc]:
        print("ADC mode is already set in flash!")
        return
    else:
        data[107] = mode[adc]  # re-write flash
        esp.flash_erase(init_sector)
        esp.flash_write(init_sector * sector_size, data)
        print("ADC mode has been changed in flash; restart to use it!")
        return
Exemplo n.º 16
0
 async def sys_monitor():
     row1 = "4. System monitor"
     row1_colour = 'black'
     row2 = "Uptime: %s" % (time() - net.startup_time)
     row2_colour = 'blue'
     row3 = "Mem free: %s" % gc.mem_free()
     row3_colour = 'blue'
     row4 = "Mem allocated: %s" % gc.mem_alloc()
     row4_colour = 'blue'
     row5 = "Flash size: %s " % esp.flash_size()
     row5_colour = 'blue'
     row6 = "MCU Temp: %sC" % ("{:.1f}".format(((float(esp32.raw_temperature())-32.0) * 5/9)))
     row6_colour = 'blue'
     row7 = "Hall sensor %s" % esp32.hall_sensor()
     row7_colour = 'blue'
     rows = row1, row2, row3, row4, row5, row6, row7
     row_colours = row1_colour, row2_colour, row3_colour, row4_colour, row5_colour, row6_colour, row7_colour
     return rows, row_colours
Exemplo n.º 17
0
def do_get(clisock, uri, content_length):
    clisock.write(b'HTTP/1.0 200 OK\r\n'
        b'Content-type: text/html; charset=utf-8\r\n'
        b'\r\n')
    clisock.write(b'<!DOCTYPE html><html><head><title>Current time</title></head>')
    clisock.write(b'<body>The current time is: ')
    timestr ='{}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}'.format(*time.localtime())
    clisock.write(timestr.encode('ascii'))
    del timestr
    uptime_s = int(time.ticks_ms() / 1000)
    uptime_h = int(uptime_s / 3600)
    uptime_m = int(uptime_s / 60)
    uptime_m = uptime_m % 60
    uptime_s = uptime_s % 60
    
    clisock.write(b'<p>Uptime: {:02d}h {:02d}:{:02d}'.format(
        uptime_h, uptime_m, uptime_s))

    clisock.write(b'<p>Flash ID: {:x}'.format(esp.flash_id()))
    clisock.write(b'<p>Flash size: {:d}'.format(esp.flash_size()))
    clisock.write(b'<p>Python: {:s} on {:s} '.format(str(sys.implementation), sys.platform))
    clisock.write(b'<p>Unique ID: ')
    for b in machine.unique_id():
        clisock.write(b'{:02x}'.format(b))
    clisock.write(b'\n<h2>Network interfaces</h2>\n')
    clisock.write(b'\n<table><tr><th>mac<th>active</th><th>connected</th><th>IP</th><th>Gateway</th>')
    for i in network.STA_IF, network.AP_IF:
        wlan = network.WLAN(i)
        # Show MAC address.
        clisock.write(b'<tr>')
        clisock.write(b'<td>')
        for b in wlan.config('mac'):
            clisock.write(b'{:02X}'.format(b))

        clisock.write(b'<td>{:}</td>'.format(wlan.active()))
        clisock.write(b'<td>{:}</td>'.format(wlan.isconnected()))
        ifconfig = wlan.ifconfig() #ip, netmask, gateway, dns
        ifconfig = (ifconfig[0], ifconfig[2]) # ip, gw
        for item in ifconfig:
            clisock.write(b'<td>{:}</td>'.format(item))

    clisock.write(b'\n</table>\n')
Exemplo n.º 18
0
 def set_adc_mode(mode):
     sector_size = bdev.SEC_SIZE
     flash_size = esp.flash_size()  # device dependent
     init_sector = int(flash_size / sector_size - 4)
     try:
         data = bytearray(
             esp.flash_read(init_sector * sector_size, sector_size))
         if data[107] == mode:
             return True  # flash is already correct; nothing to do
         else:
             data[107] = mode  # re-write flash
             esp.flash_erase(init_sector)
             esp.flash_write(init_sector * sector_size, data)
             return False
     except MemoryError:
         log = logger.get_logger()
         log.log_msg(
             logger.ERROR,
             "Could not allocate memory for setting adc mode, assuming it's {}"
             .format(_num_to_mode[mode]))
         return True
Exemplo n.º 19
0
def Maintain():
    import esp, gc

    # gc.collect() after boot.py
    # Memory Stats: Allocated(12352) Free(23616) Diff(-Freed 560) Total(4194304) in bytes
    # gc.collect() after idling
    # Memory Stats: Allocated(12352) Free(23616) Diff(-Freed 832) Total(4194304) in bytes
    # gc.collect() after a single request
    # Memory Stats: Allocated(12608) Free(23360) Diff(-Freed 1248) Total(4194304) in bytes

    mem_before = gc.mem_free()
    gc.collect()
    mem_after = gc.mem_free()
    if mem_before > mem_after:
        mem_diff = '+Freed {}'.format(mem_before - mem_after)
    else:
        mem_diff = '-Freed {}'.format(mem_after - mem_before)

    mem_total = esp.flash_size()
    print(
        'Memory Stats: Allocated({1}) Free({2}) Diff({3}) Total({0}) in bytes'.
        format(mem_total, gc.mem_alloc(), gc.mem_free(), mem_diff))
    return
Exemplo n.º 20
0
# This file is executed on every boot (including wake-boot from deepsleep)
#
import sys
import esp
#esp.osdebug(None)
import uos, machine
# uos.dupterm(None, 1) # disable REPL on UART(0)
import gc
# import webrepl
# webrepl.start()
gc.collect()
sys.path.append('/main')

reasons = {
    0: "Power On Reset",
    1: "Watchdog Timer Reset",
    4: "Soft Reset",
    5: "Deepsleep Reset",
    6: "Hard Reset"
}

# print ("Machine id: " + hex(machine.unique_id()) )
print("")
print(uos.uname().machine)
print("Running verson: " + uos.uname().version)
print("Reason for reset: " + reasons.get(machine.reset_cause()))
print("Flash size: " + str(esp.flash_size()))
print("Free memory: " + str(esp.freemem()))

import app
 MicroPython with the ESP32
 https://techexplorations.com

'''

import random
from esp32 import Partition
import esp
import uos

filename = "csv_data_file.txt"

# Get some statistics:
print(
    "Available flash space: ",
    esp.flash_size())  # This will give you the total amount of Flash available

partition = Partition(Partition.RUNNING)
print(
    partition.info()
)  # Print out information about the running flash partition on which you can store your files.

file_stats = uos.stat(filename)
print(
    "File size before write: ", file_stats[6]
)  # the item at index 6 of the tupple contains the total bytes in the file.

# This loop will add 10 lines that contain dummy comma-delimited data.
for x in range(10):
    random_temp = random.randint(0, 50)
    random_humi = random.randint(20, 90)
Exemplo n.º 22
0
Pins 6, 7, 8, 11, 16, and 17 are used for connecting the embedded flash, and are not recommended for other uses
Pins 34-39 are input only, and also do not have internal pull-up resistors
The pull value of some pins can be set to Pin.PULL_HOLD to reduce power consumption during deepsleep.

"""

print(os.uname(), '\n')

print("implementation: ", sys.implementation)  # no ()
print("platform: ", sys.platform)
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))
Exemplo n.º 23
0
    RESERVED_SECS = 0
    START_SEC = esp.flash_user_start() // SEC_SIZE + RESERVED_SECS
    NUM_BLK = 0x6b - RESERVED_SECS

    def __init__(self, blocks=NUM_BLK):
        self.blocks = blocks

    def readblocks(self, n, buf):
        #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        esp.flash_read((n + self.START_SEC) * self.SEC_SIZE, buf)

    def writeblocks(self, n, buf):
        #print("writeblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        #assert len(buf) <= self.SEC_SIZE, len(buf)
        esp.flash_erase(n + self.START_SEC)
        esp.flash_write((n + self.START_SEC) * self.SEC_SIZE, buf)

    def ioctl(self, op, arg):
        #print("ioctl(%d, %r)" % (op, arg))
        if op == 4:  # BP_IOCTL_SEC_COUNT
            return self.blocks
        if op == 5:  # BP_IOCTL_SEC_SIZE
            return self.SEC_SIZE

size = esp.flash_size()
if size < 1024*1024:
    bdev = None
else:
    # 20K at the flash end is reserved for SDK params storage
    bdev = FlashBdev((size - 20480) // FlashBdev.SEC_SIZE - FlashBdev.START_SEC)
Exemplo n.º 24
0
        code = 2
    buf = bytearray(4096)
    esp.flash_read(0, buf)
    buf[3] = (buf[3] & 0xf) | (code << 4)
    esp.flash_erase(0)
    esp.flash_write(0, buf)


# If bootloader size ID doesn't correspond to real Flash size,
# fix bootloader value and reboot.
size = esp.flash_id() >> 16
# Check that it looks like realistic power of 2 for flash sizes
# commonly used with esp8266
if 22 >= size >= 18:
    size = 1 << size
    if size != esp.flash_size():
        import machine
        import time
        print(
            "Bootloader Flash size appear to have been set incorrectly, trying to fix"
        )
        set_bl_flash_size(size)
        machine.reset()
        while 1:
            time.sleep(1)

size = esp.flash_size()
if size < 1024 * 1024:
    bdev = None
else:
    # 20K at the flash end is reserved for SDK params storage
Exemplo n.º 25
0
class FlashBdev:

    SEC_SIZE = 4096
    START_SEC = 0x89000 // SEC_SIZE
    NUM_BLK = 0x73

    def __init__(self, blocks=NUM_BLK):
        self.blocks = blocks

    def readblocks(self, n, buf):
        print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        esp.flash_read((n + self.START_SEC) * self.SEC_SIZE, buf)

    def writeblocks(self, n, buf):
        print("writeblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        assert len(buf) <= self.SEC_SIZE, len(buf)
        esp.flash_erase(n + self.START_SEC)
        esp.flash_write((n + self.START_SEC) * self.SEC_SIZE, buf)

    def ioctl(self, op, arg):
        print("ioctl(%d, %r)" % (op, arg))
        if op == 4:  # BP_IOCTL_SEC_COUNT
            return self.blocks
        if op == 5:  # BP_IOCTL_SEC_SIZE
            return self.SEC_SIZE

if esp.flash_size() < 1024*1024:
    bdev = None
else:
    bdev = FlashBdev()
Exemplo n.º 26
0
    START_SEC = esp.flash_user_start() // SEC_SIZE

    def __init__(self, blocks):
        self.blocks = blocks

    def readblocks(self, n, buf):
        #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        esp.flash_read((n + self.START_SEC) * self.SEC_SIZE, buf)

    def writeblocks(self, n, buf):
        #print("writeblocks(%s, %x(%d))" % (n, id(buf), len(buf)))
        #assert len(buf) <= self.SEC_SIZE, len(buf)
        esp.flash_erase(n + self.START_SEC)
        esp.flash_write((n + self.START_SEC) * self.SEC_SIZE, buf)

    def ioctl(self, op, arg):
        #print("ioctl(%d, %r)" % (op, arg))
        if op == 4:  # BP_IOCTL_SEC_COUNT
            return self.blocks
        if op == 5:  # BP_IOCTL_SEC_SIZE
            return self.SEC_SIZE


size = esp.flash_size()
if size < 1024 * 1024:
    # flash too small for a filesystem
    bdev = None
else:
    # for now we use a fixed size for the filesystem
    bdev = FlashBdev(256 * 1024 // FlashBdev.SEC_SIZE)
Exemplo n.º 27
0
    async def send_response(self, reader, writer):
        peername = writer.get_extra_info('peername')
        print('\nRequest from:', peername)
        await writer.awrite(b'HTTP/1.0 200 OK\r\n')
        await writer.awrite(b'Content-type: text/html; charset=utf-8\r\n\r\n')

        await writer.awrite(_HTML_PREFIX)

        await writer.awrite(b'Your IP: %s port:%s\n' % peername)

        await writer.awrite(b'\n')

        method, url, querystring = await self.parse_request(reader)

        offset = int(querystring.get('offset', 0))
        print('Current offset:', repr(offset))
        search_text = querystring.get('text', '')
        print('search text:', repr(search_text))

        await writer.awrite(b'<pre>')
        # await writer.awrite(b'Method: %s\n' % method)
        # await writer.awrite(b'URL: %s\n' % url)
        # await writer.awrite(b'querystring: %s\n' % querystring)

        await writer.awrite(b'flash size: {size} Bytes (0x{size:x})\n'.format(
            size=esp.flash_size()
        ))
        await writer.awrite(b'flash user start: {user_start} Bytes (0x{user_start:x})\n'.format(
            user_start=esp.flash_user_start()
        ))

        if search_text:
            await writer.awrite(b'search for: %r\n' % search_text)
            offset = await search(writer, offset, text=search_text.encode('UTF-8'))

        await writer.awrite(b'</pre>')

        await writer.awrite(b'<table id="hex">')

        await hex_dump(writer, offset=offset)
        await writer.awrite(b'</table>')

        back_offset = offset - (LINE_COUNT * CHUNK_SIZE)
        next_offset = offset + (LINE_COUNT * CHUNK_SIZE)
        print('back', back_offset, 'next', next_offset)
        await writer.awrite(
            b'<a href="/?offset={back}">back</a> <a href="/?offset={next}">next</a>'.format(
                back=back_offset,
                next=next_offset,
            )
        )

        alloc = gc.mem_alloc() / 1024
        free = gc.mem_free() / 1024

        await writer.awrite(
            b'<p>RAM total: {total:.2f} KB, used: {alloc:.2f} KB, free: {free:.2f} KB</p>'.format(
                total=alloc + free,
                alloc=alloc,
                free=free
            )
        )
        await writer.awrite(
            b'<p>Render time: %i ms</p>' % utime.ticks_diff(utime.ticks_ms(), self.start_time)
        )

        await writer.awrite(_HTML_FOOTER.format(text=search_text))
        await writer.aclose()
Exemplo n.º 28
0
station.active(True)

station.connect(ssid, password)

while station.isconnected() == False:
    pass

webrepl.start()

try:
    settime()
    log('set time successful!')
except:
    log('set time failed!!!')

log('Connection successful')
log('Controller IP: ' + str(station.ifconfig()[0]))
log('Allocated Heap: ' + str(gc.mem_alloc()))
log('Free Heap: ' + str(gc.mem_free()))
log('Flash ID: ' + str(esp.flash_id()))
log('Flash Size: ' + str(esp.flash_size()))
log('Current hour: ' + str(utime.localtime()[3] + 7))
log('UTC DateTime: ' + str(utime.localtime()))

day = str((utime.localtime()[2]))
hour = str(int((utime.localtime()[3]) + 7))
min = str((utime.localtime()[4]))

log('-->Boot completed at day:' + day + ' hour:' + hour + ' min:' + min)
Exemplo n.º 29
0
        code = 3
    elif real_size == 4096*1024:
        code = 4
    else:
        code = 2
    buf = bytearray(4096)
    esp.flash_read(0, buf)
    buf[3] = (buf[3] & 0xf) | (code << 4)
    esp.flash_erase(0)
    esp.flash_write(0, buf)

# If bootloader size ID doesn't correspond to real Flash size,
# fix bootloader value and reboot.
size = esp.flash_id() >> 16
# Check that it looks like realistic power of 2 for flash sizes
# commonly used with esp8266
if 22 >= size >= 18:
    size = 1 << size
    if size != esp.flash_size():
        import machine
        import time
        print("Bootloader Flash size appear to have been set incorrectly, trying to fix")
        set_bl_flash_size(size)
        machine.reset()
        while 1: time.sleep(1)

if esp.flash_size() < 1024*1024:
    bdev = None
else:
    bdev = FlashBdev()
Exemplo n.º 30
0
"""
Utilities for ESP based devices
MIT license
(C) Konstantin Belyalov 2017-2018
"""
import esp
import gc

# Store config right before SDK params close to the end of flash
BLOCK_SIZE = const(4096)
SDK_BLOCKS = 19
CONFIG_BLOCK = (esp.flash_size() // BLOCK_SIZE) - SDK_BLOCKS


class ConfigError(Exception):
    pass


def validate_name(name):
    if len(name) > 32:
        raise ConfigError('Name too long')
    if name.startswith('_'):
        raise ConfigError('Name shouldnt start with underscore')
    if ' ' in name:
        raise ConfigError('Spaces arent allowed in name')


def validate_value_type(value):
    if isinstance(value, int):
        return
    elif isinstance(value, str):
Exemplo n.º 31
0
 def __init__(self, start, size, sec_size):
     self.blocks = (esp.flash_size() - start) // sec_size
     self.START_SEC = start // sec_size
     self.SEC_SIZE = sec_size
Exemplo n.º 32
0
        code = 4
    else:
        code = 2
    buf = bytearray(4096)
    esp.flash_read(0, buf)
    buf[3] = (buf[3] & 0xf) | (code << 4)
    esp.flash_erase(0)
    esp.flash_write(0, buf)

# If bootloader size ID doesn't correspond to real Flash size,
# fix bootloader value and reboot.
size = esp.flash_id() >> 16
# Check that it looks like realistic power of 2 for flash sizes
# commonly used with esp8266
if 22 >= size >= 18:
    size = 1 << size
    if size != esp.flash_size():
        import machine
        import time
        print("Bootloader Flash size appear to have been set incorrectly, trying to fix")
        set_bl_flash_size(size)
        machine.reset()
        while 1: time.sleep(1)

size = esp.flash_size()
if size < 1024*1024:
    bdev = None
else:
    # 20K at the flash end is reserved for SDK params storage
    bdev = FlashBdev((size - 20480) // FlashBdev.SEC_SIZE - FlashBdev.START_SEC)
import esp, machine
# import gc
print("CPU frequency = {CPU}Mhz".format(CPU=machine.freq() /
                                        1000000))  #输出当前 CPU 频率
print("RAM used = {RAM_used}KB".format(RAM_used=gc.mem_alloc() /
                                       1024))  #输出已用 RAM
print("RAM free = {RAM_free}KB".format(RAM_free=gc.mem_free() /
                                       1024))  #输出可用 RAM
#print("RAM total = {RAM_total}KB".format(RAM_total = ( gc.mem_free() + gc.mem_alloc() ) / 1024))
print("FLASH total = {FLASH_total}KB".format(FLASH_total=esp.flash_size() /
                                             1024))  #输出 FLASH 的总容量
Exemplo n.º 34
0
    return hex(int(mac[0:2], 16) ^ 2)[2:] + mac[2:]


if IS_MICROPYTHON:

    # Node Name
    import machine
    import ubinascii
    uuid = ubinascii.hexlify(machine.unique_id()).decode()

    if IS_ESP8266:
        NODE_NAME = 'ESP8266_'
    if IS_ESP32:
        NODE_NAME = 'ESP32_'
        import esp
        IS_TTGO_LORA_OLED = (esp.flash_size() > 5000000)

    NODE_EUI = mac2eui(uuid)
    NODE_NAME = NODE_NAME + uuid

    # millisecond
    millisecond = time.ticks_ms

    # Controller
    SOFT_SPI = None
    if IS_TTGO_LORA_OLED:
        from controller_esp_ttgo_lora_oled import Controller
        SOFT_SPI = True
    else:
        from controller_esp import Controller
Exemplo n.º 35
0
def getstorage():
    try:
        s = esp.flash_size()
    except:
        s = 0
    return s