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


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