tcp_socket.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 """Use the TCPSocket class to establish a serial connection with a compatible device via USB port."""
3 
4 from __future__ import print_function
5 import socket
6 
7 
8 # TODO use threading??
9 class TCPSocket:
10  """Establish a TCP/IP connection with a connected device."""
11  def __init__(self, host, port=10001):
12  """
13  Initialize reader class for serial connection.
14  :param host: String: IP address of the device you want to communicate with
15  :param port: Int (default=10001): port to use for the connection
16  """
17  # port of the device
18  self.host = host
19  # baudrate used for communication
20  self.port = port
21  # initialize serial connection object with the specified parameters
22  self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
23  self.sock.connect((self.host, self.port))
24 
25  def open(self):
26  """Open a socket to establish TCP/IP connection."""
27  # try do open the serial connection and throw error if not successful
28  try:
29  self.sock.connect((self.host, self.port))
30  except:
31  print('Unable to open socket connection with: ' + self.host + ', ' + self.port)
32 
33  def close(self):
34  """Close the socket."""
35  # try do close the serial connection and throw error if not successful
36  try:
37  self.sock.shutdown(socket.SHUT_RDWR)
38  self.sock.close()
39  except:
40  print('Unable to close socket connection with: ' + self.host + ', ' + self.port)
41 
42  def send(self, msg):
43  """
44  Send message to the socket.
45  :param msg: String: message to be sent to the socket
46  """
47  try:
48  self.sock.send(msg)
49  except:
50  print('Unable to send message to socket.')
51 
52  def get_line(self, eol_character):
53  """
54  Return a single line from the TCP stream with a custom end-of-line character.
55  :param eol_character: Bytes: character or sequence to use as end-of-line character.
56  :return: Bytes: the most recent line that has been sent via the socket connection
57  """
58  # define end-of-line-character
59  eol = eol_character
60  # determine length of the eol-character
61  leneol = len(eol)
62  # initialize empty line as bytearray
63  line = bytearray()
64  # collect single bytes and concatenate line until eol-character is encountered
65  while True:
66  # read one byte
67  c = self.sock.recv(1)
68  if c:
69  # append to line
70  line += c
71  # break if the current character is the specified eol-character
72  if line[-leneol:] == eol:
73  break
74  else:
75  break
76  # return line
77  return bytes(line)


indoor_positioning
Author(s): Christian Arndt
autogenerated on Mon Jun 10 2019 13:33:13