Beaglebone Black revC - javascript

I am connecting BBB and a set of arduinos over the serial port (ttyO2).
I have an array to be sent from BBB to a set of arduinos.
I need to make the BBB sends a request and wait for a reply from one of the arduinos, but if no arduino replies within an interval, the BBB must send the following value in the array.
I have the connection and arduinos ready for their jobs.
The problem is that the BBB will listen on the port and complete the execution of the code at the same time. I need to make it listen for a specific time, if data received=> process it; else complete the following part of code (send the remaining part of the array). This job need to be in a loop.
I have been trying to use setTimeout, recursion, but with no success!
I am using the following code to listen and write on ttyO2:
` var b = require('bonescript');
//opening the serial port
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200
});
var i = 0;
serialPort.on("open", function () {
console.log('opened');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
serialPort.write( i + "\n", function(){});
});
});
serialPort.on("data", function (data) {
console.log("here: "+data);
});
`

var b = require('bonescript');
//opening the serial port
var SerialPort = require("serialport").SerialPort;
var serialPort = new SerialPort('/dev/ttyO2', {
baudrate: 115200
});
var i = 0;
var waiting_interval = 5000;
var slaves = ["S1", "S2" , "S3", "S4", "S5"];
serialPort.on('open',function my(){
console.log("opened");
serialPort.on('data', function listenToSlaves(data){
console.log("returned: " + data);
});
writeToSlaves();
});
function writeToSlaves(){
// setInterval(serialPort.write(slaves[i], function(){ console.log("I
wrote to slave: " + i)}), 5000);
serialPort.write(slaves[i], function(){ });
console.log("I wrote to slave: " + i);
if(i<slaves.length - 1) i++;
else i=0;
setTimeout(writeToSlaves, waiting_interval);
}

Related

TypeError: serialport.parsers.readline is not a function

I am trying to run this program in Raspberry Pi 3.
I have installed nodejs and ws on my raspberry pi.
Then I installed serial port module.
I am trying to create this project:enter link description here
I have tried to find solutions everywhere but I could not find one.
If any one knows how to solve this problem please help me.
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "5bb3ba9304674086bee67fa507a215cf"; //DEVICE ID
var device_token = "36b278345b6d4d11abf764ae213c5c70"; //DEVICE TOKEN
var WebSocket = require('ws');
var isWebSocketReady = false;
var data="";
var ws = null;
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var sp = new SerialPort("/dev/ttyACM0", { //for serial communication with arduino
baudrate: 9600,
// The baud rate of uno is 9600
parser: serialport.parsers.readline("\n")
});
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket connection and setup GPIO pin
*/
function start() {
//Create the WebSocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("WebSocket connection is open ....");
register();
});
ws.on('message', function(data) {
//this loop is called whenever the client sends some message
handleRcvMsg(data); //data is send to the function handleRcvMsg()
});
ws.on('close', function() {
console.log("WebSocket connection is closed ....");
});
}
/**
* Sends a register message to /websocket endpoint
*/
//Client will only work when device gets registered from here
function register(){
console.log("Registering device on the WebSocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
//data after receiving is sent here for processing
function handleRcvMsg(msg){
var msgObj = JSON.parse(msg);
if (msgObj.type != "action") return; //Early return;
var actions = msgObj.data.actions;
var actionName = actions[0].name; //assume that there is only one action in actions
console.log("The received action is " + actionName);
}
/**
* Send one message to ARTIK Cloud
*/
//This function is responsible for sending commands to cloud
//function sendStateToArtikCloud(parking,temperature,water){
function sendDataToArtikCloud(pantry){
var result=pantry.split(" ");//data gets split by " " to get the values
try{
ts = ', "ts": '+getTimeMillis();
var data = {
"Garlic": result[1],
"Potato":result[2],
"Temperature":result[3],
"Chilli":result[4],
"Humidity": result[5],
"Ginger":result[6],
"Onion": result[7]
};
var payload = '{"sdid":"'+device_id+'"'+ts+', "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload + '\n');
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString() +'\n');
}
}
function exitClosePins() {
console.log('Exit and destroy all pins!');
process.exit();
}
start();
//exectes every second when data is received from arduino (5sec programmed delay from arduino)
sp.on("open", function () {
sp.on('data', function(data) {
console.log("Serial port received data:" + data);
//var result=data.split(" ");//data gets split by " " to get the values
//sendStateToArtikCloud(result[0],result[2],result[1]);//parking,temperature,waterlevel
sendDataToArtikCloud(data);
});
});
process.on('SIGINT', exitClosePins);
I am getting an error on my raspberry pi
enter image description here
Suggest me a solution.
The documentation will tell you that Readline is spelled with a capital R
https://www.npmjs.com/package/serialport#module_serialport--SerialPort.parsers
parser: serialport.parsers.Readline("\n")
~
[TypeError: serialport.parsers.readline is not a function.]
If it has not been resolved yet, try this method.
var serialport = require("serialport")
var SerialPort = serialport.SerialPort;
var sp = new serialport("/dev/ttyACM0"),{
BaudRate: 9600,
parser: new serialport.parsers.Readline("\r\n")
});
I hope your problem is solved.

