Source: plugins/outbound/divera247/divera24.js

const https = require('https');
const gk = require('gauss-krueger')

/**
 * Class for interacting with DIVERA247 Cloud Service
 * @class
 */
class Divera24 {

    /**
     * @constructor
     */
    constructor() {
        this._alarmAccessKey = null;
        this._baseUrl = 'https://www.divera247.com/api/alarm?';
        this._gaussKruegerX = 0;
        this._gaussKruegerY = 0;
        this._lat = 0;
        this._lng = 0;
        this._priority = null;
        this._ric = null;
        this._address = null;
        this._text = null;
        this._type = null;
        this._vehicle = null;
        this._title = null;
        this._person = null;
        this._number = null;
        this._zveis = null;
    }

    // GETTERS AND SETTERS
    /**
     * ALARM Access Key
     */
    /**
    * @type {string}
    */
    set alarmAccessKey(alarmAccessKey) {
        this._alarmAccessKey = alarmAccessKey;
    }
    /**
    * @type {string}
    */
    get alarmAccessKey() {
        return this._alarmAccessKey;
    }


    /**
     * Divera Base URL for WebService
     */
    /**
    * @type {string}
    */
    set baseUrl(baseUrl) {
        this._baseUrl = baseUrl;
    }
    /**
    * @type {string}
    */
    get baseUrl() {
        return this._baseUrl;
    }

    /**
     * Stichwort - String (max 30 characters)
     */
    /**
    * @type {string}
    */
    set type(type) {
        this._type = type;
    }
    /**
    * @type {string}
    */
    get type() {
        return this._type;
    }


    /**
     * Priority/Sonderrechte - Integer (0 = ohne, 1 = mit)
     */
    /**
    * @type {integer}
    */
    set priority(priority) {
        this._priority = priority;
    }
    /**
    * @type {integer}
    */
    get priority() {
        return this._priority;
    }


    /**
     * Meldung - string (max. 64.000 Zeichen)
     */
    /**
    * @type {string}
    */
    set text(text) {
        this._text = text;
    }
    /**
    * @type {string}
    */
    get text() {
        return this._text;
    }


    /**
     * Adresse - string (max. 250 Zeichen)
     */
    /**
    * @type {string}
    */
    set address(address) {
        this._address = address;
    }
    /**
    * @type {string}
    */
    get address() {
        return this._address;
    }


    /**
     * Breitengrad - float
     */
    /**
    * @type {float}
    */
    set lng(lng) {
        this._lng = lng;
    }
    /**
    * @type {float}
    */
    get lng() {
        return this._lng;
    }


    /**
     * Längengrad - float
     */
    /**
    * @type {float}
    */
    set lat(lat) {
        this._lat = lat;
    }
    /**
    * @type {float}
    */
    get lat() {
        return this._lat;
    }


    /**
     * Gauss-Krueger X-Koordinate - float
     * berechnet automatisch lat und lng
     */
    /**
    * @type {string}
    */
    set gaussKruegerX(gaussKruegerX) {
        this._gaussKruegerX = gaussKruegerX;
        // check if y-coordinate is already set. if so calculate lat and lng
        if ((typeof this._gaussKruegerY !== 'undefinded') && (this._gaussKruegerY > 0)) {
            let wgs84 = gk.toWGS({ x: gaussKruegerX, y: this._gaussKruegerY });
            this._lng = wgs84.longitude;
            this._lat = wgs84.latitude;
            console.log('DIVERA247 | lat lon calculated from gauss krueger [lat|lng]:' + this._lat + ' | ' + this._lng);
        }
    }
    /**
    * @type {string}
    */
    get gaussKruegerX() {
        return this._gaussKruegerX;
    }

