Unable to access serial port from dash app

Hi, I am trying to access com port to read data from an STM32 based sensor board. My main problem at this point is that i cannot access the serial port through the dash app. I am using windows 10 and serial port works fine without the app. here is my code

import serial
import re
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

s = serial.Serial(port='COM5',baudrate=460800, timeout =1)
s.parity = serial.PARITY_NONE       #set parity check: no parity
s.stopbits = serial.STOPBITS_ONE    #number of stop bits
s.bytesize = serial.EIGHTBITS

# s.timeout = 1                       #timeout block read
s.xonxoff = True                   #disable software flow control
s.rtscts = False                     #enable hardware (RTS/CTS) flow control
s.dsrdtr = False                    #disable hardware (DSR/DTR) flow control
s.writeTimeout = 5                  #timeout for write


app = dash.Dash(__name__)
app.layout = html.Div(
            interval=1*1000, # in milliseconds

@app.callback(Output('live-update-text', 'children'),
              [Input('interval-component', 'n_intervals')])
def update_metrics(n):
    (x,y,z) = re.sub(b'\x00','',s.readline().strip('\r\n')).split(',')
    style = {'padding': '5px', 'fontSize': '16px'}
    return [
        html.Span('X: {0:.2f}'.format(float(x)), style=style),
        html.Span('Y: {0:.2f}'.format(float(y)), style=style),
        html.Span('Z: {0:0.2f}'.format(float(z)), style=style)

if __name__ == '__main__':

The error i get is:

Traceback (most recent call last):
  File "C:\Users\Mano\Documents\CPP\workspace\DashTest\src\serialStream.py", line 40, in <module>
    s = serial.Serial(port='COM5',baudrate=460800, timeout =1)
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 31, in __init__
    super(Serial, self).__init__(*args, **kwargs)
  File "C:\Python27\lib\site-packages\serial\serialutil.py", line 240, in __init__
  File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 62, in open
    raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM5': WindowsError(5, 'Access is denied.')

‘Access is denied.’ with serial ports usually means you opened a connection at some point and didn’t close it. Are you running multiple programs that access that serial port? Can you try restarting, which will force all connections to close?

I am running a single program, some additional info on this is that as soon as I make this code independent of dash components (app.run_server and app.callback), serial port works in prints out values.

I am running it as an administrator so there shouldn’t be any access issues.

Several weird things going on here.

You’re trying to open it twice because for serial.Serial The port is immediately opened on object creation, when a port is given. See: https://pyserial.readthedocs.io/en/latest/pyserial_api.html

Second weird thing: Opening the port seems to always fail on the first try, but the 2nd try will work. I was able to force it to retry by wrapping it in a try, except statement.

I’ve no idea why it fails on the first try…still looking into it

I will try to force it and see what happens.

So wrapping it inside try, except alone did not work for me, i had to set the app.run_server(debug=False) and wrap it in try and except.

Also it seems that i need to reset read buffer after every read to actually get the most recent values on the serial port even though the update interval to 1 second on my sensor and in the callback in dash.

callback interval smaller than 100 ms causes the app to throw exception in the s.readline() command, the data read in that case is scrambled. All the bytes are there however they are arranged in a weird order. I have tested serial port with python and i can read 800+ rows a second without any problems IF i don’t use dash.

My next step is to try and get this on a line graph and for now update it at 10Hz rate and see if i can buffer more values in a separate function and use the callback to simply plot the buffered values.

Hi…I’m trying to get the data from the serial port to which my Arduino is connected.I’m always getting this error message:AttributeError: ‘module’ object has no attribute ‘Serial’
I was first using Python 3.7 and did not work, so i went to Python 2.7 and did not work either.
I’m currently using Anaconda (Spyder) for python 3.7 and Canopy for Python 2.7.

Do you have pySerial installed (serial is a module from pySerial) in your environment?

pip install pyserial

Hi All,

I am currently facing the same issue. I am not able to access data from my serial port (using pyserial(3.4) while using dash (1.9.1)).
Since, this threat is pretty much exactly what I am looking for, but does not provide a clear answer on how to do it or if it just does not work (properly), I want to hereby bump the threat.

Are there any solutions for this issue?

Also experiencing this issue. It is obviously only when running a Dash app as I can access the serial connection perfectly fine outside my Dash code. Just comment everything out except the PySerial portion and it works! Try doing this from within a Dash program and it fails.

This is the only functionality missing for me to be able to use this. Has anyone found a workaround yet? Or at the very least some sort of acknowledgment of a solution coming?

First time using Dash, this is a neat product!

Hi…I have attempted all sort of sequential links, one in particular that will associates and works dependably is CP2102, yet just if first thing in quite a while choice.

Additionally I have FTDI links that the show on list however don’t interface by any stretch of the imagination.

One in particular that interfaces so far is PL2303, yet doesn’t work dependably and since there is no check sun for bundles things begin bouncing on the screen.

Baud rate is 115200, and running at maxing out with insignificant holes in information.