Skip to content
Snippets Groups Projects
api.js 17.1 KiB
Newer Older
Alfredo Chissotti's avatar
Alfredo Chissotti committed
"use strict";

import { mqtt_tree, sendMessage } from "./mqtthat.js";
Alfredo Chissotti's avatar
Alfredo Chissotti committed
class Api {

    static antifurto = null;
    static scenari = null;
    static luci = null;

    constructor (boolArray) {
alfredo's avatar
alfredo committed
	    Api.init(boolArray);
alfredo's avatar
alfredo committed
    }

alfredo's avatar
alfredo committed
    static async init(boolArray){
alfredo's avatar
alfredo committed
        if(boolArray[0]){
            const antifurto = await import("../antifurto.js");
	    Api.antifurto = antifurto.default;
	}
        if(boolArray[1]){
            const scenari = await import("../scenari.js");
	    Api.scenari = scenari.default;
	}
        if(boolArray[2]){
            const luci = await import("../luci.js");
	    Api.luci = luci.default;
	}

    static async onConnect(){
        // require all modules to free their resources using freeAll method
        // launch the fillTable function of each module available
        if(Api.antifurto != null){
alfredo's avatar
alfredo committed
            Api.antifurto.freeAll();
            Api.antifurto.fillTable();
        }
        if(Api.scenari != null){
alfredo's avatar
alfredo committed
            Api.scenari.freeAll();
            Api.scenari.fillTable();
        }
        if(Api.luci != null){
alfredo's avatar
alfredo committed
            Api.luci.freeAll();
            Api.luci.fillTable();
    // /api/luci/
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * gets the luci of the user from the server
     * @returns {*} all the lights of the user
     */
    static getLuci = () => { console.log('ciao');
        const topic = "to/all";
        const message = "{request:status}";
        sendMessage(topic, message);
    static sendLuciWeb = luciInput => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.luci.luciFromMqtt(luciInput);
    // static callbackGetAllLuci = null;
    static getAllLuci = () => { console.log('ciao');
        const topic = `rpc/${mqtt_tree}luci`;
        const message = "{request:description}";
        sendMessage(topic, message);
    static sendDataLuciWeb = luciInput => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.luci.luciFromMqtt(luciInput);
    }

    static luceMakeNewLuci = null;
    static callbackMakeNewLuci = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * adds a new luce to the server
     * @param {luceTemplate} luce the luce to add to the server
     * @returns {*} null if the light was added
     */
    static makeNewLuci = luce => { console.log('ciao');
        if (luce == null)
Alfredo Chissotti's avatar
Alfredo Chissotti committed
            throw new Error("luce must be defined");
        const luceSent = {nome: luce.luogo, stato: luce.stato, input: luce["sensore-in"], output: luce["luce-out"]};
        Api.luceMakeNewLuci = luce;
        const topic = `to/${mqtt_tree}luci/new`;
        const message = JSON.stringify(luceSent);
        sendMessage(topic, message);
    static sendWebNewLuci = luce => { console.log('ciao');
        const oldLuce = Api.luceMakeNewLuci;
        const luceReceived = {luogo: luce.nome, stato: luce.stato, "sensore-in": luce.input, "luce-out": luce.output, id : oldLuce.id};
        if (oldLuce != luce) {
Alfredo Chissotti's avatar
Alfredo Chissotti committed
            console.log('le luci non corrispondono', { oldLuce, luceReceived });
alfredo's avatar
alfredo committed
        Api.luci.showCreatedLight(luceReceived);
Alfredo Chissotti's avatar
Alfredo Chissotti committed

    static sensoreMakeNewSensore = null;
    /**
     * invia il sensore al microservizio per aggiornarlo //FIXME YET TO BE USED
Alfredo Chissotti's avatar
Alfredo Chissotti committed
     * @param {*} sensore l'oggetto sensore che dev'essere inviato al microservizio
     */
    static makeNewSensoreLuci = sensore => { console.log('ciao');
        if (sensore == null || sensore.nome == null)
            throw new Error("sensore must be defined");
        Api.sensoreMakeNewSensore = sensore;

        const newSensore = {sensM: sensore.nome};
        const topic = `to/${mqtt_tree}luci/sensore`;
        const message = JSON.stringify(newSensore);
        sendMessage(topic, message);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    }
    static sendWebNewSensore = sensore => { console.log('ciao');
        const oldSensore = Api.sensoreMakeNewSensore;
        if(oldSensore != null && oldSensore.nome !== sensore.sensM) {
Alfredo Chissotti's avatar
Alfredo Chissotti committed
            console.log('i sensori non corrispondono', { oldSensore, sensore });
        }
alfredo's avatar
alfredo committed
        Api.luci.showCreatedSensore(sensore);//FIXME not used
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    }
    static callbackLuciStatoToBeStatic = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    static toggleForLuciStato = null;
    static fixedCallbackLuciStato = null;
    // /api/luci/stato/
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * changes the status of a luce on the server
     * @param {luceTemplate} luce the luce to change the status of
     * @returns {*} null if the light's status was changed
     */
    static setLuciStato = (luce, toggle, callback) => { console.log('ciao');
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (Api.fixedCallbackLuciStato == null)
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (luce == null)
            throw new Error("luce must be defined");
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (toggle == null)
            throw new Error("toggle must be defined");
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (callback == null)
            throw new Error("callback must be defined");

        if(Api.callbackLuciStatoToBeStatic == null)
            Api.callbackLuciStatoToBeStatic = callback;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        Api.toggleForLuciStato = toggle;

        const topic = `from/${mqtt_tree}gpio/${luce["sensore-in"].toUpperCase()}`;
        const message = `{"event":1}`;
        // Api.outForToggleLuciStato = luce;
        sendMessage(topic, message);
    static sendLuciStatoWeb = response => { console.log('ciao');
        //response == {"output":outVal,stato};
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (response == null) {
            const toggle = Api.toggleForLuciStato;
            Api.toggleForLuciStato = null;
            Api.callbackLuciStatoToBeStatic(toggle);
        } else {
            Api.fixedCallbackLuciStato(response);
        }
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    }
    // /api/scenari/
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * gets the scenari of the user from the server
     * @returns {*} all the scenarios of the user
     */
    static getScenari = () => { console.log('ciao');
        const topic = `rpc/${mqtt_tree}scenari`;
        const message = "{request:status}";
        sendMessage(topic, message);
    static sendScenariWeb = scenari => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.scenari.mostraScenariServer(scenari);
alfredo's avatar
alfredo committed
    static setAntifurtoINbtnFromScenari = newINbtn => { console.log('ciao');
alfredo's avatar
alfredo committed
    	console.log(newINbtn)
        if(newINbtn == null || newINbtn?.nome == null)
Alfredo Chissotti's avatar
Alfredo Chissotti committed
            throw new Error("newINbtn must be defined");

        const btn = newINbtn.nome;
        if(btn == null)
            return;
        const topic = `to/${mqtt_tree}scenari/sensoreAntifurto`;
        const message = `{"attiva-scenari":"${btn}"}`;
        sendMessage(topic, message);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    }
    // /api/scenari/attiva/
    static scenarioSetscenarioStatus = null;
    static activatingSetscenarioStatus = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * activates or deactivates a scenario on the server
     * @param {scenarioTemplate} scenario the scenario to activate or deactivate
     * @returns {*} null if the scenario was activated or deactivated
     */
    static setScenarioStatus = (scenario, activating) => { console.log('ciao');
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (scenario == null)
            throw new Error("scenario must be defined");
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (activating == null)
            throw new Error("activating must be defined");
        Api.scenarioSetScenarioStatus = scenario;
        Api.activatingSetScenarioStatus = activating;

        const topic = `to/${mqtt_tree}scenari`;
        const message = `{"evento":${scenario.stato === false ? '0' : '1'},"nome":"${scenario.nome}"}`;
        sendMessage(topic, message);
    static sendWebNewScenarioStatus = scenarioNome => { console.log('ciao');
        const scenario = Api.scenarioSetScenarioStatus;
        const activating = Api.activatingSetScenarioStatus;
        Api.scenarioSetScenarioStatus = null;
        Api.activatingSetScenarioStatus = null;
        if(scenario == null || activating == null)
            return;
        // FIXME forse dovrei controllare scenarioNome
        console.log(scenario)
        if (scenarioNome.startsWith(scenario.nome))
alfredo's avatar
alfredo committed
            Api.scenari.showScenarioAfterToggling(scenario, activating,true);

    static sendWebScenarioAttivoAutomatico = scenarioNome => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.scenari.showScenarioAfterToggling(scenarioNome, true,true);

    static overlayScenariAntifurto = stato => {
alfredo's avatar
alfredo committed
        Api.scenari.correctlySetAntifurto(stato,false,true);
    // /api/scenari/registra/
    static recordingRecordScenario = null;
    static learnINBtnRecordScenario = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * starts/stop the recording of a scenario
     * @param {Boolean} recording true to start the recording, false to stop it
     * @returns {*} null if the recording was started or stopped
     */
    static recordScenario = (recording, learnINBtn) => { console.log('ciao');
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (recording == null)
            throw new Error("recording must be defined");
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (learnINBtn == null)
            throw new Error("learnINBtn must be defined");
        Api.recordingRecordScenario = recording;//true se voglio registrare
        Api.learnINBtnRecordScenario = learnINBtn;
        console.log(learnINBtn)

        const INBtn = learnINBtn.nome;
        const topic = `from/${mqtt_tree}gpio/${INBtn.toUpperCase()}`;
        const message = `{"event":1}`;
        sendMessage(topic, message);
    }
    static retriesRecordScenario = 0;
    static sendWebScenarioAutoma = stato => { console.log('ciao');
            return;
        const recording = Api.recordingRecordScenario;
        // const statoAspettato = recording ? 1 : 0;
        if (recording != null && stato !== recording && Api.retriesRecordScenario < 3) {
            Api.retriesRecordScenario++;

            const INBtn = Api.learnINBtnRecordScenario.nome;
            const topic = `from/${mqtt_tree}gpio/${INBtn.toUpperCase()}`;
            const message = `{"event":1}`;
            sendMessage(topic, message);
        }
        Api.recordingRecordScenario = null;
        Api.learnINBtnRecordScenario = null;
        Api.retriesRecordScenario = 0;
alfredo's avatar
alfredo committed
        Api.scenari.apiCallbackRecordScenario(recording);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    }
    // /api/scenari/salva/
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * tells the server to save the currently recorded scenario
     * @returns {*} the scenario if it was saved
     */
    static saveScenario = nome => { console.log('ciao');
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (nome == null)
            throw new Error("nome must be defined");

        const topic = `to/${mqtt_tree}scenari/salva`;
        const message = JSON.stringify({nome});
        sendMessage(topic, message);
    static sendWebSavedScenario = scenario => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.scenari.saveScenarioCallback(scenario);
    // /api/scenari/conf
    static sendScenariConfiguration = conf => { console.log('ciao');
        const topic = `conf/${mqtt_tree}scenari`;
        const message = JSON.stringify(conf);
        sendMessage(topic, message);
    }
    static sendWebConfigurationScenari = conf => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.scenari.updateConfiguration(conf);
    // /api/antifurto/
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * gets everything about the antifurto (stato, allarme, attenzione (valore progress bar), soglia, sensori)
Alfredo Chissotti's avatar
Alfredo Chissotti committed
     * @returns {*} the antifurto's values
     */
    static getAntifurto = () => { console.log('ciao');
        const topic = `rpc/${mqtt_tree}antifurto`;
        const message = `{"request":"description"}`;
        sendMessage(topic, message);
    static sendWebGetAntifurto = antifurto => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.antifurto.mostraAntifurtoServer(antifurto);
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    }
    // /api/antifurto/stato/
    static payloadSetAntifurtoStatus = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * sets the status of the antifurto
     * @param {Boolean} payload {previousStatus, fromScenari, fromServer}
Alfredo Chissotti's avatar
Alfredo Chissotti committed
     * @returns {*} null if the status was changed
     */
    static setAntifurtoStatus = payload => { console.log('ciao');
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (payload == null)
            throw new Error("payload must be defined");
        // Api.newStatusSetAntifurtoStatus = newStatus;
        // Api.antifurtoINbtnSetAntifurtoStatus = antifurtoINbtn;
        Api.payloadSetAntifurtoStatus = payload;
alfredo's avatar
alfredo committed
        const INBtn = Api.antifurto?.attivaAntifurtoINbtn != null ? Api.antifurto.attivaAntifurtoINbtn.nome : Api.scenari?.antifurtoINbtn.nome;

        const topic = `from/${mqtt_tree}gpio/${INBtn.toUpperCase()}`;
        const message = `{"event":1}`;
        sendMessage(topic, message);
    static retriesSetAntifurtoStatus = 0;
    static sendWebSetAntifurtoStatus = stato => { console.log('ciao');
        if(stato === NaN)
alfredo's avatar
alfredo committed
        const newStatus = Api.antifurto?.status != null ? !Api.antifurto.status : !Api.scenari?.antifurtoStatus;
        const expectedStatus = newStatus ? 2 : 0;
alfredo's avatar
alfredo committed
        const nomeIN = Api.antifurto?.attivaAntifurtoINbtn != null ? Api.antifurto.attivaAntifurtoINbtn.nome : Api.scenari?.antifurtoINbtn.nome;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (stato !== expectedStatus && Api.retriesSetAntifurtoStatus < 3) {
            Api.retriesSetAntifurtoStatus++;

            const topic = `from/${mqtt_tree}gpio/${nomeIN.toUpperCase()}`;
            const message = `{"event":1}`;
            sendMessage(topic, message);
        }
        const payload = Api.payloadSetAntifurtoStatus;
        // Api.newStatusSetAntifurtoStatus = null;
        // Api.antifurtoINbtnSetAntifurtoStatus = null;
        Api.payloadSetAntifurtoStatus = null;
        Api.retriesSetAntifurtoStatus = 0;
alfredo's avatar
alfredo committed
            Api.antifurto?.showChangeAntifurtoStatus(payload?.previousStatus ? payload?.previousStatus : Api.antifurto?.status, newStatus, payload?.fromScenari ? payload?.fromScenari : false, payload?.fromServer ? payload?.fromServer : true);
        } catch (error) {
            if(error.message !== "Antifurto.showChangeAntifurtoStatus is not a function")
                throw error;
alfredo's avatar
alfredo committed
            else Api.scenari?.showChangeAntifurtoStatus(newStatus, payload?.fromServer ? payload?.fromServer : true);

    static overlayAntifurtoAntifurto = stato => {
alfredo's avatar
alfredo committed
        Api.antifurto.activate(stato,false,true);
    // /api/antifurto/allarme/
    static fixedCallbackStatoAllarme = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * sets the status of the antifurto's alarm
     * @param {Boolean} allarme the new status of the antifurto's alarm
     * @returns {*} null if the status was changed
     */
    static setAntifurtoAllarme = allarme => { console.log('ciao');
        // const booleanAlarm = allarme == 'true';
        if (allarme == null || Api.fixedCallbackStatoAllarme == null)
            return;
        Api.fixedCallbackStatoAllarme(allarme);
    };
    // /api/antifurto/attenzione/
    static fixedCallbackValoreAttenzione = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * sets the status for the progress bar of the antifurto's alarm
     * @param {Number} attenzione the new value of the antifurto's attention
Alfredo Chissotti's avatar
Alfredo Chissotti committed
     * @returns {*} null if the value was changed
Alfredo Chissotti's avatar
Alfredo Chissotti committed
     */
    static setAntifurtoAttenzione = attenzione => { console.log('ciao');
        if (attenzione == null || isNaN(parseInt(attenzione)) || Api.fixedCallbackValoreAttenzione == null)
            return;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        const val = parseInt(attenzione);
        Api.fixedCallbackValoreAttenzione(val);
    };
    // /api/antifurto/soglia/
    static sogliaSetAntifurtoSoglia = null;
    static fromServerSetAntifurtoSoglia = null;
    static callbackSetAntifurtoSoglia = null;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
    /**
     * sets the value of the antifurto's threshold
     * @param {Number} soglia the user's value of the antifurto's threshold
     * @returns {*} null if the value was changed
     */
    static setAntifurtoSoglia = (soglia, fromServer) => { console.log('ciao');
        if (soglia == null || isNaN(parseInt(soglia)))
Alfredo Chissotti's avatar
Alfredo Chissotti committed
            throw new Error("soglia must be a set integer");
        const val = parseInt(soglia);
        if (val < 0 || val > 100)
Alfredo Chissotti's avatar
Alfredo Chissotti committed
            throw new Error("soglia must be between 0 and 100");
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (fromServer == null)
            throw new Error("fromServer must be defined");
        Api.sogliaSetAntifurtoSoglia = val;
        Api.fromServerSetAntifurtoSoglia = fromServer;
        const topic = `conf/${mqtt_tree}antifurto/soglia`;
        const message = `{"soglia":${val}}`;
        sendMessage(topic, message);
    static sendWebSoglia = soglia => { console.log('ciao');
        const expectedSoglia = Api.sogliaSetAntifurtoSoglia;
Alfredo Chissotti's avatar
Alfredo Chissotti committed
        if (expectedSoglia !== soglia) {
            console.log('soglie differenti', { expectedSoglia, soglia });
        }
        const fromServer = Api.fromServerSetAntifurtoSoglia;
        Api.sogliaSetAntifurtoSoglia = null;
        Api.fromServerSetAntifurtoSoglia = null;
alfredo's avatar
alfredo committed
        Api.antifurto.showEditsSoglia(soglia, fromServer);
    }
    // /api/antifurto/conf
    static sendAntifurtoConfiguration = json => { console.log('ciao');
        const topic = `conf/${mqtt_tree}antifurto`;
        const message = JSON.stringify(json);
        sendMessage(topic, message);
    }
    static sendWebConfigurationAntifurto = conf => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.antifurto.updateConfiguration(conf);
    static sendSensoreConfiguration = json => { console.log('ciao');
        const topic = `conf/${mqtt_tree}antifurto/sensore`;
        const message = JSON.stringify(json);
        sendMessage(topic, message);
    }
    static sendWebConfigurationSensore = conf => { console.log('ciao');
alfredo's avatar
alfredo committed
        Api.antifurto.updateSensoreConfiguration(conf);


    static testSensore = sensore => {//usato da sensori.js
        const topic = `from/${mqtt_tree}gpio/${sensore.toUpperCase()}`;
        const message = `{"event":1}`;
        sendMessage(topic, message);
    }
Alfredo Chissotti's avatar
Alfredo Chissotti committed
}

alfredo's avatar
alfredo committed
export default Api;