Callback a function after a process

I use the bittorent-tracker package for get numbers of seeders and leechers for a given torrent but there is no way to know if the torrent scraping procedure is terminated client.on('scrape_terminated') for exemple ... Is there a way to detects the scraping is terminated ?
var Tracker = require('bittorrent-tracker')
var magnet = require('magnet-uri')
var magnetURI = "magnet:?xt=urn:btih:7a0e02e22744ddb807480f580cc328925d5810d4&dn=Terminator+2%3A+Judgment+Day+DC+%281991%29+1080p+BrRip+x264+-+YIFY&tr=udp%3A%2F%2Ftracker.leechers-paradise.org%3A6969&tr=udp%3A%2F%2Fzer0day.ch%3A1337&tr=udp%3A%2F%2Fopen.demonii.com%3A1337&tr=udp%3A%2F%2Ftracker.coppersurfer.tk%3A6969&tr=udp%3A%2F%2Fexodus.desync.com%3A6969"
var parsedTorrent = magnet(magnetURI)
var opts = {
infoHash: parsedTorrent.infoHash,
announce: parsedTorrent.announce,
peerId: new Buffer('01234567890123456789'), // hex string or Buffer
port: 6881 // torrent client port
}
var client = new Tracker(opts)
client.scrape();
client.on('scrape', function (data) {
console.log('number of seeders in the swarm: ' + data.complete)
console.log('number of leechers in the swarm: ' + data.incomplete)
});
client.on('error',function(data) {
console.log('erreur');
})

Bug in sending multiple 2-D Arrays through socket.io

