<commit_before>/* Router for RPC interface */
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    RPCrouter = express.Router(),
    jayson = require('jayson'),
    http = require('http');

var exportDataToFile = function exportDataToFile (ref, data) {

    switch (ref) {

      case 'uplink' :

          var packetsdatabase = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/packets.json'), 'utf8'));;

          packetsdatabase.push(data);

          fs.writeFileSync(path.join(__dirname, './../config/packets.json'), JSON.stringify(packetsdatabase));

          break;

      case 'cmdack' :

          var commandqueue = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/command_queue.json'), 'utf8'));

          if ( data.dev_eui == commandqueue[data.dev_eui] || !commandqueue[data.dev_eui] ) {

              commandqueue[data.dev_eui] = data.cmd_ack;

              fs.writeFileSync(path.join(__dirname, './../config/packets.json'), JSON.stringify(commandqueue));

          }

      case 'erase' :

          fs.writeFileSync(path.join(__dirname, './../config/device.json'), JSON.stringify({}));

          break;
    }
};

var decode1m2mpayload = function (obj) {

    return new Promise ( function (resolve, reject) {

        console.log('1m2m payload to make human readable: ', obj);

        var hex_o =  Buffer.from(obj.toString(), 'base64').toString('hex');
        var url = 'http://1m2m.eu/services/GETPAYLOAD?Human=0&PL=' + hex_o;

        http.get(url, function (res) {

            const { statusCode } = res;
            const contentType = res.headers['content-type'];

            let error;

            if (statusCode !== 200) {

                error = new Error('Request Failed.\n' +
                                `  Status Code: ${statusCode}`);
            }

            if (error) {

                console.error(error.message);
                // consume response data to free up memory
                res.resume();
                return;
            }

            let rawData = '';

            res.on('data', function (chunk) { rawData += chunk; });

            res.on('end', function () {

              try {
                  const parsedData = JSON.parse(rawData);
                  console.log('Parsed response data', parsedData.toString());
                  resolve( parsedData );

              } catch (e) {
                  console.error(e.message);
              }
            });

        }).on('error', (e) => {
          console.error(`Got error: ${e.message}`);
        });
    });
};

var getQualityIndex = function (AnIn1, AnIn2) {

    var quality;

    if ( AnIn1 < 250 && AnIn2 < 250 ) {
        quality = 'clean';
    } else if ( AnIn1 < 250 && AnIn2 > 3000 ) {
        quality = 'light';
    } else if ( AnIn1 > 3000 && AnIn2 < 250 ) {
        quality = 'medium';
    } else if ( AnIn1 > 3000 && AnIn2 > 3000 ) {
        quality = 'high';
    }

    return quality;
};

var convertTime = function (s) {

    // var jstime = s * 1e3;

    return new Date(s * 1e3).toISOString().slice(-13, -5);

};

// TODO keep track of CmdAck value in the app for each device

var catchRpc = function catchRpc (req, res, next) {

    var io = req.app.get('socketio');

    console.log('req value from RPCRouter.post(*): ', req.body);

    // Make the time readable
    if ( req.body.params.rx_time || req.body.params.tx_time ) {

        var unixtime = req.body.params.rx_time ? req.body.params.rx_time : req.body.params.tx_time;

        req.body.params.human_time = convertTime(unixtime);
    }

    // Create a promise for decoding the 1m2m payload before sending it to the listen.pug view
    if (req.body.params.payload) {

        decode1m2mpayload(req.body.params.payload).then( function (obj) {

              req.body.params.human_payload = obj;

              // set the polluton scale for the winsen ZP01-MP503 module if the analog data is present
              if (req.body.params.human_payload.MsgID == 'Analog') {

                  req.body.params.pollution_level = getQualityIndex(parseInt(req.body.params.human_payload.AnIn1, 10), parseInt(req.body.params.human_payload.AnIn2, 10));
              }

              // check if it's a TAlive message so we an extract the CmdAck param
              if (req.body.params.human_payload.MsgID == 'Alive') {

                  exportDataToFile('cmdack', { "dev_eui" : req.body.params.dev_eui,
                                               "cmd_ack" : red.body.params.human_payload.CmdAck });

              }

              console.log('Added decoded payload to req.body: ', req.body);

              io.emit("rpcrequest", req.body);

              next();
        }) ;

    } else {

        io.emit("rpcrequest", req.body);

        next();
    }
};

