Can't send data over serialPort - javascript

I would like to control my Arduino robot with Node.js and a joystick, but serialport.write doesn't send any data to Arduino. I have tried to use code without a joystick and it works but only with one serial.write.
Is there a bug in my code?
Arduino code:
String data = Serial.readString();
Serial.println(data);
if(data=="2") {
//motor1
}
Node.js
var hid = require('node-hid');
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('COM3', {
baudrate: 9600
});
serialPort.on("open", function() {
console.log('open');
function sentData(data) {
console.log(data);
if (data == 0)
setTimeout(function() {
serialPort.write('1')
}, 2000);
else if (data > 999)
setTimeout(function() {
serialPort.write('2')
}, 2000);
}
var device = new hid.HID(1133, 49685);
device.on('data', function(buf) {
var ch = buf.toString('hex').match(/.{1,2}/g).map(function(c) {
return parseInt(c, 16);
});
var position = ((ch[2] & 0x0f) << 6) + ((ch[1] & 0xfc) >> 2);
position = parseInt(position);sentData(position);
});
});

The arduino code should look like this:
String data = '';
while(Serial.available() > 0) {
data = data + Serial.read();
}
Serial.println(data);
if(data == "2") {
//code
}
But, sorry, I can't see if there is problem in you node.js

Related

How do I keep both the child process running and parent communicating in Node JS?

I'm using a blynk client written in Node JS on my raspberry pi that connects and authenticates to the blynk server. I have another process I want to run that scans for BLE beacons at the same time as keeping connected to the server and polling for button presses. I am getting them both to execute at the same time but the communication is only happening if I change the state of virtual pin "V0". I'm new to Node JS and perhaps I misunderstanding but, why does it stop my parent process once the child process authenticates and doesn't execute output the parent process unless I change the state of "V0"
//Parent Process
var Bleacon = require('./index');
var uuid = '3247ff7d3f0d4b2c9df61189398eb85e';
var arr = [];
var ledPin = 17;
var math = require('mathjs');
var child_process=require('child_process');
const child = child_process.fork("doorlock.js");
console.log("child scanning...");
Bleacon.startScanning(uuid);
Beacon()
function Beacon() {
Bleacon.on('discover', function(bleacon) {
if (bleacon.uuid == uuid) {
console.log("uuid matches");
if (bleacon.proximity == 'immediate') {
console.log('immediate: ' + bleacon.rssi);
arr.push(bleacon.rssi);
//console.log(arr);
//console.log(math.mean(arr));
if (arr.length>=20 && math.mean(arr)>=-65) {
child.send('unlock door');
arr = [];
}
} else if (bleacon.proximity == 'near') {
console.log('near: ' + bleacon.rssi);
arr.push(bleacon.rssi);
//console.log('avg rssi: ' + math.mean(arr));
//console.log(arr);
if (arr.length>=20 && math.mean(arr)<=-65) {
child.send('lock door');
arr = [];
}
} else {
arr = [];
}
}
//console.log('bleacon found: ' + JSON.stringify(bleacon));
});
}
The child process:
#!/usr/bin/env node
//Child Process
//*** SMARTPHONE DOORLOCK ***//
var unlockedState = 825;
var lockedState = 2100;
var motorPin = 18;
var buttonPin = 4;
var ledPin = 17;
var blynkToken = '191d2e5c8f754fad9af08a3b9cc81eaa';
var arr = [];
var len = 20;
var Bleacon = require('./index');
var math = require('mathjs');
var uuid = '3247ff7d3f0d4b2c9df61189398eb85e';
// *** Start code *** //
var locked = true;
//Setup servo
var Gpio = require('pigpio').Gpio,
motor = new Gpio(motorPin, {mode: Gpio.OUTPUT}),
button = new Gpio(buttonPin, {
mode: Gpio.INPUT,
pullUpDown: Gpio.PUD_DOWN,
edge: Gpio.FALLING_EDGE
}),
led = new Gpio(ledPin, {mode: Gpio.OUTPUT});
//Setup blynk
var Blynk = require('blynk-library');
var blynk = new Blynk.Blynk(blynkToken);
var v0 = new blynk.VirtualPin(0);
var v1 = new blynk.VirtualPin(1);
console.log("locking door")
lockDoor()
process.on('message', function(message) {
console.log('[child] received message from server:', message);
if (message == 'unlock door') {
console.log('I read from parent that I am to unlock the door');
}
});
button.on('interrupt', function (level) {
console.log("level: " + level + " locked: " + locked)
if (level == 0) {
if (locked) {
unlockDoor()
} else {
lockDoor()
}
}
});
v0.on('write', function(param) {
console.log('V0:', param);
if (param[0] === '0') { //unlocked
unlockDoor()
} else if (param[0] === '1') { //locked
lockDoor()
} else {
blynk.notify("Door lock button was pressed with unknown parameter");
}
});
blynk.on('connect', function() {
//console.log("Blynk ready.");
});
blynk.on('disconnect', function() { console.log("DISCONNECT"); });
function lockDoor() {
motor.servoWrite(lockedState);
led.digitalWrite(1);
locked = true
//notify
blynk.notify("Door has been locked!");
//After 1.5 seconds, the door lock servo turns off to avoid stall current
setTimeout(function(){motor.servoWrite(0)}, 1500)
}
function unlockDoor() {
motor.servoWrite(unlockedState);
led.digitalWrite(0);
locked = false
//notify
blynk.notify("Door has been unlocked!");
//After 1.5 seconds, the door lock servo turns off to avoid stall current
setTimeout(function(){motor.servoWrite(0)}, 1500)
}

