def _print_ex(msg, e): print('== [Exception] ====================') print(msg) sys.print_exception(e) print('---------------------') micropython.mem_info() print('===================================')
async def request_handler(self, reader, writer): Pins.power_led.off() print( '__________________________________________________________________________________' ) gc.collect() try: await self.send_response(reader, writer) except Exception as e: sys.print_exception(e) self.message = str(e) from http_utils import send_redirect await send_redirect(writer) await uasyncio.sleep(3) if isinstance(e, MemoryError): micropython.mem_info(1) from reset import ResetDevice ResetDevice(reason='MemoryError: %s' % e).reset() print('close writer') gc.collect() await writer.aclose() self.context.watchdog.garbage_collection() if __debug__: micropython.mem_info(1) Pins.power_led.on() print( '----------------------------------------------------------------------------------' )
async def main_state_machine(): STATES = { "checkready": action_checkready, "time": action_time, "departure": action_departure, } state = "checkready" exCount = 0 while True: sync_garbage_collect() if __debug__: log.debug("state -> {}".format(state)) log.debug('free: {} allocated: {}'.format(gc.mem_free(), gc.mem_alloc())) # pylint: disable=no-member m.mem_info() try: state = await STATES[state]() except Exception as e: exCount += 1 if exCount > 5: machine.reset() display.text("err") log.error("failed on state({}) ".format(state)) sys.print_exception(e) # pylint: disable=no-member await asyncio.sleep_ms(10000) await asyncio.sleep_ms(config.get("toggle_delay"))
def parse(verbose=False): mem_info() gc.collect() mem_info() count = 0 while True: pkt = Radio.rx() if pkt is None: continue try: ieee, typ = Parser.parse(pkt, filter_dupes=True) if typ is None: continue except: print(pkt) raise if typ != "zcl": if typ == "zcl?" and ieee.payload.payload.cluster != 0: print(ieee) continue if verbose: print(ieee) #cluster = ieee.payload.payload.cluster # IEEE/NWK/APS/ZCL/ZCL zb = ieee.payload.payload.payload zcl = zb.payload #print(ieee) if verbose or zb.command != 0x0B: print(zcl)
def __thread(self): while True: console("\t| thread --[{}s] {}".format(self.period_sec, self.callback)) output = self.callback(None) console("\t|--> {}\n".format(output), end='\r') micropython.mem_info() time.sleep(self.period_sec)
def main(server=SERVER): #client = MQTTClient(CLIENT_ID, server) # Subscribed messages will be delivered to this callback client.set_callback(sub_cb) #print("connecting MQTT client") ### 20180407 with deepsleep OSError 118 after this message ### #client.connect() mqtt_connect() print("subcribing to topic") client.subscribe(TOPIC) print_pub_status("Connected to {}, subscribed to {} topic".format( server, TOPIC)) try: # this is the main loop # while 1: micropython.mem_info() # 1. publish led status print_pub_status("led state is {}".format(ledstate)) # 2. publish dht publish_dht() # 3. check message -> led on/off/toggle #print("waiting message") #client.wait_msg() print_pub_status('checking message') client.check_msg( ) ### 20180407 with deepsleep, no message are found by check.msg() print_pub_status('going to sleep') sleep(5) print_pub_status('waking from sleep') print('going to deepsleep') deepsleep(5000) finally: client.disconnect()
def system(): i = 0 components = Components() gpu = components.gpu screen = components.screen gpu.bind(screen.address) gpu.setBackground(0x000000) gpu.setForeground(0xFFFFFF) gpu.fill(1, 1, 80, 25, " ") gpu.set(1, 1, "hello world in MicroPython") gc.enable() x = 1 while True: micropython.mem_info() signal = oc.computer.pullSignal() if not signal: # obj = oc.execution.Sleep(0) obj = None pause(obj) continue print(signal) name, args = signal if name == "key_down": address, ch, limit, user = args ch = int(ch) char = chr(ch) gpu.set(x, 2, char) x += 1
async def request_handler(self, reader, writer): self.start_time = utime.ticks_ms() await self.send_response(reader, writer) gc.collect() if __debug__: micropython.mem_info(1) print('----------------------------------------------------------------------------------')
def test(): import framebuf, gc, micropython # direct display access test (display.fill(colors.BGR565_WHITE)) display.fill_rectangle(20, 20, 90, 90, colors.BGR565_RED) display.fill_rectangle(200, 20, 90, 90, colors.BGR565_GREEN) display.fill_rectangle(114, 130, 90, 90, colors.BGR565_BLUE) display.text("test 1 2 3", 20, 20, colors.BGR565_BLACK, colors.BGR565_WHITE) # framebuffered access tesst rawbuffer = bytearray(display.width * display.height * 2) fb = framebuf.FrameBuffer(rawbuffer, display.width, display.height, framebuf.RGB565) fb.fill(colors.BGR565_RED) display.blit_buffer(rawbuffer, 0, 0, display.width, display.height) fb.fill(colors.BGR565_GREEN) display.blit_buffer(rawbuffer, 0, 0, display.width, display.height) fb.fill(colors.BGR565_BLUE) display.blit_buffer(rawbuffer, 0, 0, display.width, display.height) fb.fill(colors.BGR565_BLACK) display.blit_buffer(rawbuffer, 0, 0, display.width, display.height) # Higher level access text() fb.fill(colors.BGR565_BLACK) display.blit_buffer(rawbuffer, 0, 0, display.width, display.height) display.text("Random plot", 10, 10, colors.BGR565_BLACK, colors.BGR565_WHITE) graph() micropython.mem_info() fb = None rawbuffer = None gc.collect() micropython.mem_info()
def print_memory_diagnostics(): # see https://docs.micropython.org/en/latest/reference/constrained.html gc.enable() gc.collect() micropython.mem_info() print("-----------------------------") print("Initial free: {} allocated: {}".format(gc.mem_free(), gc.mem_alloc())) def func(): # dummy memory assignment import urandom x = [urandom.random() for i in range(100)] return gc.collect() print("Func definition: {} allocated: {}".format(gc.mem_free(), gc.mem_alloc())) func() print("Func run free: {} allocated: {}".format(gc.mem_free(), gc.mem_alloc())) gc.collect() print("Garbage collect free: {} allocated: {}".format( gc.mem_free(), gc.mem_alloc())) print("-----------------------------") micropython.mem_info(1)
def pye(file_name, tab_size=4, undo=50): from micropython import mem_info ## prepare content gc.collect() ## all (memory) is mine edit = Editor(tab_size, undo) try: edit.get_file(file_name) except Exception as err: edit.message = "{!r}".format(err) ## edit edit.init_tty() while True: try: key = edit.edit_loop() ## edit buffer if key == KEY_QUIT: break elif key == KEY_GET: pass elif key == KEY_NEXT: pass except Exception as err: edit.message = "{!r}".format(err) ## All windows closed, clean up edit.deinit_tty() edit.yank_buffer = [] ## close mem_info() edit = None gc.collect()
def main(): print("") print("Boot") if sys_config.ssid: sta_if = network.WLAN(network.STA_IF) if not sta_if.isconnected(): print('Connecting to network...') sta_if.active(True) sta_if.connect(sys_config.ssid, sys_config.password) while not sta_if.isconnected(): pass print('network config:', sta_if.ifconfig()) network.WLAN(network.AP_IF).active(False) mqtt = mqtt_wrap.mqtt_wrap() bootloader = mqtt_bootloader(mqtt) gc.collect() micropython.mem_info() mqtt.check_msg() if sys_config.app_autorun: bootloader.run_app() while True: mqtt.check_msg() utime.sleep(1)
def collectMemory(memoryMap=False): s = mem_free() collect() e = mem_free() reportText = '{:d}->{:d}'.format(s, e) if memoryMap: mem_info(1) return reportText
def profiling_info(label=""): """ Runtime memory measurements """ if cfgget('dbg'): console_write("{} [PROFILING INFO] - {} {}".format('~'*5, label, '~'*5)) mem_info() console_write("~"*30)
def mem(verbose=False): if verbose: print("{:18} {:9}".format("GC total ", gc.mem_alloc() + gc.mem_free())) micropython.mem_info() print("{:18} {:9}".format("mp stack use", micropython.stack_use())) print("{:18} {:9}".format("GC free", gc.mem_free())) print("{:18} {:9}".format("heap internal free", pycom.get_free_heap()[0])) print("{:18} {:9}".format("heap external free", pycom.get_free_heap()[1]))
def mem_info(verbose=True, auto_free=True): if auto_free: gc.collect() if verbose: micropython.mem_info(1) else: micropython.mem_info() return gc.mem_free()
def cmd_mem(cmd: dict) -> tuple: if MICROPYTHON: import micropython micropython.mem_info() # print direct only :-( import gc gc.collect() f = gc.mem_free() return (0, f)
async def memory_stats(interval): import micropython import gc sleep = loop.sleep(interval * 1000 * 1000) while True: micropython.mem_info() gc.collect() await sleep
def do_read(): global canAccess working = True if uname()[0] == 'esp32': rdr = mfrc522.MFRC522(18, 23, 19, 4, 26) else: raise RuntimeError("Unsupported platform") print("") print("Place card before reader to read from address 0x08") print("") hex_uid = "" global start_reading start_reading = time.ticks_ms() try: while (working): client.check_msg() (stat, tag_type) = rdr.request(rdr.REQIDL) if stat == rdr.OK: (stat, raw_uid) = rdr.anticoll() if stat == rdr.OK: start_reading = time.ticks_ms() print("New card detected") print(" - tag type: 0x%02x" % tag_type) hex_uid = twoDigitHex(raw_uid[0]) + twoDigitHex(raw_uid[1]) + twoDigitHex(raw_uid[2]) + twoDigitHex(raw_uid[3]) print(hex_uid) msg = ("UID={}".format(hex_uid)) client.publish(rfid_swipe, msg) print("Publish to broker") if rdr.select_tag(raw_uid) == rdr.OK: key = [0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF] if rdr.auth(rdr.AUTHENT1A, 8, key, raw_uid) == rdr.OK: print("Address 8 data: %s" % rdr.read(8)) rdr.stop_crypto1() else: print("Authentication error") else: print("Failed to select tag") sleep_ms(300) micropython.mem_info() client.wait_msg() sleep_ms(1000) print("Can Access Value") print(canAccess) else: if (abs(time.ticks_diff(time.ticks_ms(), start_reading) > 60000)): print("Going to sleep") client.publish(device_state, "OFF") sleep_ms(1000) machine.deepsleep() except KeyboardInterrupt: print("Bye")
async def __gc(self): hw.log.debug("Starting ntp update job") while True: try: hw.log.debug("GC") mem_info() collect() mem_info() await sleep(hw.GC_INTERVAL) except BaseException as e: hw.log.error("GC exception %s", e)
def handle_command(self, args): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format(capacity, mem_free, int( ((capacity - mem_free) / capacity) * 100.0))) if "-i" in args: import micropython micropython.mem_info(1)
def onclose(w): workflows.remove(w) if not layouts and default_layout: startdefault(default_layout) if __debug__: import micropython from trezor import utils if utils.LOG_MEMORY: micropython.mem_info()
def mem(level=None): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format(capacity, mem_free, int( ((capacity - mem_free) / capacity) * 100.0))) if level: import micropython micropython.mem_info(level)
def showOS(): import micropython micropython.mem_info(1) gg.display.fill(0) gg.display.text("Free: " + str(gc.mem_free()), 0, 10) gg.display.text("Alloc: " + str(gc.mem_alloc()), 0, 20) gg.display.show() utime.sleep_ms(5000) micropython.mem_info(1) gc.collect() drawMenu(10)
def mem(level=None): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format( capacity, mem_free, int(((capacity - mem_free) / capacity) * 100.0))) if level: import micropython micropython.mem_info(level)
def handle_command(self, args): import gc mem_alloc = gc.mem_alloc() mem_free = gc.mem_free() capacity = mem_alloc + mem_free print(" capacity\tfree\tusage") print(" {}\t{}\t{}%".format( capacity, mem_free, int( ((capacity - mem_free) / capacity) * 100.0))) if "-i" in args: import micropython micropython.mem_info(1)
def main(debug=False): guidescope = AutoguiderScope(debug=True) while True: try: guidescope.task() except KeyboardInterrupt: raise except MemoryError as exc: exclogger.log_exception(exc, to_file=False) micropython.mem_info(True) except Exception as exc: exclogger.log_exception(exc)
def main(debug = False): #polarscope = PolarScope(debug = True, simulate_file = "simulate.bmp") polarscope = PolarScope(debug = True) while True: try: polarscope.task() except KeyboardInterrupt: raise except MemoryError as exc: exclogger.log_exception(exc, to_file = False) micropython.mem_info(True) except Exception as exc: exclogger.log_exception(exc)
async def report(channel): # DEBUG global started while not rx_started: await asyncio.sleep(1) await asyncio.sleep(30) print('Start recording statistics') started = True fs = '************** Fail count: {} dupes: {} missing: {} wrong length: {}' while True: print(fs.format(channel._radio.failcount, dupe, missing, strfail)) await asyncio.sleep(60) gc.collect() micropython.mem_info()
def on_close(workflow: loop.Task) -> None: """Call when a workflow task has finished running.""" # Remove task from the running set. tasks.remove(workflow) if not tasks and default_constructor: # If no workflows are running, we should create a new default workflow # and run it. start_default(default_constructor) if __debug__: # In debug builds, we dump a memory info right after a workflow is # finished. if utils.LOG_MEMORY: micropython.mem_info()
def profiling_info(label=""): """ Runtime memory measurements """ if cfgget('dbg'): console_write("{} [PROFILING INFO] - {} {}".format( '~' * 5, label, '~' * 5)) try: mem_info() except Exception as e: console_write("MEM INFO QUERY ERROR: {}".format(e)) console_write("~" * 30) else: console_write("[PROFILING INFO] SKIP dbg:{}".format(cfgget('dbg')))
def main(**params): gc.collect() import logging logging.basicConfig(level=logging.INFO) # Preload templates to avoid memory fragmentation issues gc.collect() app._load_template('homepage.html') app._load_template('note.html') gc.collect() import micropython micropython.mem_info() app.run(debug=True, **params)
def mem_dump(filename: str) -> None: from micropython import mem_info print(f"### sysmodules ({len(sys.modules)}):") for mod in sys.modules: print("*", mod) if EMULATOR: from trezorutils import meminfo print("### dumping to", filename) meminfo(filename) mem_info() else: mem_info(True)
def check_mem(x: str | int = "") -> None: global PREV_MEM, CUR_MES gc.collect() free = gc.mem_free() diff = PREV_MEM - free log.debug( __name__, f"======= {CUR_MES} {x} Diff: {diff} Free: {free} Allocated: {gc.mem_alloc()}", ) micropython.mem_info() gc.collect() CUR_MES += 1 PREV_MEM = free
# tests meminfo functions in micropython module import micropython # these functions are not always available if not hasattr(micropython, 'mem_info'): print('SKIP') else: micropython.mem_info() micropython.mem_info(1) micropython.qstr_info() micropython.qstr_info(1)
def _handle(self, reader, writer): if self.debug > 1: micropython.mem_info() close = True req = None try: request_line = yield from reader.readline() if request_line == b"": if self.debug >= 0: self.log.error("%s: EOF on request start" % reader) yield from writer.aclose() return req = HTTPRequest() # TODO: bytes vs str request_line = request_line.decode() method, path, proto = request_line.split() if self.debug >= 0: self.log.info('%.3f %s %s "%s %s"' % (utime.time(), req, writer, method, path)) path = path.split("?", 1) qs = "" if len(path) > 1: qs = path[1] path = path[0] #print("================") #print(req, writer) #print(req, (method, path, qs, proto), req.headers) # Find which mounted subapp (if any) should handle this request app = self while True: found = False for subapp in app.mounts: root = subapp.url #print(path, "vs", root) if path[:len(root)] == root: app = subapp found = True path = path[len(root):] if not path.startswith("/"): path = "/" + path break if not found: break # We initialize apps on demand, when they really get requests if not app.inited: app.init() # Find handler to serve this request in app's url_map found = False for e in app.url_map: pattern = e[0] handler = e[1] extra = {} if len(e) > 2: extra = e[2] if path == pattern: found = True break elif not isinstance(pattern, str): # Anything which is non-string assumed to be a ducktype # pattern matcher, whose .match() method is called. (Note: # Django uses .search() instead, but .match() is more # efficient and we're not exactly compatible with Django # URL matching anyway.) m = pattern.match(path) if m: req.url_match = m found = True break if not found: headers_mode = "skip" else: headers_mode = extra.get("headers", self.headers_mode) if headers_mode == "skip": while True: l = yield from reader.readline() if l == b"\r\n": break elif headers_mode == "parse": req.headers = yield from self.parse_headers(reader) else: assert headers_mode == "leave" if found: req.method = method req.path = path req.qs = qs req.reader = reader close = yield from handler(req, writer) else: yield from start_response(writer, status="404") yield from writer.awrite("404\r\n") #print(req, "After response write") except Exception as e: if self.debug >= 0: self.log.exc(e, "%.3f %s %s %r" % (utime.time(), req, writer, e)) if close is not False: yield from writer.aclose() if __debug__ and self.debug > 1: self.log.debug("%.3f %s Finished processing request", utime.time(), req)