Why are my COM ports busy? - python-3.x

I have a python program I am using to talk to a microcontroler. It opens the com ports like this:
def STM32_connect():
ports = list(serial.tools.list_ports.comports())
for p in ports:
if "STM32" in p.description:
connection = serial.Serial(p.device, timeout = .01)
return(connection)
print("ERROR: No STM32 Device Found")
sys.exit()
serial_connection = STM32_connect()
And then does a bunch of things, sending and receiving data until I close the program like this with a keyboard interput:
except:
print("\n Program Interrupted...")
finally:
print("\n Closing Serial Port\n")
serial_connection.close()
This all works fine. My problem is when the python script is improperly killed by disconnecting the USB cable or powering off the board I can no longer connect to the micro on any COM port. I receive this error:
Traceback (most recent call last):
File "/home/---/.local/lib/python3.5/site-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
OSError: [Errno 16] Device or resource busy: '/dev/ttyACM2'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "flextester.py", line 1, in <module>
from flex_usb_class import *
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 30, in <module>
serial_connection = STM32_connect()
File "/home/---/Code/RobotFlexTester/flex_usb_class.py", line 25, in STM32_connect
connection = serial.Serial(p.device, timeout = .01)
File "/home/---/.local/lib/python3.5/site-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/home/janey/.local/lib/python3.5/site-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 16] could not open port /dev/ttyACM2: [Errno 16] Device or resource busy: '/dev/ttyACM2'
I can change COM ports and I receive the exact same error at a different ttyACM port. But I can connect to the same device on the same port if I try to run a different python script. The problem seems to somehow be locked to the initial test script but ps -a does not show it to still be running. The problem goes away without me doing anything after about 30 seconds - 1 min.

