webrepl.py 2.1 KB

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