Skip to content

Instantly share code, notes, and snippets.

@projectgus
Created November 21, 2023 23:31
Show Gist options
  • Save projectgus/51b35be90c87a849ae467e5476db5bf7 to your computer and use it in GitHub Desktop.
Save projectgus/51b35be90c87a849ae467e5476db5bf7 to your computer and use it in GitHub Desktop.
Simple MicroPython TLS socket memory test
import esp
import esp32
import micropython
import network
import gc
import socket
import ssl
import time
SSID = 'DebugAP'
PSK = 'debug_ap'
def dump_memory_info():
micropython.mem_info()
hi = esp32.idf_heap_info(esp32.HEAP_DATA)
print(hi)
print("total free heap", sum(x[1] for x in hi))
print("largest free block", max(x[2] for x in hi))
print('Startup...')
dump_memory_info()
# eat a bunch of memory
use_ram = []
for _ in range(6):
use_ram.append(bytearray(10000))
print('After eating...')
dump_memory_info()
esp.osdebug(0, esp.LOG_INFO)
def wifi_connect():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to Wi-Fi...')
print(wlan.scan())
wlan.connect(SSID, PSK)
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
micropython.mem_info()
secure_sockets = []
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
wifi_connect()
print('WiFi connected')
dump_memory_info()
try:
for i in range(1000):
print(f'Socket {i}')
ai = socket.getaddrinfo('micropython.org', 443, 0, socket.SOCK_STREAM)[0]
print(ai)
s = socket.socket(ai[0], socket.SOCK_STREAM, ai[2])
s.connect(ai[-1])
ss = context.wrap_socket(s)
secure_sockets.append(ss)
dump_memory_info()
print('\n')
time.sleep(1)
except OSError as e:
print(f'{e} after {len(secure_sockets)} TLS sockets')
while secure_sockets:
ss = secure_sockets.pop()
ss.close()
print('Closed socket')
micropython.mem_info()
print('Force GC')
gc.collect()
micropython.mem_info()
print('Done!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment