|
1 | | -"""Terminal handling, using microcom or telnet""" |
| 1 | +"""Terminal handling, using microcom, telnet or an internal function""" |
2 | 2 |
|
3 | 3 | import asyncio |
| 4 | +import collections |
| 5 | +import contextlib |
4 | 6 | import logging |
| 7 | +import os |
5 | 8 | import sys |
6 | 9 | import shutil |
| 10 | +import time |
| 11 | + |
| 12 | +from pexpect import TIMEOUT |
| 13 | +from prompt_toolkit.input import create_input |
| 14 | +from serial.serialutil import SerialException |
7 | 15 |
|
8 | 16 | EXIT_CHAR = 0x1d # FS (Ctrl + ]) |
9 | 17 |
|
@@ -69,3 +77,159 @@ async def external(check_allowed, host, port, resource, logfile, listen_only): |
69 | 77 | if p.returncode: |
70 | 78 | print("connection lost", file=sys.stderr) |
71 | 79 | return p.returncode |
| 80 | + |
| 81 | + |
| 82 | +BUF_SIZE = 1024 |
| 83 | + |
| 84 | +async def run(check_allowed, cons, log_fd, listen_only, inp=None): |
| 85 | + """Handle the console session, passing data between board and terminal |
| 86 | +
|
| 87 | + Args: |
| 88 | + check_allowed (lambda): Function to call to make sure the terminal is |
| 89 | + still accessible. No args. Returns True if allowed, False if not. |
| 90 | + cons (ConsoleProtocol): Console device to read/write |
| 91 | + log_fd (file): File to write console output to, or None |
| 92 | + listen_only (bool): True to ignore keyboard input |
| 93 | + inp (prompt_toolkit Input): Terminal to read keystrokes from, or None |
| 94 | + to ignore the keyboard |
| 95 | + """ |
| 96 | + prev = collections.deque(maxlen=2) |
| 97 | + |
| 98 | + deadline = None |
| 99 | + to_cons = b'' |
| 100 | + next_cons = time.monotonic() |
| 101 | + txdelay = cons.txdelay |
| 102 | + typed = bytearray() |
| 103 | + |
| 104 | + def read_keys(): |
| 105 | + """Collect what the user types, called by the event loop |
| 106 | +
|
| 107 | + This reads the bytes as they arrive, rather than using prompt_toolkit's |
| 108 | + read_keys(), since the board needs a transparent stream: it must see |
| 109 | + escape sequences and control characters exactly as they were typed. |
| 110 | + """ |
| 111 | + try: |
| 112 | + data = os.read(inp.fileno(), BUF_SIZE) |
| 113 | + except OSError: |
| 114 | + data = b'' |
| 115 | + if data: |
| 116 | + typed.extend(data) |
| 117 | + else: |
| 118 | + # The terminal is gone (e.g. a closed pipe), so stop watching it, |
| 119 | + # else the event loop calls us forever |
| 120 | + asyncio.get_running_loop().remove_reader(inp.fileno()) |
| 121 | + |
| 122 | + # Show a message to indicate we are waiting for output from the board |
| 123 | + msg = 'Terminal ready...press Ctrl-] twice to exit' |
| 124 | + sys.stdout.write(msg) |
| 125 | + sys.stdout.flush() |
| 126 | + erase_msg = '\b' * len(msg) + ' ' * len(msg) + '\b' * len(msg) |
| 127 | + have_output = False |
| 128 | + |
| 129 | + # Ask the event loop to tell us when the user types something |
| 130 | + watch_keys = inp.attach(read_keys) if inp else contextlib.nullcontext() |
| 131 | + |
| 132 | + with watch_keys: |
| 133 | + while True: |
| 134 | + activity = bool(to_cons) |
| 135 | + try: |
| 136 | + data = cons.read(size=BUF_SIZE, timeout=0.001) |
| 137 | + if data: |
| 138 | + activity = True |
| 139 | + if not have_output: |
| 140 | + # Erase our message |
| 141 | + sys.stdout.write(erase_msg) |
| 142 | + sys.stdout.flush() |
| 143 | + have_output = True |
| 144 | + sys.stdout.buffer.write(data) |
| 145 | + sys.stdout.buffer.flush() |
| 146 | + if log_fd: |
| 147 | + log_fd.write(data) |
| 148 | + log_fd.flush() |
| 149 | + |
| 150 | + except TIMEOUT: |
| 151 | + pass |
| 152 | + |
| 153 | + except SerialException: |
| 154 | + break |
| 155 | + |
| 156 | + if typed: |
| 157 | + data = bytes(typed) |
| 158 | + typed.clear() |
| 159 | + activity = True |
| 160 | + if not deadline: |
| 161 | + deadline = time.monotonic() + .5 # seconds |
| 162 | + prev.extend(data) |
| 163 | + count = prev.count(EXIT_CHAR) |
| 164 | + if count == 2: |
| 165 | + break |
| 166 | + |
| 167 | + to_cons += data |
| 168 | + |
| 169 | + if to_cons and time.monotonic() > next_cons: |
| 170 | + cons._write(to_cons[:1]) |
| 171 | + to_cons = to_cons[1:] |
| 172 | + if txdelay: |
| 173 | + next_cons += txdelay |
| 174 | + |
| 175 | + if deadline and time.monotonic() > deadline: |
| 176 | + prev.clear() |
| 177 | + deadline = None |
| 178 | + if check_allowed(): |
| 179 | + break |
| 180 | + |
| 181 | + # Give the event loop a chance to run read_keys() |
| 182 | + await asyncio.sleep(0 if activity else .001) |
| 183 | + |
| 184 | + # Blank line to move past any partial output |
| 185 | + print() |
| 186 | + |
| 187 | + |
| 188 | +async def internal(check_allowed, cons, logfile, listen_only): |
| 189 | + """Start an internal terminal session |
| 190 | +
|
| 191 | + This talks to the board directly, rather than starting a separate tool. |
| 192 | +
|
| 193 | + Args: |
| 194 | + check_allowed (lambda): Function to call to make sure the terminal is |
| 195 | + still accessible. No args. Returns True if allowed, False if not. |
| 196 | + cons (ConsoleProtocol): Console device to read/write |
| 197 | + logfile (str): Logfile to write output too, or None |
| 198 | + listen_only (bool): True to ignore keyboard input |
| 199 | +
|
| 200 | + Return: |
| 201 | + int: Result code |
| 202 | + """ |
| 203 | + returncode = 0 |
| 204 | + log_fd = None |
| 205 | + inp = None |
| 206 | + try: |
| 207 | + # Watch the keyboard, unless we only care about what the board says |
| 208 | + if not listen_only: |
| 209 | + inp = create_input() |
| 210 | + |
| 211 | + if logfile: |
| 212 | + log_fd = open(logfile, 'wb') |
| 213 | + |
| 214 | + logging.info('Console start:') |
| 215 | + |
| 216 | + # Put the terminal in raw mode, so that keystrokes reach the board |
| 217 | + # untouched. As well as the echo and line editing, this turns off |
| 218 | + # flow control (so that Ctrl-S and Ctrl-Q get through) and the |
| 219 | + # carriage-return translation. It does nothing if stdin is not a |
| 220 | + # terminal, such as when input is piped in |
| 221 | + raw_mode = inp.raw_mode() if inp else contextlib.nullcontext() |
| 222 | + with raw_mode: |
| 223 | + await run(check_allowed, cons, log_fd, listen_only, inp) |
| 224 | + |
| 225 | + except OSError as err: |
| 226 | + print('error', err) |
| 227 | + returncode = 1 |
| 228 | + |
| 229 | + finally: |
| 230 | + if inp: |
| 231 | + inp.close() |
| 232 | + if log_fd: |
| 233 | + log_fd.close() |
| 234 | + |
| 235 | + return returncode |
0 commit comments