sertotcp.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #!/usr/bin/env python
  2. """
  3. map a serial port to an outgoing TCP connection
  4. Released under GNU GPLv3 or later
  5. """
  6. from __future__ import print_function
  7. from argparse import ArgumentParser
  8. import errno
  9. import serial
  10. import socket
  11. import time
  12. parser = ArgumentParser(description=__doc__)
  13. parser.add_argument("--baudrate", default=57600, type=int, help="baud rate")
  14. parser.add_argument("serialport", type=str, help="serial port")
  15. parser.add_argument("desthost", type=str, help="destination host")
  16. parser.add_argument("destport", type=int, help="destination port")
  17. args = parser.parse_args()
  18. serport = serial.Serial(args.serialport, args.baudrate, timeout=0)
  19. tcpsock = None
  20. def open_socket():
  21. global tcpsock
  22. try:
  23. tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  24. tcpsock.connect((args.desthost, args.destport))
  25. tcpsock.setblocking(0)
  26. print("Connected to %s:%u" % (args.desthost, args.destport))
  27. except Exception:
  28. pass
  29. open_socket()
  30. while True:
  31. gotdata = False
  32. if tcpsock is None:
  33. open_socket()
  34. time.sleep(0.1)
  35. continue
  36. n = serport.inWaiting()
  37. if n > 0:
  38. b = serport.read(n)
  39. if b:
  40. try:
  41. tcpsock.send(b)
  42. except socket.error:
  43. tcpsock.close()
  44. tcpsock = None
  45. continue
  46. gotdata = True
  47. try:
  48. b = tcpsock.recv(1000)
  49. except socket.error as e:
  50. if e.args[0] in [errno.EWOULDBLOCK, errno.EAGAIN]:
  51. time.sleep(0.02)
  52. continue
  53. tcpsock.close()
  54. tcpsock = None
  55. continue
  56. if b:
  57. serport.write(b)
  58. gotdata = True
  59. if not gotdata:
  60. time.sleep(0.02)