UNPKG

@libs-scripts-mep/inv-img-tool

Version:

Ferramenta de visão computacional com implementações dedicadas à validação de displays em testes automatizados de linha de produção.

204 lines (159 loc) 8.26 kB
import Log from "../script-loader/utils-script.js" import FWLink from "../daq-fwlink/FWLink.js" export class IITClient { static port = 8765 /**@type {WebSocket} */ static ws = null static debugMode = true static reconnectAttempts = null static workflowDone = null static error = null /**@type {HTMLVideoElement | null} */ static streamVideoElement = null /**@type {HTMLVideoElement | null} */ static resultVideoElement = null /**@type {Map<[image: string], { result: boolean, name: string, image: string, size: [number, number] }>} */ static workflowResult = new Map() /** * Starts a workflow in the Image Tool. * * @param {string} wfPath - The path to the workflow file. * @param {string} wfName - The name of the workflow file. * @param {HTMLVideoElement} [streamVideoElement] - The video element where the stream will be set. * @param {HTMLVideoElement} [resultVideoElement] - The video element where the result will be set. * @param {boolean} [debugMode] - Whether the workflow should run in debug mode. */ static async startWorkflow(wfPath, wfName, streamVideoElement = null, resultVideoElement = null, debugMode = false) { this.workflowDone = false await this.connect() IITClient.streamVideoElement = streamVideoElement IITClient.resultVideoElement = resultVideoElement IITClient.workflowResult = new Map() IITClient.ws.send(JSON.stringify({ wfpath: wfPath, wffilename: wfName, debug: debugMode })) } static async stopWorkflow() { if (this.workflowDone || this.workflowDone == null) return console.warn("Parando workflow...") IITClient.ws.send(JSON.stringify({ stop: true })) while (!this.workflowDone) { await this.delay(100) } } static async getError() { return new Promise((resolve) => { resolve(this.error) this.error = null }) } static async connect() { await this.delay(1000) if (IITClient.ws == null || IITClient.ws.readyState != WebSocket.OPEN) { IITClient.ws = new WebSocket(`ws://localhost:${this.port}`) IITClient.ws.onopen = () => { Log.warn(`🟢 Connected to IIT server on port ${this.port}`, Log.Colors.Green.MediumSpringGreen) } IITClient.ws.onclose = () => { Log.warn(`🔴 Disconnected from IIT server on port ${this.port}`, Log.Colors.Red.IndianRed), this.connect() } IITClient.ws.onerror = (error) => { console.error(error) } IITClient.ws.onmessage = (event) => { try { const obj = JSON.parse(event.data) if (obj.stream && IITClient.streamVideoElement != null) { IITClient.streamVideoElement.src = 'data:image/jpeg;base64,' + obj.stream } else if (obj.img_result) { IITClient.workflowResult.set(obj.img_result.name, obj.img_result) if (obj.img_result.image != null && IITClient.resultVideoElement != null) { IITClient.resultVideoElement.src = 'data:image/jpeg;base64,' + obj.img_result.image if (obj.img_result.result != null) { console.log(obj.img_result) } } } else if (obj.error) { this.workflowDone = true this.error = obj.error } else { console.log(obj) if (obj.done) this.workflowDone = true } } catch (error) { console.log(error) } } } else { console.warn("🟢 IIT client already connected") } } static showImageResult(name) { if (!IITClient.workflowResult.has(name)) { return } if (IITClient.resultVideoElement == null) { return } IITClient.resultVideoElement.src = 'data:image/jpeg;base64,' + IITClient.workflowResult.get(name).image return } static async killWebsocket() { IITClient.ws.send(JSON.stringify({ kill: true })) } static async delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } static { window.IITClient = IITClient; IITClient.connect() } } export class IITServer { static debugMode = true static async init(checkDependencies = true) { if (checkDependencies) { await DepChecker.checkDependencies() } await IITServer.startWebsocket() await IITClient.connect() } static getScriptPath() { let pathC = location.pathname.slice(location.pathname.indexOf("C:/"), location.pathname.lastIndexOf("/")) let pathI = location.pathname.slice(location.pathname.indexOf("I:/"), location.pathname.lastIndexOf("/")) if (pathC.length > 0) { return pathC } else if (pathI.length > 0) { return pathI } } static async startWebsocket(pyFilePath = IITServer.getScriptPath() + '/node_modules/@libs-scripts-mep/inv-img-tool/websocket.py') { const start = Date.now() while (true) { const elapsed = Date.now() - start if (IITClient.ws?.readyState === WebSocket.OPEN) { Log.warn(`✅ IIT server already running on port ${IITClient.port}`, Log.Colors.Orange.Orange) return { success: true, msg: "IIT server already running on port " + IITClient.port } } else if (elapsed > 1000) { Log.warn(`⚙️ Starting IIT server on port ${IITClient.port}`, Log.Colors.Orange.Orange) FWLink.runInstructionS("EXEC", ["Python", pyFilePath, "true", "true"]) return Promise.race([ new Promise((resolve) => { const id = FWLink.PVIEventObserver.add((message, params) => { const msg = params?.[0] if (IITServer.debugMode && msg.includes("[IIT SERVER]")) { Log.warn(msg, Log.Colors.Purple.Violet) } if (msg.includes("[IIT SERVER]") && msg?.includes("Servidor WebSocket IIT iniciado")) { FWLink.PVIEventObserver.remove(id) resolve({ success: true, msg }) } }, "PVI.Sniffer.sniffer.PID_") }), new Promise((resolve) => setTimeout(() => { resolve({ success: false, msg: `❌ IIT server failed to start on port ${IITClient.port}` }) }, 10000) ) ]) } await IITClient.delay(100) } } static { window.IITServer = IITServer } } export class DepChecker { static debugMode = true static async checkDependencies(pyFilePath = IITServer.getScriptPath() + '/node_modules/@libs-scripts-mep/inv-img-tool/dep_checker.py') { return new Promise((resolve) => { FWLink.runInstructionS("EXEC", ["Python", pyFilePath, "true", "true"]) const id = FWLink.PVIEventObserver.add((message, params) => { const msg = params[0] if (msg != undefined) { if (DepChecker.debugMode && msg.includes("[IIT DEP]")) { Log.warn(msg, Log.Colors.Purple.Violet) } if (msg.includes("[IIT DEP]") && msg.includes("Package version check and update completed.")) { Log.console("IIT: Dependências instaladas com sucesso.", Log.Colors.Green.SpringGreen) FWLink.PVIEventObserver.remove(id) resolve({ success: true, msg: msg, }) } } }, "PVI.Sniffer.sniffer.PID_") }) } static { window.DepChecker = DepChecker } }