Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reset ESP8266 MicroPython after main.py crashes?

I have a NodeMCU ESP8266 board running MicroPython. I'm running a web server on my ESP8266. This is my first IoT project based on one of these boards.

The below is a snippet of the code.

This is being executed within main.py. Every now and then, something causes the code to crash (perhaps timing and request based). When main.py exits, for whatever reason, I'm dropped back at the python CLI.

I'd like for the board to reset when this happens (if there isn't a better way).

What is the best method of restarting/reseting the ESP8266?

addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print('listening on', addr)

while True:
    cl, addr = s.accept()
    print('client connected from', addr)
    cl_file = cl.makefile('rwb', 0)
    print("Request:")
    while True:
        line = cl_file.readline()
        print("Line:" , line)
        if not line or line == b'\r\n':
            print("breaking")
            break
        if line == b'GET /active HTTP/1.1\r\n':
like image 498
user1600747 Avatar asked Mar 05 '17 07:03

user1600747


1 Answers

MicroPython has machine.reset() function to reset a board.

Python (not just MicroPython) uses exception handling to handle errors.

Combining the two, you can easily achieve what you want. For example:

a = 4
b = 2
try:
    a / b
except:
    machine.reset()

If in the code above you replace value of b with 0, your board will reset. If you think about it for a bit, you probably will find out that it doesn't make much sense - you don't want your board suddenly reset if you just divide by 0 by mistake or otherwise. There're got to be better ways to handle errors! Likewise, you may want to think about your own case and see if resetting the board is really the best choice. If you think that yes, that's fine, just always keep in mind that you programmed your board to suddenly reset. Otherwise, your next question here may be "My board suddenly resets! Why???" ;-)

like image 143
pfalcon Avatar answered Sep 22 '22 21:09

pfalcon