The aREST cloud server code

It's now time to actually deploy an application on the server that you just created. As the software for your cloud server, we are going to use the aREST cloud server that we have already used before.

It is completely free and open source, and you can get the latest version of the software from here:

https://github.com/marcoschwartz/meteor-aREST-mqtt

For now, simply copy all the files from this repository and put them inside any folder on your computer.

Note

This application actually uses the Meteor framework, which is a complete framework based on JavaScript and Node.js and can be used to create powerful web applications.

If it's not been done yet, install Meteor on your computer by going to:

https://www.meteor.com/install

Now, let's have a quick overview of the code of the aREST cloud server. The code is quite complicated, but I just wanted to highlight some parts here so you understand how it works.

Whenever a device connects to the server, the software first checks whether the server already knows the device. If that's the case, we set the device to connected, so it can be accessible from the cloud. If the device is unknown, it is added to the database on the server.

This is the piece of code that handles those functions:

Server.on('clientConnected', Meteor.bindEnvironment(function(client) {

  console.log('client connected', client.id);

  // Already exist?
  if (Devices.find({clientId: client.id}).fetch().length == 0) {

    // Insert in DB
    console.log('New device detected');
    device = {
      clientId: client.id,
      connected: true
    }
    Devices.insert(device);
  }
  else {
    console.log('Existing device detected');

    // Update device status
    Devices.update({clientId: client.id}, {$set: {"connected": true}});

  }

}) );

Whenever the user wants to access a device, the user types a command inside a web browser. The cloud server will then first match this command with the commands that are available, for example:

Router.route('/:device', {

The server then checks whether the device exists:

var currentDevice = Devices.findOne({clientId: device});

If the device exists and is connected at the moment, the server prepares a message to be sent to the device, for example:

var message = {
  topic: currentDevice.clientId + '_in',
  payload: '',
  qos: 0,
  retain: false
};

Then, once the answer comes back from the device, we send it back to the user in JSON format:

answer = sendMessage(message);
this.response.setHeader('Content-Type', 'application/json');
this.response.end(answer);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.245.1