feat(ocp): completly moved ocp to lst

This commit is contained in:
2025-04-06 07:48:05 -05:00
parent 95bebbde2b
commit 51cc4aa370
13 changed files with 448 additions and 96 deletions

View File

@@ -3,7 +3,6 @@ import { settings } from "../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { getLots } from "../lots/lots.js";
import { getMac } from "../specialProcesses/utils/getMachineId.js";
import { billingCheck } from "../specialProcesses/billingCheck/billingCheck.js";
import { isMainMatStaged } from "../materials/mainMaterial.js";
import { firstLotLabel } from "../specialProcesses/lotChangeLabel/lotCHangeLabel.js";
@@ -12,9 +11,11 @@ import { createLabel } from "./createLabel.js";
import { bookInLabel } from "./bookIn.js";
import { delieryInhouse } from "../specialProcesses/inhouse/inhouseDelivery.js";
import { dualPrintingProcess } from "../specialProcesses/dualPrinting/dualPrinting.js";
import { getMac } from "../../utils/getMachineId.js";
interface Printer {
name: string;
humanReadableId: string;
// Add any other expected properties
}
@@ -72,7 +73,9 @@ export const labelingProcess = async ({
if (printer) {
// filter the lot based on the printerID
// console.log(printer);
filteredLot = lots.data.filter((l: any) => l.printerID === printer);
filteredLot = lots.data.filter(
(l: any) => l.printerID === parseInt(printer?.humanReadableId)
);
if (filteredLot.length === 0) {
// console.log(`There is not a lot assigned to ${printer.name}`);
createLog(

View File

@@ -1,20 +1,81 @@
import { eq } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { settings } from "../../../../../database/schema/settings.js";
import { tryCatch } from "../../../../globalUtils/tryCatch.js";
import { createLog } from "../../../logger/logger.js";
import { getPrinters } from "./getPrinters.js";
import { printerStatus } from "./printerStatus.js";
export const printerCycle = async () => {
/**
* We will cycle through the printers to check there states.
*/
let printers = await getPrinters();
/**
* if the last timeprinted would be greater than x well just change the status to idle and extended based on the 2 times.
*
* to get a printer going again label will need to come from the front end as that will just unpause the printer and start the labeling, or the api for manual print
* well need to adjust this to actually print the label then unpause it.
*
* it will be
*
* less than x since time printed run the printer status
* greater than x but less than y change the status to idle, but ping to make sure its online,
* if greater than y change to extended idle but stil also ping to make sure its online.
*/
// get the printers
const { data: s, error: se } = await tryCatch(
db.select().from(settings).where(eq(settings.name, "ocpCycleDelay"))
);
if (se) {
createLog(
"error",
"ocp",
"ocp",
"There was an error getting the ocpCycleDelay."
);
return {
success: false,
message: "Error getting printers.",
};
}
const ocpDelay: any = s;
// start the actual printer cycle
const actualPrinterCycle = setInterval(async () => {
const { data, error } = await tryCatch(getPrinters());
if (error) {
createLog(
"error",
"ocp",
"ocp",
"There was an error getting the printers."
);
return {
success: false,
message: "Error getting printers.",
};
}
let printers: any = data.data;
// only keep the assigned ones
printers = printers.filter((p: any) => p.assigned === true);
// for autolabelers like dayton and MCD we want to ignore them from the loop as well.
printers = printers.filter(
(p: any) => p.name != "Autolabeler" && !p.remark.includes("ignore")
);
printers.forEach(async (p: any) => {
/**
* if the last timeprinted would be greater than x well just change the status to idle and extended based on the 2 times.
*
* to get a printer going again label will need to come from the front end as that will just unpause the printer and start the labeling, or the api for manual print
* well need to adjust this to actually print the label then unpause it.
*
* it will be
*
* less than x since time printed run the printer status
* greater than x but less than y change the status to idle, but ping to make sure its online,
* if greater than y change to extended idle but stil also ping to make sure its online.
*/
// ignore pdf printer as we want it here for testing purposes
if (p.name.toLowerCase() === "pdf24") {
return;
}
await printerStatus(p);
});
}, parseInt(ocpDelay[0]?.value) * 1000);
};

View File

@@ -0,0 +1,61 @@
import { eq, sql } from "drizzle-orm";
import { db } from "../../../../../database/dbclient.js";
import { printerData } from "../../../../../database/schema/printers.js";
import { createLog } from "../../../logger/logger.js";
export const printStatus = [
{ code: 1, text: "Printing" },
{ code: 2, text: "Pending labels" },
{ code: 3, text: "Printing to fast" },
{ code: 4, text: "Creating label" },
{ code: 6, text: "Printer Paused" },
{ code: 7, text: "Printer error" },
{
code: 8,
text: "First time printing",
},
];
export const printerUpdate = async (printer: any, status: any) => {
/**
* Updates the status of the printer.
*/
// get current time
let pd = {};
const currentTime = sql`NOW()`;
if (status === 3) {
pd = {
status: status,
statusText: printStatus.filter((c) => c.code === status)[0]?.text,
};
} else if (status === 6) {
pd = {
status: status,
statusText: printStatus.filter((c) => c.code === status)[0]?.text,
};
} else {
pd = {
lastTimePrinted: currentTime,
status: status,
statusText: printStatus.filter((c) => c.code === status)[0]?.text,
};
}
if (printer.humanReadableId) {
try {
await db
.update(printerData)
.set(pd)
.where(
eq(printerData.humanReadableId, printer.humanReadableId)
);
} catch (error) {
createLog("error", "ocp", "ocp", `Error updating printer state`);
}
}
// console.log(printerUpdate.name);
return;
};

View File

@@ -0,0 +1,190 @@
import net from "net";
import { pausePrinter } from "../../utils/pausePrinter.js";
import { addHours, differenceInSeconds } from "date-fns";
import { printerUpdate } from "./printerStatUpdate.js";
import { createLog } from "../../../logger/logger.js";
import { unPausePrinter } from "../../utils/unpausePrinter.js";
import { labelingProcess } from "../labeling/labelProcess.js";
import { timeZoneFix } from "../../../../globalUtils/timeZoneFix.js";
let logLevel: string = process.env.LOG_LEVEL || "info";
let errorCheck = false;
export const printerStatus = async (p: any) => {
/**
* Checks each printer to see what the current state is
*/
createLog("debug", "ocp", "ocp", `Printer cycling`);
const printer = new net.Socket();
return new Promise((resolve) => {
// connect to the printer, and check its status
printer.connect(p.port, p.ipAddress, async () => {
// write the message to the printer below gives us a feedback of the printer
printer.write("~HS");
});
// read the data from the printer
printer.on("data", async (data) => {
const res = data.toString();
// turn the data into an array to make it more easy to deal with
const tmp = res.split(",");
//--------------- time stuff-----------------------------------------------------------------
// get last time printed
const lastTime = new Date(p.lastTimePrinted).toISOString();
// console.log(lastTime);
// current time?
/**
*
* add the time zone to the settings db
*/
// const currentTime = addHours(
// new Date(Date.now()),
// -6
// ).toISOString();
const currentTime = timeZoneFix();
let timeBetween = 0;
// if this is our first time printing pause the printer to start the timer, else we just update the time between timer
if (lastTime === undefined) {
printer.end();
printerUpdate(p, 8);
pausePrinter(p);
resolve({ success: true, message: "First Time printing" });
} else {
timeBetween = differenceInSeconds(currentTime, lastTime);
}
// --- end time ---
// --- printer logic ---
createLog(
"debug",
"ocp",
"ocp",
`${p.name}: timeBetween: ${timeBetween}, delay ${
p.printDelay || 90
}, ${currentTime}... ${lastTime}`
);
if (tmp[2] === "0" && tmp[4] !== "000") {
// unpaused and printing labels - reset timer
createLog(
"debug",
"ocp",
"ocp",
`Unpaused and printing labels, time remaing ${differenceInSeconds(
p.printDelay || 90,
timeBetween
)}`
);
// update last time printed in the array
printerUpdate(p, 1);
} else if (tmp[2] === "1" && tmp[4] !== "000") {
// was paused or label sent from somewhere else
createLog(
"info",
"ocp",
"ocp",
`${
p.name
} paused to soon, unpausing, remaining time: ${differenceInSeconds(
p.printDelay || 90,
timeBetween
)}`
);
// reset the timer for this printer as well other labels shouldnt be sent but if we send them ok
printerUpdate(p, 2);
unPausePrinter(p);
} else if ((tmp[2] === "0" && timeBetween < p.printDelay) || 90) {
// was unpaused to soon so repause it
createLog(
"debug",
"ocp",
"ocp",
`${p.name} Unpaused before the time allowed, time left ${
differenceInSeconds(p.printDelay || 90, timeBetween) //seconds
}`
);
printerUpdate(p, 3);
pausePrinter(p);
} else if ((tmp[2] === "0" && timeBetween > p.printDelay) || 90) {
// its been long enough we can print a label
createLog(
"debug",
"ocp",
"ocp",
`${p.name} Allowed time passed and printing new label`
);
// update last time printed in the array
printerUpdate(p, 4);
// sending over for labeling.
labelingProcess({ printer: p });
} else if (tmp[2] === "0") {
// printer was unpaused for the first time or made it here
createLog(
"debug",
"ocp",
"ocp",
`${p.name} Frist time printing`
);
// add the time and printer
printerUpdate(p, 4);
// sending over for labeling.
labelingProcess({ printer: p });
} else if (tmp[2] === "1") {
// printer is paused and waiting
createLog(
"debug",
"ocp",
"ocp",
`${p.name} paused and waiting`
);
printerUpdate(p, 6);
}
printer.end();
resolve({ success: true, message: "Print cycle completed." });
});
printer.on("error", async (error) => {
// just going to say theres an error with the printer
if (!errorCheck) {
createLog(
"error",
"ocp",
"ocp",
`${p.name} encountered an error: ${error}`
);
}
await printerUpdate(p, 7);
errorCheck = true;
// send log data
// fake line
printer.end();
resolve({
success: false,
message: "There was an error with the printer.",
});
});
});
};

View File

@@ -25,7 +25,7 @@ export const updatePrinters = async () => {
);
if (prodError) {
console.log(prodError);
//console.log(prodError);
return {
success: false,
message: "there was an error getting the printers.",

View File

@@ -88,7 +88,7 @@ export const dualPrintingProcess = async (lotInfo: any) => {
"info",
"ocp",
"ocp",
`Printing label for ${whatToPrint.MachineDescription}`
`Printing label for ${whatToPrint[0].MachineDescription}`
);
return whatToPrint;
}
@@ -103,7 +103,7 @@ export const dualPrintingProcess = async (lotInfo: any) => {
"info",
"ocp",
"ocp",
`Printing label for ${whatToPrint.MachineDescription}`
`Printing label for ${whatToPrint[0].MachineDescription}`
);
return whatToPrint;
}

View File

@@ -1,24 +0,0 @@
import { createLog } from "../../../../logger/logger.js";
import { query } from "../../../../sqlServer/prodSqlServer.js";
import { machineCheck } from "../../../../sqlServer/querys/ocp/machineId.js";
export const getMac = async (machine: string) => {
let updateQuery = machineCheck.replaceAll("[loc]", machine);
// create blank lots in case there is an error and dose not work
let mac = [];
try {
mac = await query(updateQuery, "Machine id check");
// console.log("Machine data", mac); // removed due to swr being activated
} catch (err) {
createLog(
"error",
"lst",
"ocp",
`Error with Machine id Check query: ${err}`
);
}
return mac;
};