cordovarduino icon indicating copy to clipboard operation
cordovarduino copied to clipboard

Error writing 337 bytes at offset 0 length=337

Open Freezus opened this issue 9 years ago • 35 comments

Hey, I'm trying to write something from my android app to the payment terminal iWL250. Application should send json with data and then terminal prints something.

serial.requestPermission({
                vid: '079B',
                pid: '0028'
            },
                function (successMessage) {
                    serial.open(
                        { baudRate: 57600 },
                        function (successMessage) {

                            serial.writeHex(
                                JSON.stringify(text),
                                function (successMessage) {
                                    $cordovaToast.showLongBottom(succesMessage);
                                    alert(successMessage);
                                },
                                errorCallback
                            );
                        },
                        errorCallback
                    );
                },
                errorCallback
            );

application connects to the terminal, but when it tries to write data I get an error: "Error writing 337 bytes at offset 0 length=337"

Freezus avatar Oct 19 '16 13:10 Freezus

Hello, Are you sure about your serial connection? (e.g. Rx and Tx are correctly wired) Also are you sure about the port configuration? (baudRate, dataBits, stopBits, parity, dtr and rts)

Do you have some documentation about the serial capabilities of your device so I can check and help you?

Regards

xseignard avatar Oct 19 '16 15:10 xseignard

What u mean about serial connection? How I can wire it?

In documentation I have recommended for port: baud: 115200, dataBits: 8, stopBits: none, parity 0

I have no idea about dtr or rts....

I can connect it as RS-232 or USB, I'm using USB.

Freezus avatar Oct 19 '16 15:10 Freezus

Re, You wrote the following for the port configuration:

{ baudRate: 57600 }

According to what you say it should be:

{ baudRate: 115200, dataBits: 8, stopBits: 0, parity: 0 },

No?

xseignard avatar Oct 19 '16 16:10 xseignard

baud: 115200, dataBits: 8, stopBits: 1, parity 0 (my mistake, i wrote stopbits: 0 before) anyway, i can configure device if i want to set other values

but still doesn't work... I think, the similar problem is here, but i cant change this values in library .... https://github.com/mik3y/usb-serial-for-android/issues/91

When I connected terminal to notebook, by usb, and used Terminal 1.9b, there were no errors with sending json to terminal...

I'm using write(), tried writeHex() and nothing...

Freezus avatar Oct 19 '16 17:10 Freezus

I used this "tutorial" and this application allows me to write to terminal, and it works...

http://www.allaboutcircuits.com/projects/communicate-with-your-arduino-through-android/

Freezus avatar Oct 24 '16 17:10 Freezus

https://www.bountysource.com/issues/23844779-incorrect-endpoint-assignment-in-cdc-driver-with-fix

is there any chance to fix it? It seems to be the same problem.

Freezus avatar Oct 24 '16 21:10 Freezus

Hello @Freezus I'll try to fix it during next week. Will you be able to test it?

Regards

xseignard avatar Feb 07 '17 08:02 xseignard

Hey, I changed endpoints in library and it's working :)

Freezus avatar Feb 07 '17 08:02 Freezus

But of course I can help with tests ;)

Freezus avatar Feb 07 '17 08:02 Freezus

Great.

I'll add some options in the cordovarduino plugin.

I'll let you know

xseignard avatar Feb 07 '17 11:02 xseignard

Hi again @xseignard,

With your guidance on #84, I'm successfully able to read and write to device through serial port.

Now I have another weighing device which uses beaglebone black, and I connect the device usb to my android mobile using USB-OTG.

Here is the code,

serial.requestPermission({ vid: '1d6b', pid: '0104', driver: 'CdcAcmSerialDriver' },
	function success(successMessage) {
		serial.open(
			{ baudRate: 9600, dataBits: 8, stopBits: 1, parity: 0 },
			function success(successMessage) {
				open = true;
				alert('Port opened');
				serial.write('root\r\n', function success() { alert('Write success'); }, errorCallback);
				serial.registerReadCallback(
					function success(data) {
						var dec = new TextDecoder();
						var arr = new Uint8Array(data);
						var strout = dec.decode(arr);
						alert(strout);
					},
					function error() {
						new Error("Failed to register read callback");
					});
			},
		errorCallback);
	    },
	    errorCallback);

