You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

313 lines
10KB

  1. #!/usr/bin/python
  2. # Jim Paris <jim@jtan.com>
  3. # Simple terminal program for serial devices. Supports setting
  4. # baudrates and simple LF->CRLF mapping on input, but does not
  5. # configure flow control, carrier detection, etc.
  6. # ^C quits. There is no escaping, so you can't currently send this
  7. # character to the remote host. Piping input or output should work.
  8. # Supports multiple serial devices simultaneously. When using more
  9. # than one, each device's output is in a different color. Input
  10. # is directed to the first device, or can be sent to all devices
  11. # with --all.
  12. import sys
  13. import os
  14. import serial
  15. import threading
  16. import traceback
  17. import time
  18. import signal
  19. # Need OS-specific method for getting keyboard input.
  20. if os.name == 'nt':
  21. import msvcrt
  22. class Console:
  23. def __init__(self):
  24. pass
  25. def cleanup(self):
  26. pass
  27. def getkey(self):
  28. while 1:
  29. z = msvcrt.getch()
  30. if z == '\0' or z == '\xe0': # function keys
  31. msvcrt.getch()
  32. else:
  33. if z == '\r':
  34. return '\n'
  35. return z
  36. elif os.name == 'posix':
  37. import termios, select
  38. class Console:
  39. def __init__(self):
  40. self.fd = sys.stdin.fileno()
  41. try:
  42. self.old = termios.tcgetattr(self.fd)
  43. tc = termios.tcgetattr(self.fd)
  44. tc[3] = tc[3] & ~termios.ICANON & ~termios.ECHO & ~termios.ISIG
  45. tc[6][termios.VMIN] = 1
  46. tc[6][termios.VTIME] = 0
  47. termios.tcsetattr(self.fd, termios.TCSANOW, tc)
  48. except termios.error:
  49. # ignore errors, so we can pipe stuff to this script
  50. pass
  51. def cleanup(self):
  52. try:
  53. termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old)
  54. except:
  55. # ignore errors, so we can pipe stuff to this script
  56. pass
  57. def getkey(self):
  58. # Return -1 if we don't get input in 0.1 seconds, so that
  59. # the main code can check the "alive" flag and respond to SIGINT.
  60. [r, w, x] = select.select([self.fd], [], [self.fd], 0.1)
  61. if r:
  62. return os.read(self.fd, 1)
  63. elif x:
  64. return ''
  65. else:
  66. return -1
  67. else:
  68. raise ("Sorry, no terminal implementation for your platform (%s) "
  69. "available." % sys.platform)
  70. class JimtermColor(object):
  71. def setup(self, total):
  72. self.total = total
  73. if total > 1:
  74. self.codes = [
  75. "\x1b[1;36m", # cyan
  76. "\x1b[1;33m", # yellow
  77. "\x1b[1;35m", # magenta
  78. "\x1b[1;31m", # red
  79. "\x1b[1;32m", # green
  80. "\x1b[1;34m", # blue
  81. "\x1b[1;37m", # white
  82. ]
  83. self.reset = "\x1b[0m"
  84. else:
  85. self.codes = [""]
  86. self.reset = ""
  87. total = 1
  88. def code(self, n):
  89. return self.codes[n % self.total]
  90. class Jimterm:
  91. """Normal interactive terminal"""
  92. def __init__(self,
  93. serials,
  94. suppress_write_bytes = None,
  95. suppress_read_firstnull = True,
  96. transmit_all = False,
  97. add_cr = False,
  98. color = True):
  99. self.color = JimtermColor()
  100. if color:
  101. self.color.setup(len(serials))
  102. self.serials = serials
  103. self.suppress_write_bytes = suppress_write_bytes or ""
  104. self.suppress_read_firstnull = suppress_read_firstnull
  105. self.last_color = ""
  106. self.threads = []
  107. self.transmit_all = transmit_all
  108. self.add_cr = add_cr
  109. def print_header(self, nodes, bauds):
  110. for (n, (node, baud)) in enumerate(zip(nodes, bauds)):
  111. print (self.color.code(n)
  112. + node + ", " + str(baud) + " baud"
  113. + self.color.reset)
  114. print "^C to exit"
  115. print "----------"
  116. def start(self):
  117. self.alive = True
  118. # serial->console, all devices
  119. for (n, serial) in enumerate(self.serials):
  120. self.threads.append(threading.Thread(
  121. target = self.reader,
  122. args = (serial, self.color.code(n))
  123. ))
  124. # console->serial
  125. self.console = Console()
  126. self.threads.append(threading.Thread(target = self.writer))
  127. # start all threads
  128. for thread in self.threads:
  129. thread.daemon = True
  130. thread.start()
  131. def stop(self):
  132. self.alive = False
  133. def join(self):
  134. for thread in self.threads:
  135. while thread.isAlive():
  136. thread.join(0.1)
  137. def reader(self, serial, color):
  138. """loop and copy serial->console"""
  139. first = True
  140. try:
  141. while self.alive:
  142. data = serial.read(1)
  143. if not data:
  144. continue
  145. # don't print a NULL if it's the first character we
  146. # read. This hides startup/port-opening glitches with
  147. # some serial devices.
  148. if self.suppress_read_firstnull and first and data == '\0':
  149. first = False
  150. continue
  151. first = False
  152. if color != self.last_color:
  153. self.last_color = color
  154. sys.stdout.write(color)
  155. if ((ord(data) >= 32 and ord(data) < 128) or
  156. data == '\r' or data == '\n' or data == '\t'):
  157. if self.add_cr and data == '\n':
  158. sys.stdout.write('\r' + data)
  159. else:
  160. sys.stdout.write(data)
  161. else:
  162. sys.stdout.write('\\x'+("0"+hex(ord(data))[2:])[-2:])
  163. sys.stdout.flush()
  164. except Exception as e:
  165. sys.stdout.write(color)
  166. sys.stdout.flush()
  167. traceback.print_exc()
  168. sys.stdout.write(self.color.reset)
  169. sys.stdout.flush()
  170. self.console.cleanup()
  171. os._exit(1)
  172. def writer(self):
  173. """loop and copy console->serial until ^C"""
  174. try:
  175. while self.alive:
  176. try:
  177. c = self.console.getkey()
  178. except KeyboardInterrupt:
  179. c = '\x03'
  180. if c == '\x03':
  181. self.stop()
  182. return
  183. elif c == -1:
  184. # No input, try again
  185. continue
  186. elif c == '':
  187. # EOF on input. Wait a tiny bit so we can
  188. # flush the remaining input, then stop.
  189. time.sleep(0.25)
  190. self.stop()
  191. return
  192. elif c in self.suppress_write_bytes:
  193. # Don't send these bytes
  194. continue
  195. else:
  196. # send character
  197. if self.transmit_all:
  198. for serial in self.serials:
  199. serial.write(c)
  200. else:
  201. self.serials[0].write(c)
  202. except Exception as e:
  203. sys.stdout.write(self.color.reset)
  204. sys.stdout.flush()
  205. traceback.print_exc()
  206. self.console.cleanup()
  207. os._exit(1)
  208. def run(self):
  209. # Set all serial port timeouts to 0.1 sec
  210. saved_timeouts = []
  211. for (n, serial) in enumerate(self.serials):
  212. saved_timeouts.append(serial.timeout)
  213. serial.timeout = 0.1
  214. # Handle SIGINT gracefully
  215. signal.signal(signal.SIGINT, lambda *args: self.stop())
  216. # Go
  217. self.start()
  218. self.join()
  219. # Restore serial port timeouts
  220. for (n, serial) in enumerate(self.serials):
  221. serial.timeout = saved_timeouts[n]
  222. # Cleanup
  223. print self.color.reset # and a newline
  224. self.console.cleanup()
  225. if __name__ == "__main__":
  226. import argparse
  227. import re
  228. formatter = argparse.ArgumentDefaultsHelpFormatter
  229. description = ("Simple serial terminal that supports multiple devices. "
  230. "If more than one device is specified, device output is "
  231. "shown in varying colors. All input goes to the "
  232. "first device.")
  233. parser = argparse.ArgumentParser(description = description,
  234. formatter_class = formatter)
  235. parser.add_argument("device", metavar="DEVICE", nargs="+",
  236. help="serial device. Specify DEVICE@BAUD for "
  237. "per-device baudrates.")
  238. parser.add_argument("--crlf", "-c", action="store_true",
  239. help="add CR before incoming LF")
  240. parser.add_argument("--all", "-a", action="store_true",
  241. help="Send keystrokes to all devices, not just "
  242. "the first one")
  243. parser.add_argument("--baudrate", "-b", metavar="BAUD", type=int,
  244. help="default baudrate for all devices", default=115200)
  245. parser.add_argument("--quiet", "-q", action="store_true",
  246. help="Less verbose output")
  247. args = parser.parse_args()
  248. devs = []
  249. nodes = []
  250. bauds = []
  251. for (n, device) in enumerate(args.device):
  252. m = re.search(r"^(.*)@([1-9][0-9]*)$", device)
  253. if m is not None:
  254. node = m.group(1)
  255. baud = m.group(2)
  256. else:
  257. node = device
  258. baud = args.baudrate
  259. if node in nodes:
  260. sys.stderr.write("error: %s specified more than once\n" % node)
  261. raise SystemExit(1)
  262. try:
  263. dev = serial.Serial(node, baud)
  264. except serial.serialutil.SerialException:
  265. sys.stderr.write("error opening %s\n" % node)
  266. raise SystemExit(1)
  267. nodes.append(node)
  268. bauds.append(baud)
  269. devs.append(dev)
  270. term = Jimterm(devs,
  271. transmit_all = args.all,
  272. add_cr = args.crlf,
  273. color = (os.name == "posix"))
  274. if not args.quiet:
  275. term.print_header(nodes, bauds)
  276. term.run()