Node.js formidable file upload working slow on server

I am trying to send files as form data along with some fields using http post request in angular.js and receiving file in app.post in node.js. The file sending works fine on localhost. As they say formidable uploads files at 500 mb/sec speed but on server when I am trying to send a file of 5 to 10 mb it takes 40 to 80 seconds. Please check is there any problem in my implementation.
I am using nginx and pm2 on server.
Node.js code:
// route for uploading audio asynchronously
app.post('/v1/uploadAudio', function(req, res) {
var userName, useravatar, hasfile, ismusicfile, isType, showMe, DWimgsrc, DWid, msgtime;
var imgdatetimenow = Date.now();
var form = new formidable.IncomingForm({
uploadDir: __dirname + '/public/app/upload/music',
keepExtensions: true
});
form.on('end', function() {
res.end();
});
form.parse(req, function(err, fields, files) {
console.log("files : ", files);
console.log("fields : ", fields);
var data = {
username: fields.username,
userAvatar: fields.userAvatar,
repeatMsg: true,
hasFile: fields.hasFile,
isMusicFile: fields.isMusicFile,
istype: fields.istype,
showme: fields.showme,
dwimgsrc: fields.dwimgsrc,
dwid: fields.dwid,
serverfilename: baseName(files.file.path),
msgTime: fields.msgTime,
filename: files.file.name,
size: bytesToSize(files.file.size)
};
var audio_file = {
dwid: fields.dwid,
filename: files.file.name,
filetype: fields.istype,
serverfilename: baseName(files.file.path),
serverfilepath: files.file.path,
expirytime: imgdatetimenow + (120000)
};
files_array.push(audio_file);
ios.sockets.emit('new message music', data);
});
});
AngularJS code:
// =========================================== Audio Sending Code =====================
$scope.$watch('musicFiles', function() {
$scope.sendAudio($scope.musicFiles);
});
// opens the sent music file on music_icon click on new window
$scope.openClickMusic = function(msg) {
$http.post($rootScope.baseUrl + "/v1/getfile", msg).success(function(response) {
if (!response.isExpired) {
window.open($rootScope.baseUrl + '/' + response.serverfilename, "_blank");
} else {
var html = '<p id="alert">' + response.expmsg + '</p>';
if ($(".chat-box").has("p").length < 1) {
$(html).hide().prependTo(".chat-box").fadeIn(1500);
$('#alert').delay(1000).fadeOut('slow', function() {
$('#alert').remove();
});
}
}
});
}
// recieving new music message
$socket.on("new message music", function(data) {
if (data.username == $rootScope.username) {
data.ownMsg = true;
data.dwimgsrc = "app/images/spin.gif";
} else {
data.ownMsg = false;
}
if ((data.username == $rootScope.username) && data.repeatMsg) {
checkMessegesMusic(data);
} else {
$scope.messeges.push(data);
}
});
// replacing spinning wheel in sender message after music message delivered to everyone.
function checkMessegesMusic(msg) {
for (var i = ($scope.messeges.length - 1); i >= 0; i--) {
if ($scope.messeges[i].hasFile) {
if ($scope.messeges[i].istype === "music") {
if ($scope.messeges[i].dwid === msg.dwid) {
$scope.messeges[i].showme = true;
$scope.messeges[i].serverfilename = msg.serverfilename;
$scope.messeges[i].filename = msg.filename;
$scope.messeges[i].size = msg.size;
$scope.messeges[i].dwimgsrc = "app/images/musicplay_icon.png";
break;
}
}
}
};
}
// download music file if it exists on server else return error message
$scope.downloadMusic = function(ev, elem) {
var search_id = elem.id;
for (var i = ($scope.messeges.length - 1); i >= 0; i--) {
if ($scope.messeges[i].hasFile) {
if ($scope.messeges[i].istype === "music") {
if ($scope.messeges[i].dwid === search_id) {
$http.post($rootScope.baseUrl + "/v1/getfile", $scope.messeges[i]).success(function(response) {
if (!response.isExpired) {
var linkID = "#" + search_id + "A";
$(linkID).find('i').click();
return true;
} else {
var html = '<p id="alert">' + response.expmsg + '</p>';
if ($(".chat-box").has("p").length < 1) {
$(html).hide().prependTo(".chat-box").fadeIn(1500);
$('#alert').delay(1000).fadeOut('slow', function() {
$('#alert').remove();
});
}
return false;
}
});
break;
}
}
}
};
}
// validate file type to 'music file' function
$scope.validateMP3 = function(file) {
if (file.type == "audio/mp3" || file.type == "audio/mpeg") {
return true;
} else {
var html = '<p id="alert">Select MP3.</p>';
if ($(".chat-box").has("p").length < 1) {
$(html).hide().prependTo(".chat-box").fadeIn(1500);
$('#alert').delay(1000).fadeOut('slow', function() {
$('#alert').remove();
});
}
return false;
}
}
// sending new 'music file' function
$scope.sendAudio = function(files) {
if (files && files.length) {
$scope.isFileSelected = true;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var dateString = formatAMPM(new Date());
var DWid = $rootScope.username + "dwid" + Date.now();
var audio = {
username: $rootScope.username,
userAvatar: $rootScope.userAvatar,
hasFile: $scope.isFileSelected,
isMusicFile: true,
istype: "music",
showme: false,
dwimgsrc: "app/images/musicplay_icon.png",
dwid: DWid,
msgTime: dateString
}
$socket.emit('send-message', audio, function(data) { // sending new image message via socket
});
var fd = new FormData();
fd.append('file', file);
fd.append('username', $rootScope.username);
fd.append('userAvatar', $rootScope.userAvatar);
fd.append('hasFile', $scope.isFileSelected);
fd.append('isMusicFile', true);
fd.append('istype', "music");
fd.append('showme', false);
fd.append('dwimgsrc', "app/images/musicplay_icon.png");
fd.append('dwid', DWid);
fd.append('msgTime', dateString);
fd.append('filename', file.name);
$http.post('/v1/uploadAudio', fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).then(function(response) {
// console.log(response);
});
}
}
};
I've used Formidable on a couple of side projects, and when uploading to localhost, I do see the 500mb/sec quoted capability (depending on physical hardware of the computer).
However, when uploading a file over the internet, you are subject to the bandwidth limitations of your ISP upload speed as well as the download speed of your server.
You report that a 10MB file takes ~80 seconds to upload to the server. That's about 125KBps (or around 1 megabit/second) which seems fairly reasonable for a home/office ISP upload speed (depending on region of the world).
A good way to eliminate your home/office network performance from the troubleshooting equation would be to write a node.js script that uploads a file several times and calculates an average speed. Run that test file on your local computer, then try again from a different server in the cloud.

