Python: PySerial disconnecting from device randomly
<p>I have a process that runs data acquisition using PySerial. It's working fine now, but there's a weird thing I had to do to make it work continuously, and I'm not sure this is normal, so I'm asking this question.</p>

<p><strong>What happens:</strong> It looks like that the connection drops now and then! Around once every 30-60 minutes, with big error bars (could go for hours and be OK, but sometimes happens often).</p>

<p><strong>My question</strong>: Is this standard?</p>

<p><strong>My temporary solution</strong>: I wrote a simple "reopen" function that looks like this:</p>

<pre><code>def ReopenDevice(devObject):
    try:
        devObject.close()
        devObject.open()
    except Exception as e:
        print("Error while trying to connect to device " + devObject.port + ". The error says: " + str(e))
        time.sleep(2)
</code></pre>

<p>And what I do is that if data pulling fails for 2 minutes, I reopen the device with this function, and it continues working well with no problems.</p>

<p><strong>My program model</strong>: It's a GUI program, where the user clicks something like "Start", and that button does some preparations and runs a function through <code>multiprocessing.Process()</code> that starts with:</p>

<pre><code>devObj = serial.Serial()
#... other params
devObj.open()
</code></pre>

<p>and that function then runs a while loop that keeps polling data with something like:</p>

<pre><code>bytesToRead = devObj.inWaiting()
if bytesToRead != 0:
    buffer = decodeString(devObj.read(bytesToRead))
    #process buffer and push it to a list...
</code></pre>

<p>The way I know that the problem happened, is that <code>devObj.inWaiting()</code> Keeps returning zero... no matter how much data there's on the device!</p>

<p>Is this behavior expected and should always be considered whether it happens or doesn't happen?</p>

<p>The problem reduced a lot after not calling <code>inWaiting()</code> very frequently. Anyway, I kept the reconnect part to ensure that my program never fails. Thanks for "Kobi K" for suggesting the possible cause of the problem.</p>

python pyserial stability