xseignard / cordovarduino

Cordova/Phonegap plugin for USB host serial communication from an Android device.
MIT License
166 stars 110 forks source link

How to detect device plug out? #95

Open MTA1711 opened 6 years ago

MTA1711 commented 6 years ago

Hi, I'm using the plugin to communicate with a serial device over USB. I am able to communicate with the device, but I would like to detect when user plug out the device.

I tried to call open function every second and when an error occurs I conclude that device has been plug out.

sureshkumar-s89 commented 6 years ago

Hi,

I was also in need of USB plug out status. I created a fork repository from this repository, and added a function called serial.usbDetached() to detect USB detached status. It works for me, but is not yet confirmed by the author of this repository.

You don't need to call the open function every second if you use this function. Once you opened the port, just call serial.usbDetached function only once and that's it.

You have to remove the existing plugin and add it from forked repository like this, to use this function: cordova plugin add https://github.com/sureshkumar-s89/cordovarduino.git

Here is the sample code to use the function,

var errorCallback = function (message) {
    alert('Error: ' + message);
};

serial.requestPermission(
    function success(successMessage) {
        serial.open(
            { baudRate: 9600 },
            function success(successMessage) {
                serial.usbDetached(function (success) { }, function (error) { alert(error) });
                //your code
            },
            errorCallback
        );
    },
    errorCallback
);