Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove support for threaded IO from rs232.SerialData #148

Merged
merged 3 commits into from
Dec 2, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pocs/mount/serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self, *args, **kwargs):
self.logger.error('No mount port specified, cannot create mount\n {}'.format(self.config['mount']))

try:
self.serial = rs232.SerialData(port=self._port, threaded=False, baudrate=9600)
self.serial = rs232.SerialData(port=self._port, baudrate=9600)
except Exception as err:
self.serial = None
raise error.MountNotFound(err)
Expand Down
93 changes: 26 additions & 67 deletions pocs/utils/rs232.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,31 @@


class SerialData(PanBase):

"""
Main serial class
"""

def __init__(self, port=None, baudrate=115200, threaded=True, name="serial_data"):
def __init__(self,
port=None,
baudrate=115200,
threaded=None,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm temped to say we should just add a *args, **kwargs and remove the threaded=None.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer to rip out the param as soon as the PACE code is merged in here, as that way we don't accidentally accept bogus params.

name="serial_data"):
"""Init a SerialData instance.

Args:
port: The port (e.g. /dev/tty123 or socket://host:port) to which to
open a connection.
baudrate: For true serial lines (e.g. RS-232), sets the baud rate of
the device.
threaded: Obsolete, ignored.
name: Name of this object.
"""
PanBase.__init__(self)

try:
self.ser = serial.Serial()
self.ser.port = port
self.ser.baudrate = baudrate
self.is_threaded = threaded

self.ser.bytesize = serial.EIGHTBITS
self.ser.parity = serial.PARITY_NONE
Expand All @@ -37,25 +49,16 @@ def __init__(self, port=None, baudrate=115200, threaded=True, name="serial_data"
self.ser.open()

self.name = name
self.queue = deque([], 1)
self._is_listening = False
self.loop_delay = 2.

if self.is_threaded:
self._serial_io = TextIOWrapper(BufferedRWPair(self.ser, self.ser),
newline='\r\n', encoding='ascii', line_buffering=True)

self.logger.debug("Using threads (multiprocessing)")
self.process = Thread(target=self.receiving_function, args=(self.queue,))
self.process.daemon = True
self.process.name = "PANOPTES_{}".format(name)

self.logger.debug('Serial connection set up to {}, sleeping for two seconds'.format(self.name))
self.logger.debug(
'Serial connection set up to {}, sleeping for two seconds'.
format(self.name))
time.sleep(2)
self.logger.debug('SerialData created')
except Exception as err:
self.ser = None
self.logger.critical('Could not set up serial port {} {}'.format(port, err))
self.logger.critical('Could not set up serial port {} {}'.format(
port, err))

@property
def is_connected(self):
Expand All @@ -68,22 +71,6 @@ def is_connected(self):

return connected

@property
def is_listening(self):
return self._is_listening

def start(self):
""" Starts the separate process """
self.logger.debug("Starting serial process: {}".format(self.process.name))
self._is_listening = True
self.process.start()

def stop(self):
""" Starts the separate process """
self.logger.debug("Stopping serial process: {}".format(self.process.name))
self._is_listening = False
self.process.join()

def connect(self):
""" Actually set up the Thread and connect to serial """

Expand All @@ -97,7 +84,8 @@ def connect(self):
if not self.ser.isOpen():
raise BadSerialConnection(msg="Serial connection is not open")

self.logger.debug('Serial connection established to {}'.format(self.name))
self.logger.debug('Serial connection established to {}'.format(
self.name))
return self.ser.isOpen()

def disconnect(self):
Expand All @@ -109,24 +97,6 @@ def disconnect(self):
self.ser.close()
return not self.is_connected

def receiving_function(self, q):
self.connect()
while self.is_listening:
try:
line = self.read()
ts = time.strftime('%Y-%m-%dT%H:%M:%S %Z', time.gmtime())
self.queue.append((ts, line))
except IOError as err:
self.logger.warning("Device is not sending messages. IOError: {}".format(err))
time.sleep(2)
except UnicodeDecodeError:
self.logger.warning("Unicode problem")
time.sleep(2)
except Exception:
self.logger.warning("Unknown problem")

time.sleep(self.loop_delay)

def write(self, value):
"""
For now just pass the value along to serial object
Expand All @@ -135,10 +105,7 @@ def write(self, value):
assert self.ser.isOpen()

# self.logger.debug('Serial write: {}'.format(value))
if self.is_threaded:
response = self._serial_io.write(value)
else:
response = self.ser.write(value.encode())
response = self.ser.write(value.encode())

return response

Expand All @@ -154,14 +121,9 @@ def read(self):
delay = 0.5

while True and retry_limit:
if self.is_threaded:
response_string = self._serial_io.readline()
else:
response_string = self.ser.readline(self.ser.inWaiting()).decode()

response_string = self.ser.readline(self.ser.inWaiting()).decode()
if response_string > '':
break

time.sleep(delay)
retry_limit -= 1

Expand All @@ -177,11 +139,8 @@ def get_reading(self):
"""

try:
if self.is_threaded:
info = self.queue.pop()
else:
ts = time.strftime('%Y-%m-%dT%H:%M:%S %Z', time.gmtime())
info = (ts, self.read())
ts = time.strftime('%Y-%m-%dT%H:%M:%S %Z', time.gmtime())
info = (ts, self.read())
except IndexError:
raise IndexError
else:
Expand Down