Source: plugins/outbound/wallboard/base.js

const EventEmitter = require('events');


/**
 * Class for Wallboard
 * @class plugins/outbound/wallboard
 * @namespace plugins/outbound/wallboard
 * @memberof plugins/outbound/wallboard
  */
class wallboard extends EventEmitter {

    /**
     * Constructor
     * 
     * Sets up everything, starts websocket
     */
    constructor() {
        super();
        global.plgManager.logger.info('-------- PLUGIN Wallboard -----------');
        this.serviceProcess = null;
        this.registerForEvents();
        this.serviceProcId = null;
        this.loadConfig((success) => {
            if (success) {
                // set plugin as configured
                this.initializePlugin((initsuccess) => {
                    global.plgManager.logger.debug('PLUGIN | WALLBOARD | initialized Plugin: ' + initsuccess);
                    if (initsuccess) {
                        this.isConfigured = true;
                        this.prepareService();
                        this.wireServiceCommunication();
                        this.configService();
                        this.startService();
                    }
                })
            }
        })

    }

    /**
     * Registration of Events at the plugin manager (hook in to events provided by the plugin manager)
     */
    registerForEvents() {
        global.plgManager.logger.info('PLUGIN | WALLBOARD | Registering events');
        global.plgManager.on('event_pluginConfig_refreshed', (namespace) => {
            if (namespace === 'wallboard') {
                // plugins config has changed --> refresh
                this.loadConfig((success) => {
                    if (success) {
                        global.plgManager.logger.info('PLUGIN | WALLBOARD | successfully reloaded plugin configuration');
                        this.restartService();
                    } else {
                        global.plgManager.logger.error('PLUGIN | WALLBOARD | could not reload plugin config!');
                    }
                });
            }
        })
    }

    

    /**
     * Loads configuration for Wallboard Service
     * @memberof plugins/outbound/wallboard
     */
    loadConfig(callback) {
        global.plgManager.loadConfigFromStore('wallboard', (configRows) => {
            if (configRows !== null) {
                this.config = configRows[0];
                this.config = JSON.parse(this.config.configstore);
                callback(true);
            } else {
                callback(false);
            }
            global.plgManager.logger.info('PLUGIN | WALLBOARD | Configuration loaded from core database');
        })
    }

    /**
     * returns config parameter for given fieldname
     * @param {string} fieldname 
     * @memberof plugins/outbound/wallboard
     */
    getConfigValue(fieldname) {
        var retVal = null;
        this.config.fields.forEach((field) => {
            if (field.fieldname === fieldname) {
                retVal = field.value;
            }
        });
        return retVal;
    }

    /**
     * reconfigures plugin with new config settings
     * @param {function} callback success, true or false
     * @memberof plugins/outbound/wallboard
     */
    initializePlugin(callback) {
        // LAU

        console.log(this.getConfigValue('subtoken'));
        this.katSysConfig = {
            masterToken: this.getConfigValue('mastertoken'),
            subToken: this.getConfigValue('subtoken'),
            pemFile: __dirname + '/uploads/' + this.getConfigValue('pemfile'),
            loglevel: 'debug'
        }

        if ((typeof this.katSysConfig.masterToken !== 'undefined') && (typeof this.katSysConfig.subToken !== 'undefined') && (typeof this.katSysConfig.pemFile !== 'undefined')) {
            global.plgManager.logger.info('PLUGIN | WALLBOARD | Properly inititlized settings');
            callback(true);
        } else {
            global.plgManager.logger.error('PLUGIN | WALLBOARD | could not initialize settings');
            callback(false);
        }
    }

