Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@solarkraft
Last active December 20, 2022 06:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solarkraft/d1dec26de817de98a59c6ea1d82becec to your computer and use it in GitHub Desktop.
Save solarkraft/d1dec26de817de98a59c6ea1d82becec to your computer and use it in GitHub Desktop.
(Simple) MicroPython WebREPL CLI to work around newline issues
#!/usr/bin/env python
import sys
import tty
import termios
import asyncio
import websockets
uri = "ws://192.168.2.69:8266"
password = ""
async def login(ws):
await ws.send(password)
await ws.send("\r\n")
async def receive(ws):
await ws.recv()
while True:
message = await ws.recv()
# It's not even really an issue; terminals just swallow it
if message == "\r\n":
sys.stdout.write("\n")
continue
sys.stdout.write(message)
sys.stdout.flush()
async def send(ws):
while True:
# cheap async stdin
loop = asyncio.get_event_loop()
char = await loop.run_in_executor(None, sys.stdin.buffer.raw.read, 1)
character = char.decode("utf-8")
# print("Raw character:", char, "Decoded:", character)
# This is why we can't just use websocat ...
if char == b"\n":
await ws.send("\r\n")
continue
await ws.send(character)
async def main():
async for ws in websockets.connect(uri):
try:
await asyncio.gather(login(ws), receive(ws), send(ws))
except websockets.ConnectionClosed:
continue
if __name__ == "__main__":
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setcbreak(fd)
asyncio.run(main())
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment