How to get variable value from server to client?


#1

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.


#2

Why don’t you want to use a collection?

If I were to try and tackle this one, I would subscribe the client to a collection and update that collection on the server.
Meteor reactivity and DDP will take care of the client getting updates (as long as the subscription is good to go), and you just need to make sure that the server keeps updating the collection.


#3

Create a server Meteor method which you could call from the client.


#4

So, I would do something like @cstrat suggests, like this (I don’t know the library you’re using - I assume temperature is updated automatically once initialised?):

In a client/ folder

TestData = new Mongo.Collection(null); // Put this on the client only
// It will reactively update with a doc like {_id:'abc123', temp:23.5}
Meteor.subscribe('test-docs'); // An arbitrary subscription name

Then, on the server, you generate and publish data within a roll-your-own publication. Maybe something along the lines of:

In a server/ folder

Meteor.publish('test-docs', function() {
  let init = true;
  Meteor.setInterval(() => {
    if (init) {
    let temperature;
    board.on('ready', Meteor.bindEnvironment(function() {
      temperature = new five.Thermometer({
        controller: 'TMP36',
        pin: 'A0'
      });
      // Use a unique doc id like 'abc123', so you know what to look for on the client
      this.added('test-data', 'abc123', {temp: temperature.celsius});
    } else {
      this.changed('test-data', 'abc123', {temp: temperature.celsius});
    }
    this.ready();
    init = false;
  }, 5000);
});

For more information, check the docs.


Need to push javascript objects ( not from collections ) asynchronously for a specific user from server to client on meteor
Method calls are from client to server. What is there for the reverse direction (server -> client)?
How to publish/subscribe custom list?
Receiving/Showing realtime data via rpc
#5

This sounds good. I didn’t want to save the data to collection because its updated anyway and I just want to display it in real time. I will give this approach a try.