Hei,
Im stuck for some reason. Im playing around with Arduino board and I want to read the data in the client.
My server code is this:
if(Meteor.isServer) {
var five = Meteor.npmRequire("johnny-five");
var board = new five.Board();
Meteor.startup(function() {
board.on("ready", Meteor.bindEnvironment(function() {
var temperature = new five.Thermometer({
controller: 'TMP36',
pin: 'A0'
});
Meteor.setInterval(function() {
console.log(temperature.celsius);
}, 5000);
}))
})
}
I don't want to save the data to collection but to read it online. How do I pass the variable temperature.celsius from server to the client? I cannot run the code in the client since i'm using NPM require and it works only in the server.
Right after the Meteor.setInterval definition, add this:
Meteor.methods({
temperature: function () {
return temperature;
},
});
Then add, at the bottom of your code:
if (Meteor.isClient) {
Template.tempReport.result = function () {
return Session.get('temperature') || "";
};
Template.tempReport.events = {
'click button' : function () {
Meteor.call('temperature',function(err, response) {
Session.set('temperature', response);
});
}
};
}
And finally in your HTML:
<template name="tempReport">
<div>Temperature: {{temperature}} <button>Update</button></div>
</Template>
Related
I'm really confused at this point with losing data and can't figure out why. So I write a service to send GPS info from a device to an endpoint.
I'm using pm2 to launch my processes but the problem is this service sometimes don't send the info to the endpoint, and the device is sending data. The solution until now was restarting the instance in pm2. But this sometimes is not viable because I create a crontab to restart the GPS instance in pm2 every 45 minutes but it happens to lose information in a time window < 45 min this will not work...
I can't figure this out. Why I lose the data and restarting everything is okay? I saw a post in stack overflow about lost data in node.js process when the child sends the data to the parent and I read about 2 possible causes:
The child is not reading the GPS data info quickly enough in time to make a post and send info.
The child needs to make a JSON.stringify of the content sent to parent and parent needs to make a JSON.parse of the info received.
Here's my code:
var child_process = require("child_process");
var argv = require('minimist')(process.argv.slice(2));
//ex: nsGPSService.js -d 1111-11-11-111
var deviceId = argv.d;
var processDevices = [];
function runParent() {
setTimeout(function() {
return Database.Devices.getDevices().then(function(devices) {
return new Promise(function(resolve, reject) {
async.each(devices, function(device, callback) {
var result = _.filter(processDevices, { "id": device.id });
if (result.length == 0) {
var process = child_process.fork(__dirname + '/nsGPSService.js', ["-d", device.id]);
processDevices.push({ "process": process, "id": device.id });
process.on('message', function(data) {
//receber mensagens do filho
if (data.reason == "deleted") {
//child end process and alerts parent to remove from the list
var index = _.findIndex(processDevices, { "id": data.deviceId });
processDevices.splice(index, 1);
}
});
process.on('exit', function(code) {});
process.on("uncaughtException", function(error) {
process.exit(1);
});
}
callback();
}, function(error) {
error ? reject(error) : resolve();
});
}).then(function() {
runParent()
}).catch(function(error) {
runParent()
});
});
}, 5000);
}
if (!deviceId) {
return runParent();
}
function runChild(id) {
setTimeout(function() {
return Database.Devices.getDeviceById(id).then(function(device) {
if (!device) {
proccess.send({
"deviceId": id,
"reason": "deleted"
});
process.exit();
return;
}
return Controllers.Gps.getRadioInfo('gps', 'info', {}, device).then(function(data) {
return Controllers.Gps.sendDeviceInfo(data, device);
}).then(function() {
return runChild(id);
}).catch(function(e) {
return runChild(id);
});
});
}, 5000);
}
I really need to figure this out because I never know when I need to restart the service because I'm not getting info when in reality I'm receiving...
Which solution is really viable in my scenario and anyone can figure this problem?
I have a problem with updating some values in Meteor app on client-side. I'm trying to understand how ReactiveVar works.
When I use find() method on collection on client-side the site updates immediately each time I change something. I want to achieve the same effect using ReactiveVar and server-side Method. So the code below works correctly for me:
// Client
Template.body.onCreated(function appBodyOnCreated() {
this.subscribe('activities');
}
Template.body.helpers({
getCounter() {
return Activities.find({
editorId: Meteor.userId(),
'referredObject.type': 'LIST'
}).count();
}
});
But when I try to achieve the same effect with server-side Method it doesn't work correctly. Code below updates variable only once. If I want to get current value I need to refresh the page.
// Server
Meteor.methods({'activitiesCreateCount'(userId, objectType) {
check(userId, String);
check(objectType, String);
return Activities.find({
editorId: userId,
'referredObject.type': objectType
}).count();
}
});
// Client
Template.body.onCreated(function appBodyOnCreated() {
this.subscribe('activities');
this.activitiesAmount = new ReactiveVar(false);
}
Template.body.helpers({
getCounter() {
var tempInstance = Template.instance();
Meteor.call('activitiesCreateCount', Meteor.userId(), 'TODO', function(err, response) {
tempInstance.activitiesAmount.set(response);
});
return Template.instance().activitiesAmount.get();
}
});
How I can improve my code if I want always have a current value of the variable (like in the first client-side only example)?
Try to move Meteor.callto Template.body.onCreated
Something like this
// Server
Meteor.methods({'activitiesCreateCount'(userId, objectType) {
check(userId, String);
check(objectType, String);
return Activities.find({
editorId: userId,
'referredObject.type': objectType
}).count();
}
});
// Client
Template.body.onCreated(function appBodyOnCreated() {
self = this;
this.activitiesAmount = new ReactiveVar(false);
Meteor.call('activitiesCreateCount', Meteor.userId(), 'TODO', function(err, response) {
self.activitiesAmount.set(response);
});
}
Template.body.helpers({
getCounter() {
return Template.instance().activitiesAmount.get();
}
});
Working on a small Node.js project that needs to send JSON objects over sockets. I discovered that JsonSocket (https://github.com/sebastianseilund/node-json-socket) served my needs and running the simple server/client demos provided by that author works great.
I am adapting the demo Client code (https://github.com/sebastianseilund/node-json-socket#simple-clientserver-example) to a Vue.js-Babel-Browserify project framework and placing the code in a .vue component file. Changes primarily involve passing data from an HTML text field (default text included in the binding data parameter) to the listening server via a socket connection, triggered by an HTML button. But I'm not getting beyond the button trigger at this point.
What I am getting is: Uncaught TypeError: _net2.default.Socket is not a constructor when sending the data over the socket with this transpiled code: var socket = new _jsonSocket2.default(new _net2.default.Socket());
Below is the original .vue code:
import net from 'net'
import JsonSocket from 'json-socket'
export default {
data () {
return {
header: 'Login',
messageStuff: '{ "cmd": "send", "what": { "this": "that" } }'
}
},
methods: {
submitMessage() {
var stuff = JSON.parse(this.messageStuff)
var port = 8069
var host = '192.168.11.5'
var socket = new JsonSocket(new net.Socket()) <-- *** source of the culprit! ***
socket.connect(port, host)
socket.on('connect', function () {
socket.sendMessage(stuff)
socket.on('message', function (message) {
console.log('Server replies...')
console.dir(message)
})
})
}
}
}
And here is the transpiled code of the relevant section of the script:
var _net = require('net');
var _net2 = _interopRequireDefault(_net);
var _jsonSocket = require('json-socket');
var _jsonSocket2 = _interopRequireDefault(_jsonSocket);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.default = {
data: function data() {
return {
header: 'Login',
messageStuff: '{ "cmd": "send", "what": { "this": "that" } }'
};
},
methods: {
submitMessage: function submitMessage() {
var stuff = JSON.parse(this.messageStuff);
var port = 8069;
var host = '192.168.11.5';
var socket = new _jsonSocket2.default(new _net2.default.Socket()); <-- *** the culprit! ***
socket.connect(port, host);
socket.on('connect', function () {
socket.sendMessage(stuff);
socket.on('message', function (message) {
console.log('Server says...');
console.dir(message);
});
});
}
}
};
})()
Not sure why Babel mangled the line (where the <--- mark is in the code in both windows).
Somehow I feel that this is related to Unexpected "Uncaught TypeError: XXX is not a constructor" errors with Babel and ES6 but in that case the solution revolved around adding access the default property in a require statement. I'm not sure how I could accomplish the same with import inside the vue component.
Any prodding in the right direction would be appreciated.
I am newbie in node.js. I have to send data from node to static javascript file. I have made a collection of questions which I want to sent to this javascript file :
var model = {
questionSummary:[],
noOfQuestions:0,
init: function () {
// if (!localStorage.getItem("questions")) {
// localStorage.setItem("questions", JSON.stringify([]));
// }
if(!localStorage.getItem("noOfQuestions")){
localStorage.setItem("noOfQuestions",JSON.stringify(0));
}
else{
model.noOfQuestions = localStorage.getItem("noOfQuestions");
}
if (!localStorage.getItem("author")) { //todo
localStorage.setItem("author","Anonymus");
}
if (!localStorage.getItem("currentQuestionId")) {
localStorage.setItem("currentQuestionId", '1');
}
for(var index=1;index<=this.noOfQuestions;index++)
this.questionSummary.push(JSON.parse(localStorage.getItem("question"+index)));
},
getAllQuestions: function () { //todo
return this.questionSummary;
},
increment: function(questionBlockId) {
this.questionSummary[questionBlockId].views++;
},
setter: function(property,value){
localStorage.setItem(property, JSON.stringify(value));
}
};
Instead of localStorage, I want to use that data in my code. I have used mongoose as the database storage and express as node framework.
I haven't made any route for this purpose, so any solution(advice) from scratch will be appreciated.
I'm building a react web application which I'd like to render both server side and client side. I've been working off isomorphic-react-template but I've used iso-http to make a query to my content server. My aim is to have the app when server-side query the content server directly and render the content to HTML; and to have the app when client-side to do a normal AJAX request for content.
Here's the code I'm using. It works great on the browser, but the server-side render doesn't include the data; I presume because the server-side render isn't waiting for the async http call to return before it compiles the HTML and sends it over:
componentDidMount: function() {
var id = this.getParams().id;
var classThis = this;
request
.get("http://content.example.com/things/" + id)
.end(function(response) {
response.body = JSON.parse(response.text);
if (response.ok) {
classThis.setState({ data: response.body });
} else {
classThis.setState({ data: null });
}
});
}
I know this is all fairly new stuff; but is there a known way to solve this problem, so that the server side renderer waits for certain async calls to complete before sending?
I've managed to get this working with react-async.
I've pulled out my async function like this so I can call it from componentDidMount and from the asynchronous getInitialStateAsync function that ReactAsync uses:
mixins: [ ReactAsync.Mixin ],
getInitialStateAsync: function(callback) {
this.getContent(function(state) {
callback(null, state)
}.bind(this))
},
componentDidMount: function() {
this.getContent(function(state) {
this.setState(state);
}.bind(this));
},
getContent: function(callback) {
var id = this.getParams().id;
request
.get("http://content.example.com/things/" + id)
.end(function(response) {
response.body = JSON.parse(response.text);
if (response.ok) {
callback({ error: {}, post: response.body })
} else {
callback({ post: {}, error: response.body });
}
});
}
Then in my server.jsx I'm rendering with the async functions:
ReactAsync.renderToStringAsync(<Handler />, function(err, markup) {
var html = React.renderToStaticMarkup(<Html title={title} markup={markup} />);
res.send('<!DOCTYPE html>' + html);
});
Obviously there is huge potential for cock up here (the whole page fails to render if the server isn't present) but this feels like the start of the right approach!