Downloading files stuck android application: worklight

i implemented a application on work-light in which I need to download files from the server, its works well on Iphone5 means files are downloading smoothly without stuck the application flow.however when i run the application on my Samsung galaxy s2 (V 4.1) and start downloading files using for loop my application get stuck till the downloading completed. however its works fine when i have only one file to dowload but when the count is above 3 or 4 application get stuck.
if(networkInfo.networkConnectionType=='WIFI'){
$(brandClassDis).addClass('ui-disabled'); // Disabling the Brand.
$(".lms_loadernew").css("display", "block");
var syncProgBar = "#syncProgressBar"+result[0].json.BrandID;
var syncProgLabel = "#syncLoadingLabel"+result[0].json.BrandID;
$(syncProgBar).progressbar({
value: 0,
}).show();
$(syncProgLabel).text(parseInt(0, 10)+"%").show();
localStorage.setItem("download"+result[0].json.BrandID,0);
localStorage.setItem("downloadSucc"+result[0].json.BrandID,0);
for(var i=0; i<result.length; i++){
var obj = {VideoID:result[i].json.VideoID,BrandID:result[i].json.BrandID,CourseID:result[i].json.CourseID,LoadingStatus:"0"};
VideosList.add(obj,{push:false});
result[i].json.IsDownload = 2;
Videos.replace(result);
**downloadFolder(result[i],result.length)**
}
}
function downloadFolder(result,numVideoBrand){
try{
var loaderPer = 0;
var courseId ="#sync_"+result.json.CourseID.replace(/ /g,'');
var courseLabelId ="#loadingLabel"+result.json.CourseID.replace(/ /g,'');
var syncProgBar = "#syncProgressBar"+result.json.BrandID.replace(/ /g,'');
var syncProgLabel = "#syncLoadingLabel"+result.json.BrandID.replace(/ /g,'');
var serverLoc = encodeURI(result.json.DownloadName);
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getDirectory("LMS_APP", {create: true, exclusive: false}, function(directory){
var localPath = directory.fullPath+"/"+"Videos"+"/"+zipFileName;
var ft = new FileTransfer();
ft.download(serverLoc,localPath, function(entry) {
entry.file(function(file) {
WL.Logger.debug("File size: " + file.size);
if(file.size<=854){
downloadFail("",result,numVideoBrand);
entry.remove(successRemove, failRemove);
}else{
if(localStorage.getItem("download"+result.json.BrandID) == null || localStorage.getItem("download"+result.json.BrandID) =="" || localStorage.getItem("download"+result.json.BrandID) == undefined){
localStorage.setItem("download"+result.json.BrandID,1);
}else{
localStorage.setItem("download"+result.json.BrandID,(localStorage.getItem("download"+result.json.BrandID)-(-1)));
}
localStorage.setItem("downloadSucc"+result.json.BrandID,(localStorage.getItem("downloadSucc"+result.json.BrandID)-(-1)));
WL.Logger.debug("Folder is:---->"+directory.fullPath+"/"+zipFileName);
WL.Logger.debug("download"+localStorage.getItem("download"+result.json.BrandID)+"..."+numVideoBrand+"........"+ localStorage.getItem("downloadSucc"+result.json.BrandID));
var loadedVideoPer = (( localStorage.getItem("download"+result.json.BrandID)/numVideoBrand)* 100);
$(syncProgBar).progressbar({
value: loadedVideoPer,
});
$(syncProgLabel).text(parseInt(loadedVideoPer, 10)+"%");
$(courseId).hide();
$(courseLabelId).hide();
}
}, function(error){downloadFail(error,result,numVideoBrand);});
}, function(error) {
});
$(courseId).progressbar({
value: loaderPer,
}).show();
$(courseLabelId).text(parseInt(loaderPer, 10)+"%").show();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
loaderPer = ((progressEvent.loaded / progressEvent.total)*100);
$(courseId).progressbar({
value: loaderPer,
});
$(courseLabelId).text(parseInt(loaderPer, 10)+"%");
//courseLabelId.text(parseInt(loaderPer, 10) + "%" );
loadingStatus(result);
}
};
},function(error){
downloadFail(error,result,numVideoBrand);
});
}, function(error){
downloadFail(error,result,numVideoBrand);
});
}catch(e){
WL.Logger.debug("exp in downloadFile: "+e);
//alert("exp "+videoLoader);
}
}
From the comments, the solution was to:
download file in queue, coz downloading all file at once cause the
application stuck...

