def testSizes(self): gc.collect() m0 = gc.mem_free() leds = WS2812(spi_bus=1, led_count=256, mem=PREALLOCATE) gc.collect() m1 = gc.mem_free() print((m1-m0)/256)
def testMemoryUsed8(self): leds = WS2812(spi_bus=1, led_count=64, mem=PREALLOCATE) prev_mem_free = gc.mem_free() for i in range(8): r,g,b = leds[i].r, leds[i].g, leds[i].b # no leak delta_mem = gc.mem_free() - prev_mem_free if platform == 'pyboard': self.assertEqual(delta_mem, 0)
def testMemoryUsed2(self): leds = WS2812(spi_bus=1, led_count=64, mem=PREALLOCATE) prev_mem_free = gc.mem_free() for i in range(8): leds[0] = b'\x08\x00\x00' # no leak delta_mem = gc.mem_free() - prev_mem_free if platform == 'pyboard': self.assertEqual(delta_mem, 0)
def testMemoryUsed4(self): leds = WS2812(spi_bus=1, led_count=64, mem=PREALLOCATE) bar = bytearray(range(3)) prev_mem_free = gc.mem_free() for i in range(8): leds[0] = bar # no leak delta_mem = gc.mem_free() - prev_mem_free if platform == 'pyboard': self.assertEqual(delta_mem, 0)
def testMemoryUsed10(self): leds = WS2812(spi_bus=1, led_count=64, mem=PREALLOCATE) prev_mem_free = gc.mem_free() for i in range(8): for k in range(len(leds[i])): # no leak leds[i][k] = leds[i-1][k] delta_mem = gc.mem_free() - prev_mem_free if platform == 'pyboard': self.assertEqual(delta_mem, 0)
def testMemoryUsed11(self): leds = WS2812(spi_bus=1, led_count=64, mem=PREALLOCATE) foolist = list(range(3)) prev_mem_free = gc.mem_free() for i in range(8): leds[i] = foolist # no leak delta_mem = gc.mem_free() - prev_mem_free if platform == 'pyboard': self.assertEqual(delta_mem, 0)
def perform(self) : import gc mem_free_before = gc.mem_free() gc.collect() self.mem_free = gc.mem_free() self.mem_alloc = gc.mem_alloc() mem_collected = self.mem_free - mem_free_before if mem_collected < self.min_collected : self.min_collected = mem_collected if self.max_collected < mem_collected : self.max_collected = mem_collected self.sum_collected += mem_collected self.num_collections += 1 return True
def install(to_install, install_path=None): # Calculate gzip dictionary size to use global gzdict_sz sz = gc.mem_free() + gc.mem_alloc() if sz <= 65536: gzdict_sz = 16 + 12 if install_path is None: install_path = get_install_path() if install_path[-1] != "/": install_path += "/" if not isinstance(to_install, list): to_install = [to_install] print("Installing to: " + install_path) # sets would be perfect here, but don't depend on them installed = [] try: while to_install: if debug: print("Queue:", to_install) pkg_spec = to_install.pop(0) if pkg_spec in installed: continue meta = install_pkg(pkg_spec, install_path) installed.append(pkg_spec) if debug: print(meta) deps = meta.get("deps", "").rstrip() if deps: deps = deps.decode("utf-8").split("\n") to_install.extend(deps) except Exception as e: print("Error installing '{}': {}, packages may be partially installed".format( pkg_spec, e), file=sys.stderr)
def tinyartnet(): while True: if transmitter: pktgen(drawdata) else: pktshow(drawdata) print("{} bytes free".format(gc.mem_free()))
def test(): dt = rtc.get_datetime() print("Now: %04d-%02d-%02d %02d:%02d:%02d" % dt[0:6], ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")[dt[6]]) day_date, hour, minute, second, mask = rtc.get_alarm_time_1(); print("Alarm 1: %d (%s) %02d:%02d:%02d" % (day_date, ('DT', 'DY')[mask >> 4], hour, minute, second), "Mask: {:04b}".format(mask & 0b1111), rtc.get_alarm1()) eosc, bbsqw, rs, intcn, a1ie, en32khz = rtc.get_config() for l in [("SYMBOL", 'NAME', 'DEFAULT', 'CURRENT VALUE'), ("EOSC", "Enable battery backup", True, eosc), ("BBSQW", "Enable battery backed square wave", False, bbsqw), ("RS", "Square wave rate select", "8.192kHz", ("1Hz", "1.024kHz", "4.096kHz", "8.192kHz")[rs]), ("INTCN", "Interrupt control (SQW=False INT=True)", True, intcn), ("A1IE", "Alarm 1 interrupt enable", True, a1ie), ("EN32kHz", "Enable 32kHz Output", True, en32khz)]: print("{:8} {:45} {!s:10} {}".format(*l)) print("Temperature: ", rtc.temp()) print("Aging offset: ", rtc.age_offset()) print("Mem Pre Collect:", gc.mem_free()) gc.collect() print("Mem Post Collect:", gc.mem_free())
def redraw(self, flag): self.cursor(False) Editor.height, Editor.width = self.get_screen_size() Editor.height -= 1 Editor.scrbuf = [(False,"\x00")] * Editor.height self.row = min(Editor.height - 1, self.row) if sys.implementation.name == "micropython": gc.collect() if flag: self.message = "{} Bytes Memory available".format(gc.mem_free())
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 redraw(self, flag): scr.cursor(False) Editor.scrbuf = [(False,"\x00")] * self.height ## force delete self.row = min(self.height - 1, self.row) #ifdef SCROLL scr.scroll_region(self.height) #endif #ifdef LINUX if sys.platform in ("linux", "darwin") and sys.implementation.name == "cpython": signal.signal(signal.SIGWINCH, scr.signal_handler) #endif if sys.implementation.name == "micropython": gc.collect() if flag: self.message = "{} Bytes Memory available".format(gc.mem_free())
def redraw(self, flag): self.cursor(False) Editor.height, Editor.width = self.get_screen_size() Editor.height -= 1 Editor.scrbuf = [(False,"\x00")] * Editor.height self.row = min(Editor.height - 1, self.row) self.scroll_region(Editor.height) self.mouse_reporting(True) if is_linux and not is_micropython: signal.signal(signal.SIGWINCH, Editor.signal_handler) self.message = PYE_VERSION if is_micropython: gc.collect() if flag: self.message += "{} Bytes Memory available".format(gc.mem_free())
def redraw(self, flag): self.cursor(False) Editor.height, Editor.width = self.get_screen_size() Editor.height -= 1 Editor.scrbuf = [(False,"\x00")] * Editor.height ## force delete self.row = min(Editor.height - 1, self.row) #ifdef SCROLL self.scroll_region(Editor.height) #endif #ifdef MOUSE self.mouse_reporting(True) ## enable mouse reporting #endif #ifdef LINUX if sys.platform in ("linux", "darwin") and sys.implementation.name == "cpython": signal.signal(signal.SIGWINCH, Editor.signal_handler) #endif if sys.implementation.name == "micropython": gc.collect() if flag: self.message = "{} Bytes Memory available".format(gc.mem_free())
def update_loop(url, interval=0, port=80): """ Download image, update display, sleep, loop. Gives up on any error :param url: :param interval: :param port: :return: """ e = EPD() e.enable() sep = url.find('/') host = url[:sep] path = url[sep:] del sep while True: print("Mem free: %d" % gc.mem_free()) c = Connect(host, port, debug=True) content = c.get_quick(path) print("Uploading...", end='') e.upload_whole_image(content) print("done.") e.display_update() del content del c if interval > 0: to_sleep = interval print("Sleeping for %ds" % interval, end='') time.sleep(to_sleep) print('.') else: input("Press enter to update (Ctrl-C to stop).") gc.collect()
def info_cmd(cli, cmd, rol): yield from cli.write('mem_alloc %s, mem_free %s' \ % (gc.mem_alloc(), gc.mem_free())) loop = yield GetRunningLoop(None) yield from cli.write(', qlen %d' % len(loop.q)) yield from cli.writeln('')
async def _garbage_collect(self): while True: await asyncio.sleep_ms(100) gc.collect() gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
import gc gc.threshold((gc.mem_free() + gc.mem_alloc()) // 2) import uos from flashbdev import bdev try: if bdev: vfs = uos.VfsFat(bdev, "") except OSError: import inisetup vfs = inisetup.setup() gc.collect()
import time import utime from L76micropyGPS import L76micropyGPS from micropyGPS import MicropyGPS from pytrack import Pytrack import gc # # You will need the following lines # The print statements can be removed - they are just here to debug # # enable GC gc.enable() print("Free Mem: {}".format(gc.mem_free())) # Start GPS, you need this line py = Pytrack() print("Free Mem post pytrack instantiation: {}".format(gc.mem_free())) # Start a microGPS object, you need this line my_gps = MicropyGPS(location_formatting='dd') print("Free Mem post my_gps instantiation: {}".format(gc.mem_free())) # Start the L76micropyGPS object, you need this line L76micropyGPS = L76micropyGPS(my_gps, py) # Start the thread, you need this line
async def mem_manage(): # Necessary for long term stability while True: await asyncio.sleep_ms(100) gc.collect() gc.threshold(gc.mem_free() // 4 + gc.mem_alloc())
import gc gc.threshold((gc.mem_free() + gc.mem_alloc()) // 4) import uos from flashbdev import bdev try: if bdev: uos.mount(bdev, '/') except OSError: import inisetup inisetup.setup() gc.collect() # Run Dobby loader import dobby.loader as DobbyLoader DobbyLoader.Run()
def dosettings(): switch_to(settings) settings.set_memfree(str(gc.mem_free()))
from taskmgr import * import taskmgr from opencom import syscall def hello(t:int) -> int: pass print(hello) @taskmgr.auto() def bios(): def syscall_dbg(funcname, *args): result = syscall(funcname, *args) print('>', result) return result syscall_dbg("hello", 3) syscall_dbg("hello2", "world!") syscall_dbg("hello2", "world2!") taskmgr.run(bios) import gc print(gc.collect()) print(gc.mem_alloc(), '/', gc.mem_alloc() + gc.mem_free(), "KB") def main(): pass
def get_gc_stats(self): import gc return { 'mem_alloc': gc.mem_alloc(), 'mem_free': gc.mem_free() }
import esp import machine esp.osdebug(None) machine.freq(160000000) import gc import uos import time print("Mem Pre Import:", gc.mem_free()) import at24cxx print("Mem Pre Collect:", gc.mem_free()) gc.collect() print("Mem Post Collect:", gc.mem_free()) i2c = machine.I2C(machine.Pin(12), machine.Pin(13), freq=100000) eeprom = at24cxx.AT24CXX(i2c) rnd = bytearray(uos.urandom(10)) eeprom.write(0, rnd) time.sleep(.1) print(eeprom.read(0, 10) == rnd) eeprom.write_address(1) time.sleep(.1) print(eeprom.read_sequential(4) == rnd[1:5]) rnd_ = uos.urandom(1)[0]
def run(): wlan = network.WLAN(network.STA_IF) wlan.active(True) if not wlan.isconnected(): print('connecting to network...') wlan.connect(ssid, pw) while not wlan.isconnected(): pass print('network config:', wlan.ifconfig()) s = socket.socket() #s.settimeout(0) s.connect((host, 1883)) s.send(mtpConnect("somename")) m = s.recv(100) # need to get the return code print("CONNACK = ",m) #sleep(3) s.send(mtpUnsubscribe("sonos/nyc/current_track")) m = s.recv(100) s.send(mtpSubscribe("sonos/ct/current_track")) m = s.recv(100) # need to get the return code print("SUBACK = ",m) sleep(3) #s.settimeout(5) #try: # s.recv(200) #except: # pass while 1: m = s.recv(200) if m: #print("first byte =", m[0]) #first byte should be 48 #print("second byte =", m[1]) # see spec but basically if first remaining length byte is # > 128 then the highest bit is signalling continuation # and the following byte contributes 128 x it's value # note that remaining_length and topic used for debugging but not otherwise used if m[1] > 127: remaining_length = m[2]*128 + m[1] - 128 i = 5 else: remaining_length = m[1] i = 4 #print("remaining length =", remaining_length) #topic = m[i:i+m[i-1]] #print("topic =", topic.decode('utf-8')) msg = m[i+m[i-1]:] if msg == b'STOPPED': print("msg =", msg) continue #msg = msg.decode('utf-8') zzz = json.loads(msg.decode('utf-8')) if 'position' in zzz: # not clearing the display because adding time d.draw_text(75, 24, zzz['position']) else: d.clear() d.display() d.draw_text(0, 0, zzz['artist'][:20]) d.draw_text(0, 12, zzz['title'][:20]) d.draw_text(0, 24, zzz['title'][20:]) d.display() gc.collect() print(gc.mem_free()) sleep(3)
from machine import SD from machine import Timer from L76GNSS import L76GNSS from pytrack import Pytrack # setup as a station import gc time.sleep(2) gc.enable() # setup rtc rtc = machine.RTC() rtc.ntp_sync("pool.ntp.org") utime.sleep_ms(750) print('\nRTC Set from NTP to UTC:', rtc.now()) utime.timezone(7200) print('Adjusted from UTC to EST timezone', utime.localtime(), '\n') py = Pytrack() l76 = L76GNSS(py, timeout=30) chrono = Timer.Chrono() chrono.start() #sd = SD() #os.mount(sd, '/sd') #f = open('/sd/gps-record.txt', 'w') while (True): coord = l76.coordinates() #f.write("{} - {}\n".format(coord, rtc.now())) print("{} - {} - {}".format(coord, rtc.now(), gc.mem_free()))
def writeData(self): t = time.time() curDir = os.getcwd() os.chdir("/sd")#change directory to SD card try: f = open(self.filePath, 'w') # json.dump(self.daqDict, f)#assumes the data has already been converted to a string-Redis doesn't like arrays f.write("%s\n"%self.dataID) f.write("%s\n"%str(self.numPnts)) f.write("%s\n"%str(self.numAves)) f.write("%s\n"%str(self.gpw)) f.write("%s\n"%str(self.acqSpeed)) f.write("%s\n"%str(self.freq)) f.write("%s\n"%self.filePath) f.write("%s\n"%str(self.acqType)) f.write("%s\n"%str(self.multiplexParam)) for d in self.dataArray: f.write("%s,\n"%str(d)) f.close() os.chdir(curDir) except: os.chdir(curDir) print("Saving to %s failed"%fileName) gc.collect() print("Write Time: %s"%(time.time()-t)) print(gc.mem_free()) daq = DAQ_Unit() print("Go ADC!") # daq.writeData() # print("Done with ADC")
def gc_cmd(cli, cmd, rol): before = gc.mem_alloc(), gc.mem_free() gc.collect() after = gc.mem_alloc(), gc.mem_free() yield from cli.writeln('mem_alloc %d, mem_free %d (up %d)' \ % (after[0], after[1], after[1]-before[1]))
# basic tests for gc module try: import gc except ImportError: print("SKIP") import sys sys.exit() print(gc.isenabled()) gc.disable() print(gc.isenabled()) gc.enable() print(gc.isenabled()) gc.collect() if hasattr(gc, 'mem_free'): # uPy has these extra functions # just test they execute and return an int assert type(gc.mem_free()) is int assert type(gc.mem_alloc()) is int if hasattr(gc, 'threshold'): # uPy has this extra function # check execution and returns assert(gc.threshold(1) is None) assert(gc.threshold() == 0) assert(gc.threshold(-1) is None) assert(gc.threshold() == -1)
def run(self): woken = self.wifi_pin() self.epd.enable() if not self.check_battery_level(): return False try: self.epd.get_sensor_data() except ValueError: self.log("Can't communicate with display, flashing light and giving up") heartbeat(True) sleep_ms(15000) return True if self.rtc.alarm_left() > 0: self.log("Woken up but the timer is still running, refreshing screen only") self.epd.display_update() self.feed_wdt() return True try: self.cfg = Config.load(sd=self.sd) self.log("Loaded config") except (OSError, ValueError) as e: self.log("Failed to load config: " + str(e)) self.display_no_config() try: self.connect_wifi() except: pass # everything while True: sleep_ms(10) self.feed_wdt() self.feed_wdt() self.connect_wifi() content = b'' try: self.log("Connecting to server %s:%d" % (self.cfg.host, self.cfg.port)) c = Connect(self.cfg.host, self.cfg.port, debug=self.debug) self.feed_wdt() cause = Display.reset_cause() if woken: cause = "user" self.log("Reset cause: " + cause) if len(self.cfg.upload_path) > 0: temp = self.epd.get_sensor_data() # we read this already c.post(self.cfg.upload_path, battery=self.battery.value(), reset=cause, screen=temp) self.log("Fetching metadata from " + self.cfg.metadata_path) metadata = c.get_quick(self.cfg.metadata_path, max_length=1024, path_type='json') # This will set the time to GMT, not localtime self.set_alarm(c.last_fetch_time, metadata) self.feed_wdt() del metadata del self.battery self.log("Fetching image from " + self.cfg.image_path) self.epd.image_erase_frame_buffer() self.feed_wdt() length, socket = c.get_object(self.cfg.image_path) if length != 15016: raise ValueError("Wrong data size for image: %d" % length) self.feed_wdt() except (RuntimeError, ValueError, OSError) as e: self.log("Failed to get remote info: " + str(e)) self.display_cannot_connect() self.rtc.alarm(time=3600000) return True sleep_ms(1000) # How do we make the write to display more reliable? self.feed_wdt() self.log("Uploading to display") self.display_file_image(socket) c.get_object_done() # close off socket if self.cfg.src == "sd": # If we've got a working config from SD instead of flash self.log("Transferring working config") Config.transfer() self.log("SUCCESS") self.log("Finished. Mem free: %d" % gc.mem_free()) return True