// RPC methods for Everynet network
var methods = {

    uplink: jayson.Method(function (args, done) {

     /* Parameters in the request
      * uplink method only needs to return 'ok'
      * args.dev_eui
      * args.dev_addr
      * args.rx_time
      * args.counter_up<commit_msg>modified CmdAck tracking<commit_after>/* Router for RPC interface */
var express = require('express'),
    path = require('path'),
    fs = require('fs'),
    RPCrouter = express.Router(),
    jayson = require('jayson'),
    http = require('http');

var exportDataToFile = function exportDataToFile (ref, data) {

    switch (ref) {

      case 'uplink' :

          var packetsdatabase = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/packets.json'), 'utf8'));;

          packetsdatabase.push(data);

          fs.writeFileSync(path.join(__dirname, './../config/packets.json'), JSON.stringify(packetsdatabase));

          break;

      case 'cmdack' :

          var commandqueue = JSON.parse(fs.readFileSync(path.join(__dirname, './../config/command_queue.json'), 'utf8'));

          commandqueue[data.dev_eui] = data.cmd_ack;

          fs.writeFileSync(path.join(__dirname, './../config/packets.json'), JSON.stringify(commandqueue));

          break;

      case 'erase' :

          fs.writeFileSync(path.join(__dirname, './../config/device.json'), JSON.stringify({}));

          break;
    }
};

var decode1m2mpayload = function (obj) {

    return new Promise ( function (resolve, reject) {

        console.log('1m2m payload to make human readable: ', obj);

        var hex_o =  Buffer.from(obj.toString(), 'base64').toString('hex');
        var url = 'http://1m2m.eu/services/GETPAYLOAD?Human=0&PL=' + hex_o;

        http.get(url, function (res) {

            const { statusCode } = res;
            const contentType = res.headers['content-type'];

            let error;

            if (statusCode !== 200) {

                error = new Error('Request Failed.\n' +
                                `  Status Code: ${statusCode}`);
            }

            if (error) {

                console.error(error.message);
                // consume response data to free up memory
                res.resume();
                return;
            }

            let rawData = '';

            res.on('data', function (chunk) { rawData += chunk; });

            res.on('end', function () {

              try {
                  const parsedData = JSON.parse(rawData);
                  console.log('Parsed response data', parsedData.toString());
                  resolve( parsedData );

              } catch (e) {
                  console.error(e.message);
              }
            });

        }).on('error', (e) => {
          console.error(`Got error: ${e.message}`);
        });
    });
};

var getQualityIndex = function (AnIn1, AnIn2) {

    var quality;

    if ( AnIn1 < 250 && AnIn2 < 250 ) {
        quality = 'clean';
    } else if ( AnIn1 < 250 && AnIn2 > 3000 ) {
        quality = 'light';
    } else if ( AnIn1 > 3000 && AnIn2 < 250 ) {
        quality = 'medium';
    } else if ( AnIn1 > 3000 && AnIn2 > 3000 ) {
        quality = 'high';
    }

    return quality;
};

var convertTime = function (s) {

    // var jstime = s * 1e3;

    return new Date(s * 1e3).toISOString().slice(-13, -5);

};

// TODO keep track of CmdAck value in the app for each device

var catchRpc = function catchRpc (req, res, next) {

    var io = req.app.get('socketio');

    console.log('req value from RPCRouter.post(*): ', req.body);

    // Make the time readable
    if ( req.body.params.rx_time || req.body.params.tx_time ) {

        var unixtime = req.body.params.rx_time ? req.body.params.rx_time : req.body.params.tx_time;

        req.body.params.human_time = convertTime(unixtime);
    }

    // Create a promise for decoding the 1m2m payload before sending it to the listen.pug view
    if (req.body.params.payload) {

        decode1m2mpayload(req.body.params.payload).then( function (obj) {

              req.body.params.human_payload = obj;

              // set the polluton scale for the winsen ZP01-MP503 module if the analog data is present
              if (req.body.params.human_payload.MsgID == 'Analog') {

                  req.body.params.pollution_level = getQualityIndex(parseInt(req.body.params.human_payload.AnIn1, 10), parseInt(req.body.params.human_payload.AnIn2, 10));
              }

              // check if it's a TAlive message so we an extract the CmdAck param
              if (req.body.params.human_payload.MsgID == 'Alive') {

                  exportDataToFile('cmdack', { "dev_eui" : req.body.params.dev_eui,
                                               "cmd_ack" : red.body.params.human_payload.CmdAck });
              }

              console.log('Added decoded payload to req.body: ', req.body);

              io.emit("rpcrequest", req.body);

              next();
        }) ;

    } else {

        io.emit("rpcrequest", req.body);

        next();
    }
};

// RPC methods for Everynet network
var methods = {

    uplink: jayson.Method(function (args, done) {

     /* Parameters in the request
      * uplink method only needs to return 'ok'
      * args.dev_eui
      * args.dev_addr
      * args.rx_time
      * args.counter_up
{'fraction_non_alphanumeric': 0.1374987661632613, 'fraction_numerical': 0.01460862698647715, 'mean_word_length': 1.922411306605134, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2074161', 'n_tokens_mistral': 3226, 'n_tokens_neox': 2983, 'n_words': 686}