UNPKG

@libs-scripts-mep/daq-fwlink

Version:

Torna capaz o controle do DAQ através do PVI via WebSocket

279 lines (243 loc) 8.21 kB
/** * Classe que gerencia funções de callback relacionando-os com filtros. * * # Exemplos * * ```js * let el = new EventList() * ``` */ class EventList { constructor() { this.functions = new Array() this.lastEvt = { message: "", params: [] } } /** * * @param {Function} func função de callback que será invocada quando houver mensagem com o filtro informado * @param {String} filter filtro que dispara a função de callback * @param {this} context contexto de origem da função informada * @returns id randômico para gerenciamento posterior * * # Exemplos * * ⚠️ Para que seja invocadas as funções de callback adicionadas aqui, é necessário a chamada do método `call()` desta classe * * ```js * let messagesObservers = new EventList() * messagesObservers.add((message, params) => { console.log(message, params) }, "PVI.DaqScript.DaqHardware.DSDaq.usbDevice", this) * ``` */ add(func, filter, context) { filter = filter || "" context = context || null let id = crypto.randomUUID() this.functions[id] = { func: func, filter: filter, context: context } return id } /** * * @param {String} id * * # Exemplos * * ```js * let messagesObservers = new EventList() * messagesObservers.remove("2a3f69e8-e82e-40c2-99ea-58d45204a576") * ``` */ remove(id) { delete this.functions[id] } /** * * @param {String} message * @param {Array} param * * # Exemplos * * ```js * let messageObserver = new EventList() * messageObserver.call("this is my message to be filtered", [0.0390625, 'COM31']) * ``` */ call(message, params) { this.lastEvt.message = message this.lastEvt.params = params for (let cont in this.functions) { if ((this.functions[cont].filter == "") || (message.indexOf(this.functions[cont].filter) != -1)) { this.functions[cont].func.call(this.functions[cont].context, message, params) } } } /** * Limpa todas as funções de callbacks * * # Exemplos * *⚠️ CUIDADO! A chamada desse método pode parar processos cruciais * * ```js * let messagesObservers = new EventList() * messagesObservers.clear() * ``` */ clear() { functions = new Array() evalFunctions = new Array() } } export default class FWLink { static PVIEventObserver = new EventList() static baseUri = "http://" + location.host + "/" //"http://127.0.0.1:5020/"; static formatParams(params) { return "?" + Object.keys(params).map(function (key) { return key + "=" + encodeURIComponent(params[key]) }).join("&") } /** * * @param {String} stringinstruction * @param {Array} arrayparams * @param {Function} assyncFunction * @param {String} objectparams * @returns null * ```js * FWLink.runInstruction("CONF_TENSAO", ["12VC"], () => { }, "COM3_1") * ``` */ static runInstruction(stringinstruction, arrayparams, assyncFunction, objectparams) { let uri = `${this.baseUri}API1.0/VM/INSTRUCTIONS/${stringinstruction}` if (objectparams != null && objectparams != undefined) { uri += this.formatParams(objectparams) } if (assyncFunction == null) { return this.syncAjax(uri, JSON.stringify(arrayparams), "POST") } else { this.asyncAjax(uri, assyncFunction, JSON.stringify(arrayparams), "POST") } return null } /** * * @param {String} stringinstruction * @param {Array} arrayparams * @param {Function} assyncFunction * @param {String} queryparams * @returns null * * ```js * FWLink.runInstructionS("RESET", []) * ``` */ static runInstructionS(stringinstruction, arrayparams, assyncFunction, queryparams) { for (let cont = 0; cont < arrayparams.length; cont++) { arrayparams[cont] = arrayparams[cont] + "" if ((arrayparams[cont].length == 0) || (arrayparams[cont].charAt(0) != '"')) arrayparams[cont] = '"' + arrayparams[cont].replace(/\\/g, '\\\\').replace(/\'/, '\\"') + '"' } return this.runInstruction(stringinstruction, arrayparams, assyncFunction, queryparams) } static getVar(varname, assyncFunction = () => { }) { const uri = `${this.baseUri}API1.0/VM/VARS/${varname}` this.asyncAjax(uri, assyncFunction, new Array(), "GET") } static getVarList(arrayList, assyncFunction) { assyncFunction = assyncFunction || null const jsonArr = JSON.stringify(arrayList) const uri = `${this.baseUri}API1.0/VM/VARS?LIST=${jsonArr}` if (assyncFunction != null) { this.asyncAjax(uri, function (resp) { eval("let objResp= " + resp) assyncFunction(objResp) }, new Array(), "GET") } else { let resp = this.syncAjax(uri, new Array(), "GET") eval("let objResp= " + resp) return objResp } } static setVar(varname, varvalue, assyncFunction) { assyncFunction = assyncFunction || null const uri = `${this.baseUri}API1.0/VM/VARS/${varname}` if (assyncFunction != null) { this.asyncAjax(uri, assyncFunction, varvalue, "POST") } else { return this.syncAjax(uri, varvalue, "POST") } } /** * * @param {String} url * @param {String} body * @param {String} httpmethod * @returns responseText */ static syncAjax(url, body, httpmethod) { body = body || null httpmethod = httpmethod || "GET" if ((httpmethod != "POST") && (httpmethod != "PUT")) body = null let request = new XMLHttpRequest() request.open(httpmethod, url, false) request.send(body) return request.responseText } /** * * @param {String} url * @param {Function} asyncFunction * @param {String} body * @param {String} httpmethod */ static asyncAjax(url, asyncFunction, body, httpmethod) { body = body || null httpmethod = httpmethod || "GET" if ((httpmethod != "POST") && (httpmethod != "PUT")) body = null let xhr = new XMLHttpRequest() xhr.onload = function () { if (xhr.readyState === 4) { asyncFunction(xhr.responseText) } } xhr.open(httpmethod, url, true) xhr.send(body) } /** * Estabelece comunicação com o PVI via webSocket. * * # Exemplos * ```js * FWLink.initWebSocket() * ``` */ static initWebSocket() { var ws = new WebSocket(this.baseUri.replace("http://", "ws://")) ws.onopen = (res) => { console.log("WebSocket:", res) } ws.onmessage = (evt) => { if (this.isValidJSON(evt.data)) { let receivedmsg = JSON.parse(evt.data) FWLink.PVIEventObserver.call(receivedmsg.message, receivedmsg.params) receivedmsg = null } ws.onerror = (err) => { console.error(err) } ws.onclose = () => { console.log("WebSocket was closed, restarting...") FWLink.initWebSocket() } } } static isValidJSON(jsonString) { try { JSON.parse(jsonString); return true } catch (e) { return false } } static { window.FWLink = this FWLink.initWebSocket() console.log('FWLink is ready!') } }