I get 'Port opened' alert message, but while writing I get this 'Error writing 6 bytes at offset 0 length=6' message.

I'm able to connect the device using putty serial, and it connects to the terminal window of beaglebone black (uses Linux OS), here is the info,

root@beaglebone:~# lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description:    Debian GNU/Linux 7.11 (wheezy)
Release:        7.11
Codename:       wheezy

Please let me know on how to write through serial to connect the terminal window.

sureshkumar-s89 avatar Dec 19 '17 07:12 sureshkumar-s89

Mmmm, I guess you face the same issue as @Freezus

I should add an option to switch endpoints. And for this I would need your help @sureshkumar-s89

I come back to you in about an hour.

xseignard avatar Dec 19 '17 08:12 xseignard

Thank you @xseignard and I'm happy to get your guidance to achieve my requirement.

sureshkumar-s89 avatar Dec 19 '17 09:12 sureshkumar-s89

Hello @sureshkumar-s89

Could you try to change the jar file in the cordovaduino plugin in your project? With the following

https://drive.google.com/open?id=1EDRnA9Q9wHvrNZjmgsx11qAc3rM-0F0n

And let me know if it works

Regards

xseignard avatar Dec 19 '17 13:12 xseignard

Hi @xseignard,

I copied this latest jar file into plugin/fr.drangies.cordova.serial folder and as well in the node_modules/cordovarduino folder.

But the error persist. Do I need to set or change any properties in serial.requestPermission code?

sureshkumar-s89 avatar Dec 19 '17 13:12 sureshkumar-s89

Hello @sureshkumar-s89

Could you try with this new version of the jar? https://drive.google.com/open?id=1NPPHRboI3F7wuQHXTYArh1vZelCpPzLC

Regards

Xavier

xseignard avatar Dec 25 '17 15:12 xseignard

Hello @xseignard

After replacing with this latest jar file, the write process works fine and I'm able to get the success alert message. Thank you so much.

I have this latest code:

serial.requestPermission({ vid: '1d6b', pid: '0104', driver: 'CdcAcmSerialDriver' },
	function success(successMessage) {
		serial.open(
			{ baudRate: 9600, dataBits: 8, stopBits: 1, parity: 0 },
			function success(successMessage) {
				open = true;
				alert('Port opened');
				serial.write('root\r\n', function success() { alert('Write success'); }, errorCallback);
				serial.write('cat /tmp/fifo_file\r\n', function success() { alert('Write success'); }, errorCallback);
				serial.registerReadCallback(
					function success(data) {
						var dec = new TextDecoder();
						var arr = new Uint8Array(data);
						var strout = dec.decode(arr);
						alert(strout);
					},
					function error() {
						new Error("Failed to register read callback");
					});
			},
		errorCallback);
	    },
	    errorCallback);

The first write is to login (as root), then I need to read a FIFO file where my weighing value is stored. But I get the alert message from registerReadCallback only once and I didn't get data for the second write command. I have a node script (SerialReadWrite.zip) to read from the device using node-serialport package, and it continually prints value on console. I would like to get the same output with this plugin.

Could you please help me to find what am I missing?

sureshkumar-s89 avatar Dec 26 '17 06:12 sureshkumar-s89

Hello @sureshkumar-s89

Due to the async nature of javascript, I would change a bit your code.

// attach the callback before anything else, to be sure to miss nothing
serial.registerReadCallback(
  function success(data) {
    var dec = new TextDecoder();
    var arr = new Uint8Array(data);
    var strout = dec.decode(arr);
    alert(strout);
  },
  function error() {
   new Error("Failed to register read callback");
  }
);
// write the first sequence, and when it is succesful, write the second in the success callback
serial.write(
  'root\r\n',
  function success() {
    alert('Write success');
    serial.write('cat /tmp/fifo_file\r\n', function success() { alert('Write success'); }, errorCallback);
  },
  errorCallback
);

Hope this helps

Regards

xseignard avatar Dec 26 '17 14:12 xseignard

Hello @xseignard

Thank you for suggesting those changes, I have modified the code but still I get no output from read callback except an alert message.

