From c7b6ddac61113812a6f633dbdaac29174e883b19 Mon Sep 17 00:00:00 2001 From: gpulido Date: Thu, 18 Jul 2024 00:37:06 +0200 Subject: [PATCH] use lock for serial port use --- selve/__init__.py | 56 +++++++++++++++++++++++++---------------------- setup.py | 2 +- 2 files changed, 31 insertions(+), 27 deletions(-) diff --git a/selve/__init__.py b/selve/__init__.py index 711b915..85402dd 100644 --- a/selve/__init__.py +++ b/selve/__init__.py @@ -1,7 +1,8 @@ #!/usr/bin/python +import time import serial -from enum import Enum import logging +from threading import Lock from selve.utils import * from selve.iveo import * @@ -22,6 +23,7 @@ def __init__(self, port, discover = True): the devices on init (default: {True}) """ self.port = port + self.lock = Lock() if discover: self.discover() @@ -64,35 +66,37 @@ def executeCommand(self, command): _LOGGER.info('Gateway writting: ' + str(commandstr)) try: + self.lock.adquire() self.configserial() + if self.ser.isOpen(): + try: + self.ser.flushInput() + self.ser.flushOutput() + self.ser.write(commandstr) + self.ser.flush() + time.sleep(0.5) + response_str = "" + while True: + response = self.ser.readline().strip() + response_str += response.decode() + _LOGGER.info('read data: ' + response_str) + if response.decode() == '': + break + + self.ser.close() + _LOGGER.info('read data: ' + response_str) + return process_response(response_str) + except Exception as e1: + _LOGGER.exception ("error communicating...: " + str(e1)) + else: + _LOGGER.error ("cannot open serial port") + except Exception as e: _LOGGER.error ('error open serial port: ' + str(e)) exit() - - if self.ser.isOpen(): - try: - self.ser.flushInput() - self.ser.flushOutput() - self.ser.write(commandstr) - self.ser.flush() - #time.sleep(0.5) - response_str = "" - while True: - response = self.ser.readline().strip() - response_str += response.decode() - _LOGGER.info('read data: ' + response_str) - if response.decode() == '': - break - - self.ser.close() - _LOGGER.info('read data: ' + response_str) - return process_response(response_str) - except Exception as e1: - _LOGGER.exception ("error communicating...: " + str(e1)) - else: - _LOGGER.error ("cannot open serial port") - + finally: + self.lock.release() return None # def serial_data(self, data): @@ -108,7 +112,7 @@ def discover(self): while not hasattr(command, "ids") and retry_n <=num_retries: command.execute(self) retry_n += 1 - #time.sleep(1) + time.sleep(1) if not hasattr(command, "ids"): _LOGGER.info("Associated Devices not found") diff --git a/setup.py b/setup.py index bbf2054..0129fd2 100644 --- a/setup.py +++ b/setup.py @@ -15,7 +15,7 @@ setup( name='python-selve', # Required - version='1.3.1', # Required + version='1.4.0', # Required description='Python library for interfacing with selve devices using the USB-RF controller', # Required long_description=long_description, # Optional url='https://github.com/gpulido/python-selve', # Optional