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


mavlink
Author(s): Lorenz Meier
autogenerated on Sun Apr 7 2019 02:06:02