the 30s to 1min delay are due to the internals of RS232 protocol. see the closing_wait option ( default 30 sec ) in setserial command ( http://manpages.ubuntu.com/manpages/zesty/man8/setserial.8.html ) when disconnecting USB cable and connection is killed the protocol waits for the time specified in the closing_wait option until it closes the port / session. session_lockout forbids attaching a second process to an open port...

Related

Method "StopDiscovery" with signature "" on interface "org.bluez.Adapter1" doesn't exist

Running a script here that connects to 2 Bluetooth adapters and collects data to send via mqtt. Its been running relatively smoothly on my RPi Zero 2 W with LM1010 BT USB adapter (internal wifi and BT adapter for RPi are disabled) for about 2 years now. However, yesterday, I ran just your normal system updates 'sudo apt-get update then upgrade', now when I try to run the script, I get these errors.
I don't know even where to start with this one, and if you can provide some suggestions, that would be great.
INFO: Adapter status - Powered: True
INFO: Starting discovery...
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.9/site-packages/gatt/gatt_linux.py", line 156, in stop_discovery
self._adapter.StopDiscovery()
File "/usr/lib/python3/dist-packages/dbus/proxies.py", line 141, in __call__
return self._connection.call_blocking(self._named_service,
File "/usr/lib/python3/dist-packages/dbus/connection.py", line 652, in call_blocking
reply_message = self.send_message_with_reply_and_block(
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.UnknownObject: Method "StopDiscovery" with signature "" on interface "org.bluez.Adapter1" doesn't exist
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/solar-monitor/solar-monitor.py", line 84, in <module>
device_manager.stop_discovery()
File "/home/pi/.local/lib/python3.9/site-packages/gatt/gatt_linux.py", line 161, in stop_discovery
raise _error_from_dbus_error(e)
gatt.errors.Failed: Method "StopDiscovery" with signature "" on interface "org.bluez.Adapter1" doesn't exist
ran script, but seems to crash at BLE scan part now after system updates

Connect TCP socket failed with: 111 (No connection between python in linux and twincat in windows)

I have been trying to get a connection between TwinCAT 3 on Windows and Python on Ubuntu. I already have the connection between Twincat 3 Windows and Python Windows working, but not to Ubuntu. I have a virtual machine set up through Oracle VM Virtualbox. I tried many things but so far had no success in creating the connection.
I have a bridged adapter network and tried to open the port of the IP address of the virtual machine in linux through sudo ufw allow
I have the following code:
pyads.open_port()
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
pyads.close_port()
plc = pyads.Connection('10.11.104.206.1.1', 851)
plc.open()
try:
# try to connect to PLC
plc.read_state()
print('Connection succeeded')
except Exception:
print('Connection failed')
And this is the error I get:
2020-11-22T22:45:46+0100 Error: Connect TCP socket failed with: 111
Traceback (most recent call last):
File "/home/laurence/ws_moveit/devel/lib/moveit_tutorials/move_panda_LKO.py", line 15, in <module>
exec(compile(fh.read(), python_script, 'exec'), context)
File "/home/laurence/ws_moveit/src/moveit_tutorials/doc/move_panda_LKO/scripts/move_panda_LKO.py", line 64, in <module>
pyads.add_route('10.11.104.206.1.1','127.0.0.1')
File "/usr/local/lib/python3.8/dist-packages/pyads/ads.py", line 188, in add_route
return adsAddRoute(adr.netIdStruct(), ip_address)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 155, in wrapper
return fn(*args, **kwargs)
File "/usr/local/lib/python3.8/dist-packages/pyads/pyads_ex.py", line 177, in adsAddRoute
raise ADSError(error_code)
pyads.pyads_ex.ADSError: ADSError: target port not found ADS Server not started (6).
These are the netid/IPadresses.
-
-
-
CX-52EE70
169.254.64.202
5.82.238.112.1.1
TCP_IP
-
LEENLAPTOP19
127.0.0.1
10.11.104.206.1.1
TCP_IP
I have tried combinations with other netid/IP addresses so sometimes I get other errors (110,113) but usually 111 which means connection refused, but I do not know what I am doing wrong. Any ideas?
Please make sure the plc runtime is running (a plc program) when you connect. If the plc is in config or exception mode the plc runtime ads port (851 (or 801 for TC2)) is not present. That is what the ADS error 6 target port not found is trying to tell us.

What's the problem with serial connection in the following code (running on Raspberry Pi 4, Raspbian OS)?

this serial connection thing on RPi should not be this challenging, though right now I'm facing something quite weird
This is the code:
.
.
import serial
.
.
ser=serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
.
.
The Error is:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
FileNotFoundError: [Errno 2] No such file or directory: '/dev/ttyUSB0'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/pi/Desktop/rtu-v4/dnp3/rtu.py", line 27, in <module>
timeout=1
File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 240, in __init__
self.open()
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 2] could not open port /dev/ttyUSB0: [Errno 2] No such file or directory: '/dev/ttyUSB0'
I alraedy checked out:
https://www.raspberrypi.org/forums/viewtopic.php?t=224369
https://github.com/brendan-w/python-OBD/issues/137
and ran the following commands in terminal:
sudo pip3 uninstall serial
sudo pip3 install pyserial
The Device is a Raspberry Pi 4
Any Help would be appreciated.
Thnx.
The message "No such file or directory: '/dev/ttyUSB0'" means that you do not have a device conected to you USB0.
You can use the command:
lsusb
to find out which ports are available and then change in you code de USB name to connect with the rigth device.
Since you are trying to communicate (I assume) with a USB to serial adapter, you can use dmesg to get the device that it is attached to the ttyUSB0.
In a terminal type this command:
dmesg|grep ttyUSB*
It will print out all the devices that are attached to all ttyUSBs.
In my case the result is:
[ 5072.316991] usb 3-1: ch341-uart converter now attached to ttyUSB0
If there were more devices connected, the result would have listed ttyUSB1/2..etc.
Should you disconnect the device, running the same command in a terminal will show the disconnection message:
dmesg|grep ttyUSB*
[ 5361.353142] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0

How to insert socat sniffing between pyserial and actual serial port

I have an app written in python3 that uses pyserial (python3-serial) to communicate with another processor via serial cable. And I'm losing some responses. I have a tap on the line itself and have determined that the responses are indeed being placed on the wire.
So I wanted to sniff the port at a low linux level to see if the responses are showing up there. My python3 apps uses something like
port = serial.Serial(path, baudrate=115200, timeout=0)
where path is something like _port_TD200_ which is a symlink to \dev\ttyS3.
My general approach was to change that link, so that it points at a virtual port, and then bridge the real port to the virtual port. So I used ln -sf to relink the _port_TD200_ to /tmp/ttyV0 and then run this
sudo socat /dev/ttyS3,raw,echo=0 SYSTEM:'tee input.txt | socat - "PTY,link=/tmp/ttyV0,raw,echo=0,waitslave" | tee output.txt'
However, when I try to restart the service that runs the pyserial app... it chokes on the change:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 265, in open
self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
PermissionError: [Errno 13] Permission denied: '/opt/pilot/_port_TD200_'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/opt/pilot/radio.py", line 19, in __init__
self.port = serial.Serial(path, baudrate=115200, timeout=0)
File "/usr/lib/python3/dist-packages/serial/serialutil.py", line 236, in __init__
self.open()
File "/usr/lib/python3/dist-packages/serial/serialposix.py", line 268, in open
raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /opt/pilot/_port_TD200_: [Errno 13] Permission denied: '/opt/pilot/_port_TD200_'
I have a guess that the pyserial open machinery which opens a file descriptor, but ALSO does setserial like things, is not happy because /tmp/ttyV0 is not enough of a real serial port. Is this correct? If so, is there a way to modify the socat incantation to make it possible?
Or is it something else? I admit I don't really understand the socat incantation. I pulled it from this stack exchange question...

Why a simple UDP Socket gives me OSError: WinError 10048?

I am trying to write a simple socket (server side) to communicate with a process on the same machine, using UDP as Transport Protocol. This is the code:
from socket import *
serverPortS = 1234
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('localhost', serverPortS))
print ('Il server e pronto a ricevere')
messageS, clientAddressS =serverSocket.recvfrom(2048)
modifiedMessageS = messageS.upper()
serverSocket.sendto(modifiedMessageS, clientAddressS)
serverSocket.close()
The console gives me the error, just launching the server (no client yet):
Traceback (most recent call last):
File "E:\Laboratorio Python\udp_server.py", line 12, in <module>
serverSocket.bind(('localhost', serverPortS))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
I don't know how to fix it or how does it means, and searching on the Web I found more complex problem; would love to hear a possible solution!

Resources