Hybrid application development-Serial Communication (2), application development-Serial Communication
Sending instructions and parsing data
Cordova Plugin: https://github.com/xseignard/cordovarduino
Install: cordova plugin add cordovarduino
Sample Code:
Var opts = {baudRate: 115200}; $ scope. allData = []; serial. requestPermission (function success (res) {console. log (res); serial. open (opts, function success (res) {console. log (res) ;}, function error (err) {console. log (err) ;}) ;}, function error (err) {console. log (err) ;}); var view = []; serial. registerReadCallback (function success (res) {var lin = new Uint8Array (res); view = view. concat (Array. from (lin); // because the plug-in returns data multiple times at a time, concatenate if (view. length = 35) {// single card $ scope. anaData (view); console. log ('singles' + view)} else {// multi-card if (view. length-35) % 20 = 0) {console. log ('do' + view) $ scope. anaDatas (view) ;}}, function error (error) {console. log (error)}); // sends the command $ scope. sendOrder = function () {serial. writeHex (myOrderString, function success (res) {console. log (res) ;}, function error (err) {console. log (err) ;}) ;}// receives data // parses a single $ scope of data. anaData = function (aaa) {var bbb = aaa. slice (13,29); var ccc = ''; var arr = []; var ddd = []; function topow (x) {return x. toString (16)}; bbb. map (topow); ccc = String. fromCharCode. apply (null, bbb); for (var I = 0; I <ccc. length; I = I + 2) {arr. push (ccc. substring (I, I + 2);} arr. reverse (); ddd = arr. join ('') console. log (ddd); $ scope. allData. push (ddd); $ scope. $ apply ();};
Note:
I don't know whether the plug-in problem is still a hardware problem. I should have returned the data packet multiple times at a time, therefore, when monitoring callback receives data, splice the received data before processing. This step can be removed if your device is normal.