|
| 1 | +# This module should be imported from REPL, not run from command line. |
| 2 | +import socket |
| 3 | +import uos |
| 4 | +import network |
| 5 | +import uwebsocket |
| 6 | +import websocket_helper |
| 7 | +import _webrepl |
| 8 | + |
| 9 | +listen_s = None |
| 10 | +client_s = None |
| 11 | + |
| 12 | +def setup_conn(port, accept_handler): |
| 13 | + global listen_s |
| 14 | + listen_s = socket.socket() |
| 15 | + listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 16 | + |
| 17 | + ai = socket.getaddrinfo("0.0.0.0", port) |
| 18 | + addr = ai[0][4] |
| 19 | + |
| 20 | + listen_s.bind(addr) |
| 21 | + listen_s.listen(1) |
| 22 | + if accept_handler: |
| 23 | + listen_s.setsockopt(socket.SOL_SOCKET, 20, accept_handler) |
| 24 | + for i in (network.AP_IF, network.STA_IF): |
| 25 | + iface = network.WLAN(i) |
| 26 | + if iface.active(): |
| 27 | + print("WebREPL daemon started on ws://%s:%d" % (iface.ifconfig()[0], port)) |
| 28 | + return listen_s |
| 29 | + |
| 30 | + |
| 31 | +def accept_conn(listen_sock): |
| 32 | + global client_s |
| 33 | + cl, remote_addr = listen_sock.accept() |
| 34 | + prev = uos.dupterm(None) |
| 35 | + uos.dupterm(prev) |
| 36 | + if prev: |
| 37 | + print("\nConcurrent WebREPL connection from", remote_addr, "rejected") |
| 38 | + cl.close() |
| 39 | + return |
| 40 | + print("\nWebREPL connection from:", remote_addr) |
| 41 | + client_s = cl |
| 42 | + websocket_helper.server_handshake(cl) |
| 43 | + ws = uwebsocket.websocket(cl, True) |
| 44 | + ws = _webrepl._webrepl(ws) |
| 45 | + cl.setblocking(False) |
| 46 | + # notify REPL on socket incoming data (ESP32/ESP8266-only) |
| 47 | + if hasattr(uos, 'dupterm_notify'): |
| 48 | + cl.setsockopt(socket.SOL_SOCKET, 20, uos.dupterm_notify) |
| 49 | + uos.dupterm(ws) |
| 50 | + |
| 51 | + |
| 52 | +def stop(): |
| 53 | + global listen_s, client_s |
| 54 | + uos.dupterm(None) |
| 55 | + if client_s: |
| 56 | + client_s.close() |
| 57 | + if listen_s: |
| 58 | + listen_s.close() |
| 59 | + |
| 60 | + |
| 61 | +def start(port=8266, password=None): |
| 62 | + stop() |
| 63 | + if password is None: |
| 64 | + try: |
| 65 | + import webrepl_cfg |
| 66 | + _webrepl.password(webrepl_cfg.PASS) |
| 67 | + setup_conn(port, accept_conn) |
| 68 | + print("Started webrepl in normal mode") |
| 69 | + except: |
| 70 | + print("WebREPL is not configured, run 'import webrepl_setup'") |
| 71 | + else: |
| 72 | + _webrepl.password(password) |
| 73 | + setup_conn(port, accept_conn) |
| 74 | + print("Started webrepl in manual override mode") |
| 75 | + |
| 76 | + |
| 77 | +def start_foreground(port=8266): |
| 78 | + stop() |
| 79 | + s = setup_conn(port, None) |
| 80 | + accept_conn(s) |
0 commit comments