I am hoping someone can shed some light between the difference of a closed/open serial port and getting the permissions of a serial port? Specifically with pyserial. Currently, I feel like they are one of the same.
I will try to illustrate my question by using pyserial. Let say I am trying to talk to a microcontroller using uart and I have a serial port open on a windows pc to talk to it. Running code with pyserial everything works fine as expected.
However lets say I am using realterm to use the serial port to read data on the line.
Now if I run the python code again, I will get a permission error from pyserial indicating it is not available. It is NOT saying the serial port is currently open.
The reason why I am making the distinction between the two is in my code with pyserial, I am detecting if the serial port is open or not. If the serial port is open, use the serial port. If not, do not use it.
Here is some code I am using currently to check and open a serial port (using python/pyserial):
def open_port(self):
# Checking if the port is already open or not. If it is not open, lets open it.
if(self.isOpen() == False): # NOTE This check will not goes as I expect if another program has opened it. Shouldn't this check determine if the resource is available to be used?
try:
self.open()
except serial.SerialException as e:
print(e) # Printing the raw message.
error_message = "The port you are trying to open ("+str(self.port)+")"+" is currently open." # My own message. This might be wrong based on this discussion.
print(error_message)
sys.exit()
else:
... # Do other things
Normally this code works fine without any issues.
However, here is the output of the same code if another program (realterm) is using the serial port or if I am using another instance of pyserial with the same serial port:
could not open port 'COM4': PermissionError(13, 'Access is denied.', None, 5)
The port you are trying to open (COM4) is currently open.
As you can see here it could not use the serial port (which makes sense because I am using realterm.)
What I am confused though is that shouldn't if(self.isOpen() == False):
check if the serial port is available to be used?
I thought a serial port being open or closed is equivalent to saying the resource is being used or not. Where if the serial port is open it is being used by a application and other applications should not touch it.
However the raw error indicates there is a permission error with the serial port. Is there a difference between opening and closing a port and the permissions of the port? I thought they were essentially the same?
If they are different can some please explain the differences between them? Also how can I in pyserial determine if a serial resource can be used?
Thank you for your help and please let me know if you have any more questions!