I am trying to host a webpage from my NodeMCU that displays a table of random integers (0 or 1). NodeMCU is in station mode. My code that creates the table and hosts the page looks like this:
Code: Select all
import socket
from utilities.mathUtils import randint
N = 19
table = [[randint(0,1) for i in range(N)] for j in range(N)]
html = """<!DOCTYPE html>
<html>
<head> <title>Page</title> </head>
<body> <h1>Random numbers</h1>
<font face='Courier New'>
%s
</font>
</body>
</html>
"""
def generateHTMLrows(table):
stringRows = ''
for c in range(len(table[0])):
stringRow = ''
for r in range(len(table)):
stringRow += str(table[c][r]) + ' '
stringRows += stringRow + '<br>'
return stringRows
def connect():
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
rows = generateHTMLrows(table)
response = html % ''.join(rows)
cl.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
cl.send(response)
cl.close()
print(gc.mem_free())
connect()
But if I make that table any larger... Set N to 20 or more - the page fails to load. Says "connection reset". NodeMCU console shows nothing. But if I increase the N to say 30, then the page fails to load too, and the console prints "memory allocation failed, allocating 8192 bytes". Which is really weird, because I run gc.mem_free(), and it shows that there is actually plenty of memory available. Besides, such a simple table is nothing, it definitely shouldn't take much memory anyway. I am not running anything else. And besides, if I set the random number generator to generate numbers say, between 0 and 10, the page fails to load even with with lower N value.
Why am I seeing this? Is this really a memory error? How can that possibly be with such a small table?