Also the output I'm getting from the read callback alert(data) (before decoding) is:

[object Object]

I tried with this { baudRate: 9600, dataBits: 8, stopBits: 1, parity: 0, dtr: true, rts: true } option, but no luck.

sureshkumar-s89 avatar Dec 27 '17 06:12 sureshkumar-s89

Hello,

So to be clear, do you get the 2 "Write success" alerts?

Beside of that you may need to to use writeHex instead of write. And I'm not sure the way you decode the data in the read callback is the right way to do it. Please check the readme to see a proper way to do it.

Regards

xseignard avatar Dec 27 '17 08:12 xseignard

Hello @xseignard

So to be clear, do you get the 2 "Write success" alerts?

Yes, I get 2 "Write success" alerts, but only after the read callback alert.

Beside of that you may need to use writeHex instead of write

I tried to use writeHex, but application quits after "Port opened" alert.

And I'm not sure the way you decode the data in the read callback is the right way to do it. Please check the readme to see a proper way to do it

Thank you, I have changed the decoding part as instructed in readme.

sureshkumar-s89 avatar Dec 27 '17 09:12 sureshkumar-s89

And? Does it work?

I checked your node.js version, and the parser you use relies on new lines, so the code on the readme should do the trick.

Regards

xseignard avatar Dec 27 '17 10:12 xseignard

You can try something like this:

var str;
serial.registerReadCallback(
    function success(data){
        // decode the received message
        var view = new Uint8Array(data);
        if(view.length >= 1) {
            for(var i=0; i < view.length; i++) {
                // if we received a \n, the message is complete, display it
                if(view[i] == 13) {
                    // do what you need with the variable str
					// ...
					// ...
					// ...
					// don't forget to reset it
                    str = '';
                }
                // if not, concatenate with the begening of the message
                else {
                    var temp_str = String.fromCharCode(view[i]);
                    var str_esc = escape(temp_str);
                    str += unescape(str_esc);
                }
            }
        }
    },
    // error attaching the callback
    errorCallback
);

xseignard avatar Dec 27 '17 10:12 xseignard

I tried this code:

serial.requestPermission({ vid: '1d6b', pid: '0104', driver: 'CdcAcmSerialDriver' },
    function success(successMessage) {
        serial.open(
            { baudRate: 9600, dataBits: 8, stopBits: 1, parity: 0, dtr: true, rts: true },
            function success(successMessage) {
                var str;
                alert('Port opened');
                serial.registerReadCallback(
                    function success(data) {
                        alert("Readcallback data: " + JSON.stringify(data));
                        var view = new Uint8Array(data);
                        if (view.length >= 1) {
                            alert("data length >1");
                            for (var i = 0; i < view.length; i++) {
                                // if we received a \n, the message is complete, display it
                                if (view[i] == 13) {
                                    var value = parseInt(str);
                                    alert(value);
                                    str = '';
                                }
                                    // if not, concatenate with the begening of the message
                                else {
                                    var temp_str = String.fromCharCode(view[i]);
                                    var str_esc = escape(temp_str);
                                    str += unescape(str_esc);
                                }
                            }
                        }
                    },
                    function error() {
                        new Error("Failed to register read callback");
                    }
                );
                serial.write(
                    'root\r',
                    function success() {
                        alert('Write Success1!!');
                        serial.write('cat /tmp/fifo_file\r', function success(data) { alert('Write Success2!!'); }, errorCallback);
                    },
                    errorCallback
                );
            },
            errorCallback
        );
    },
    errorCallback
);

It gives following alert messages in the same sequence: Port opened Readcallback data: {"registerReadCallback":"true"} // alert("Readcallback data: " + JSON.stringify(data)); Write Success1!! Write Success2!!

sureshkumar-s89 avatar Dec 27 '17 11:12 sureshkumar-s89

It's hard to debug without the hardware, but for me it should work, please try to remove alert("Readcallback data: " + JSON.stringify(data));

And use console.log instead. After that you will be able to debug your app over wifi. https://github.com/xseignard/cordovarduino/issues/24#issuecomment-73859313

Could you also try the following write sequence:

