Call mDash device from Node.js

This tutorial has an example code on how to call device function in Node.js

  1. Save snippet below into a file, e.g. mdashcall.js
  2. Edit ACCESS_TOKEN, save the file
  3. Optionally, edit DEVICE_ID/PARAMETERS if you want to call other functions
  4. In the command prompt/terminal, run node mdashcall.js
var ACCESS_TOKEN = 'xxx';  // To get token, see Account page
var DEVICE_ID = 'd1';
var METHOD = 'Sys.GetInfo';
var PARAMETERS = {pin: 2, val: 0};

// mdashRequest definition
var https = require('https');
var mdashRequest = function(apiToken, deviceID, method, params, func) {
  return new Promise(function(resolve, reject) {
    var received = '';
    var strParams = JSON.stringify(params || {});
    var url = 'https://mdash.net/api/v2/devices/' + deviceID + '/rpc/' +
        method + '?access_token=' + apiToken;
    var options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Content-Length': strParams.length
      }
    };
    var req = https.request(url, options, function(res) {
      res.on('data', data => received += data);
      res.on('end', () => resolve(received));
    });
    req.on('error', err => reject(err));
    req.write(strParams);
    req.end();
    });
};

// example call
mdashRequest(ACCESS_TOKEN, DEVICE_ID, METHOD, PARAMETERS)
    .then(response => console.log('RESPONSE:', response))
    .catch(err => console.error('ERROR:', err));