WinRT - StreamSocket - Connection closing while reading data via LoadAsync

I'm trying to send HTTP requests via StreamSocket, but response is truncated with
"failedWinRTError: The object has been closed."
Here is my code:
var count, hostName, raw_request, raw_response, reader, socketProtection, startReader, streamSocket, writer;
streamSocket = new Windows.Networking.Sockets.StreamSocket();
hostName = new Windows.Networking.HostName("www.reddit.com", "80");
raw_response = "";
count = 0;
startReader = function() {
return reader.loadAsync(8 * 1000).done(function(bytesRead) {
raw_response += reader.readString(reader.unconsumedBufferLength);
if (raw_response.indexOf("</html>") > 0) {
return;
} else {
startReader();
}
}, function(error) {
raw_response += reader.readString(reader.unconsumedBufferLength);
window.raw_response = raw_response;
return;
});
};
streamSocket.connectAsync(hostName, "80", 0).done(function(response) {
var string;
reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = 1;
writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);
string = "Hello world";
writer.writeString(raw_request);
return writer.storeAsync().done(function() {
writer.flushAsync();
writer.detachStream();
return startReader();
});
});
I noticed that the beginning of the response is truncated as well.
This is what I get at the beginning of HTTP responses.
/1.1 200 OK
Also strangely... HTTPS requests work perfectly.
Any idea what I'm doing wrong? Thanks :)
Remove http:// from the host name and the second parameter is not needed:
var hostName = new Windows.Networking.HostName("www.reddit.com");
Use this object in ConnectAsync, just hostname and service name parameters are needed:
streamSocket.connectAsync(hostName, "80").done(function (response) {
// ....
}, function (error) {
console.log(error);
});
UPDATE: Ok, if the connection is being closed, probably the server closes it. Are you sending a well formed request? Here is an example:
var raw_request, raw_response, reader, writer;
var streamSocket = new Windows.Networking.Sockets.StreamSocket();
function doRequest() {
var hostName = new Windows.Networking.HostName("www.reddit.com");
streamSocket.connectAsync(hostName, "808").then(function () {
reader = new Windows.Storage.Streams.DataReader(streamSocket.inputStream);
reader.inputStreamOptions = Windows.Storage.Streams.InputStreamOptions.partial;
writer = new Windows.Storage.Streams.DataWriter(streamSocket.outputStream);
raw_request = "GET / HTTP/1.1\r\nHost: www.reddit.com/\r\nConnection: close\r\n\r\n";
writer.writeString(raw_request);
return writer.storeAsync();
}).then(function () {
raw_response = "";
return startReader();
}, function (error) {
console.log(error);
});
}
function startReader() {
return reader.loadAsync(99999999).then(function (bytesRead) {
raw_response += reader.readString(reader.unconsumedBufferLength);
if (bytesRead === 0) {
window.raw_response.value = raw_response;
return;
}
return startReader();
});
};

