xseignard / cordovarduino

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

Partial receiving data #85

Closed gitsad closed 7 years ago

gitsad commented 7 years ago

I have simple program in arduino:

void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(2000);
  Serial.println(12123);
}

and here is my part of cordova project:

 connect = () => {
        const errorCallback = (message) => alert('Error: ' + message);
        serial.requestPermission(
            function(successMessage) {
                if (!'TextDecoder' in window) {
                    alert('Your browser does not support the Encoding API.');
                }
                alert(successMessage);
                serial.open(
                    {
                        baudRate: 9600,
                        dataBits: 2048
                    },
                    function() {
                        serial.registerReadCallback(
                            function success(data){
                                const view = new Uint8Array(data);
                                const enc = new TextDecoder();
                                const decodedString = enc.decode(view);
                                alert(decodedString);
                            },
                            function error(){
                                new Error("Failed to register read callback");
                            });
                    },
                    errorCallback
                );
            },
            errorCallback
        )
    };

I'm confused because success read callback executes 3-4 times due to receiving partial data from arduino. For instance messages are 1, 21 and 23. Someone could explain me how to receive a full message and why my code isn't work? Thanks!

xseignard commented 7 years ago

You need to check for the end of line char before displaying the received message. Please read the docs here: https://github.com/xseignard/cordovarduino#a-complete-example