    /**
     * Wires messages from service to event model of plugin
     * All Messages in service need to be wired here to be recognised in plugin
     * @memberof plugins/outbound/wallboard
     */
    wireServiceCommunication() {
        this.serviceProcess.on('message', function (msg) {
            console.log('-----------> MESSAGE FROM WALLBOARD SERVICE: ' + msg);
            var payload = null;
            try {
                payload = JSON.parse(msg);
            } catch (err) {
                payload = err.message;
            }
            
            /**
             * check what payload comes in
             */
            if (typeof payload.error != 'undefined') {
                // child has sent an error
                // try restarting the whole service
                global.plgManager.event_new_admin_notification('WALLBOARD Service meldet einen Fehler');
                this.restartService();
            } else if (typeof payload.logmessage != 'undefined') {
                // LOGMESSAGE COMING FROM SERVICE
                console.log('PLUGIN | WALLBOARD | SERVICE | ' + payload.logmessage);
                global.plgManager.logger.info('PLUGIN | WALLBOARD | SERVICE | ' + payload.logmessage);
            } else if (typeof payload.newConnection != 'undefined') {
                // NEW CLIENT CONNECTED TO WEBSOCKET
                console.log('PLUGIN | WALLBOARD | SERVICE | NEW CLIENT CONNECTION');
                global.plgManager.logger.info('PLUGIN | WALLBOARD | SERVICE | NEW CLIENT CONNECTION');
            } else if (typeof payload.lostConnection != 'undefined') {
                // LOST A CLIENT CONNECTED TO WEBSOCKET
                console.log('PLUGIN | WALLBOARD | SERVICE | LOST CLIENT CONNECTION');
                global.plgManager.logger.info('PLUGIN | WALLBOARD | SERVICE | LOST CLIENT CONNECTION');
            } else {
                console.log('PLUGIN | WALLBOARD | SERVICE | UNSOLICITED MESSAGE: ' + msg);
                global.plgManager.logger.info('PLUGIN | WALLBOARD | SERVICE | UNSOLICITED MESSAGE: ' + msg);
            }
        }.bind(this));
    }

    /**
     * Registration of Events at the plugin manager (hook in to events provided by the plugin manager)
     */
    registerForEvents() {
        global.plgManager.logger.info('PLUGIN | WALLBOARD | Registering events')
        global.plgManager.on('event_new_feedback_received', (operationUUID, basedataUUID, stateId) => {
            global.plgManager.logger.info('PLUGIN | WALLBOARD | EVENT event_new_feedback_received recieved');
            this.informWebSocketAboutNewFeedback();
        });
        global.plgManager.on('event_new_alarm', (alarmInfo) => {
            global.plgManager.logger.info('PLUGIN | WALLBOARD | EVENT event_new_alarm recieved');
            this.informWebSocketAboutNewAlarm();
        })
    }

    /**
     * Creates the service as a seperate node-process (fork)
     * sets the serviceProcId of the forked process
     * @memberof plugins/outbound/wallbord
     */
    prepareService() {
        global.plgManager.logger.info('PLUGIN | WALLBOARD | Starting Service');
        const { fork } = require('child_process');
        this.serviceProcess = fork(__dirname + '/service.js');
        this.serviceProcId = this.serviceProcess.pid;
        this.serviceProcess.title = 'ALARMiator Plugin - WALLBOARD Connector';
        global.plgManager.logger.info('PLUGIN | WALLBOARD | WebSocket - Service started with pid ' + this.serviceProcId);
        this.serviceProcess.on('exit', function (code) {
            this.serviceProcess = null;
            console.log("WALLBOARD Service EXITED " + code);
        });
    }

    /**
     * Sends the service configuration to the process
     */
    configService() {
        this.serviceProcess.send({ config: this.wallboardConfig });
    }

    /**
     * tells the service to connect
     */
    startService() {
        this.serviceProcess.send({ start: 1 });
    }

    /**
     * restarts the Plugin Service
     */
    restartService() {
        global.plgManager.logger.info('PLUGIN | WALLBOARD | restart Service...');
        if (this.serviceProcess !== null) {
            global.plgManager.logger.info('PLUGIN | WALLBOARD | Killing Service...');
            this.serviceProcess.kill("SIGHUP");
        }
        this.initializePlugin((initsuccess) => {
            global.plgManager.logger.debug('PLUGIN | WALLBOARD | initialized Plugin: ' + initsuccess);
            if (initsuccess) {
                this.isConfigured = true;
                this.prepareService();
                this.wireServiceCommunication();
                this.configService();
                this.startService();
            }
        })
    }

    /**
     * Methods to control wallboard clients
     * 
     * Methods send event to service. WebSocket then loads corresponding data and
     * sends this to the clients.
     * 
     * Responsibility for refreshing of needed data is at the websocket implementation.
     * The following methods shall only signal the websocket to do something and no payload is transmitted
     * 
     */
    informWebSocketAboutNewAlarm() {
        this.serviceProcess.send('{ "event_new_alarm" : 1 }');
    }

    informWebsocketAboutClosedAlarm() {
        this.serviceProcess.send('{"event_closed_alarm" : 1}')
    }

    informWebSocketAboutNewFeedback() {
        this.serviceProcess.send('{ "event_new_feedback" : 1 }');
    }


}

module.exports = wallboard;