How to get all images from document and store to local

My goal is to get all images from document, then download all images bigger than 150x150px to local.
I'm stucked on retrieving files from URL i got on previous steps. Here is the buggy code line (full code - at the end):
...
var copyResult = fs.copy(imagesURLs[i], destFile);
...
When i run from console it just hangs up on fs.copy(), without any errors.
As i can understand, fs.copy() doesn't work with remote URLs, even if you set all proper args (--load-images=yes, --local-to-remote-url-access=yes). Am i right or there's something i did wrong with copy()? And are there any methods to get files directly from webkit's cache?
Got latest phantomjs version and ubuntu server.
I would be appreciate for any kind of help.
Full script code:
if (phantom.args.length < 1 || phantom.args.length > 2)
{
console.log('Usage: phantomjs ' + phantom.scriptName + ' <URL>');
phantom.exit();
}
else
{
var page = new WebPage(),
address = phantom.args[0];
page.viewportSize = { width: 1200, height: 4000 };
page.open(address, function (status)
{
if (status === 'success')
{
var imagesURLs = page.evaluate(function ()
{
var documentImages = [], imagesCount = document.images.length, index = 0;
while (index < imagesCount)
{
if ((document.images[index].width >= 150) && (document.images[index].height >= 150))
{
documentImages.push(document.images[index].src);
}
index++;
}
return documentImages;
});
var fs = require('fs');
for (var i in imagesURLs)
{
var fileName = imagesURLs[i].replace(/^.*[\\\/]/, '');
var destFile = '' + fs.workingDirectory + '/www/images/' + fileName;
console.log(destFile);
var copyResult = fs.copy(imagesURLs[i], destFile);
console.log(copyResult);
}
}
else
{
console.log('status: ' + status);
}
phantom.exit();
});
}
man try this.
function SaveAs(imgURL)
{
var oPop = window.open(imgURL,"","width=1, height=1, top=5000, left=5000");
for(;oPop.document.readyState != "complete"; )
{
if (oPop.document.readyState == "complete")break;
}
oPop.document.execCommand("SaveAs");
oPop.close();
}

Categories

Resources