    /**
     * Gauss-Krueger Y-Koordinate - float
     * berechnet automatisch lat und lng
     */
    /**
    * @type {string}
    */
    set gaussKruegerY(gaussKruegerY) {
        this._gaussKruegerY = gaussKruegerY;
        // check if y-coordinate is already set. if so calculate lat and lng
        if ((typeof this._gaussKruegerX !== 'undefinded') && (this._gaussKruegerX > 0)) {
            let wgs84 = gk.toWGS({ x: parseFloat(this._gaussKruegerX), y: parseFloat(this._gaussKruegerY) });
            this._lng = wgs84.longitude;
            this._lat = wgs84.latitude;
            console.log('DIVERA247 | lat lon calculated from gauss krueger [lat|lng]:' + this._lat + ' | ' + this._lng);
        }
    }
    /**
    * @type {string}
    */
    get gaussKruegerY() {
        return this._gaussKruegerY;
    }

    /**
     * ZVEIs
     */
    set zveis(zveis) {
        this._zveis = zveis;
    }

    get zveis() {
        return this._zveis;
    }

    /**
     * Alarmschleifen, Gruppen / Standorte - String, bei mehreren Kommasepariert
     */
    /**
    * @type {string}
    */
    set ric(ric) {
        this._ric = ric;
    }
    /**
    * @type {string}
    */
    get ric() {
        return this._ric;
    }


    /**
     * Fahrzeuge - String, bei mehreren Kommasepariert
     */
    /**
    * @type {string}
    */
    set vehicle(vehicle) {
        this._vehicle = vehicle;
    }
    /**
    * @type {string}
    */
    get vehicle() {
        return this._vehicle;
    }

    /**
     * Person - String, bei mehreren Kommasepariert
     */
    /**
    * @type {string}
    */
    set person(person) {
        this._person = person;
    }
    /**
    * @type {string}
    */
    get person() {
        return this._person;
    }

    /**
     * Nummer - string
     */
    /**
    * @type {string}
    */
    set number(number) {
        this._number = number;
    }
    /**
    * @type {string}
    */
    get number() {
        return this._number;
    }

    /**
     * Title - string
     */
    /**
    * @type {string}
    */
    set title(title) {
        this._title = title;
    }
    /**
    * @type {string}
    */
    get title() {
        return this._title;
    }

    /**
     * render Path for alarm
     */
    renderAlarmGetPath() {
        var path = '/api/alarm?accesskey=' + encodeURI(this._alarmAccessKey) + '&type=' + encodeURI(this._type) + '&title=' + encodeURI(this._title) + '&priority=' + encodeURI(this._priority) + '&text=' + encodeURI(this._text) + '&address=' + encodeURI(this._address) + '&lat=' + encodeURI(this._lat) + '&lng=' + encodeURI(this._lng) + '&ric=' + encodeURI(this._ric) + '&vehicle=' + encodeURI(this._vehicle);
        return path;
    }
    
    /**
     * render Path for Message
     */
    renderMessageGetPath() {
        // Example
        var path = '/api/news?accesskey=' + encodeURI(this._alarmAccessKey) +
            '&title=' + encodeURI(this._title) +
            '&text=' + encodeURI(this._text) +
            '&person=' + encodeURI(this._person);
        return path;
    }

 
    /**
     * render Path for state change of gear with issi, opta, name or id to state "state"
     * @param {integer} status_id 1-9, (individuelle Fahrzeug-Status können künftig ebenfalls inkl. Farbton angelegt werden)
     * @param {string} vehicle_issi Identifizierung des Fahrzeugs anhand des Felds ISSI
     * @param {string} vehicle_name Identifizierung des Fahrzeugs anhand des Felds Funkrufname
     * @param {string} vehicle_id dentifizierung des Fahrzeugs anhand der ID
     * @param {string} vehicle_ric Identifizierung des Fahrzeugs anhand des Felds Alarmierungs-RIC
     * @param {string} status_note Freitext-Rückmeldung
     */
    renderStateGetPath(status_id, vehicle_issi = null, vehicle_name = null, vehicle_id = null, vehicle_ric = null, status_note = 'von ALARMiator') {
        /**
         * 
         * Example:
         * 
         * https://www.divera247.com/api/fms?status_id=STATUS&vehicle_ric=FAHRZEUGRIC&accesskey=ACCESSKEY
         * 
         *  status_id	    1 - 9 (individuelle Fahrzeug-Status können künftig ebenfalls inkl. Farbton angelegt werden)
         *  status_note	    Freitext-Rückmeldung
         *  vehicle_ric	    Identifizierung des Fahrzeugs anhand des Felds Alarmierungs-RIC
         *  vehicle_name	Identifizierung des Fahrzeugs anhand des Felds Funkrufname
         *  vehicle_issi	Identifizierung des Fahrzeugs anhand des Felds ISSI
         *  vehicle_id	    Identifizierung des Fahrzeugs anhand der ID
         *  accesskey	    Access-Key der Alarmübertragungs-API/Web-Schnittstelle
         * 
         */

        var path = '/api/fms?accesskey=' + encodeURI(this._alarmAccessKey) +
            '&status_id=' + encodeURI(status_id);
        if (vehicle_issi != null) {
            path += '&vehicle_issi=' + encodeURI(vehicle_issi);
        }
        if (vehicle_name != null) {
            '&vehicle_name=' + encodeURI(vehicle_name);
        }
        if (vehicle_id != null) {
            '&vehicle_id=' + encodeURI(vehicle_id);
        }
        if (vehicle_ric != null) {
            '&vehicle_ric=' + encodeURI(vehicle_ric);
        }
        if (status_note != null) {
            '&status_note=' + encodeURI(status_note);
        }
        return path;
    }

