refactor(plc connection zechetti): added in more logging due to a weird issue with line 7 not sendin

This commit is contained in:
2025-10-15 21:17:08 -05:00
parent 2142c06ac3
commit 38edc6214b

View File

@@ -1,155 +1,171 @@
import { ControllerManager } from "st-ethernet-ip"; import { ControllerManager } from "st-ethernet-ip";
import { createLog } from "../../../../logger/logger.js";
import { getMac } from "../../../utils/getMachineId.js"; import { getMac } from "../../../utils/getMachineId.js";
import { labelingProcess } from "../../labeling/labelProcess.js"; import { labelingProcess } from "../../labeling/labelProcess.js";
export const createPlcMonitor = (config: any) => { export const createPlcMonitor = (config: any) => {
let cm: any; let cm: any;
let controllers: any = {}; let controllers: any = {};
let stats: any = {}; let stats: any = {};
let isRunning = false; let isRunning = false;
const nowISO = () => { const nowISO = () => {
return new Date().toISOString(); return new Date().toISOString();
}; };
const start = () => { const start = () => {
if (isRunning) return; if (isRunning) return;
cm = new ControllerManager(); cm = new ControllerManager();
config.controllers.forEach((cfg: any) => { config.controllers.forEach((cfg: any) => {
const plc: any = cm.addController( const plc: any = cm.addController(
cfg.ip, cfg.ip,
cfg.slot, cfg.slot,
cfg.rpi, cfg.rpi,
true, true,
cfg.retrySP || 3000 cfg.retrySP || 3000,
); );
plc.connect(); plc.connect();
controllers[cfg.id] = plc; controllers[cfg.id] = plc;
// initialize stats // initialize stats
stats[cfg.id] = { stats[cfg.id] = {
id: cfg.id, id: cfg.id,
ip: cfg.ip, ip: cfg.ip,
slot: cfg.slot, slot: cfg.slot,
scanRate: cfg.rpi, scanRate: cfg.rpi,
connected: false, connected: false,
lastConnectedAt: null, lastConnectedAt: null,
lastDisconnectedAt: null, lastDisconnectedAt: null,
reconnectCount: 0, reconnectCount: 0,
}; };
// Add tags // Add tags
cfg.tags.forEach((tag: any) => plc.addTag(tag)); cfg.tags.forEach((tag: any) => plc.addTag(tag));
// Events // Events
plc.on("Connected", () => { plc.on("Connected", () => {
const s = stats[cfg.id]; const s = stats[cfg.id];
s.connected = true; s.connected = true;
s.lastConnectedAt = nowISO(); s.lastConnectedAt = nowISO();
if (s.lastDisconnectedAt) { if (s.lastDisconnectedAt) {
s.reconnectCount++; s.reconnectCount++;
} }
console.log(`[${cfg.id}] Connected @ ${cfg.ip}:${cfg.slot}`); createLog(
}); "info",
"zechette",
"ocp",
`[${cfg.id}] Connected @ ${cfg.ip}:${cfg.slot}`,
);
});
plc.on("Disconnected", () => { plc.on("Disconnected", () => {
const s = stats[cfg.id]; const s = stats[cfg.id];
s.connected = false; s.connected = false;
s.lastDisconnectedAt = nowISO(); s.lastDisconnectedAt = nowISO();
console.log(`[${cfg.id}] Disconnected`); createLog("info", "zechette", "ocp", `[${cfg.id}] Disconnected`);
}); });
plc.on("error", (err: any) => { plc.on("error", (err: any) => {
console.error(`[${cfg.id}] Error:`, err.message); createLog(
}); "error",
"zechette",
"ocp",
`[${cfg.id}] Error: ${JSON.stringify(err.message)}`,
);
});
plc.on("TagChanged", async (tag: any, prevVal: any) => { plc.on("TagChanged", async (tag: any, prevVal: any) => {
if (tag.value !== 0) { if (tag.value !== 0) {
const time = nowISO(); const time = nowISO();
if (tag.value === 0) return; if (tag.value === 0) return;
setTimeout(async () => { setTimeout(async () => {
if (tag.value === 0) return; if (tag.value === 0) return;
const macId = await getMac(tag.value); const macId = await getMac(tag.value);
// const { data, error } = (await tryCatch( // const { data, error } = (await tryCatch(
// query( // query(
// getCurrentLabel // getCurrentLabel
// .replace( // .replace(
// "[macId]", // "[macId]",
// macId[0]?.HumanReadableId // macId[0]?.HumanReadableId
// ) // )
// .replace( // .replace(
// "[time]", // "[time]",
// format(time, "yyyy-MM-dd HH:mm") // format(time, "yyyy-MM-dd HH:mm")
// ), // ),
// "Current label data" // "Current label data"
// ) // )
// )) as any; // )) as any;
// createLog( // createLog(
// "info", // "info",
// "zechettii", // "zechettii",
// "zechettii", // "zechettii",
// `${format(time, "yyyy-MM-dd HH:mm")} [${cfg.id}] ${ // `${format(time, "yyyy-MM-dd HH:mm")} [${cfg.id}] ${
// tag.name // tag.name
// }: ${prevVal} -> ${ // }: ${prevVal} -> ${
// tag.value // tag.value
// }, the running number is ${ // }, the running number is ${
// error ? null : data.data[0]?.LfdNr // error ? null : data.data[0]?.LfdNr
// }}` // }}`
// ); // );
const zechette = { const zechette = {
line: tag.value.toString(), line: tag.value.toString(),
printer: cfg.printerId, // this is the id of the zechetti 2 to print we should move this to the db printer: cfg.printerId, // this is the id of the zechetti 2 to print we should move this to the db
printerName: cfg.id, printerName: cfg.id,
}; };
labelingProcess({ zechette: zechette }); createLog(
}, 1000); "info",
} "zechette",
}); "ocp",
}); `Date being sent to labeler: ${JSON.stringify(zechette)}`,
);
labelingProcess({ zechette: zechette });
}, 1000);
}
});
});
isRunning = true; isRunning = true;
}; };
const stop = () => { const stop = () => {
if (!isRunning) return; if (!isRunning) return;
Object.values(controllers).forEach((plc: any) => { Object.values(controllers).forEach((plc: any) => {
try { try {
plc.disconnect(); plc.disconnect();
} catch {} } catch {}
}); });
controllers = {}; controllers = {};
cm = null; cm = null;
isRunning = false; isRunning = false;
console.log("Monitor stopped"); console.log("Monitor stopped");
}; };
const restart = () => { const restart = () => {
console.log("Restarting the plc(s)"); console.log("Restarting the plc(s)");
stop(); stop();
new Promise((resolve) => setTimeout(resolve, 1500)); new Promise((resolve) => setTimeout(resolve, 1500));
start(); start();
}; };
const status = () => { const status = () => {
const result: any = {}; const result: any = {};
for (const [id, s] of Object.entries(stats)) { for (const [id, s] of Object.entries(stats)) {
let s: any; let s: any;
let uptimeMs = null, let uptimeMs = null,
downtimeMs = null; downtimeMs = null;
if (s.connected && s.lastConnectedAt) { if (s.connected && s.lastConnectedAt) {
uptimeMs = Date.now() - new Date(s.lastConnectedAt).getTime(); uptimeMs = Date.now() - new Date(s.lastConnectedAt).getTime();
} else if (!s.connected && s.lastDisconnectedAt) { } else if (!s.connected && s.lastDisconnectedAt) {
downtimeMs = downtimeMs = Date.now() - new Date(s.lastDisconnectedAt).getTime();
Date.now() - new Date(s.lastDisconnectedAt).getTime(); }
} result[id] = { ...s, uptimeMs, downtimeMs };
result[id] = { ...s, uptimeMs, downtimeMs }; }
} return result;
return result; };
};
return { start, stop, restart, status }; return { start, stop, restart, status };
}; };