Skip to content

Instantly share code, notes, and snippets.

@darconeous
Created September 21, 2022 00:23
Show Gist options
  • Save darconeous/204ac138ca1bb3978e88e5f5bb2bfb84 to your computer and use it in GitHub Desktop.
Save darconeous/204ac138ca1bb3978e88e5f5bb2bfb84 to your computer and use it in GitHub Desktop.
Micropython TCP/telnet REPL
# REPL Prompt over TCP socket.
# Use `$ telnet <ip-addr>` to connect.
import network
import os
import socket
import sys
listen_s = None
client_s = None
DEBUG = 0
def setup_conn(port, accept_handler):
global listen_s
listen_s = socket.socket()
listen_s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
ai = socket.getaddrinfo("0.0.0.0", port)
addr = ai[0][4]
listen_s.bind(addr)
listen_s.listen(1)
if accept_handler:
listen_s.setsockopt(socket.SOL_SOCKET, 20, accept_handler)
for i in (network.AP_IF, network.STA_IF):
iface = network.WLAN(i)
if iface.active():
print("TCPREPL server started on telnet://%s:%d/" % (iface.ifconfig()[0], port))
return listen_s
def accept_conn(listen_sock):
global client_s
cl, remote_addr = listen_sock.accept()
client_s = cl
cl.setblocking(False)
# notify REPL on socket incoming data (ESP32/ESP8266-only)
if hasattr(os, "dupterm_notify"):
cl.setsockopt(socket.SOL_SOCKET, 20, os.dupterm_notify)
prev = os.dupterm(cl)
if prev:
prev.close()
return True
def stop():
global listen_s, client_s
os.dupterm(None)
if client_s:
client_s.close()
if listen_s:
listen_s.close()
def start(port=23, password=None, accept_handler=accept_conn):
stop()
s = setup_conn(port, accept_handler)
if accept_handler is None:
print("Starting tcprepl in foreground mode")
# Run accept_conn to serve HTML until we get a websocket connection.
while not accept_conn(s):
pass
else:
print("Started tcprepl in normal mode")
def start_foreground(port=23, password=None):
start(port, password, None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment