Question

I am writing an application like a serial port driver for a RS232 port connecting device. I have a problem with handling Plug and Play events (How to notify connect and disconnect devices to installed RS232 ports of the PC ?). I am opening a file descriptor (/dev/ttySx) for each device and I need to open it when connecting the device to PC and need to close it when disconnected. My questions are do I need to handle PNP events in Serial port programming like in USB devices (in libusb library) and if yes, What is the best method for that ?

Operating System : CentOS

Programming Language : C++

Was it helpful?

Solution

So, there are no direct PNP events for traditional serial ports - obviously a USB serial port will at some level be a serial port, but I believe that is handled by the "usb driver" for the serial device, and not something you need to deal with.

Unfortunnately, there is no distinct way to determine that something is connected on a serial port in it's most basic behaviour (three wires for RX, TX and ground). If you use at least four wires, you can use DCD (Data Carrier Detect) to notice that a serial port is "connected at the other end". In linux, there is no way to recognise the change in the DCD pin itself in user-mode. It can be used to "wait for serial port to become active" if you try to use fd = open("/dev/ttyS0", O_RDWR); - if you specify O_NONBLOCK it will open immediately, regardless of the state of DCD. If you don't specify O_NONBLOCK, the OS waits for the carrier to be present before it opens. It is possible to change the file to non-blocking later, should you need to. You will then have to poll the DCD using IOCTL calls (or some other wrapping of these): http://man7.org/linux/man-pages/man4/tty_ioctl.4.html

The other way to "detect" serial ports is simply to send something out the port, and see if you get a reply (of the right kind). This obviously assumes that the device is actually designed to respond to some activity on the serial port in some way - a modem for example, will accept "Hayes Commands" or "AT commands", and give some information back to those commands. But of course, for this to work, you need to first open the device, then send something, and (in case of a modem) it can be difficult to detect when the device goes away. Of course, if you have "your own" device at the other end, you can, if there is no "traffic" going on, send a "ping" command to ask if the other machine is still there. If no reply, then the device has gone...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top