serial.write(
  'root\r',
  function success() {
    console.log('Write Success1!!');
    setTimeout(function() {  
      serial.write(
        'cat /tmp/fifo_file\r',
        function success(data) { console.log('Write Success2!!'); }, 
        errorCallback
      );
    }, 500);
  },
  errorCallback
);

xseignard avatar Dec 27 '17 18:12 xseignard

Hello @xseignard

I tried the above write sequence with setTimeout and removed alert("Readcallback data: " + JSON.stringify(data)); But I get no output.

And with reference to this #24 (comment), I do not know how to find my android mobile IP address. Could you please let me know how to find it and debug through wifi, so that I can replace alert with console.log

sureshkumar-s89 avatar Dec 28 '17 05:12 sureshkumar-s89

https://android.stackexchange.com/questions/2984/how-can-i-see-what-ip-address-my-android-phone-has

xseignard avatar Dec 28 '17 07:12 xseignard

Thank you, I have replaced alert with console.log and please find the attached adb logcat log file (CordovaConsoleLog.txt). I do not know where the error occurs.

sureshkumar-s89 avatar Dec 28 '17 09:12 sureshkumar-s89

Hello,

Actually there are no errors, for me there is something wrong somewhere else. Maybe with the \r char.

Does the \n could work?

xseignard avatar Dec 28 '17 18:12 xseignard

Hello @xseignard

I tried with \n and \r\n but I didn't get the output. I had included console.log lines in my code as below:

console.log(view.length);
if(view.length >= 1) {
    console.log('Data length > 1');
    for(var i=0; i < view.length; i++) {
        // if we received a \n, the message is complete, display it
        if(view[i] == 13) {
            // logic
        }
        else {
            var temp_str = String.fromCharCode(view[i]);
            var str_esc = escape(temp_str);
            str += unescape(str_esc);
        }
    }
}

console.log(view.length) prints length as "0" only once and it is not get printed after write process.

I/chromium( 8810): [INFO:CONSOLE(30)] "0", source: file:///android_asset/www/js/index.js (30)

due to this it is not getting into the if statement. I don't know what is wrong in my code.

sureshkumar-s89 avatar Dec 29 '17 05:12 sureshkumar-s89

Hello,

I'm out of idea here. I think something is wrong with the write.

It is very hard for me to debug without your hardware.

Do you have the brand/model of your weight scale, so I can check the docs/datasheet?

Regards

xseignard avatar Dec 30 '17 08:12 xseignard

Hello,

I took a quick look to this https://dok.kern-sohn.com/manuals/files/English/PCB-BA-e-1718.pdf

And I don't get how does it match with your node.js code? Does your node.js code works? Could you show me the exact datasheet of your scale?

Regards

xseignard avatar Dec 30 '17 12:12 xseignard

Hello @xseignard

Here is the link (http://www.belengineering.com/product/m5-m723i/) for model of the weight scale.

And the node.js code works for me (running from Windows commandline connecting the device via USB). Here is the node.js code (SerialReadWrite.zip) and sample output I get from windows console:

E:\WeighScaleProject\Node\SerialExample>node SerialReadWrite.js
ress for usb0 is: 192.168.7.2
beaglebone login: root
Last login: Sun Mar  1 20:48:18 UTC 2015 from 192.168.7.1 on pts/0
Linux beaglebone 3.8.13-bone70 #1 SMP Fri Jan 23 02:15:42 UTC 2015 armv7l

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
root@beaglebone:~# timeout 0.2s cat /tmp/fifo_file
0.000
0.000
0.000
0.000
0.127
0.051
0.030

sureshkumar-s89 avatar Jan 02 '18 05:01 sureshkumar-s89

I used this (https://play.google.com/store/apps/details?id=aws.apps.usbDeviceEnumerator&hl=en) android app to get information of connected device. Here I have attached the screenshot (DeviceInfo.zip) of my weight scale device info using this app.

I found that it has five interface of which two are CDC class and both have two Endpoints. Does it causes any problem? I don't know whether this information is useful.

sureshkumar-s89 avatar Jan 02 '18 11:01 sureshkumar-s89

How to change the endpoint as mentioned above ?

ghost avatar Jun 19 '18 21:06 ghost