    /**
     * sends a state update to divera
     * @param {function} callback success (true/false)
     */
    sendState(status_id, vehicle_issi = null, status_note = 'von ALARMiator', callback) {
        var statePath = this.renderStateGetPath(status_id, vehicle_issi, null, null, null, status_note);
        console.log('DIVERA247 | DEBUG | URL-Path | ' + statePath);
        const options = {
            hostname: 'www.divera247.com',
            port: 443,
            path: statePath,
            method: 'GET'
        }
        const req = https.request(options, res => {
            console.log(`DIVERY247 | sendState | statusCode: ${res.statusCode}`)
            if (res.statusCode === 200) {
                callback(true);
            } else {
                callback(false);
            }
        })
        req.on('error', error => {
            console.error('DIVERA247 | sendState | error: ' + error.message);
            callback(false);
        })
        req.end()
        this.cleanup();
    }

    /**
     * sends out a new alarm to Divera247 service
     * @param {function} callback success (true/false)
     */
    sendAlarm(callback) {
        console.log('DIVERA247 | DEBUG | URL-Path | ' + this.renderAlarmGetPath());
        const options = {
            hostname: 'www.divera247.com',
            port: 443,
            path: this.renderAlarmGetPath(),
            method: 'GET'
        }
        const req = https.request(options, res => {
            console.log(`statusCode: ${res.statusCode}`)
            if (res.statusCode === 200) {
                callback(true);
            } else {
                callback(false);
            }
        })
        req.on('error', error => {
            console.error(error);
            callback(false);
        })
        req.end()
        this.cleanup();
    }

    /**
     * sends out a new message to Divera247 service
     * @param {function} callback success (true/false)
     */
    sendMessage(callback) {
        //console.log('DIVERA247 | MESSAGE | DEBUG | URL-Path | ' + this.renderMessageGetPath());
        const options = {
            hostname: 'www.divera247.com',
            port: 443,
            path: this.renderMessageGetPath(),
            method: 'GET'
        }
        const req = https.request(options, res => {
            //global.logger.log(`DIVERA247 | MESSAGE | SENT | statusCode: ${res.statusCode}`);
            if (res.statusCode === 200) {
                callback(true);
            } else {
                callback(false);
            }
        })
        req.on('error', error => {
            //global.logger.error(`DIVERA247 | MESSAGE | SENT | ERROR: ` + error);
            callback(false);
        })
        req.end()
        // clean up data
        this.cleanup();
    }

    /**
     * Cleans up all set variables, so that a new alarm only sends content from the actual alarm 
     * and not left over information from alarm before
     */
    cleanup() {
        this._gaussKruegerX = 0;
        this._gaussKruegerY = 0;
        this._lat = 0;
        this._lng = 0;
        this._priority = null;
        this._ric = null;
        this._address = null;
        this._text = null;
        this._type = null;
        this._vehicle = null;
        this._title = null;
        this._person = null;
        this._number = null;
    }
}

module.exports = Divera24;