Is it possible to query a particular serial port is connected/disconnected on linux pc? is there any way we can read sysfs information to query if particular port is connected or not?
It rather depends on what you mean by "connected". I'll address the least accurate, but simplest meaning first.
Existence of the port
If you mean to find out if the port itself is present in the system, then you could check for the existence of a loaded module which would support it, check for the existence of a device such as /dev/ttyS0 or /dev/ttyUSB0, and verify that you can open it (for example, I have a /dev/ttyS0 device file present on a system which doesn't actually have that hardware). USB converters can be hotplugged, so today you can see actual "serial ports" come and go in a running system.
"Modem" control / status signals
Another possibility is that you want to find out if there is anything cabled to the port. This is not something that the system can necessarily know. There are modem control and status signals which a peripheral could assert, and which you could read. However, peripherals are not required to make use of those, or even use them in the way that once made sense in the era of modems. Many systems you might find yourself connected to only utilize the receive and transmit data lines and ground.
Detect by receiving data
The remaining possibility is that there may be no way to tell if the port is connected, other than by looking for data from it. Some peripherals might automatically produce data at regular intervals, so you could just try reading and see if you get any. For others, you could send a query (hopefully not one with undesired side effects), and see if you get back an expected response. For example, an instrument approximately implementing the SCPI standard might respond with some identifying information if you sent it the string "*IDN?\n".
An additional major catch to this is that you have to have the port and peripheral configured with compatible baud rates and word formats. If not, you may get seemingly random data. You may in some cases be able to read a framing error bit out of the implementing UART engine (you'd have to check if the driver exposes this) and use that as an indication that there is probably something there, but at the wrong baud rate.
With fine grained control of the hardware and expected data from the other end, it's also possible to write an automatic baud rate detection routine, though that usually implemented on the "peripheral" end rather than on the "host".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With