I am noticing a bug in socket.io. I am sending multiple (5) 2-D Array's through socket.io. All of the Array's are coming through, at different lengths/sizes and at different times, if that matters with how node.js or socket.io handle them. But they are seperate so I didn't think it mattered, just mentioning.
I have the incoming data from another source that populates Array1, Array2....ect. Here are some examples of what's happening, when sending through socket.io.
When I send test1: test1 does populate on the client side.
When I send test2: test2 does not populate on the client side.
when I send test2, then test1: test1 and test2 populate on the client side.
var Array1 = [];
var Array2 = [];
var Array3 = [];
var Array4 = [];
var Array5 = [];
jsonResults = JSON.stringify({
'test1': Array1,
'test2': Array2,
'test3': Array3,
'test4': Array4,
'test5': Array5
});
Just for an example of how I am calling variables on the client side
var socket = io.connect();
socket.on('message', function(message){
var obj = jQuery.parseJSON(message);
var value1 = obj.test1[1][1];
var value2 = obj.test2[0][5];
I have another question, If on the client side I call out a variable that doesn't exist like obj.test1[5][5] when test1 is only [4,5] sometimes it doesn't populate on the client side, for all the variables like test1[1][1] which does exist; Is there a particular reason for this or am I approaching this wrong?
Is there a better way to program this from .js side I have to handle multiple 2-D arrays of unknown size coming in at different times.
Server Side Listening to outside traffic.
// start UDP server listening on port 3001
udpRunningResultsServer.on("listening", function () {
var address = udpRunningResultsServer.address();
console.log("UDP Running Results Server listening on port: " + address.port);
console.log(" ")
});
udpRunningResultsServer.bind(3001);
// process datagram
udpRunningResultsServer.on("message", function (Runningmsg, Runninginfo) {
// check if datagram is full (size=536)
if(Runninginfo.size == 536){
tempRunningResults = tempRunningResults + Runningmsg.toString();
}
// datagram is not full, so this is the end of the message
else{
finalRunningResults = tempRunningResults + Runningmsg.toString();
RunningArray = finalRunningResults.split(';');
for (var a = 0; a < RunningArray.length; a++) {
var Runningtmp = RunningArray[a].length;
if (Runningtmp == 14 || Runningtmp == 0){
RunningArray.splice(a,1);
}
else {
RunningArray[a]= RunningArray[a].split(',');
}
}
RunningArray.unshift(time);
tempRunningResults ='';
}
});
// start UDP server listening on port 3002
udpShotPutWeightThrowResultsServer.on("listening", function () {
var address = udpShotPutWeightThrowResultsServer.address();
console.log("UDP Shotput/Weight Throw Server listening on port: " + address.port);
console.log(" ")
});
udpShotPutWeightThrowResultsServer.bind(3002);
// process datagram
udpShotPutWeightThrowResultsServer.on("message", function (ShotputWeightThrowmsg, ShotputWeightThrowinfo) {
tempShotputWeightThrowResults = ShotputWeightThrowmsg.toString();
finalShotputWeightThrowResults = finalShotputWeightThrowResults+tempShotputWeightThrowResults;
finalShotputWeightThrowResults = finalShotputWeightThrowResults.trim()
console.log(finalShotputWeightThrowResults);
//if (tempShotputWeightThrowResults == '~'){
console.log(finalShotputWeightThrowResults);
ShotputWeightThrowArray = finalShotputWeightThrowResults.split(';');
for (var a = 0; a < ShotputWeightThrowArray.length; a++) { =
ShotputWeightThrowArray[a]= ShotputWeightThrowArray[a].split(',');
}
var serv_io = io.listen(htmlServer, { log: false });
serv_io.sockets.on('connection', function(socket){
//send data to client
setInterval(function(){
jsonResults = JSON.stringify({
'runningobj': ShotputWeightThrowArray,
'shotputweightthrowobj': RunningArray,
'longtriplejumpobj': LongTripleJumpArray,
'highjumpobj': HighJumpArray,
'polevaultobj': PoleVaultArray
});
console.log(jsonResults);
socket.send(jsonResults);
}, 1000);
});
Here is an example of what is coming through the socket.
{"runningobj":["0.0",["UNOFFICIAL","Decat Men 110 Meter Hurdles","nwi","41","6","4","041-6-04","AUTO","4"],["","2","504","Klaus Ambrosch","Arizona","","","","","","","","","",""],["","4","693","Troy McDonough","Montana","","","","","","","","","",""],["","6","818","Pat Buckheit","Tennessee","","","","","","","","","",""],["","8","746","James Cook","Penn State","","","","","","","","","",""],",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",",,,,,,,,,,,,,,",["\u0003\u0004"]],"shotputweightthrowobj":[["\u0001R\u0002Unofficial","HammerThrowWomen","","19","1","1","019-1-01",""],["1","1","79","Crozier","Unattached","33.55","","110'01\""],["~"],["","","","","","","",""],["~"],["","","","","","","",""],["~"],["","","","","","","",""],["~"]],"longtriplejumpobj":[],"highjumpobj":[],"polevaultobj":[]}

Sending data from client to server in Node.js

I'm trying to write a simple client-server program in Node.js where the client will enter 2 arguments (for example, user will type S 4 to get the value of the square root of 4) for a mathematical computation, send it to the server, and the server will return the answer. It works for the most part; however, when the server returns the answer, the client displays the answer and also displays the original input. Can anyone point out why this is happening?
server.js
var net = require('net');
var server= net.createServer(function(c) {
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.on('data', function(data) {
data = data.toString().split(" ");
var num = parseInt(data[1], 10);
switch (data[0]){
case 'S':
c.write(Math.sqrt(num).toString());
}
});
c.write('What would you like to do?\n');
c.write('(S) - Square root <arg>\n');
c.pipe(c);
});
server.listen(3000, function() {
console.log('server bound');
});
client.js
var net = require('net');
var num = 1;
var client = net.connect({port:3000}, function() {
console.log('client connected');
});
client.on('data', function(data) {
if (num == 1) {
console.log(data.toString());
process.stdin.resume();
process.stdin.once('data', function(input) {
client.write(input);
});
num++;
} else {
console.log("Server returned: " + data.toString() + "\n");
process.exit();
}
});
client.on('end', function() {
console.log('\nclient disconnected\n');
});
To clarify: when I input S 4 in the client, the result printed to the screen is Server returned: 2S 4
You are piping the input to the output

Using Node.js to retrieve data from Redis through an AJAX request

I'm going through a Node, Express, & Socket.io chat tutorial. I decided to use Redis to store the chat history and have successfully set it up so that my information is correctly posting to the database. I am now trying to access that information to use on the client-side (in this case I'm trying to access the list of users currently in the chat so I can show them to the side of the chat). I am using $.getJSON to make a GET request. Right now I have it setup so that the file it tries to access only has this JSON object : {"dog" : "2","cat":"3"} just to test it, and that is working, but I'm not sure where to go from there because anytime I try adding a function into that file, even if I specify to return a JSON object and call that function, the request stops returning the correct information.
For example I tried :
var data = function(){
return {"dog" : "2","cat":"3"}
}
data();
and that doesn't return anything ( I understand that when I make a GET request the function isn't run, but it doesn't even return that text, and if it doesn't run a function than I'm not sure how I can access redis from this file)
Here's what I'm thinking:
var redis = require('redis')
//figure out how to access the redis client that I have at localhost:6379, something like var db = redis.X
//and then call (for example) db.smembers('onlineUsers') and be returned the object which I can iterate through
Here's my relevant code:
server.js:
var jade = require('jade');
var PORT = 8080;
var redis = require('redis');
var db = redis.createClient();
var pub = redis.createClient();
var sub = redis.createClient();
var http = require('http');
var express = require('express');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(PORT, function(){
console.log("Now connected on localhost:" + PORT)
});
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.render('home');
});
io.sockets.on('connection', function(client){
sub.subscribe("chatting");
sub.on("message", function (channel, message) {
console.log("message received on server from publish");
client.send(message);
});
client.on("sendMessage", function(msg) {
pub.publish("chatting",msg);
});
client.on("setUsername", function(user){
pub.publish("chatting","A new user in connected:" + user);
db.sadd("onlineUsers",user);
}
);
client.on('disconnect', function () {
sub.quit();
pub.publish("chatting","User is disconnected :" + client.id);
});
});
script.js:
$(document).ready( function(){
$client = io.connect();
initialize();
});
var setUsername = function(){
var username = $("#usernameInput").val();
if (username)
{
var user = username;
$client.emit('setUsername', username);
$('#chatControls').show();
$('#usernameInput').hide();
$('#usernameSet').hide();
showCurrentUsers();
}
}
var showCurrentUsers = function(){
$('#list_of_users').empty();
$.getJSON('getusers.js', function(data){
for (var i = 0; i < data.length; i++){
$('list_of_users').append("<li>"+data[i]+"</li>")
}
})
}
var sendMessage = function(){
var msg = $('#messageInput').val();
var username = $("#usernameInput").val();
if (msg)
{
var data = {msg: msg, user: username}
$client.emit('message', data);
addMessage(data);
$('#messageInput').val('');
// populate(username,msg);
}
}
var addMessage = function(data) {
$("#chatEntries").append('<div class="message"><p>' + data.user + ' : ' + data.msg + '</p></div>');
}
// var populate = function(username,msg) {
// var data ;
// }
var initialize = function(){
$("#chatControls").hide();
$("#usernameSet").on('click', setUsername);
$("#submit").on('click',sendMessage);
showCurrentUsers();
}
and right now all that the getusers.js file has in it is:
{"dog" : "2","cat":"3"}
It looks like you're expecting your call to $.getJSON to load and execute the javascript it loads. It doesn't work this way. You need to make a node endpoint (via a route) which renders the JSON. The node endpoint would then do the data manipulation / querying redis:
Node:
In routes.js:
app.get('/chatdata', ChatController.getChatData);
In ChatController.js (manipulate, create the data as you like here)
exports.getChatData = function (req, res) {
var data = function(){
return {"dog" : "2","cat":"3"}
};
res.JSON(data);
};
Front-end
$.getJSON('getChatData', function(data){
//...
})
I think you need to setup a route to handle the GET request that $.getJSON makes, or if getusers.js is in the /public directory, then you need to modify your $.getJSON call as follows:
$.getJSON('http://localhost:8080/public/getusers.js', function(data){
Ok, it looks like it is a problem with your getusers.js file. $.getJSON seems to prefer double quotes. Try formatting it like this:
{
"dog" : "2",
"cat" : "3"
}
Also, try using this to display the data:
$.getJSON('getusers.js', function(data){
var items = [];
$.each( data, function( key, val ) {
items.push("<li id='" + key + "'>" + val +"</li>");
});
$('#list_of_users').append(items.join(""));
});

Categories

Resources