views:

415

answers:

0

Hi everybody. I'm writing an RXTX based code in order to detect the plug and unlug of a USB serial device on linux/windows.

public class PortMonitor implements Runnable
{
    String portname;
    boolean life = false;
    CommPort p = null;

    public PortMonitor(String name)
    {
        this.portname = name;
    }

    public void start()
    {
        new Thread(this).start();
    }

    public void run()
    {
        life=true;
        while (life)
        {
            synchronized (this)
            {
                try
                {
                    wait(1000);
                    //System.out.println("trying ....");
                    CommPortIdentifier.getPortIdentifiers();
                    CommPortIdentifier cpi =CommPortIdentifier.getPortIdentifier(portname);
                    p=cpi.open("",1);
                    onConnect(p);
                }
                catch (PortInUseException e1)
                {
                    continue;
                }
                catch (NoSuchPortException e1)
                {
                    if (p!=null)
                    {
                        onDisconnect(p);
                        p.close();
                        p=null;
                    }
                }
                catch (Exception e1)
                {
                    break;
                }

            }
        }
        life=false;
    }

    void onConnect(CommPort p)
    {
            System.out.println("Port "+portname+" Connected");
    }

    void onDisconnect(CommPort p)
    {
            System.out.println("Port "+portname+" Disconnected");
    }

    CommPort getPort()
    {
        return p;
    }
}

On windows it work fine but in linux there is a sort of ping pong on onConnect and onDisconnect. Between the events I can observe this error:

RXTX fhs_lock() Error: creating lock file /var/lock/LCK..ttyACM3 : file exists

I suppose the problem is in CommPortIdentifier.getPortIdentifiers(); , the lock file is no correctly deleted and so the device is not enumerated when the port is opened (by open() ).

Do you have some suggestions ?

Alternatively, there is a way to get the plug/unplug event through a listener interface that can tell to my class when a device is atached or is detached so i could be sure to open/close the port ?

Thanks