Source: modules/services/outbound/wallboard/service.js

/**
 * Service Wallboard.
 *
 * Service provides a websocket for wallboards.
 *
 * @link   URL
 * @file   This files defines the wallboard service provider.
 * @author Jens Dinstühler.
 * @since  1.0.0
 */
 


 // required for websocket funcionality
var ws = require('ws')

// Logging
var log4js = require('log4js');
log4js.configure({
    appenders: { mylogger: { type:"dateFile", filename: "logs/modules/outbound/wallboard/wallboard.log" }, console: { type:"console" } },
    categories: { default: { appenders:["mylogger", "console"], level:"ALL" } }
});
const logger = log4js.getLogger("default");

const mysql = require('mysql');
// Read global config
var config = require('../../../../config/config.js');

// Wallboard Helper
const wallboardObj = require('../../../../models/wallboardhelper');
const wallboardHelper = new wallboardObj();

// Create db connection
const db = mysql.createConnection (config.databaseOptions);
// Connect to database
db.connect((err) => {
    if (err) {
        throw err;
    }
    logger.info(`${svcName} | Connected to database `, config.databaseOptions.database);
});
global.db = db;



// Get arguments main application sent during startup
var args = process.argv.slice(2); // Get arguments main application sent during startup
const orgId = args[1]; // Set organizationID this service instance is active for
const ibSvcId = args[2]; // Set ibSvcId this service instance has in database (needed for reading the instance configuration from database)



const svcName = 'WALLBOARD-' + args[0];

// Send startup-message to console
logger.info(`${svcName} | organization ${orgId} | service instance id ${ibSvcId} | starting up .. `); // Send startup-message to console/log

//
//
//  Service specific implementation
//
//
/**
 * Function reads the configuration key/value pairs from database
 * 
 * @param ibSvcId - id of the service in db table services_inbound_store
 */
function readModuleConfiguration(ibSvcId, callback) {
    var funcResult = true;
    let query = "SELECT keyword, value FROM services_outbound_config WHERE keyword LIKE 'outbound.wallboard%' AND svcInstanceId = " + ibSvcId;
    db.query(query, (err, result) => {
      if (err) {
        logger.error(`${svcName} | cannot read module configuration from database`);
        funcResult = false;
      } else {
        if (result.length > 0) {
          result.forEach(element => {
            if (element.keyword === 'outbound.wallboard.port') port = element.value;
          });
        } else {
          funcResult = false;
        }
      }
      callback(funcResult);
    });
  }



readModuleConfiguration(ibSvcId, (result) => {
    if (result === true) {
        logger.info(`${svcName} | starting Wallboard at port ${port}`);
        var WebSocketServer = require('ws').Server;
        var wss = new WebSocketServer({port: port});

        wss.on('connection', function (ws) {
            // get ip address of client
            var clientIpAddress = ws._socket.remoteAddress;
            ws.on('message', function (message) {
                logger.info(`${svcName} | received from wallboard with ip address ${clientIpAddress}: %s`, message)
            });

            var wallboardIntervalID = setInterval(() => {
                //logger.info('Start Interval');
                wallboardHelper.getOperationsList((operationslist) => {
                    if(operationslist.length > 0) {
                            try { 
                                ws.send(`${JSON.stringify(operationslist)}`);
                            } catch (e) {
                                logger.info(`${svcName} | Could not send heartbeat to wallboard client with ip address ${clientIpAddress} %s`, e);
                                clearInterval(wallboardIntervalID);
                            }
                    } else {
                            try {
                                ws.send('{}');
                            } catch (e) {
                                logger.info(`${svcName} | Could not send heartbeat to wallboard client with ip address ${clientIpAddress} %s`, e);
                                clearInterval(wallboardIntervalID);
                            }
                    }
                    });
            }, 5000);
        });
    } else {
        // Database had no configuration for this service
        logger.error(svcName + ' | could not initialize Service, Service - configuration values in database not found!');
    }
});






//
//
// GENERIC Keep-alive Service Functionality (--don't change--)
//
//
process.on('message', (m) => {
  if (m == 'stop') {
      logger.info(`${svcName} | ${args} | ${m} | Service termination command recieved from host`);
      process.exit();
  } else if(m == 'healthcheck') {
      process.send('{"state":"1", "pid":"' + process.pid + '"}');
  }
});