Python Forum
Multiple process access to a serial port - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Multiple process access to a serial port (/thread-17512.html)



Multiple process access to a serial port - mkonnov - Apr-14-2019

Hi all,


I need to implement the multiple process access to a serial port.
Do anybody implemented that ?

My code call will look like the following:
[bash]
python3 xbee_process_1.py &
python3 xbee_process_2.py &
python3 xbee_process_3.py &
[/bash]

For now, without of multiprocess support, the single process looks like this:
from digi.xbee.devices import XBeeDevice
xbee = XBeeDevice('/dev/ttyUSB0', 9600)
xbee.open()
Obviously, when I'm using this code in each process, they start to interfere with each other and see the different serial port errors.
I know that XBeeDevice contains the XBeeSerialPort as one of its dependencies and contains ._serial_port instance as a descriptor for the serial port.
So I'm going to implement my own serial port instance with necessary process locks and rewrite the ._serial_port instance:

from xbee_device_wrapper import xbee_device_wrapper
xbee = xbee_device_wrapper('/dev/ttyUSB0', 9600)
from digi.xbee.devices import XBeeDevice
from digi.xbee.serial import XBeeSerialPort
import traceback

class serial_port_proxy(XBeeSerialPort):
    def __init__(self, baud_rate, port, **kwargs):
        super().__init__(baud_rate, port, **kwargs)  

    def open(self):
        print("\n-----------", traceback.extract_stack())
        return super().open()

class xbee_device_wrapper(XBeeDevice):
    def __init__(self, port, baud_rate):

        super().__init__(port, baud_rate)
        self._serial_port = serial_port_proxy(baud_rate, port)
        self.open()