import { ref } from "vue"; import { defineStore } from "pinia"; import type { NiagaraElecDemandData } from "../utils/types"; const useElecDemandStore = defineStore("elecDemand", () => { const elecData = ref([]); const subscribers = ref([]); // get data from baja const getElecDemandFromBaja = () => { // @ts-ignore window.require && // @ts-ignore window.requirejs(["baja!"], (baja: any) => { let eleclist: NiagaraElecDemandData[] = []; baja.Ord.make( `local:|foxs:4918|station:|neql:EMS:kw|bql:select slotPath,parent.displayName,name,out` ).get({ cursor: { before: () => {}, each: (record: any) => { const newItem: NiagaraElecDemandData = { slotPath: record.get("slotPath"), displayName: record.get("parent$2edisplayName"), name: record.get("name"), out: record.get("out")?.get("value") ?? 0, }; eleclist.push(newItem); }, after: () => { elecData.value = []; elecData.value.push(...eleclist); eleclist.forEach((item, index) => { subscribeToHistory(item, index); }); }, }, }); }); }; const subscribeToHistory = (item: NiagaraElecDemandData, index: number) => { const slotPath = item.slotPath; const ordString = `local:|foxs:4918|station:|${slotPath}`; // @ts-ignore window.require && // @ts-ignore window.requirejs(["baja!"], (baja: any) => { // 建立訂閱器 const subscriber = new baja.Subscriber(); // 定義 changed 事件的處理函數 subscriber.attach("changed", (prop: any) => { try { if (prop && prop.getName() === "out") { // 取得 out 的新值 const match = prop.$display.match(/^(\d+(\.\d+)?)/); const newValue = match ? parseFloat(match[0]) : 0; // 更新 elecData 中對應的 out 值 const updatedIndex = elecData.value.findIndex( (data) => data.slotPath === item.slotPath ); if (updatedIndex !== -1) { elecData.value[updatedIndex].out = Number(newValue); console.log(`Niagara 用電需求 ${item.name} 更新:`, newValue); } } } catch (error: any) { console.error( `處理 ${item.name || index} 告警變化失敗: ${error.message}`, error ); } }); baja.Ord.make(ordString) .get({ subscriber }) .then(() => { console.log(`Successfuly subscribed to ${item.name}`); }) .catch((err: any) => { console.error(`訂閱 ${item.name || index} 失敗: ${err.message}`); subscriber.detach("changed"); // 移除事件監聽器 }); subscribers.value.push(subscriber); }); }; const clearAllSubscriber = () => { subscribers.value.forEach((subscriber) => { subscriber.detach("changed"); subscriber.unsubscribeAll(); // 移除所有訂閱 }); subscribers.value = []; console.log("所有訂閱已清除"); }; return { getElecDemandFromBaja, elecData, clearAllSubscriber }; }); export default useElecDemandStore;